answer stringlengths 17 10.2M |
|---|
package com.kickstarter.models;
import android.os.Parcel;
import android.os.Parcelable;
import com.hannesdorfmann.parcelableplease.annotation.ParcelablePlease;
import com.kickstarter.libs.AutoGson;
import auto.parcel.AutoParcel;
@AutoGson @AutoParcel
public abstract class Video implements Parcelable {
public abstract String base();
public abstract String frame();
public abstract String high();
public abstract String webm();
@AutoParcel.Builder
public abstract static class Builder {
public abstract Builder base(String __);
public abstract Builder frame(String __);
public abstract Builder high(String __);
public abstract Builder webm(String __);
public abstract Video build();
}
public static Builder builder() {
return new AutoParcel_Video.Builder();
}
public abstract Builder toBuilder();
} |
package de.eightbitboy.hijacr.data;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import de.eightbitboy.hijacr.data.dao.Comic;
import de.eightbitboy.hijacr.data.dao.ComicDao;
import de.eightbitboy.hijacr.data.dao.DaoMaster;
public class Database {
public static String DB_NAME = "comics.dao.db";
private static Database instance;
private Context context;
private SQLiteDatabase db;
private DaoMaster master;
private Database(Context context) {
this.context = context;
setUp();
insertDefaultData();
}
public static synchronized Database getInstance(Context context) {
if (instance == null) {
instance = new Database(context);
}
return instance;
}
private void setUp() {
db = new DaoMaster.DevOpenHelper(context, DB_NAME, null).getWritableDatabase();
master = new DaoMaster(db);
}
/**
* Populate the empty database with comic data.
*/
private void insertDefaultData() {
if (getAllComics().isEmpty()) {
ComicDao dao = createSessionDao();
Comic comic;
comic = new Comic(
1L,
"xkcd",
"XKCD",
"http://xkcd.com/",
"http://c.xkcd.com/random/comic/",
"https://xkcd.com/1/",
null,
null,
"#comic img[src]",
".comicNav a[rel=prev]",
".comicNav a[rel=next]",
null,
false,
false);
dao.insert(comic);
comic = new Comic(
2L,
"smbc",
"SMBC",
"http:
null,
"http:
null,
null,
"#comic",
".prev",
".next",
".random",
false,
false);
dao.insert(comic);
comic = new Comic(
3L,
"vgcats",
"VgCats",
"http:
null,
"http:
null,
null,
"tbody div img[width]",
"a:has(img[src=back.gif])",
"a:has(img[src=next.gif])",
null,
false,
false);
dao.insert(comic);
comic = new Comic(
4L,
"extralife",
"ExtraLife",
"http:
null, //TODO
"http:
null,
null,
".comic",
".prev_comic_link",
".next_comic_link",
null, //TODO
false,
false);
dao.insert(comic);
comic = new Comic(
5L,
"explosm",
"Explosm",
"http://explosm.net/",
null, //TODO
"http://explosm.net/comics/15",
null,
null,
"#main-comic",
".previous-comic",
".next-comic",
null, //TODO
false,
false);
dao.insert(comic);
comic = new Comic(
6L,
"dilbert",
"Dilbert",
"http://dilbert.com/",
null, //TODO
"http://dilbert.com/strip/1989-04-16",
null,
null,
".img-comic",
".nav-left a",
".nav-right a",
null, //TODO
false,
false);
dao.insert(comic);
}
}
private ComicDao createSessionDao() {
return master.newSession().getComicDao();
}
public List<Comic> getAllComics() {
return createSessionDao().loadAll();
}
public List<Comic> getAllComicsSortedAlphabetically() {
List<Comic> comics = createSessionDao().loadAll();
Collections.sort(comics, new Comparator<Comic>() {
@Override
public int compare(Comic lhs, Comic rhs) {
return lhs.getTitle().compareToIgnoreCase(rhs.getTitle());
}
});
return comics;
}
public Comic getComicById(long id) {
return createSessionDao().load(id);
}
public void updateComic(Comic comic) {
createSessionDao().update(comic);
}
} |
package com.squareup.otto;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import info.nightscout.androidaps.events.Event;
/** Logs events has they're being posted to and dispatched from the event bus.
*
* A summary of event-receiver calls that occurred so far is logged
* after 10s (after startup) and then again every 60s.
* */
public class LoggingBus extends Bus {
private static Logger log = LoggerFactory.getLogger(LoggingBus.class);
private static long everyMinute = System.currentTimeMillis() + 10 * 1000;
private Map<String, Set<String>> event2Receiver = new HashMap<>();
public LoggingBus(ThreadEnforcer enforcer) {
super(enforcer);
}
@Override
public void post(Object event) {
if (event instanceof DeadEvent) {
log.debug("Event has no receiver: " + ((DeadEvent) event).event + ", source: " + ((DeadEvent) event).source);
return;
}
if (!(event instanceof Event)) {
log.error("Posted event not an event class: " + event.getClass());
}
log.debug("<<< " + event);
try {
StackTraceElement caller = new Throwable().getStackTrace()[1];
String className = caller.getClassName();
className = className.substring(className.lastIndexOf(".") + 1);
log.debug(" source: " + className + "." + caller.getMethodName() + ":" + caller.getLineNumber());
} catch (RuntimeException e) {
log.debug(" source: <unknown>");
}
super.post(event);
}
@Override
protected void dispatch(Object event, EventHandler wrapper) {
try {
log.debug(">>> " + event);
Field methodField = wrapper.getClass().getDeclaredField("method");
methodField.setAccessible(true);
Method targetMethod = (Method) methodField.get(wrapper);
String className = targetMethod.getDeclaringClass().getSimpleName();
String methodName = targetMethod.getName();
String receiverMethod = className + "." + methodName;
log.debug(" receiver: " + receiverMethod);
String key = event.getClass().getSimpleName();
if (!event2Receiver.containsKey(key)) event2Receiver.put(key, new HashSet<String>());
event2Receiver.get(key).add(receiverMethod);
} catch (ReflectiveOperationException e) {
log.debug(" receiver: <unknown>");
}
if (everyMinute < System.currentTimeMillis()) {
log.debug("***************** Event -> receiver pairings seen so far ****************");
for (Map.Entry<String, Set<String>> stringSetEntry : event2Receiver.entrySet()) {
log.debug(" " + stringSetEntry.getKey());
for (String s : stringSetEntry.getValue()) {
log.debug(" -> " + s);
}
}
log.debug("*************************************************************************");
everyMinute = System.currentTimeMillis() + 60 * 1000;
}
super.dispatch(event, wrapper);
}
} |
package de.sopa.scene.game;
import de.sopa.model.GameService;
import de.sopa.model.GameServiceImpl;
import de.sopa.model.Level;
import de.sopa.observer.Observer;
import de.sopa.scene.BaseScene;
import org.andengine.engine.handler.timer.ITimerCallback;
import org.andengine.engine.handler.timer.TimerHandler;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.text.Text;
import org.andengine.input.touch.detector.ContinuousHoldDetector;
import org.andengine.util.color.Color;
/**
* David Schilling - davejs92@gmail.com
*/
public abstract class GameScene extends BaseScene implements Observer {
protected GameService gameService;
private ContinuousHoldDetector continuousHoldDetector;
private float spacePerTile;
private Text scoreText;
private GameFieldView gameFieldView;
private Level level;
protected Level levelBackup;
public GameScene(Object o) {
super(o);
}
@Override
public void createScene(Object o) {
initializeLogic(o);
calculateSpacePerTile(gameService.getLevel().getField().length);
levelBackup = gameService.getLevel().copy();
addBackground();
addTiles();
addButtons();
addScoreText();
registerTouchHandler();
gameService.attach(this);
resourcesManager.menuMusic.stop();
resourcesManager.musicIsPlaying = false;
}
@Override
public void update() {
updateTiles();
scoreText.setText(String.valueOf(gameService.getLevel().getMovesCount()));
if (gameService.solvedPuzzle()) {
gameService.detach(this);
this.clearTouchAreas();
this.clearUpdateHandlers();
baseScene.registerUpdateHandler(new TimerHandler(0.1f, new ITimerCallback() {
public void onTimePassed(final TimerHandler pTimerHandler) {
baseScene.unregisterUpdateHandler(pTimerHandler);
onSolvedGame();
}
}));
}
}
private void addTiles() {
float tilesSceneStartY = getTileSceneStartY();
gameFieldView = new GameFieldView(0, tilesSceneStartY, spacePerTile,
gameService, resourcesManager.regionTileMap, vbom, resourcesManager.tilesBorderRegion);
gameFieldView.addTiles();
attachChild(gameFieldView);
}
private void updateTiles() {
detachChild(gameFieldView);
gameFieldView.addTiles();
attachChild(gameFieldView);
}
private void calculateSpacePerTile(int width) {
spacePerTile = camera.getWidth() / width;
}
private float getTileSceneStartY() {
return (camera.getHeight() - (spacePerTile * gameService.getLevel().getField().length)) / 2;
}
private void addScoreText() {
scoreText = new Text(camera.getWidth() * 0.7f, camera.getHeight() * 0.01f, resourcesManager.scoreFont, String.valueOf(gameService.getLevel().getMovesCount()), 4, vbom);
attachChild(scoreText);
Text minimumMovesScore = new Text(0, camera.getHeight() * 0.01f, resourcesManager.scoreFont, String.valueOf(gameService.getLevel().getMinimumMovesToSolve()), vbom);
attachChild(minimumMovesScore);
}
private void registerTouchHandler() {
final float widthPerTile = camera.getWidth() / gameService.getLevel().getField().length;
GameSceneHoldDetector gameSceneHoldDetector = new GameSceneHoldDetector(widthPerTile, getTileSceneStartY() + widthPerTile, widthPerTile, gameFieldView, gameService, camera.getWidth());
continuousHoldDetector = new ContinuousHoldDetector(0, 100, 0.01f, gameSceneHoldDetector);
registerUpdateHandler(continuousHoldDetector);
setOnSceneTouchListener(continuousHoldDetector);
}
protected abstract void addButtons();
private void addBackground() {
setBackground(new Background(Color.BLACK));
}
private void initializeLogic(Object o) {
if (o != null && o instanceof Level) {
level = (Level) o;
}
gameService = new GameServiceImpl();
gameService.startGame(level);
}
@Override
public abstract void onBackKeyPressed();
@Override
public void disposeScene() {
final GameScene gameScene = this;
engine.registerUpdateHandler(new TimerHandler(0.1f, new ITimerCallback() {
public void onTimePassed(final TimerHandler pTimerHandler) {
engine.unregisterUpdateHandler(pTimerHandler);
gameScene.detachChildren();
}
}));
}
/**
* is called when the game is solved
*/
public abstract void onSolvedGame();
} |
package io.mokshjn.cosmo.utils;
import android.content.Context;
import android.content.SharedPreferences;
import android.support.v4.media.MediaBrowserCompat;
import android.support.v4.media.MediaMetadataCompat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.ArrayList;
public class StorageUtils {
private final static String STORAGE = " io.mokshjn.cosmo.STORAGE";
private SharedPreferences preferences;
private String AUDIO_LIST = "io.mokshjn.cosmo.AUDIO_LIST";
private String CURRENT_QUEUE = "io.mokshjn.cosmo.CURRENT_QUEUE";
private Context context;
public StorageUtils(Context context) {
this.context = context;
}
public static void storeMediaID(Context context, String mediaID) {
SharedPreferences preferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("mediaID", mediaID);
editor.apply();
}
public static String getMediaID(Context context) {
String mediaID;
SharedPreferences preferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);
mediaID = preferences.getString("mediaID", "null");
return mediaID;
}
public void storeSong(ArrayList<MediaMetadataCompat> arrayList) {
preferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(arrayList);
editor.putString(AUDIO_LIST, json);
editor.apply();
}
public ArrayList<MediaMetadataCompat> loadSongs() {
preferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);
String json = preferences.getString(AUDIO_LIST, null);
Type type = new TypeToken<ArrayList<MediaMetadataCompat>>() {
}.getType();
Gson gson = new Gson();
return gson.fromJson(json, type);
}
public void storePosition(int position) {
preferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putInt("audioPosition", position);
editor.apply();
}
public int loadPosition() {
preferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);
return preferences.getInt("audioPosition", -1);//return -1 if no data found
}
public void storeCurrentPlayingQueue(ArrayList<MediaBrowserCompat.MediaItem> tracks) {
preferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
Gson gson = new Gson();
String json = gson.toJson(tracks);
editor.putString(CURRENT_QUEUE, json);
editor.apply();
}
public ArrayList<MediaBrowserCompat.MediaItem> getCurrentPlayingQueue() {
preferences = context.getSharedPreferences(STORAGE, Context.MODE_PRIVATE);
String json = preferences.getString(CURRENT_QUEUE, null);
Type type = new TypeToken<ArrayList<MediaMetadataCompat>>() {
}.getType();
Gson gson = new Gson();
return gson.fromJson(json, type);
}
} |
package it.unical.mat.embasp.dlv;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.List;
import java.util.concurrent.TimeUnit;
import it.unical.mat.embasp.base.Output;
import it.unical.mat.embasp.base.Callback;
import it.unical.mat.embasp.base.InputProgram;
import it.unical.mat.embasp.base.OptionDescriptor;
import it.unical.mat.embasp.platforms.android.AndroidService;
public class DLVService extends AndroidService {
public DLVService() {
binder = new DLVBinder();
}
//load the static library that contains DLV code compiled for arm processors
static{
System.loadLibrary("dlvJNI");
}
/*Returns the current Service class , can be used to interact directly with the Service*/
public class DLVBinder extends AndroidBinder {
public AndroidService getService(){
return DLVService.this;
}
}
@Override
public Output startSync(List<InputProgram> programs, List<OptionDescriptor> options) {
return null;
}
// check multiple execution
@Override
public void startAsync(final Callback callback,final List <InputProgram> programs, final List<OptionDescriptor> options) {
new Thread(new Runnable() {
public void run() {
StringBuilder input_data = new StringBuilder();
input_data.append("-silent ");
for (OptionDescriptor o :options) {
input_data.append(o.getOptions()).append(" ");
}
String final_program = new String();
for (InputProgram p : programs) {
final_program += p.getProgram();
String program_file = p.getFiles();
if(program_file != null) {
if(input_data.length()==0) {
input_data.append(program_file);
}else{
input_data.append(program_file).append(" ");
}
}
}
System.out.println(final_program);
File tmp_file = new File(getFilesDir(),"tmp_file");
Writer outputStream;
try {
outputStream = new BufferedWriter(new FileWriter(tmp_file));
outputStream.append(final_program);
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
input_data.append(tmp_file.getAbsolutePath());
long startTime = System.nanoTime();
String result = dlvMain(input_data.toString());
long stopTime = System.nanoTime();
Log.i("DLV Execution Time", Long.toString(TimeUnit.NANOSECONDS.toMillis(stopTime - startTime)));
callback.callback(new DLVAnswerSets(result));
}
}).start();
}
/**
* Native function for DLV invocation
* @param filePath the path of a temporary file storing DLV program
* @return String result computed from DLV
*/
private native String dlvMain(String filePath);
} |
package net.runelite.client.plugins.examine;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import java.time.Instant;
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.concurrent.ScheduledExecutorService;
import java.util.regex.Pattern;
import javax.inject.Inject;
import lombok.extern.slf4j.Slf4j;
import net.runelite.api.ChatMessageType;
import net.runelite.api.Client;
import net.runelite.api.Constants;
import net.runelite.api.ItemComposition;
import net.runelite.api.ItemID;
import net.runelite.api.events.ChatMessage;
import net.runelite.api.events.GameStateChanged;
import net.runelite.api.events.MenuOptionClicked;
import net.runelite.api.widgets.Widget;
import net.runelite.api.widgets.WidgetID;
import net.runelite.api.widgets.WidgetInfo;
import static net.runelite.api.widgets.WidgetInfo.SEED_VAULT_ITEM_CONTAINER;
import static net.runelite.api.widgets.WidgetInfo.TO_CHILD;
import static net.runelite.api.widgets.WidgetInfo.TO_GROUP;
import net.runelite.api.widgets.WidgetItem;
import net.runelite.client.chat.ChatColorType;
import net.runelite.client.chat.ChatMessageBuilder;
import net.runelite.client.chat.ChatMessageManager;
import net.runelite.client.chat.QueuedMessage;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.game.ItemManager;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.util.StackFormatter;
import net.runelite.client.util.Text;
import net.runelite.http.api.examine.ExamineClient;
/**
* Submits examine info to the api
*
* @author Adam
*/
@PluginDescriptor(
name = "Examine",
description = "Send examine information to the API",
tags = {"npcs", "items", "inventory", "objects"}
)
@Slf4j
public class ExaminePlugin extends Plugin
{
private static final Pattern X_PATTERN = Pattern.compile("^\\d+ x ");
private final Deque<PendingExamine> pending = new ArrayDeque<>();
private final Cache<CacheKey, Boolean> cache = CacheBuilder.newBuilder()
.maximumSize(128L)
.build();
@Inject
private ExamineClient examineClient;
@Inject
private Client client;
@Inject
private ItemManager itemManager;
@Inject
private ChatMessageManager chatMessageManager;
@Inject
private ScheduledExecutorService executor;
@Subscribe
public void onGameStateChanged(GameStateChanged event)
{
pending.clear();
}
@Subscribe
public void onMenuOptionClicked(MenuOptionClicked event)
{
if (!Text.removeTags(event.getMenuOption()).equals("Examine"))
{
return;
}
ExamineType type;
int id, quantity = -1;
switch (event.getMenuAction())
{
case EXAMINE_ITEM:
{
type = ExamineType.ITEM;
id = event.getId();
int widgetId = event.getWidgetId();
int widgetGroup = TO_GROUP(widgetId);
int widgetChild = TO_CHILD(widgetId);
Widget widget = client.getWidget(widgetGroup, widgetChild);
WidgetItem widgetItem = widget.getWidgetItem(event.getActionParam());
quantity = widgetItem != null && widgetItem.getId() >= 0 ? widgetItem.getQuantity() : 1;
break;
}
case EXAMINE_ITEM_BANK_EQ:
{
type = ExamineType.ITEM_BANK_EQ;
int[] qi = findItemFromWidget(event.getWidgetId(), event.getActionParam());
if (qi == null)
{
log.debug("Examine for item with unknown widget: {}", event);
return;
}
quantity = qi[0];
id = qi[1];
break;
}
case EXAMINE_OBJECT:
type = ExamineType.OBJECT;
id = event.getId();
break;
case EXAMINE_NPC:
type = ExamineType.NPC;
id = event.getId();
break;
default:
return;
}
PendingExamine pendingExamine = new PendingExamine();
pendingExamine.setType(type);
pendingExamine.setId(id);
pendingExamine.setQuantity(quantity);
pendingExamine.setCreated(Instant.now());
pending.push(pendingExamine);
}
@Subscribe
public void onChatMessage(ChatMessage event)
{
ExamineType type;
switch (event.getType())
{
case ITEM_EXAMINE:
type = ExamineType.ITEM;
break;
case OBJECT_EXAMINE:
type = ExamineType.OBJECT;
break;
case NPC_EXAMINE:
type = ExamineType.NPC;
break;
case GAMEMESSAGE:
type = ExamineType.ITEM_BANK_EQ;
break;
default:
return;
}
if (pending.isEmpty())
{
log.debug("Got examine without a pending examine?");
return;
}
PendingExamine pendingExamine = pending.pop();
if (pendingExamine.getType() != type)
{
log.debug("Type mismatch for pending examine: {} != {}", pendingExamine.getType(), type);
pending.clear();
return;
}
log.debug("Got examine for {} {}: {}", pendingExamine.getType(), pendingExamine.getId(), event.getMessage());
// If it is an item, show the price of it
final ItemComposition itemComposition;
if (pendingExamine.getType() == ExamineType.ITEM || pendingExamine.getType() == ExamineType.ITEM_BANK_EQ)
{
final int itemId = pendingExamine.getId();
final int itemQuantity = pendingExamine.getQuantity();
if (itemId == ItemID.COINS_995)
{
return;
}
itemComposition = itemManager.getItemComposition(itemId);
if (itemComposition != null)
{
final int id = itemManager.canonicalize(itemComposition.getId());
executor.submit(() -> getItemPrice(id, itemComposition, itemQuantity));
}
}
else
{
itemComposition = null;
}
// Don't submit examine info for tradeable items, which we already have from the RS item api
if (itemComposition != null && itemComposition.isTradeable())
{
return;
}
// Large quantities of items show eg. 100000 x Coins
if (type == ExamineType.ITEM && X_PATTERN.matcher(event.getMessage()).lookingAt())
{
return;
}
CacheKey key = new CacheKey(type, pendingExamine.getId());
Boolean cached = cache.getIfPresent(key);
if (cached != null)
{
return;
}
cache.put(key, Boolean.TRUE);
submitExamine(pendingExamine, event.getMessage());
}
private int[] findItemFromWidget(int widgetId, int actionParam)
{
int widgetGroup = TO_GROUP(widgetId);
int widgetChild = TO_CHILD(widgetId);
Widget widget = client.getWidget(widgetGroup, widgetChild);
if (widget == null)
{
return null;
}
if (WidgetInfo.EQUIPMENT.getGroupId() == widgetGroup)
{
Widget widgetItem = widget.getChild(1);
if (widgetItem != null)
{
return new int[]{widgetItem.getItemQuantity(), widgetItem.getItemId()};
}
}
else if (WidgetInfo.SMITHING_INVENTORY_ITEMS_CONTAINER.getGroupId() == widgetGroup)
{
Widget widgetItem = widget.getChild(2);
if (widgetItem != null)
{
return new int[]{widgetItem.getItemQuantity(), widgetItem.getItemId()};
}
}
else if (WidgetInfo.BANK_INVENTORY_ITEMS_CONTAINER.getGroupId() == widgetGroup
|| WidgetInfo.RUNE_POUCH_ITEM_CONTAINER.getGroupId() == widgetGroup)
{
Widget widgetItem = widget.getChild(actionParam);
if (widgetItem != null)
{
return new int[]{widgetItem.getItemQuantity(), widgetItem.getItemId()};
}
}
else if (WidgetInfo.BANK_ITEM_CONTAINER.getGroupId() == widgetGroup
|| WidgetInfo.CLUE_SCROLL_REWARD_ITEM_CONTAINER.getGroupId() == widgetGroup
|| WidgetInfo.LOOTING_BAG_CONTAINER.getGroupId() == widgetGroup
|| WidgetID.SEED_VAULT_INVENTORY_GROUP_ID == widgetGroup
|| WidgetID.SEED_BOX_GROUP_ID == widgetGroup)
{
Widget[] children = widget.getDynamicChildren();
if (actionParam < children.length)
{
Widget widgetItem = children[actionParam];
return new int[]{widgetItem.getItemQuantity(), widgetItem.getItemId()};
}
}
else if (WidgetInfo.SHOP_ITEMS_CONTAINER.getGroupId() == widgetGroup)
{
Widget[] children = widget.getDynamicChildren();
if (actionParam < children.length)
{
Widget widgetItem = children[actionParam];
return new int[]{1, widgetItem.getItemId()};
}
}
else if (WidgetID.SEED_VAULT_GROUP_ID == widgetGroup)
{
Widget[] children = client.getWidget(SEED_VAULT_ITEM_CONTAINER).getDynamicChildren();
if (actionParam < children.length)
{
Widget widgetItem = children[actionParam];
return new int[]{widgetItem.getItemQuantity(), widgetItem.getItemId()};
}
}
return null;
}
private void getItemPrice(int id, ItemComposition itemComposition, int quantity)
{
// quantity is at least 1
quantity = Math.max(1, quantity);
int itemCompositionPrice = itemComposition.getPrice();
final int gePrice = itemManager.getItemPrice(id);
final int alchPrice = itemCompositionPrice <= 0 ? 0 : Math.round(itemCompositionPrice * Constants.HIGH_ALCHEMY_MULTIPLIER);
if (gePrice > 0 || alchPrice > 0)
{
final ChatMessageBuilder message = new ChatMessageBuilder()
.append(ChatColorType.NORMAL)
.append("Price of ")
.append(ChatColorType.HIGHLIGHT);
if (quantity > 1)
{
message
.append(StackFormatter.formatNumber(quantity))
.append(" x ");
}
message
.append(itemComposition.getName())
.append(ChatColorType.NORMAL)
.append(":");
if (gePrice > 0)
{
message
.append(ChatColorType.NORMAL)
.append(" GE average ")
.append(ChatColorType.HIGHLIGHT)
.append(StackFormatter.formatNumber(gePrice * quantity));
if (quantity > 1)
{
message
.append(ChatColorType.NORMAL)
.append(" (")
.append(ChatColorType.HIGHLIGHT)
.append(StackFormatter.formatNumber(gePrice))
.append(ChatColorType.NORMAL)
.append("ea)");
}
}
if (alchPrice > 0)
{
message
.append(ChatColorType.NORMAL)
.append(" HA value ")
.append(ChatColorType.HIGHLIGHT)
.append(StackFormatter.formatNumber(alchPrice * quantity));
if (quantity > 1)
{
message
.append(ChatColorType.NORMAL)
.append(" (")
.append(ChatColorType.HIGHLIGHT)
.append(StackFormatter.formatNumber(alchPrice))
.append(ChatColorType.NORMAL)
.append("ea)");
}
}
chatMessageManager.queue(QueuedMessage.builder()
.type(ChatMessageType.ITEM_EXAMINE)
.runeLiteFormattedMessage(message.build())
.build());
}
}
private void submitExamine(PendingExamine examine, String text)
{
int id = examine.getId();
switch (examine.getType())
{
case ITEM:
examineClient.submitItem(id, text);
break;
case OBJECT:
examineClient.submitObject(id, text);
break;
case NPC:
examineClient.submitNpc(id, text);
break;
}
}
} |
package com.sg.java8.training.supplier;
import com.sg.java8.training.model.Product;
import com.sg.java8.training.supplier.service.ProductService;
import java.util.Random;
import java.util.function.Supplier;
/**
* A few {@link java.util.function.Supplier} usage samples
*/
public class SuppliersMain {
public static void main(String[] args) {
simpleSuppliers();
productSuppliers();
sectionSuppliers();
managerSuppliers();
}
private static void simpleSuppliers() {
final Supplier<Double> doubleSupplier = () -> new Random(1000).nextDouble();
System.out.println(doubleSupplier.get());
final Supplier<String> holidaySupplier = () -> "I want a holiday, not just a weekend :)";
System.out.println(holidaySupplier.get());
final Supplier<RuntimeException> runtimeExceptionSupplier = () -> new IllegalArgumentException("Nope");
System.out.println(runtimeExceptionSupplier.get().getMessage());
// TODO try other simple Suppliers - String, Boolean, ...
}
private static void productSuppliers() {
final ProductService productService = new ProductService();
final Product product = productService.generateRandomProduct().get();
System.out.println(product);
// TODO try other Product Suppliers
}
private static void sectionSuppliers() {
// TODO try a few Section Suppliers
}
private static void managerSuppliers() {
// TODO try a few Manager Suppliers
}
} |
package com.quickblox.sample.chat.ui.activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.view.ActionMode;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayout;
import com.orangegangsters.github.swipyrefreshlayout.library.SwipyRefreshLayoutDirection;
import com.quickblox.chat.QBChatService;
import com.quickblox.chat.QBGroupChat;
import com.quickblox.chat.QBGroupChatManager;
import com.quickblox.chat.QBPrivateChat;
import com.quickblox.chat.QBPrivateChatManager;
import com.quickblox.chat.exception.QBChatException;
import com.quickblox.chat.listeners.QBGroupChatManagerListener;
import com.quickblox.chat.listeners.QBMessageListener;
import com.quickblox.chat.listeners.QBPrivateChatManagerListener;
import com.quickblox.chat.model.QBChatMessage;
import com.quickblox.chat.model.QBDialog;
import com.quickblox.core.QBEntityCallback;
import com.quickblox.core.exception.QBResponseException;
import com.quickblox.core.helper.StringifyArrayList;
import com.quickblox.core.request.QBRequestGetBuilder;
import com.quickblox.sample.chat.R;
import com.quickblox.sample.chat.ui.adapter.DialogsAdapter;
import com.quickblox.sample.chat.utils.Consts;
import com.quickblox.sample.chat.utils.SharedPreferencesUtil;
import com.quickblox.sample.chat.utils.chat.ChatHelper;
import com.quickblox.sample.chat.utils.qb.QbDialogHolder;
import com.quickblox.sample.core.gcm.GooglePlayServicesHelper;
import com.quickblox.sample.core.ui.dialog.ProgressDialogFragment;
import com.quickblox.sample.core.utils.ErrorUtils;
import com.quickblox.sample.core.utils.constant.GcmConsts;
import com.quickblox.users.model.QBUser;
import java.util.ArrayList;
import java.util.Collection;
public class DialogsActivity extends BaseActivity {
private static final String TAG = DialogsActivity.class.getSimpleName();
private static final int REQUEST_SELECT_PEOPLE = 174;
private static final int REQUEST_MARK_READ = 165;
private ProgressBar progressBar;
private FloatingActionButton fab;
private ActionMode currentActionMode;
private SwipyRefreshLayout setOnRefreshListener;
private QBRequestGetBuilder requestBuilder;
private int skipRecords = 0;
private BroadcastReceiver pushBroadcastReceiver;
private GooglePlayServicesHelper googlePlayServicesHelper;
private DialogsAdapter dialogsAdapter;
public static void start(Context context) {
Intent intent = new Intent(context, DialogsActivity.class);
context.startActivity(intent);
}
private QBPrivateChatManagerListener privateChatManagerListener;
private QBGroupChatManagerListener groupChatManagerListener;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dialogs);
googlePlayServicesHelper = new GooglePlayServicesHelper();
if (googlePlayServicesHelper.checkPlayServicesAvailable(this)) {
googlePlayServicesHelper.registerForGcm(Consts.GCM_SENDER_ID);
}
pushBroadcastReceiver = new PushBroadcastReceiver();
privateChatManagerListener = new QBPrivateChatManagerListener() {
@Override
public void chatCreated(QBPrivateChat qbPrivateChat, boolean createdLocally) {
qbPrivateChat.addMessageListener(privateChatMessageListener);
}
};
groupChatManagerListener = new QBGroupChatManagerListener() {
@Override
public void chatCreated(QBGroupChat qbGroupChat) {
loadDialogsFromQbInUiThread(true);
}
};
initUi();
}
@Override
protected void onResume() {
super.onResume();
googlePlayServicesHelper.checkPlayServicesAvailable(this);
LocalBroadcastManager.getInstance(this).registerReceiver(pushBroadcastReceiver,
new IntentFilter(GcmConsts.ACTION_NEW_GCM_EVENT));
if (isAppSessionActive) {
registerQbChatListeners();
}
}
@Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(pushBroadcastReceiver);
if (isAppSessionActive) {
unregisterQbChatListeners();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_dialogs, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_dialogs_action_logout:
userLogout();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
public void onSessionCreated(boolean success) {
if (success) {
QBUser currentUser = ChatHelper.getCurrentUser();
if (currentUser != null) {
actionBar.setTitle(getString(R.string.dialogs_logged_in_as, currentUser.getFullName()));
}
registerQbChatListeners();
if (QbDialogHolder.getInstance().getDialogList().size() > 0) {
loadDialogsFromQb(true, true);
} else {
loadDialogsFromQb();
}
}
}
@SuppressWarnings("unchecked")
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == REQUEST_SELECT_PEOPLE) {
ArrayList<QBUser> selectedUsers = (ArrayList<QBUser>) data
.getSerializableExtra(SelectUsersActivity.EXTRA_QB_USERS);
createDialog(selectedUsers);
} else if (requestCode == REQUEST_MARK_READ) {
ArrayList<String> chatMessageIds = (ArrayList<String>) data
.getSerializableExtra(ChatActivity.EXTRA_MARK_READ);
final StringifyArrayList<String> messagesIds = new StringifyArrayList<>();
messagesIds.addAll(chatMessageIds);
String dialogId = (String) data.getSerializableExtra(ChatActivity.EXTRA_DIALOG_ID);
markMessagesRead(messagesIds, dialogId);
}
}
}
@Override
protected View getSnackbarAnchorView() {
return findViewById(R.id.layout_root);
}
@Override
public ActionMode startSupportActionMode(ActionMode.Callback callback) {
currentActionMode = super.startSupportActionMode(callback);
return currentActionMode;
}
private void userLogout() {
if (ChatHelper.getInstance().logout()) {
if (googlePlayServicesHelper.checkPlayServicesAvailable()) {
googlePlayServicesHelper.unregisterFromGcm(Consts.GCM_SENDER_ID);
}
SharedPreferencesUtil.removeQbUser();
LoginActivity.start(this);
finish();
} else {
reconnectToChatLogout(SharedPreferencesUtil.getQbUser());
}
}
private void reconnectToChatLogout(final QBUser user) {
ProgressDialogFragment.show(getSupportFragmentManager(), R.string.dlg_restoring_chat_session_logout);
ChatHelper.getInstance().login(user, new QBEntityCallback<Void>() {
@Override
public void onSuccess(Void result, Bundle bundle) {
ProgressDialogFragment.hide(getSupportFragmentManager());
userLogout();
}
@Override
public void onError(QBResponseException e) {
ProgressDialogFragment.hide(getSupportFragmentManager());
ErrorUtils.showSnackbar(findViewById(R.id.layout_root), R.string.no_internet_connection,
R.string.dlg_retry, new View.OnClickListener() {
@Override
public void onClick(View v) {
reconnectToChatLogout(SharedPreferencesUtil.getQbUser());
}
});
}
});
}
private void markMessagesRead(StringifyArrayList<String> messagesIds, String dialogId) {
if (messagesIds.size() > 0) {
QBChatService.markMessagesAsRead(dialogId, messagesIds, new QBEntityCallback<Void>() {
@Override
public void onSuccess(Void aVoid, Bundle bundle) {
updateDialogsList();
}
@Override
public void onError(QBResponseException e) {
}
});
} else {
updateDialogsList();
}
}
private void updateDialogsList() {
if (isAppSessionActive) {
requestBuilder.setSkip(skipRecords = 0);
loadDialogsFromQb(true, true);
}
}
public void onStartNewChatClick(View view) {
SelectUsersActivity.startForResult(this, REQUEST_SELECT_PEOPLE);
}
private void initUi() {
LinearLayout emptyHintLayout = _findViewById(R.id.layout_chat_empty);
ListView dialogsListView = _findViewById(R.id.list_dialogs_chats);
progressBar = _findViewById(R.id.progress_dialogs);
fab = _findViewById(R.id.fab_dialogs_new_chat);
setOnRefreshListener = _findViewById(R.id.swipy_refresh_layout);
dialogsAdapter = new DialogsAdapter(this, QbDialogHolder.getInstance().getDialogList());
TextView listHeader = (TextView) LayoutInflater.from(this)
.inflate(R.layout.include_list_hint_header, dialogsListView, false);
listHeader.setText(R.string.dialogs_list_hint);
dialogsListView.setEmptyView(emptyHintLayout);
dialogsListView.addHeaderView(listHeader, null, false);
dialogsListView.setAdapter(dialogsAdapter);
dialogsListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
QBDialog selectedDialog = (QBDialog) parent.getItemAtPosition(position);
if (currentActionMode == null) {
ChatActivity.startForResult(DialogsActivity.this, REQUEST_MARK_READ, selectedDialog);
} else {
dialogsAdapter.toggleSelection(selectedDialog);
}
}
});
dialogsListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
QBDialog selectedDialog = (QBDialog) parent.getItemAtPosition(position);
startSupportActionMode(new DeleteActionModeCallback());
dialogsAdapter.selectItem(selectedDialog);
return true;
}
});
requestBuilder = new QBRequestGetBuilder();
setOnRefreshListener.setOnRefreshListener(new SwipyRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh(SwipyRefreshLayoutDirection direction) {
requestBuilder.setSkip(skipRecords += ChatHelper.DIALOG_ITEMS_PER_PAGE);
loadDialogsFromQb(true, false);
}
});
}
QBMessageListener<QBPrivateChat> privateChatMessageListener = new QBMessageListener<QBPrivateChat>() {
@Override
public void processMessage(QBPrivateChat privateChat, final QBChatMessage chatMessage) {
loadDialogsFromQbInUiThread(true);
}
@Override
public void processError(QBPrivateChat privateChat, QBChatException error, QBChatMessage originMessage) {
}
};
private void registerQbChatListeners() {
QBPrivateChatManager privateChatManager = QBChatService.getInstance().getPrivateChatManager();
QBGroupChatManager groupChatManager = QBChatService.getInstance().getGroupChatManager();
if (privateChatManager != null) {
privateChatManager.addPrivateChatManagerListener(privateChatManagerListener);
}
if (groupChatManager != null) {
groupChatManager.addGroupChatManagerListener(groupChatManagerListener);
}
}
private void unregisterQbChatListeners() {
QBPrivateChatManager privateChatManager = QBChatService.getInstance().getPrivateChatManager();
QBGroupChatManager groupChatManager = QBChatService.getInstance().getGroupChatManager();
if (privateChatManager != null) {
privateChatManager.removePrivateChatManagerListener(privateChatManagerListener);
}
if (groupChatManager != null) {
groupChatManager.removeGroupChatManagerListener(groupChatManagerListener);
}
}
private void createDialog(final ArrayList<QBUser> selectedUsers) {
ChatHelper.getInstance().createDialogWithSelectedUsers(selectedUsers,
new QBEntityCallback<QBDialog>() {
@Override
public void onSuccess(QBDialog dialog, Bundle args) {
ChatActivity.startForResult(DialogsActivity.this, REQUEST_MARK_READ, dialog);
}
@Override
public void onError(QBResponseException e) {
showErrorSnackbar(R.string.dialogs_creation_error, e,
new View.OnClickListener() {
@Override
public void onClick(View v) {
createDialog(selectedUsers);
}
});
}
}
);
}
private void loadDialogsFromQb() {
loadDialogsFromQb(false, true);
}
private void loadDialogsFromQbInUiThread(final boolean silentUpdate) {
runOnUiThread(new Runnable() {
@Override
public void run() {
loadDialogsFromQb(silentUpdate, true);
}
});
}
private void loadDialogsFromQb(final boolean silentUpdate, final boolean clearDialogHolder) {
if (!silentUpdate) {
progressBar.setVisibility(View.VISIBLE);
}
ChatHelper.getInstance().getDialogs(requestBuilder, new QBEntityCallback<ArrayList<QBDialog>>() {
@Override
public void onSuccess(ArrayList<QBDialog> dialogs, Bundle bundle) {
progressBar.setVisibility(View.GONE);
setOnRefreshListener.setRefreshing(false);
if (clearDialogHolder) {
QbDialogHolder.getInstance().clear();
}
QbDialogHolder.getInstance().addDialogs(dialogs);
dialogsAdapter.notifyDataSetChanged();
}
@Override
public void onError(QBResponseException e) {
progressBar.setVisibility(View.GONE);
setOnRefreshListener.setRefreshing(false);
if (!silentUpdate || !clearDialogHolder) {
showErrorSnackbar(R.string.dialogs_get_error, e,
new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!silentUpdate) {
loadDialogsFromQb();
} else {
setOnRefreshListener.setRefreshing(true);
loadDialogsFromQb(true, false);
}
}
}).setCallback(new Snackbar.Callback() {
@Override
public void onDismissed(Snackbar snackbar, int event) {
setOnRefreshListener.setEnabled(true);
switch (event) {
case Snackbar.Callback.DISMISS_EVENT_SWIPE:
if (!clearDialogHolder) {
skipRecords -= ChatHelper.DIALOG_ITEMS_PER_PAGE;
}
break;
}
}
@Override
public void onShown(Snackbar snackbar) {
setOnRefreshListener.setEnabled(false);
}
});
}
}
});
}
private class DeleteActionModeCallback implements ActionMode.Callback {
public DeleteActionModeCallback() {
fab.hide();
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.action_mode_dialogs, menu);
return true;
}
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_dialogs_action_delete:
deleteSelectedDialogs();
if (currentActionMode != null) {
currentActionMode.finish();
}
return true;
}
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
currentActionMode = null;
dialogsAdapter.clearSelection();
fab.show();
}
private void deleteSelectedDialogs() {
final Collection<QBDialog> selectedDialogs = dialogsAdapter.getSelectedItems();
ChatHelper.getInstance().deleteDialogs(selectedDialogs, new QBEntityCallback<Void>() {
@Override
public void onSuccess(Void aVoid, Bundle bundle) {
QbDialogHolder.getInstance().deleteDialogs(selectedDialogs);
}
@Override
public void onError(QBResponseException e) {
showErrorSnackbar(R.string.dialogs_deletion_error, e,
new View.OnClickListener() {
@Override
public void onClick(View v) {
deleteSelectedDialogs();
}
});
}
});
}
}
private class PushBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra(GcmConsts.EXTRA_GCM_MESSAGE);
Log.i(TAG, "Received broadcast " + intent.getAction() + " with data: " + message);
loadDialogsFromQb(true, true);
}
}
} |
package org.wikipedia.page.tabs;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.appcompat.widget.Toolbar;
import com.google.android.material.snackbar.Snackbar;
import org.wikipedia.Constants;
import org.wikipedia.R;
import org.wikipedia.WikipediaApp;
import org.wikipedia.activity.BaseActivity;
import org.wikipedia.analytics.TabFunnel;
import org.wikipedia.main.MainActivity;
import org.wikipedia.navtab.NavTab;
import org.wikipedia.page.PageActivity;
import org.wikipedia.page.PageTitle;
import org.wikipedia.util.DimenUtil;
import org.wikipedia.util.FeedbackUtil;
import org.wikipedia.util.ResourceUtil;
import org.wikipedia.util.log.L;
import org.wikipedia.views.TabCountsView;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.mrapp.android.tabswitcher.Animation;
import de.mrapp.android.tabswitcher.Tab;
import de.mrapp.android.tabswitcher.TabSwitcher;
import de.mrapp.android.tabswitcher.TabSwitcherDecorator;
import de.mrapp.android.tabswitcher.TabSwitcherListener;
import de.mrapp.android.util.logging.LogLevel;
import static org.wikipedia.util.L10nUtil.setConditionalLayoutDirection;
public class TabActivity extends BaseActivity {
private static final String LAUNCHED_FROM_PAGE_ACTIVITY = "launchedFromPageActivity";
public static final int RESULT_LOAD_FROM_BACKSTACK = 10;
public static final int RESULT_NEW_TAB = 11;
private static final int MAX_CACHED_BMP_SIZE = 800;
@BindView(R.id.tab_switcher) TabSwitcher tabSwitcher;
@BindView(R.id.tab_toolbar) Toolbar tabToolbar;
@BindView(R.id.tab_counts_view) TabCountsView tabCountsView;
private WikipediaApp app;
private boolean launchedFromPageActivity;
private TabListener tabListener = new TabListener();
private TabFunnel funnel = new TabFunnel();
private boolean cancelled = true;
private long tabUpdatedTimeMillis;
@Nullable private static Bitmap FIRST_TAB_BITMAP;
public static void captureFirstTabBitmap(@NonNull View view) {
clearFirstTabBitmap();
Bitmap bmp = null;
try {
boolean wasCacheEnabled = view.isDrawingCacheEnabled();
if (!wasCacheEnabled) {
view.setDrawingCacheEnabled(true);
view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
}
Bitmap cacheBmp = view.getDrawingCache();
if (cacheBmp != null) {
int width;
int height;
if (cacheBmp.getWidth() > cacheBmp.getHeight()) {
width = MAX_CACHED_BMP_SIZE;
height = width * cacheBmp.getHeight() / cacheBmp.getWidth();
} else {
height = MAX_CACHED_BMP_SIZE;
width = height * cacheBmp.getWidth() / cacheBmp.getHeight();
}
bmp = Bitmap.createScaledBitmap(cacheBmp, width, height, true);
}
if (!wasCacheEnabled) {
view.setDrawingCacheEnabled(false);
}
} catch (OutOfMemoryError e) {
// don't worry about it
}
FIRST_TAB_BITMAP = bmp;
}
private static void clearFirstTabBitmap() {
if (FIRST_TAB_BITMAP != null) {
if (!FIRST_TAB_BITMAP.isRecycled()) {
FIRST_TAB_BITMAP.recycle();
}
FIRST_TAB_BITMAP = null;
}
}
public static Intent newIntent(@NonNull Context context) {
return new Intent(context, TabActivity.class);
}
public static Intent newIntentFromPageActivity(@NonNull Context context) {
return new Intent(context, TabActivity.class)
.putExtra(LAUNCHED_FROM_PAGE_ACTIVITY, true);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tabs);
ButterKnife.bind(this);
app = WikipediaApp.getInstance();
funnel.logEnterList(app.getTabCount());
tabCountsView.updateTabCount();
launchedFromPageActivity = getIntent().hasExtra(LAUNCHED_FROM_PAGE_ACTIVITY);
FeedbackUtil.setToolbarButtonLongPressToast(tabCountsView);
setStatusBarColor(ResourceUtil.getThemedAttributeId(this, android.R.attr.colorBackground));
setSupportActionBar(tabToolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setTitle("");
tabSwitcher.setDecorator(new TabSwitcherDecorator() {
@NonNull
@Override
public View onInflateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup parent, int viewType) {
if (viewType == 1) {
ImageView view = new AppCompatImageView(TabActivity.this);
view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setImageBitmap(FIRST_TAB_BITMAP);
view.setPadding(0, topTabLeadImageEnabled() ? 0 : -DimenUtil.getToolbarHeightPx(TabActivity.this), 0, 0);
return view;
}
return inflater.inflate(R.layout.item_tab_contents, parent, false);
}
@Override
public void onShowTab(@NonNull Context context, @NonNull TabSwitcher tabSwitcher, @NonNull View view,
@NonNull Tab tab, int index, int viewType, @Nullable Bundle savedInstanceState) {
int tabIndex = app.getTabCount() - index - 1;
if (viewType == 1 || tabIndex < 0 || app.getTabList().get(tabIndex) == null) {
return;
}
TextView titleText = view.findViewById(R.id.tab_article_title);
TextView descriptionText = view.findViewById(R.id.tab_article_description);
PageTitle title = app.getTabList().get(tabIndex).getBackStackPositionTitle();
titleText.setText(title.getDisplayText());
if (TextUtils.isEmpty(title.getDescription())) {
descriptionText.setVisibility(View.GONE);
} else {
descriptionText.setText(title.getDescription());
descriptionText.setVisibility(View.VISIBLE);
}
setConditionalLayoutDirection(view, title.getWikiSite().languageCode());
}
@Override
public int getViewType(@NonNull final Tab tab, final int index) {
if (index == 0 && FIRST_TAB_BITMAP != null && !FIRST_TAB_BITMAP.isRecycled()) {
return 1;
}
return 0;
}
@Override
public int getViewTypeCount() {
return 2;
}
});
for (int i = 0; i < app.getTabList().size(); i++) {
int tabIndex = app.getTabList().size() - i - 1;
if (app.getTabList().get(tabIndex).getBackStack().isEmpty()) {
continue;
}
Tab tab = new Tab(app.getTabList().get(tabIndex).getBackStackPositionTitle().getDisplayText());
tab.setIcon(R.drawable.ic_image_black_24dp);
tab.setIconTint(ResourceUtil.getThemedColor(this, R.attr.material_theme_secondary_color));
tab.setTitleTextColor(ResourceUtil.getThemedColor(this, R.attr.material_theme_secondary_color));
tab.setCloseButtonIcon(R.drawable.ic_close_white_24dp);
tab.setCloseButtonIconTint(ResourceUtil.getThemedColor(this, R.attr.material_theme_secondary_color));
tab.setCloseable(true);
tab.setParameters(new Bundle());
tabSwitcher.addTab(tab);
}
tabSwitcher.setLogLevel(LogLevel.OFF);
tabSwitcher.addListener(tabListener);
tabSwitcher.showSwitcher();
}
@OnClick(R.id.tab_counts_view) void onItemClick(View view) {
onBackPressed();
}
@Override
public void onDestroy() {
if (cancelled) {
funnel.logCancel(app.getTabCount());
}
tabSwitcher.removeListener(tabListener);
clearFirstTabBitmap();
super.onDestroy();
}
@Override
public void onPause() {
super.onPause();
app.commitTabState();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_tabs, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
openNewTab();
return true;
case R.id.menu_close_all_tabs:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage(R.string.close_all_tabs_confirm);
alert.setPositiveButton(R.string.close_all_tabs_confirm_yes, (dialog, which) -> {
tabSwitcher.clear();
cancelled = false;
});
alert.setNegativeButton(R.string.close_all_tabs_confirm_no, null);
alert.create().show();
return true;
case R.id.menu_open_a_new_tab:
openNewTab();
return true;
case R.id.menu_explore:
startActivity(MainActivity.newIntent(TabActivity.this)
.putExtra(Constants.INTENT_EXTRA_GO_TO_MAIN_TAB, NavTab.EXPLORE.code()));
finish();
return true;
case R.id.menu_reading_lists:
startActivity(MainActivity.newIntent(TabActivity.this)
.putExtra(Constants.INTENT_EXTRA_GO_TO_MAIN_TAB, NavTab.READING_LISTS.code()));
finish();
return true;
case R.id.menu_history:
startActivity(MainActivity.newIntent(TabActivity.this)
.putExtra(Constants.INTENT_EXTRA_GO_TO_MAIN_TAB, NavTab.HISTORY.code()));
finish();
return true;
case R.id.menu_nearby:
startActivity(MainActivity.newIntent(TabActivity.this)
.putExtra(Constants.INTENT_EXTRA_GO_TO_MAIN_TAB, NavTab.NEARBY.code()));
finish();
return true;
default:
break;
}
return super.onOptionsItemSelected(item);
}
private boolean topTabLeadImageEnabled() {
if (app.getTabCount() > 0) {
PageTitle pageTitle = app.getTabList().get(app.getTabCount() - 1).getBackStackPositionTitle();
return pageTitle != null && (!pageTitle.isMainPage() && !TextUtils.isEmpty(pageTitle.getThumbUrl()));
}
return false;
}
private void openNewTab() {
cancelled = false;
funnel.logCreateNew(app.getTabCount());
if (launchedFromPageActivity) {
setResult(RESULT_NEW_TAB);
} else {
startActivity(PageActivity.newIntentForNewTab(TabActivity.this));
}
finish();
}
private void showUndoSnackbar(final Tab tab, final int index, final org.wikipedia.page.tabs.Tab appTab, final int appTabIndex) {
Snackbar snackbar = FeedbackUtil.makeSnackbar(this, getString(R.string.tab_item_closed, appTab.getBackStackPositionTitle().getDisplayText()), FeedbackUtil.LENGTH_DEFAULT);
snackbar.setAction(R.string.reading_list_item_delete_undo, v -> {
app.getTabList().add(appTabIndex, appTab);
tabSwitcher.addTab(tab, index);
});
snackbar.show();
}
private void showUndoAllSnackbar(@NonNull final Tab[] tabs, @NonNull List<org.wikipedia.page.tabs.Tab> appTabs) {
Snackbar snackbar = FeedbackUtil.makeSnackbar(this, getString(R.string.all_tab_items_closed), FeedbackUtil.LENGTH_DEFAULT);
snackbar.setAction(R.string.reading_list_item_delete_undo, v -> {
app.getTabList().addAll(appTabs);
tabSwitcher.addAllTabs(tabs);
appTabs.clear();
});
snackbar.show();
}
private class TabListener implements TabSwitcherListener {
@Override public void onSwitcherShown(@NonNull TabSwitcher tabSwitcher) { }
@Override public void onSwitcherHidden(@NonNull TabSwitcher tabSwitcher) { }
@Override
public void onSelectionChanged(@NonNull TabSwitcher tabSwitcher, int index, @Nullable Tab selectedTab) {
int tabIndex = app.getTabList().size() - index - 1;
L.d("Tab selected: " + index);
if (tabIndex < app.getTabList().size() - 1) {
org.wikipedia.page.tabs.Tab tab = app.getTabList().remove(tabIndex);
app.getTabList().add(tab);
}
tabCountsView.updateTabCount();
cancelled = false;
final int tabUpdateDebounceMillis = 250;
if (System.currentTimeMillis() - tabUpdatedTimeMillis > tabUpdateDebounceMillis) {
funnel.logSelect(app.getTabCount(), tabIndex);
if (launchedFromPageActivity) {
setResult(RESULT_LOAD_FROM_BACKSTACK);
} else {
startActivity(PageActivity.newIntent(TabActivity.this));
}
finish();
}
}
@Override
public void onTabAdded(@NonNull TabSwitcher tabSwitcher, int index, @NonNull Tab tab, @NonNull Animation animation) {
tabCountsView.updateTabCount();
tabUpdatedTimeMillis = System.currentTimeMillis();
}
@Override
public void onTabRemoved(@NonNull TabSwitcher tabSwitcher, int index, @NonNull Tab tab, @NonNull Animation animation) {
int tabIndex = app.getTabList().size() - index - 1;
org.wikipedia.page.tabs.Tab appTab = app.getTabList().remove(tabIndex);
funnel.logClose(app.getTabCount(), tabIndex);
tabCountsView.updateTabCount();
setResult(RESULT_LOAD_FROM_BACKSTACK);
showUndoSnackbar(tab, index, appTab, tabIndex);
tabUpdatedTimeMillis = System.currentTimeMillis();
}
@Override
public void onAllTabsRemoved(@NonNull TabSwitcher tabSwitcher, @NonNull Tab[] tabs, @NonNull Animation animation) {
L.d("All tabs removed.");
List<org.wikipedia.page.tabs.Tab> appTabs = new ArrayList<>(app.getTabList());
app.getTabList().clear();
tabCountsView.updateTabCount();
setResult(RESULT_LOAD_FROM_BACKSTACK);
showUndoAllSnackbar(tabs, appTabs);
tabUpdatedTimeMillis = System.currentTimeMillis();
}
}
} |
package thomas.jonathan.notey;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.Typeface;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.afollestad.materialdialogs.MaterialDialog;
import com.rey.material.app.Dialog;
import com.rey.material.widget.Spinner;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;
import com.wdullaer.materialdatetimepicker.time.RadialPickerLayout;
import com.wdullaer.materialdatetimepicker.time.TimePickerDialog;
import org.adw.library.widgets.discreteseekbar.DiscreteSeekBar;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class AlarmActivity extends FragmentActivity implements View.OnClickListener, DatePickerDialog.OnDateSetListener, TimePickerDialog.OnTimeSetListener {
public static final String DATEPICKER_TAG = "datepicker", TIMEPICKER_TAG = "timepicker";
private final Calendar calendar = Calendar.getInstance();
private TextView date_tv;
private TextView time_tv;
private TextView sound_tv;
private ImageButton sound_btn;
private Spinner recurrenceSpinner;
private int year, month, day, hour, minute, repeatTime = 0, spinnerSelectedValue;
private PendingIntent alarmPendingIntent;
public static final SimpleDateFormat format_date = new SimpleDateFormat("EEE, MMM dd"), format_time = new SimpleDateFormat("hh:mm a");
private CheckBox vibrate_cb, wake_cb;
SharedPreferences sharedPref;
private int id;
private Uri alarm_uri;
private DiscreteSeekBar seekBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
themeStuffBeforeSetContentView();
setContentView(R.layout.alarm_activity_dialog);
themeStuffAfterSetContentView();
Intent i = getIntent();
sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
id = i.getExtras().getInt("alarm_id", -1);
if (savedInstanceState != null) {
DatePickerDialog dpd = (DatePickerDialog) getFragmentManager().findFragmentByTag(DATEPICKER_TAG);
if (dpd != null) {
dpd.setOnDateSetListener(this);
}
TimePickerDialog tpd = (TimePickerDialog) getFragmentManager().findFragmentByTag(TIMEPICKER_TAG);
if (tpd != null) {
tpd.setOnTimeSetListener(this);
}
}
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DATE);
hour = calendar.get(Calendar.HOUR_OF_DAY);
minute = calendar.get(Calendar.MINUTE);
TextView alarm_set_tv = (TextView) findViewById(R.id.alarm_set_tv);
date_tv = (TextView) findViewById(R.id.date_tv);
time_tv = (TextView) findViewById(R.id.time_tv);
TextView alarm_mainTitle = (TextView) findViewById(R.id.alarm_mainTitle);
Button set_btn = (Button) findViewById(R.id.alarm_set_btn);
Button cancel_btn = (Button) findViewById(R.id.alarm_cancel_btn);
ImageButton alarm_delete = (ImageButton) findViewById(R.id.alarm_delete);
vibrate_cb = (CheckBox) findViewById(R.id.alarm_vibrate);
wake_cb = (CheckBox) findViewById(R.id.alarm_wake);
sound_tv = (TextView) findViewById(R.id.alarm_sound);
sound_btn = (ImageButton) findViewById(R.id.alarm_sound_btn);
ImageView repeat_iv = (ImageView) findViewById(R.id.alarm_repeat_iv);
repeat_iv.setImageDrawable(getResources().getDrawable(R.drawable.ic_refresh_grey600_24dp));
recurrenceSpinner = (Spinner) findViewById(R.id.reccurence_spinner);
setUpSeekbar();
setUpRecurrenceSpinner();
int color = getResources().getColor(getResources().getIdentifier(MainActivity.themeColor, "color", getPackageName()));
seekBar.setScrubberColor(color);
seekBar.setThumbColor(color, color);
//dark theme stuffs
if(MainActivity.darkTheme){
wake_cb.setTextColor(getResources().getColor(R.color.md_grey_400));
vibrate_cb.setTextColor(getResources().getColor(R.color.md_grey_400));
}
//if a pro user, enable the sound and repeat option
if (MainActivity.proVersionEnabled) {
sound_tv.setEnabled(true);
sound_tv.setClickable(true);
sound_tv.setOnClickListener(this);
if(MainActivity.darkTheme) sound_tv.setTextColor(getResources().getColor(R.color.md_grey_400));
else sound_tv.setTextColor(Color.BLACK);
} else { //fade the icons if not pro
sound_btn.setAlpha(0.3f);
repeat_iv.setAlpha(0.3f);
seekBar.setAlpha(0.3f);
recurrenceSpinner.setEnabled(false);
recurrenceSpinner.setClickable(false);
recurrenceSpinner.setAlpha(0.3f);
seekBar.setEnabled(false);
repeat_iv.setClickable(false);
seekBar.setThumbColor(getResources().getColor(R.color.grey_600), getResources().getColor(R.color.grey_600));
}
Typeface roboto_light = Typeface.createFromAsset(getAssets(), "ROBOTO-LIGHT.TTF");
Typeface roboto_reg = Typeface.createFromAsset(getAssets(), "ROBOTO-REGULAR.ttf");
Typeface roboto_bold = Typeface.createFromAsset(getAssets(), "ROBOTO-BOLD.ttf");
alarm_set_tv.setTypeface(roboto_bold);
date_tv.setTypeface(roboto_reg);
time_tv.setTypeface(roboto_reg);
alarm_mainTitle.setTypeface(roboto_reg);
set_btn.setTypeface(roboto_light);
cancel_btn.setTypeface(roboto_light);
vibrate_cb.setTypeface(roboto_reg);
wake_cb.setTypeface(roboto_reg);
sound_tv.setTypeface(roboto_reg);
date_tv.setOnClickListener(this);
time_tv.setOnClickListener(this);
set_btn.setOnClickListener(this);
cancel_btn.setOnClickListener(this);
alarm_delete.setOnClickListener(this);
//long click listener to delete icon. toast will appear saying what the button does
View.OnLongClickListener listener = new View.OnLongClickListener() {
public boolean onLongClick(View v) {
Toast.makeText(getApplicationContext(), getString(R.string.delete) + " " + getString(R.string.alarm), Toast.LENGTH_SHORT).show();
return true;
}
};
alarm_delete.setOnLongClickListener(listener);
// if id is valid. also checks the sharedprefs if the user is editing the alarm
if (id != -1 && sharedPref.getBoolean("vibrate" + Integer.toString(id), true))
vibrate_cb.setChecked(true);
if (id != -1 && sharedPref.getBoolean("wake" + Integer.toString(id), true))
wake_cb.setChecked(true);
if (id != -1) {
String temp_string = sharedPref.getString("sound" + Integer.toString(id), getString(R.string.none));
alarm_uri = Uri.parse(temp_string);
if(temp_string.contains("notification")) {
sound_tv.setText(getString(R.string.sound) + " " + getString(R.string.notification_sound));
sound_btn.setImageResource(R.drawable.ic_volume_up_grey600_24dp);
}
else if(temp_string.contains("alarm")) {
sound_tv.setText(getString(R.string.sound) + " " + getString(R.string.alarm_beep));
sound_btn.setImageResource(R.drawable.ic_volume_up_grey600_24dp);
}
else {
sound_tv.setText(getString(R.string.sound) + " " + getString(R.string.none));
sound_btn.setImageResource(R.drawable.ic_volume_off_grey600_24dp);
}
}
Date date = new Date();
// if an alarm is already set, show the set alarm date/time. also show the delete button
if (i.hasExtra("alarm_set_time")) {
alarm_set_tv.setText(getString(R.string.alarm_set_for));
date = new Date(Long.valueOf(i.getExtras().getString("alarm_set_time")));
repeatTime = i.getExtras().getInt("repeat_set_time", 0);
alarm_delete.setVisibility(View.VISIBLE);
alarmPendingIntent = (PendingIntent) i.getExtras().get("alarmPendingIntent");
// update the calendar and the year/mo/day/hour/min to the preset alarm time
calendar.setTime(date);
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DATE);
hour = calendar.get(Calendar.HOUR_OF_DAY);
minute = calendar.get(Calendar.MINUTE);
//depending on what the repeating time is set to, set the seekbar and spinner values
switch (repeatTime) {
//minutes
case 0: seekBar.setProgress(0); break;
case 5: seekBar.setProgress(1); break;
case 10: seekBar.setProgress(2); break;
case 15: seekBar.setProgress(3); break;
case 30: seekBar.setProgress(4); break;
case 45: seekBar.setProgress(5); break;
//hours
case 60: seekBar.setProgress(1); recurrenceSpinner.setSelection(1); break; //1hr
case 120: seekBar.setProgress(2); recurrenceSpinner.setSelection(1); break; //2hrs
case 300: seekBar.setProgress(3); recurrenceSpinner.setSelection(1); break; //5hrs
case 600: seekBar.setProgress(4); recurrenceSpinner.setSelection(1); break; //10hrs
case 720: seekBar.setProgress(5); recurrenceSpinner.setSelection(1); break; //12hrs
//days
case 1440: seekBar.setProgress(1); recurrenceSpinner.setSelection(2); break; //1day
case 10080: seekBar.setProgress(2); recurrenceSpinner.setSelection(2); break; //7days
case 20160: seekBar.setProgress(3); recurrenceSpinner.setSelection(2); break; //14days
case 30240: seekBar.setProgress(4); recurrenceSpinner.setSelection(2); break; //21days
case 40320: seekBar.setProgress(5); recurrenceSpinner.setSelection(2); break; //28days
}
} else {
alarm_delete.setVisibility(View.INVISIBLE); // no alarm? don't show delete button then
if(minute == 59) hour += 1; //if it's 8:59, we'll want to show 9:00
minute = minute + 1; //add one minute to the clock, so the default display time is one minute ahead of current time
}
date.setMinutes(minute);
date_tv.setText(format_date.format(date));
time_tv.setText(format_time.format(date));
}
@Override
public void onClick(View view) {
Dialog.Builder builder = null;
if (view.getId() == R.id.date_tv) { //show the date picker
DatePickerDialog datePickerDialog = DatePickerDialog.newInstance(this, year, month, day);
datePickerDialog.setYearRange(1985, 2028);
datePickerDialog.show(getFragmentManager(), DATEPICKER_TAG);
} else if (view.getId() == R.id.time_tv) { //show the time picker
TimePickerDialog timePickerDialog = TimePickerDialog.newInstance(this, hour, minute, DateFormat.is24HourFormat(this));
timePickerDialog.show(getFragmentManager(), TIMEPICKER_TAG);
} else if (view.getId() == R.id.alarm_set_btn) {
calendar.set(year, month, day, hour, minute); //set the calendar for the new alarm time
// send the time (in milliseconds) back to MainActivity to set alarm if the user creates the notey
if (System.currentTimeMillis() < calendar.getTimeInMillis()) { //if set time is greater than current time, then set the alarm
Intent output = new Intent();
output.putExtra("alarm_time", Long.toString(calendar.getTimeInMillis()));
output.putExtra("repeat_time", repeatTime);
setResult(RESULT_OK, output);
saveSettings();
} else
Toast.makeText(getApplicationContext(), getString(R.string.alarm_not_set), Toast.LENGTH_SHORT).show();
finish();
} else if (view.getId() == R.id.alarm_cancel_btn) {
finish();
} else if (view.getId() == R.id.alarm_delete) {
Intent output = new Intent();
output.putExtra("alarm_time", "");
output.putExtra("repeat_time", 0);
setResult(RESULT_OK, output);
// remove the no longer needed sharedprefs. to reset the UI if user clicks into this activity again
SharedPreferences.Editor editor = PreferenceManager.getDefaultSharedPreferences(this).edit();
editor.remove("vibrate" + Integer.toString(id)).apply();
editor.remove("wake" + Integer.toString(id)).apply();
editor.remove("sound" + Integer.toString(id)).apply();
editor.remove("repeat" + Integer.toString(id)).apply();
//cancel the alarm pending intent
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.cancel(alarmPendingIntent);
Toast.makeText(getApplicationContext(), getString(R.string.alarm_deleted), Toast.LENGTH_LONG).show();
finish();
} else if (view.getId() == R.id.alarm_sound) {
int sound;
//check if alarm sound is already set to have it pre-selected for the dialog
if(alarm_uri == null) sound = 0;
else if(alarm_uri.toString().contains("notification")) sound = 1;
else if(alarm_uri.toString().contains("alarm")) sound = 2;
else sound = 0;
new MaterialDialog.Builder(this)
.title(R.string.choose_alarm_type)
.items(R.array.alarm_sound_picker_array)
.itemsCallbackSingleChoice(sound, new MaterialDialog.ListCallbackSingleChoice() {
@Override
public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
//get which one the user selects and set the sound, text box, and button icon accordingly
if (which == 1) {
alarm_uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
sound_tv.setText(getString(R.string.sound) + " " + getString(R.string.notification_sound));
sound_btn.setImageResource(R.drawable.ic_volume_up_grey600_24dp);
} else if (which == 2) {
alarm_uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
sound_tv.setText(getString(R.string.sound) + " " + getString(R.string.alarm_beep));
sound_btn.setImageResource(R.drawable.ic_volume_up_grey600_24dp);
} else {
alarm_uri = null;
sound_tv.setText(getString(R.string.sound) + " " + getString(R.string.none));
sound_btn.setImageResource(R.drawable.ic_volume_off_grey600_24dp);
}
return true;
}
})
.typeface(Typeface.createFromAsset(getAssets(), "ROBOTO-REGULAR.ttf"), Typeface.createFromAsset(getAssets(), "ROBOTO-REGULAR.ttf"))
.show();
} else if (view.getId() == R.id.alarm_repeat_iv) {
switch(spinnerSelectedValue) {
case 0:
Toast.makeText(getApplicationContext(), getString(R.string.repeat_every) + repeatTime + getString(R.string.minutes), Toast.LENGTH_SHORT).show();
break;
case 1:
int hours = repeatTime/60;
//display "hour" or "hours" for the toast
if(hours == 1)
Toast.makeText(getApplicationContext(), getString(R.string.repeat_every) + hours + getString(R.string.hour), Toast.LENGTH_SHORT).show();
else Toast.makeText(getApplicationContext(), getString(R.string.repeat_every) + hours + getString(R.string.hours), Toast.LENGTH_SHORT).show();
break;
case 2:
int days = repeatTime/60/24;
//display "day" or "days" for the toast
if(days == 1)
Toast.makeText(getApplicationContext(), getString(R.string.repeat_every) + days + getString(R.string.day), Toast.LENGTH_SHORT).show();
else Toast.makeText(getApplicationContext(), getString(R.string.repeat_every) + days + getString(R.string.days), Toast.LENGTH_SHORT).show();
break;
}
}
}
//save the checkboxes and settings_jb_kk. create a new sharedpref for each alarm, this is using the id as an identifier for the alarmService.
private void saveSettings() {
if (id != -1) {
SharedPreferences.Editor editor = sharedPref.edit();
editor.putBoolean("vibrate" + Integer.toString(id), vibrate_cb.isChecked());
editor.putBoolean("wake" + Integer.toString(id), wake_cb.isChecked());
editor.putInt("repeat" + Integer.toString(id), repeatTime);
if (alarm_uri != null)
editor.putString("sound" + Integer.toString(id), alarm_uri.toString());
editor.apply();
}
}
private void setUpRecurrenceSpinner(){
ArrayAdapter<String> adapter;
if(MainActivity.darkTheme && MainActivity.CURRENT_ANDROID_VERSION >= Build.VERSION_CODES.LOLLIPOP) {
adapter = new ArrayAdapter<>(this, R.layout.spinner_row_dark, getResources().getStringArray(R.array.recurrence_array));
adapter.setDropDownViewResource(R.layout.spinner_row_dropdown_dark_lollipop);
}else if(MainActivity.darkTheme) { //pre-lollipop devices using dark theme need to color the spinner background
adapter = new ArrayAdapter<>(this, R.layout.spinner_row_dark, getResources().getStringArray(R.array.recurrence_array));
adapter.setDropDownViewResource(R.layout.spinner_row_dropdown_dark_prelollipop);
}else{
adapter = new ArrayAdapter<>(this, R.layout.spinner_row, getResources().getStringArray(R.array.recurrence_array));
adapter.setDropDownViewResource(R.layout.spinner_row_dropdown);
}
recurrenceSpinner.setAdapter(adapter);
recurrenceSpinner.setOnItemSelectedListener(new Spinner.OnItemSelectedListener() {
@Override
public void onItemSelected(Spinner spinner, View view, int i, long l) {
spinnerSelectedValue = spinner.getSelectedItemPosition();
//reset the indicator value for the seekbar bubble
seekBar.setNumericTransformer(new DiscreteSeekBar.NumericTransformer() {
@Override
public int transform(int value) {
int newValue = 0;
if (spinnerSelectedValue == 1) { //hours
switch (value) {
case 0:
newValue = 0;
break;
case 1:
newValue = 1;
break;
case 2:
newValue = 2;
break;
case 3:
newValue = 5;
break;
case 4:
newValue = 10;
break;
case 5:
newValue = 12;
break;
}
repeatTime = newValue * 60;
} else if (spinnerSelectedValue == 2) { //days
switch (value) {
case 0:
newValue = 0;
break;
case 1:
newValue = 1;
break;
case 2:
newValue = 7;
break;
case 3:
newValue = 14;
break;
case 4:
newValue = 21;
break;
case 5:
newValue = 28;
break;
}
repeatTime = newValue * 60 * 24;
} else { //minutes
switch (value) {
case 0:
newValue = 0;
break;
case 1:
newValue = 5;
break;
case 2:
newValue = 10;
break;
case 3:
newValue = 15;
break;
case 4:
newValue = 30;
break;
case 5:
newValue = 45;
break;
}
repeatTime = newValue;
}
return newValue;
}
});
}
});
}
private void setUpSeekbar(){
seekBar = (DiscreteSeekBar) findViewById(R.id.discrete_bar);
seekBar.setMin(0);
seekBar.setMax(5);
//set what the seekbar bubble displays based on the time option selected in the spinner
seekBar.setNumericTransformer(new DiscreteSeekBar.NumericTransformer() {
@Override
public int transform(int value) {
int newValue = 0;
if (spinnerSelectedValue == 1) { //hours
switch (value) {
case 0:
newValue = 0;
break;
case 1:
newValue = 1;
break;
case 2:
newValue = 2;
break;
case 3:
newValue = 5;
break;
case 4:
newValue = 10;
break;
case 5:
newValue = 12;
break;
}
repeatTime = newValue * 60;
} else if (spinnerSelectedValue == 2) { //days
switch (value) {
case 0:
newValue = 0;
break;
case 1:
newValue = 1;
break;
case 2:
newValue = 7;
break;
case 3:
newValue = 14;
break;
case 4:
newValue = 21;
break;
case 5:
newValue = 28;
break;
}
repeatTime = newValue * 60 * 24;
} else { //minutes
switch (value) {
case 0:
newValue = 0;
break;
case 1:
newValue = 5;
break;
case 2:
newValue = 10;
break;
case 3:
newValue = 15;
break;
case 4:
newValue = 30;
break;
case 5:
newValue = 45;
break;
}
repeatTime = newValue;
}
return newValue;
}
});
}
@Override
public void onResume() {
super.onResume();
}
@Override
public void onDateSet(DatePickerDialog datePickerDialog, int y, int mo, int d) {
year = y;
month = mo;
day = d;
Calendar c = Calendar.getInstance();
c.set(y, mo, d);
date_tv.setText(format_date.format(c.getTime()));
}
@Override
public void onTimeSet(RadialPickerLayout radialPickerLayout, int h, int m) {
hour = h;
minute = m;
String AM_PM;
if (h < 12) {
AM_PM = "AM";
if (h == 0) h = 12; // 12am
} else {
if (h != 12) h = h - 12;
AM_PM = "PM";
}
String h2 = Integer.toString(h);
if (h < 10) h2 = "0" + h;
String min = Integer.toString(m);
if (m < 10) min = "0" + min;
time_tv.setText(h2 + ":" + min + " " + AM_PM);
}
private void themeStuffBeforeSetContentView(){
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
//initialize theme preferences
MainActivity.themeColor = sharedPreferences.getString("pref_theme_color", "md_blue_500");
MainActivity.darkTheme = sharedPreferences.getBoolean("pref_theme_dark", false);
//set light/dark theme
if(MainActivity.darkTheme) {
super.setTheme(getResources().getIdentifier("AppBaseThemeDark_"+MainActivity.themeColor, "style", getPackageName()));
}
else {
super.setTheme(getResources().getIdentifier("AppBaseTheme_"+MainActivity.themeColor, "style", getPackageName()));
}
}
private void themeStuffAfterSetContentView(){
//set color
RelativeLayout r = (RelativeLayout) findViewById(R.id.alarm_layout_top);
r.setBackgroundResource(getResources().getIdentifier(MainActivity.themeColor, "color", getPackageName()));
}
} |
package org.spine3.time;
import java.util.Calendar;
import java.util.Date;
import java.util.SimpleTimeZone;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import static java.util.Calendar.DAY_OF_MONTH;
import static java.util.Calendar.HOUR;
import static java.util.Calendar.HOUR_OF_DAY;
import static java.util.Calendar.MILLISECOND;
import static java.util.Calendar.MINUTE;
import static java.util.Calendar.MONTH;
import static java.util.Calendar.SECOND;
import static java.util.Calendar.YEAR;
import static java.util.Calendar.ZONE_OFFSET;
import static java.util.Calendar.getInstance;
/**
* Utilities for working with {@link Calendar}.
*
* <p> This utility class is needed while Spine is based on Java 7.
* Java 8 introduces new date/time API in the package {@code java.time}.
* Spine v2 will be based on Java 8 and this class will be deprecated.
*
* @author Alexander Aleksandrov
* @since 0.6.12
*/
public class Calendars {
private static final String TIME_ZONE_GMT = "GMT";
private Calendars() {
}
/**
* Obtains zone offset using {@code Calendar}.
*/
public static int getZoneOffset(Calendar cal) {
final int zoneOffset = cal.get(ZONE_OFFSET) / 1000;
return zoneOffset;
}
/**
* Obtains year using {@code Calendar}.
*/
public static int getYear(Calendar cal) {
final int year = cal.get(YEAR);
return year;
}
/**
* Obtains month using {@code Calendar}.
*/
public static int getMonth(Calendar cal) {
// The Calendar class assumes JANUARY is zero.
// Therefore add 1 to get the reasonable value of month
final int month = cal.get(MONTH) + 1;
return month;
}
/**
* Obtains day of month using {@code Calendar}.
*/
public static int getDay(Calendar cal) {
final int result = cal.get(DAY_OF_MONTH);
return result;
}
/**
* Obtains hours using {@code Calendar}.
*/
public static int getHours(Calendar cal) {
final int hours = cal.get(HOUR);
return hours;
}
/**
* Obtains minutes using {@code Calendar}.
*/
public static int getMinutes(Calendar cal) {
final int minutes = cal.get(MINUTE);
return minutes;
}
/**
* Obtains seconds using {@code Calendar}.
*/
public static int getSeconds(Calendar cal) {
final int seconds = cal.get(SECOND);
return seconds;
}
/**
* Obtains milliseconds using {@code Calendar}.
*/
public static int getMillis(Calendar cal) {
final int millis = cal.get(MILLISECOND);
return millis;
}
/**
* Obtains calendar from year, month and day values.
*/
public static Calendar createDate(int year, int month, int day) {
final Calendar calendar = getInstance();
calendar.set(year, month - 1, day);
return calendar;
}
/**
* Sets the date to calendar.
*
* @param calendar the target calendar
* @param date the date to set
*/
public static void setDate(Calendar calendar, LocalDate date) {
calendar.set(date.getYear(), date.getMonth()
.getNumber() - 1, date.getDay());
}
/**
* Obtains {@code Calendar} from hours, minutes, seconds and milliseconds values.
*/
public static Calendar createWithTime(int hours, int minutes, int seconds, int millis) {
final Calendar calendar = getInstance();
calendar.set(HOUR, hours);
calendar.set(MINUTE, minutes);
calendar.set(SECOND, seconds);
calendar.set(MILLISECOND, millis);
return calendar;
}
/**
* Obtains {@code Calendar} from hours, minutes and seconds values.
*/
public static Calendar createWithTime(int hours, int minutes, int seconds) {
final Calendar calendar = getInstance();
calendar.set(HOUR, hours);
calendar.set(MINUTE, minutes);
calendar.set(SECOND, seconds);
return calendar;
}
/**
* Obtains {@code Calendar} from hours and minutes values.
*/
public static Calendar createWithTime(int hours, int minutes) {
final Calendar calendar = getInstance();
calendar.set(HOUR, hours);
calendar.set(MINUTE, minutes);
return calendar;
}
/**
* Obtains a {@code Calendar} with GMT time zone.
*
* @return new {@code Calendar} instance
*/
public static Calendar nowAtGmt() {
Calendar gmtCal = getInstance(TimeZone.getTimeZone(TIME_ZONE_GMT));
return gmtCal;
}
/**
* Obtains current time calendar for the passed zone offset.
*/
public static Calendar nowAt(ZoneOffset zoneOffset) {
final Calendar utc = nowAtGmt();
final Date timeAtGmt = utc.getTime();
long msFromEpoch = timeAtGmt.getTime();
final Calendar calendar = at(zoneOffset);
// Gives you the current offset in ms from UTC at the current date
int offsetFromGmt = calendar.getTimeZone()
.getOffset(msFromEpoch);
calendar.setTime(timeAtGmt);
calendar.add(MILLISECOND, offsetFromGmt);
return calendar;
}
/**
* Obtains calendar at the specified zone offset
*
* @param zoneOffset time offset for specified zone
* @return new {@code Calendar} instance at specific zone offset
*/
public static Calendar at(ZoneOffset zoneOffset) {
@SuppressWarnings("NumericCastThatLosesPrecision") // OK as a valid zoneOffset isn't that big.
final int offsetMillis = (int) TimeUnit.SECONDS.toMillis(zoneOffset.getAmountSeconds());
final SimpleTimeZone timeZone = new SimpleTimeZone(offsetMillis, "temp");
final Calendar result = getInstance(timeZone);
return result;
}
/**
* Obtains current calendar.
*/
public static Calendar now() {
final Calendar calendar = getInstance();
return calendar;
}
/**
* Obtains month of year using calendar.
*/
public static MonthOfYear getMonthOfYear(Calendar calendar) {
// The Calendar class assumes JANUARY is zero.
// Therefore add 1 to get the value of MonthOfYear.
final int monthByCalendar = calendar.get(MONTH);
final MonthOfYear month = MonthOfYear.forNumber(monthByCalendar + 1);
return month;
}
/**
* Obtains local date using calendar.
*/
public static LocalDate toLocalDate(Calendar cal) {
return LocalDates.of(getYear(cal),
getMonthOfYear(cal),
getDay(cal));
}
/**
* Obtains local time using calendar.
*/
public static LocalTime toLocalTime(Calendar calendar) {
final int hours = getHours(calendar);
final int minutes = getMinutes(calendar);
final int seconds = getSeconds(calendar);
final int millis = getMillis(calendar);
return LocalTimes.of(hours, minutes, seconds, millis);
}
/**
* Converts the passed {@code OffsetDate} into {@code Calendar}.
*
* <p>The calendar is initialized at the offset from the passed date.
*/
public static Calendar toCalendar(OffsetDate offsetDate) {
final Calendar calendar = at(offsetDate.getOffset());
setDate(calendar, offsetDate.getDate());
return calendar;
}
/**
* Converts the passed {@code LocalTime} into {@code Calendar}.
*/
public static Calendar toCalendar(LocalTime localTime) {
return createWithTime(localTime.getHours(),
localTime.getMinutes(),
localTime.getSeconds(),
localTime.getMillis());
}
/**
* Converts the passed {@code LocalDate} into {@code Calendar}.
*/
public static Calendar toCalendar(LocalDate localDate) {
return createDate(localDate.getYear(), localDate.getMonthValue(), localDate.getDay());
}
/**
* Converts the passed {@code OffsetTime} into {@code Calendar}.
*/
public static Calendar toCalendar(OffsetTime offsetTime) {
final LocalTime time = offsetTime.getTime();
final Calendar calendar = at(offsetTime.getOffset());
calendar.set(HOUR_OF_DAY, time.getHours());
calendar.set(MINUTE, time.getMinutes());
calendar.set(SECOND, time.getSeconds());
calendar.set(MILLISECOND, time.getMillis());
return calendar;
}
/**
* Converts the passed {@code OffsetDateTime} into {@code Calendar}.
*/
public static Calendar toCalendar(OffsetDateTime dateTime) {
final Calendar cal = at(dateTime.getOffset());
final LocalDate date = dateTime.getDate();
final LocalTime time = dateTime.getTime();
cal.set(date.getYear(),
date.getMonth().getNumber() - 1,
date.getDay(),
time.getHours(),
time.getMinutes(),
time.getSeconds());
cal.set(MILLISECOND, time.getMillis());
return cal;
}
} |
package com.simplewelcompage;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.simplify.WelcomPage;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new WelcomPage(this).show(R.drawable.start1, R.drawable.start2, R.drawable.start3);
}
} |
package com.voxelwind.server.network.raknet.util;
import com.google.common.base.Preconditions;
import com.voxelwind.server.network.raknet.datagrams.EncapsulatedRakNetPacket;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.PooledByteBufAllocator;
import io.netty.util.ReferenceCountUtil;
import java.util.*;
public class SplitPacketHelper {
private final EncapsulatedRakNetPacket[] packets;
private final long created = System.currentTimeMillis();
private boolean released = false;
public SplitPacketHelper(int expectedLength) {
Preconditions.checkArgument(expectedLength >= 1, "expectedLength is less than 1 (%s)", expectedLength);
this.packets = new EncapsulatedRakNetPacket[expectedLength];
}
public Optional<ByteBuf> add(EncapsulatedRakNetPacket packet) {
Preconditions.checkNotNull(packet, "packet");
Preconditions.checkArgument(packet.isHasSplit(), "packet is not split");
Preconditions.checkState(!released, "packet has been released");
Preconditions.checkElementIndex(packet.getPartIndex(), packets.length);
packets[packet.getPartIndex()] = packet;
for (EncapsulatedRakNetPacket netPacket : packets) {
if (netPacket == null) {
return Optional.empty();
}
}
ByteBuf buf = PooledByteBufAllocator.DEFAULT.directBuffer();
for (EncapsulatedRakNetPacket netPacket : packets) {
buf.writeBytes(netPacket.getBuffer());
}
release();
return Optional.of(buf);
}
public boolean expired() {
// If we're waiting on a split packet for more than 30 seconds, the client on the other end is either severely
// lagging, or has died.
Preconditions.checkState(!released, "packet has been released");
return System.currentTimeMillis() - created >= 30000;
}
public void release() {
Preconditions.checkState(!released, "packet has been released");
released = true;
for (int i = 0; i < packets.length; i++) {
ReferenceCountUtil.release(packets[i]);
packets[i] = null;
}
}
} |
package org.devilry.core.daointerfaces;
import java.util.Date;
import java.util.List;
import org.devilry.core.InvalidNameException;
import org.devilry.core.NoSuchObjectException;
import org.devilry.core.NoSuchUserException;
import org.devilry.core.PathExistsException;
import org.devilry.core.UnauthorizedException;
/** Interface to assignment manipulation. */
public interface AssignmentNodeCommon extends BaseNodeInterface {
/**
* Create a new assignment-node.
*
* @param name
* A short name containing only lower-case English letters, '-',
* '_' and numbers.
* @param displayName
* A longer name typically used in GUI's instead of the name.
* @param deadline
* The date/time of the deadline.
* @param parentId
* The id of an existing period-node. The new node will become a
* child of the given parent-node.
* @return The id of the newly created assignment-node.
* @throws PathExistsException
* If there already exists another course-node with the same
* name and parentId.
* @throws UnauthorizedException
* If the authenticated user is not Admin on the parent node.
* @throws InvalidNameException
* If the given name is not on the specified format.
* @throws NoSuchObjectException
* If the given parent does not exist.
*/
long create(String name, String displayName, Date deadline, long parentId)
throws PathExistsException, UnauthorizedException,
InvalidNameException, NoSuchObjectException;
/**
* The the parent-period-node of the given assignment-node.
*
* @param assignmentNodeId
* The id of an existing assignment-node.
* @return The id of the parent period-node.
* @throws NoSuchObjectException
* If no assignment-node with the given id exists.
*/
long getParentPeriod(long assignmentNodeId) throws NoSuchObjectException;
/**
* Get the deadline for the given assignment.
*
* @param assignmentNodeId
* The id of an existing assignment-node.
* @return the date/time of the deadline.
* @throws NoSuchObjectException
* If no assignment-node with the given id exists.
*/
Date getDeadline(long assignmentNodeId) throws NoSuchObjectException;
/**
* Set the deadline for this assignment.
*
* @param assignmentNodeId
* The id of an existing assignment-node.
* @param deadline
* The date/time of the deadline.
* @throws NoSuchObjectException
* If no assignment-node with the given id exists.
* @throws UnauthorizedException
* If the authenticated user is not <em>Admin</em> on the
* parent-period-node of the given assignment.
*/
void setDeadline(long assignmentNodeId, Date deadline)
throws UnauthorizedException, NoSuchObjectException;
/**
* Get all deliveries with this assignment as parent.
*
* @param assignmentNodeId
* The id of an existing assignment-node.
* @return List of IDs for the deliveries.
* @throws NoSuchObjectException
* If no assignment-node with the given id exists.
* @throws UnauthorizedException
* If the authenticated user is not <em>Admin</em> on the given
* assignment.
*/
List<Long> getDeliveries(long assignmentNodeId)
throws NoSuchObjectException, UnauthorizedException;
/**
* Get a list of assignments where the authenticated user is Admin.
*
* @return List of assignment-ids.
* */
List<Long> getAssignmentsWhereIsAdmin();
/**
* Add a new administrator to the given assignment node.
*
* @param assignmentNodeId
* The id of an existing assignment-node.
* @param userId
* The unique number identifying an existing user.
* @throws NoSuchObjectException
* If no assignment-node with the given id exists.
* @throws NoSuchUserException
* If the given user does not exist.
* @throws UnauthorizedException
* If the authenticated user is not <em>Admin</em> on the
* parent-period-node of the given assignment.
*/
void addAssignmentAdmin(long assignmentNodeId, long userId)
throws NoSuchObjectException, NoSuchUserException,
UnauthorizedException;
/**
* Remove an administrator from the given assignment node.
*
* @param assignmentNodeId
* The id of an existing assignment-node.
* @param userId
* The unique number identifying an existing user.
* @throws NoSuchObjectException
* If no course-node with the given id exists.
* @throws NoSuchUserException
* If the given user does not exist.
* @throws UnauthorizedException
* If the authenticated user is not <em>Admin</em> on the
* parent-period-node of the given assignment.
*/
void removeAssignmentAdmin(long assignmentNodeId, long userId)
throws NoSuchObjectException, NoSuchUserException,
UnauthorizedException;
/**
* Get the id of all administrators registered for the given assignment
* node.
*
* @param assignmentNodeId
* The id of an existing assignment-node.
* @return A list with the id of all administrators for the given node.
* @throws NoSuchObjectException
* If no course-node with the given id exists.
* @throws UnauthorizedException
* If the authenticated user is not <em>Admin</em> on the
* parent-node of the given course.
*/
List<Long> getAssignmentAdmins(long assignmentNodeId)
throws NoSuchObjectException, UnauthorizedException;
/**
* Check if the authenticated user is Admin on the given assignment-node, or
* on any of the nodes above the assignment in the tree.
*
* @param assignmentNodeId
* The id of an existing assignment-node.
* @throws NoSuchObjectException
* If no assignment-node with the given id exists.
* */
boolean isAssignmentAdmin(long assignmentNodeId)
throws NoSuchObjectException;
} |
package com.github.antag99.aquarria;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.assets.AssetManager;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.graphics.g2d.TextureAtlas;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.utils.JsonReader;
import com.badlogic.gdx.utils.JsonValue;
import com.badlogic.gdx.utils.ObjectMap;
import com.github.antag99.aquarria.entity.EntityType;
import com.github.antag99.aquarria.item.DestroyTileCallbackFactory;
import com.github.antag99.aquarria.item.DestroyWallCallbackFactory;
import com.github.antag99.aquarria.item.ItemType;
import com.github.antag99.aquarria.item.ItemUsageCallbackFactory;
import com.github.antag99.aquarria.item.ItemUsageStyle;
import com.github.antag99.aquarria.item.TilePlaceCallbackFactory;
import com.github.antag99.aquarria.item.WallPlaceCallbackFactory;
import com.github.antag99.aquarria.tile.BlockFrameStyleFactory;
import com.github.antag99.aquarria.tile.FrameStyleFactory;
import com.github.antag99.aquarria.tile.TileType;
import com.github.antag99.aquarria.tile.WallFrameStyleFactory;
import com.github.antag99.aquarria.tile.WallType;
import com.github.antag99.aquarria.util.Utils;
public final class GameRegistry {
private GameRegistry() {
throw new AssertionError();
}
// Mappings of file names (without extensions) to JSON configurations
private static ObjectMap<String, JsonValue> fileNameToItemConfiguration = new ObjectMap<>();
private static ObjectMap<String, JsonValue> fileNameToTileConfiguration = new ObjectMap<>();
private static ObjectMap<String, JsonValue> fileNameToWallConfiguration = new ObjectMap<>();
private static ObjectMap<String, JsonValue> fileNameToEntityConfiguration = new ObjectMap<>();
// Asset manager, used to get the assets when loading is done
private static AssetManager assetManager = null;
// Mappings of internal names to concrete types
private static ObjectMap<String, ItemType> internalNameToItemType = new ObjectMap<>();
private static ObjectMap<String, TileType> internalNameToTileType = new ObjectMap<>();
private static ObjectMap<String, WallType> internalNameToWallType = new ObjectMap<>();
private static ObjectMap<String, EntityType> internalNameToEntityType = new ObjectMap<>();
// Mapping of name to ItemUsageCallback factories, name is specified when registered
private static ObjectMap<String, ItemUsageCallbackFactory> itemUsageCallbackFactories = new ObjectMap<>();
private static ObjectMap<String, FrameStyleFactory> frameStyleFactories = new ObjectMap<>();
public static void registerItem(ItemType itemType) {
internalNameToItemType.put(itemType.getInternalName(), itemType);
}
public static void registerTile(TileType tileType) {
internalNameToTileType.put(tileType.getInternalName(), tileType);
}
public static void registerWall(WallType wallType) {
internalNameToWallType.put(wallType.getInternalName(), wallType);
}
public static void registerEntity(EntityType entityType) {
internalNameToEntityType.put(entityType.getInternalName(), entityType);
}
public static ItemType getItemType(String internalName) {
ItemType itemType = internalNameToItemType.get(internalName);
if (itemType == null) {
throw new IllegalArgumentException("ItemType not found: " + internalName);
}
return itemType;
}
public static TileType getTileType(String internalName) {
TileType tileType = internalNameToTileType.get(internalName);
if (tileType == null) {
throw new IllegalArgumentException("TileType not found: " + internalName);
}
return tileType;
}
public static WallType getWallType(String internalName) {
WallType wallType = internalNameToWallType.get(internalName);
if (wallType == null) {
throw new IllegalArgumentException("WallType not found: " + internalName);
}
return wallType;
}
public static EntityType getEntityType(String internalName) {
EntityType entityType = internalNameToEntityType.get(internalName);
if (entityType == null) {
throw new IllegalArgumentException("EntityType not found: " + internalName);
}
return entityType;
}
public static Iterable<ItemType> getItemTypes() {
return internalNameToItemType.values();
}
public static Iterable<TileType> getTileTypes() {
return internalNameToTileType.values();
}
public static Iterable<WallType> getWallTypes() {
return internalNameToWallType.values();
}
public static Iterable<EntityType> getEntityTypes() {
return internalNameToEntityType.values();
}
private static JsonReader jsonReader = new JsonReader();
private static void loadConfigurations() {
fileNameToItemConfiguration.clear();
fileNameToTileConfiguration.clear();
fileNameToWallConfiguration.clear();
fileNameToEntityConfiguration.clear();
// TODO: This is dependent upon the assets directory existing
// in a separate directory, rather than in the classpath.
seekConfigurationDirectory(Gdx.files.local("assets"));
}
private static void seekConfigurationDirectory(FileHandle file) {
for (FileHandle child : file.list()) {
if (child.isDirectory()) {
seekConfigurationDirectory(child);
} else {
ObjectMap<String, JsonValue> mapping = null;
switch (child.extension()) {
case "item":
mapping = fileNameToItemConfiguration;
break;
case "tile":
mapping = fileNameToTileConfiguration;
break;
case "wall":
mapping = fileNameToWallConfiguration;
break;
case "entity":
mapping = fileNameToEntityConfiguration;
break;
}
if (mapping != null) {
if (mapping.containsKey(child.nameWithoutExtension())) {
throw new RuntimeException("Conflicting file name " + child.name());
}
mapping.put(child.nameWithoutExtension(), jsonReader.parse(child));
}
}
}
}
/** Called to queue the required assets for loading */
static void loadAssets(AssetManager assetManager) {
loadConfigurations();
GameRegistry.assetManager = assetManager;
for (JsonValue itemConfiguration : fileNameToItemConfiguration.values()) {
if (itemConfiguration.has("texture")) {
assetManager.load(itemConfiguration.getString("texture"), TextureRegion.class);
}
}
for (JsonValue tileConfiguration : fileNameToTileConfiguration.values()) {
if (tileConfiguration.has("skin")) {
assetManager.load(tileConfiguration.getString("skin"), TextureAtlas.class);
}
}
for (JsonValue wallConfiguration : fileNameToWallConfiguration.values()) {
if (wallConfiguration.has("skin")) {
assetManager.load(wallConfiguration.getString("skin"), TextureAtlas.class);
}
}
}
public static void initialize() {
// Register item usage callback factories
registerItemUsageCallbackFactory("placeTile", new TilePlaceCallbackFactory());
registerItemUsageCallbackFactory("placeWall", new WallPlaceCallbackFactory());
registerItemUsageCallbackFactory("destroyTile", new DestroyTileCallbackFactory());
registerItemUsageCallbackFactory("destroyWall", new DestroyWallCallbackFactory());
// Register frame style factories
registerFrameStyleFactory("block", new BlockFrameStyleFactory());
registerFrameStyleFactory("wall", new WallFrameStyleFactory());
// Initialize and register all types, leave out references to other types
for (JsonValue itemConfiguration : fileNameToItemConfiguration.values()) {
ItemType itemType = new ItemType();
itemType.setInternalName(itemConfiguration.getString("internalName"));
itemType.setDisplayName(itemConfiguration.getString("displayName", ""));
itemType.setMaxStack(itemConfiguration.getInt("maxStack", 1));
itemType.setWidth(itemConfiguration.getFloat("width"));
itemType.setHeight(itemConfiguration.getFloat("height"));
itemType.setUsageTime(itemConfiguration.getFloat("usageTime", 0f));
itemType.setUsageAnimationTime(itemConfiguration.getFloat("usageAnimationTime", itemType.getUsageTime()));
itemType.setUsageRepeat(itemConfiguration.getBoolean("usageRepeat", false));
itemType.setUsageStyle(ItemUsageStyle.swing); // TODO: This should be changed
itemType.setConsumable(itemConfiguration.getBoolean("consumable", false));
if (assetManager != null && itemConfiguration.has("texture")) {
itemType.setTexture(assetManager.get(itemConfiguration.getString("texture", null), TextureRegion.class));
}
registerItem(itemType);
}
for (JsonValue tileConfiguration : fileNameToTileConfiguration.values()) {
TileType tileType = new TileType();
tileType.setInternalName(tileConfiguration.getString("internalName"));
tileType.setDisplayName(tileConfiguration.getString("displayName", ""));
tileType.setSolid(tileConfiguration.getBoolean("solid", true));
if (tileConfiguration.has("frame")) {
tileType.setFrame(Utils.asRectangle(tileConfiguration.get("frame")));
}
if (assetManager != null && tileConfiguration.has("skin")) {
TextureAtlas atlas = assetManager.get(tileConfiguration.getString("skin"), TextureAtlas.class);
tileType.setAtlas(atlas);
}
registerTile(tileType);
}
for (JsonValue wallConfiguration : fileNameToWallConfiguration.values()) {
WallType wallType = new WallType();
wallType.setInternalName(wallConfiguration.getString("internalName"));
wallType.setDisplayName(wallConfiguration.getString("displayName", ""));
if (wallConfiguration.has("frame")) {
wallType.setFrame(Utils.asRectangle(wallConfiguration.get("frame")));
}
if (assetManager != null && wallConfiguration.has("skin")) {
TextureAtlas atlas = assetManager.get(wallConfiguration.getString("skin"), TextureAtlas.class);
wallType.setAtlas(atlas);
}
registerWall(wallType);
}
for (JsonValue entityConfiguration : fileNameToEntityConfiguration.values()) {
EntityType entityType = new EntityType();
entityType.setInternalName(entityConfiguration.getString("internalName"));
entityType.setDisplayName(entityConfiguration.getString("displayName", ""));
entityType.setMaxHealth(entityConfiguration.getInt("maxHealth", 0));
entityType.setSolid(entityConfiguration.getBoolean("solid", true));
entityType.setWeight(entityConfiguration.getFloat("weight", 1f));
entityType.setDefaultWidth(entityConfiguration.getFloat("width"));
entityType.setDefaultHeight(entityConfiguration.getFloat("height"));
registerEntity(entityType);
}
// Set static convenience fields in type classes
for (ItemType type : getItemTypes()) {
try {
ItemType.class.getField(type.getInternalName()).set(null, type);
} catch (Exception ex) {
ex.printStackTrace();
}
}
for (TileType type : getTileTypes()) {
try {
TileType.class.getField(type.getInternalName()).set(null, type);
} catch (Exception ex) {
ex.printStackTrace();
}
}
for (WallType type : getWallTypes()) {
try {
WallType.class.getField(type.getInternalName()).set(null, type);
} catch (Exception ex) {
ex.printStackTrace();
}
}
for (EntityType type : getEntityTypes()) {
try {
EntityType.class.getField(type.getInternalName()).set(null, type);
} catch (Exception ex) {
ex.printStackTrace();
}
}
// Then fixup the references, and other stuff that might required some types to be loaded
for (JsonValue itemConfiguration : fileNameToItemConfiguration.values()) {
ItemType itemType = getItemType(itemConfiguration.getString("internalName"));
if (itemConfiguration.has("usage")) {
ItemUsageCallbackFactory factory = getItemUsageCallbackFactory(itemConfiguration.getString("usage"));
itemType.setUsageCallback(factory.create(itemConfiguration));
}
}
for (JsonValue tileConfiguration : fileNameToTileConfiguration.values()) {
TileType tileType = getTileType(tileConfiguration.getString("internalName"));
String tileFrameStyle = tileConfiguration.getString("style", "block");
FrameStyleFactory styleFactory = getFrameStyleFactory(tileFrameStyle);
tileType.setStyle(styleFactory.create(tileConfiguration));
if (tileConfiguration.has("drop")) {
tileType.setDrop(getItemType(tileConfiguration.getString("drop")));
}
}
for (JsonValue wallConfiguration : fileNameToWallConfiguration.values()) {
WallType wallType = getWallType(wallConfiguration.getString("internalName"));
String wallFrameStyle = wallConfiguration.getString("style", "wall");
FrameStyleFactory styleFactory = getFrameStyleFactory(wallFrameStyle);
wallType.setStyle(styleFactory.create(wallConfiguration));
if (wallConfiguration.has("drop")) {
wallType.setDrop(getItemType(wallConfiguration.getString("drop")));
}
}
}
public static void clear() {
internalNameToItemType.clear();
internalNameToTileType.clear();
internalNameToEntityType.clear();
itemUsageCallbackFactories.clear();
frameStyleFactories.clear();
}
public static void registerItemUsageCallbackFactory(String name, ItemUsageCallbackFactory factory) {
itemUsageCallbackFactories.put(name, factory);
}
public static ItemUsageCallbackFactory getItemUsageCallbackFactory(String name) {
ItemUsageCallbackFactory factory = itemUsageCallbackFactories.get(name);
if (factory == null) {
throw new IllegalArgumentException("ItemUsageCallbackFactory not found: " + name);
}
return factory;
}
public static void registerFrameStyleFactory(String name, FrameStyleFactory factory) {
frameStyleFactories.put(name, factory);
}
public static FrameStyleFactory getFrameStyleFactory(String name) {
FrameStyleFactory factory = frameStyleFactories.get(name);
if (factory == null) {
throw new IllegalArgumentException("FrameStyleFactory not found: " + name);
}
return factory;
}
} |
package nl.mpi.arbil.ui;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.Transferable;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.TransferHandler;
import javax.swing.table.TableCellEditor;
import nl.mpi.arbil.util.WindowManager;
public class PreviewSplitPanel extends javax.swing.JSplitPane {
private static WindowManager windowManager;
public static void setWindowManager(WindowManager windowManagerInstance) {
windowManager = windowManagerInstance;
}
private static PreviewSplitPanel instance;
public static synchronized PreviewSplitPanel getInstance() {
if (instance == null) {
instance = new PreviewSplitPanel();
}
return instance;
}
private ArbilTable previewTable = null;
private boolean previewTableShown = false;
private JScrollPane rightScrollPane;
private JLabel previewHiddenColumnLabel;
private JPanel previewPanel;
private Container parentComponent;
private PreviewSplitPanel() {
this.setDividerSize(5);
this.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
this.setName("rightSplitPane");
previewHiddenColumnLabel = new javax.swing.JLabel(" ");
previewTable = new ArbilTable(new ArbilTableModel(null), "Preview");
previewTable.getArbilTableModel().setHiddenColumnsLabel(previewHiddenColumnLabel);
initCopyPaste();
rightScrollPane = new JScrollPane(previewTable);
previewPanel = new JPanel(new java.awt.BorderLayout());
previewPanel.add(rightScrollPane, BorderLayout.CENTER);
previewPanel.add(previewHiddenColumnLabel, BorderLayout.SOUTH);
}
private void initCopyPaste() {
previewTable.setDragEnabled(false);
previewTable.setTransferHandler(new TransferHandler() {
@Override
public boolean importData(JComponent comp, Transferable t) {
// Import is always from clipboard (no drag in preview table)
if (comp instanceof ArbilTable) {
((ArbilTable) comp).pasteIntoSelectedTableRowsFromClipBoard();
}
return false;
}
@Override
public void exportToClipboard(JComponent comp, Clipboard clip, int action) throws IllegalStateException {
if (comp instanceof ArbilTable) {
((ArbilTable) comp).copySelectedTableRowsToClipBoard();
}
}
});
}
public void setPreviewPanel(boolean showPreview) {
Container selectedComponent;
if (parentComponent == null) {
parentComponent = this.getParent();
}
if (!showPreview) {
// remove the right split split and show only the jdesktoppane
parentComponent.remove(this);
selectedComponent = ((ArbilWindowManager) windowManager).getDesktopPane();
TableCellEditor currentCellEditor = previewTable.getCellEditor(); // stop any editing so the changes get stored
if (currentCellEditor != null) {
currentCellEditor.stopCellEditing();
}
// clear the grid to keep things tidy
previewTable.getArbilTableModel().removeAllArbilDataNodeRows();
} else {
// put the jdesktoppane and the preview grid back into the right split pane
this.remove(((ArbilWindowManager) windowManager).getDesktopPane());
this.setDividerLocation(0.25);
this.setTopComponent(previewPanel);
this.setBottomComponent(((ArbilWindowManager) windowManager).getDesktopPane());
// update the preview data grid
TableCellEditor currentCellEditor = previewTable.getCellEditor(); // stop any editing so the changes get stored
if (currentCellEditor != null) {
currentCellEditor.stopCellEditing();
}
previewTable.getArbilTableModel().removeAllArbilDataNodeRows();
selectedComponent = this;
// guiHelper.addToGridData(previewTable.getModel(), getSelectedNodes(new JTree[]{remoteCorpusTree, localCorpusTree, localDirectoryTree}));
}
if (parentComponent instanceof JSplitPane) {
int parentDividerLocation = ((JSplitPane) parentComponent).getDividerLocation();
((JSplitPane) parentComponent).setBottomComponent(selectedComponent);
((JSplitPane) parentComponent).setDividerLocation(parentDividerLocation);
} else {
parentComponent.add(selectedComponent);
}
previewTableShown = showPreview;
}
/**
* @return the previewTableShown
*/
public static boolean isPreviewTableShown() {
return getInstance().previewTableShown;
}
/**
* @return the previewTable
*/
public ArbilTable getPreviewTable() {
return previewTable;
}
} |
package com.boundlessgeo.spatialconnect.config;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
@JsonInclude(JsonInclude.Include.NON_NULL)
public class SCFormField {
/**
* Unique id of the form.
*/
private String id;
/**
* Name for the field that can be used as a column name.
*/
@JsonProperty("field_key")
private String key;
/**
* A label used for the display name of this field.
*/
@JsonProperty("field_label")
private String label;
/**
* Boolean indicating if the field is required.
*/
@JsonProperty("is_required")
private Boolean isRequired;
/**
* An integer representing where the field should appear in the form.
*/
private Integer position;
/**
* The type of this field.
*/
private String type;
/**
* An initial value to be set for this field.
*/
@JsonProperty("initial_value")
private Object initialValue;
/**
* An minimum value for this field.
*/
private Object minimum;
/**
* An maximum value for this field.
*/
private Object maximum;
@JsonProperty("exclusive_minimum")
private Boolean exclusiveMinimum;
@JsonProperty("exclusive_maximum")
private Boolean exclusiveMaximum;
/**
* Boolean indicating if the field must be an integer. The field must already be of type {@code numeric}
*/
@JsonProperty("is_integer")
private Boolean isInteger = false;
/**
* An minimum length for this field.
*/
@JsonProperty("minimum_length")
private Integer minimumLength;
/**
* An maximum length for this field.
*/
@JsonProperty("maximum_length")
private Integer maximumLength;
/**
* A regex pattern that the field must match.
*/
private String pattern;
/**
* A list of all possible valid values for this field.
*/
private List<String> options;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public Boolean isRequired() {
return isRequired;
}
public void setIsRequired(Boolean isRequired) {
this.isRequired = isRequired;
}
public Integer getPosition() {
return position;
}
public void setPosition(Integer position) {
this.position = position;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Object getInitialValue() {
return initialValue;
}
public void setInitialValue(Object initialValue) {
this.initialValue = initialValue;
}
public Object getMinimum() {
return minimum;
}
public void setMinimum(Object minimum) {
this.minimum = minimum;
}
public Object getMaximum() {
return maximum;
}
public void setMaximum(Object maximum) {
this.maximum = maximum;
}
public Boolean isInteger() {
return isInteger;
}
public void setIsInteger(Boolean isInteger) {
this.isInteger = isInteger;
}
public Integer getMinimumLength() {
return minimumLength;
}
public void setMinimumLength(Integer minimumLength) {
this.minimumLength = minimumLength;
}
public Integer getMaximumLength() {
return maximumLength;
}
public void setMaximumLength(Integer maximumLength) {
this.maximumLength = maximumLength;
}
public String getPattern() {
return pattern;
}
public void setPattern(String pattern) {
this.pattern = pattern;
}
public Boolean isExclusiveMinimum() {
return exclusiveMinimum;
}
public void setExclusiveMinimum(Boolean exclusiveMinimum) {
this.exclusiveMinimum = exclusiveMinimum;
}
public Boolean isExclusiveMaximum() {
return exclusiveMaximum;
}
public void setExclusiveMaximum(Boolean exclusiveMaximum) {
this.exclusiveMaximum = exclusiveMaximum;
}
public List<String> getOptions() {
return options;
}
public void setOptions(List<String> options) {
this.options = options;
}
public String getColumnType() {
switch (this.type) {
case "string":
return "TEXT";
case "number":
if (isInteger) {
return "INTEGER";
}
return "REAL";
case "boolean":
return "INTEGER";
case "date":
return "TEXT";
case "slider":
return "TEXT";
case "photo":
return "TEXT";
case "counter":
return "INTEGER";
case "select":
return "TEXT";
default:
return "NULL";
}
}
} |
package com.ardverk.utils;
import java.io.Closeable;
import java.io.Flushable;
import java.io.IOException;
import org.ardverk.utils.ExceptionUtils;
/**
* An utility class for I/O operations.
*/
public class IoUtils {
private IoUtils() {}
public static boolean close(Closeable closeable) {
if (closeable != null) {
try {
closeable.close();
return true;
} catch (IOException err) {
ExceptionUtils.exceptionCaught(err);
}
}
return false;
}
public static boolean closeAll(Closeable... closeables) {
boolean success = false;
if (closeables != null) {
for (Closeable c : closeables) {
success |= close(c);
}
}
return success;
}
public static boolean closeAll(Iterable<? extends Closeable> closeables) {
boolean success = false;
if (closeables != null) {
for (Closeable c : closeables) {
success |= close(c);
}
}
return success;
}
public static boolean flush(Flushable flushable) {
if (flushable != null) {
try {
flushable.flush();
return true;
} catch (IOException err) {
ExceptionUtils.exceptionCaught(err);
}
}
return false;
}
public static boolean flushAll(Flushable... flushables) {
boolean success = false;
if (flushables != null) {
for (Flushable c : flushables) {
success |= flush(c);
}
}
return success;
}
public static boolean flushAll(Iterable<? extends Flushable> flushables) {
boolean success = false;
if (flushables != null) {
for (Flushable c : flushables) {
success |= flush(c);
}
}
return success;
}
} |
package com.artemis.injection;
/**
* Enum used to cache class type according to their usage in Artemis.
* @author Snorre E. Brekke
*/
public enum ClassType {
/**
* Used for (sub)classes of {@link com.artemis.ComponentMapper}
*/
MAPPER,
/**
* Used for (sub)classes of {@link com.artemis.BaseSystem}
*/
SYSTEM,
/**
* Used for (sub)classes of {@link com.artemis.Manager}
*/
MANAGER,
/**
* Used for (sub)classes of {@link com.artemis.EntityFactory}
*/
FACTORY,
/**
* Used for everything else.
*/
CUSTOM
} |
package training.pft.sandbox;
import org.testng.Assert;
import org.testng.annotations.Test;
public class SquareTests {
@Test
public void testArea() {
Square s = new Square(5);
Assert.assertEquals(s.area(), 25.0);
}
} |
package edu.cmu.lti.bic.sbs.ui;
//import java.time.LocalTime;
import java.awt.EventQueue;
import java.util.HashMap;
import edu.cmu.lti.bic.sbs.engine.Engine;
import edu.cmu.lti.bic.sbs.gson.Drug;
import edu.cmu.lti.bic.sbs.gson.Patient;
import edu.cmu.lti.bic.sbs.gson.Tool;
public class UserInterface {
private Engine decisionEngine;
private MainWindow window;
private HashMap<String, Tool> toolMap;
private UserInterface ui = this;
public UserInterface(Engine decisionEngine)
throws UserInterfaceInitializationException {
this.decisionEngine = decisionEngine;
this.toolMap = new HashMap<String, Tool>();
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
window = new MainWindow(ui);
window.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void callCode(String code) {
// decisionEngine.callCode(code);
}
public void connectMonitor() {
// decisionEngine.connectMonitor();
}
public void useTool(String id) {
Tool tool = toolMap.get(id);
assert(tool != null);
System.out.println("UI: Tool " + tool.getName() + " is used.");
decisionEngine.useTool(tool);
}
public void useDrug(String id, Double dosage) {
// decisionEngine.useDrug(drug, dosage);
}
// public void setTime(LocalTime time) {
// assert(time != null);
// window.setTime(time.getHour(), time.getMinute(), time.getSecond());
public void setPatientInfo(Patient patient) {
assert (patient != null);
window.setPatient(patient.getBasic(), patient.getDescription());
}
public void addDrug(Drug drug) {
assert (drug != null);
EventQueue.invokeLater(new Runnable() {
public void run() {
window.addTool(drug.getId(), drug.getName());
}
});
}
public void addTool(Tool tool) {
assert (tool != null);
toolMap.put(tool.getId(), tool);
EventQueue.invokeLater(new Runnable() {
public void run() {
window.addTool(tool.getId(), tool.getName());
}
});
}
public void updateReport() {
}
public void updateMonitor() {
}
public void addPathography(String feedback) {
}
} |
package com.axelor.mail;
import static com.axelor.common.StringUtils.isBlank;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.activation.DataHandler;
import javax.activation.URLDataSource;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Part;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimePart;
import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
/**
* The {@link MailBuilder} defines fluent API to build {@link MimeMessage} and
* if required can send the built message directly.
*
*/
public final class MailBuilder {
private Session session;
private String subject;
private String from = "";
private String sender = "";
private Set<String> toRecipients = new LinkedHashSet<>();
private Set<String> ccRecipients = new LinkedHashSet<>();
private Set<String> bccRecipients = new LinkedHashSet<>();
private Set<String> replyRecipients = new LinkedHashSet<>();
private List<Content> contents = Lists.newArrayList();
private Map<String, String> headers = Maps.newHashMap();
private boolean textOnly;
private class Content {
String cid;
String text;
String name;
String file;
boolean inline;
boolean html;
public MimePart apply(MimePart message) throws MessagingException {
if (text == null) return message;
if (html) {
message.setText(text, "UTF-8", "html");
} else {
message.setText(text);
}
return message;
}
}
public MailBuilder(Session session) {
this.session = session;
}
public MailBuilder subject(String subject) {
this.subject = subject;
return this;
}
private MailBuilder addAll(Collection<String> to, String... recipients) {
Preconditions.checkNotNull(recipients, "recipients can't be null");
for (String email : recipients) {
Preconditions.checkNotNull(email, "email can't be null");
}
Collections.addAll(to, recipients);
return this;
}
public MailBuilder to(String... recipients) {
return addAll(toRecipients, recipients);
}
public MailBuilder cc(String... recipients) {
Preconditions.checkNotNull(recipients, "recipients can't be null");
return addAll(ccRecipients, recipients);
}
public MailBuilder bcc(String... recipients) {
return addAll(bccRecipients, recipients);
}
public MailBuilder replyTo(String... recipients) {
return addAll(replyRecipients, recipients);
}
public MailBuilder from(String from) {
this.from = from;
return this;
}
public MailBuilder sender(String sender) {
this.sender = sender;
return this;
}
public MailBuilder header(String name, String value) {
Preconditions.checkNotNull(name, "header name can't be null");
headers.put(name, value);
return this;
}
public MailBuilder text(String text) {
return text(text, false);
}
public MailBuilder html(String text) {
return text(text, true);
}
private MailBuilder text(String text, boolean html) {
Preconditions.checkNotNull(text, "text can't be null");
Content content = new Content();
content.text = text;
content.html = html;
contents.add(content);
textOnly = contents.size() == 1;
return this;
}
public MailBuilder attach(String name, String link) {
return attach(name, link, null);
}
/**
* Attach a file referenced by the given link.
*
* <p>
* If you want to reference the attachment as inline image, provide content
* id wrapped by angle brackets and refer the image with content id without
* angle brackets.
* </p>
*
* For example:
*
* <pre>
* builder
* .html("<img src='cid:logo.png'>")
* .attach("logo.png", "/path/to/logo.png", "<logo.png>"
* .send();
* <pre>
*
* @param name
* attachment file name
* @param link
* attachment file link (url or file path)
* @param cid
* content id
* @return this
*/
public MailBuilder attach(String name, String link, String cid) {
Preconditions.checkNotNull(link, "link can't be null");
Content content = new Content();
content.name = name;
content.file = link;
content.cid = cid;
contents.add(content);
textOnly = false;
return this;
}
/**
* Attach a file as inline content.
*
* @param name
* attachment file name
* @param link
* attachment file link (url or file path)
* @param inline
* whether to inline this attachment
* @return this
*/
public MailBuilder inline(String name, String link) {
Preconditions.checkNotNull(link, "link can't be null");
Content content = new Content();
content.name = name;
content.file = link;
content.cid = "<" + name + ">";
content.inline = true;
contents.add(content);
textOnly = false;
return this;
}
/**
* Build a new {@link MimeMessage} instance from the provided details.
*
* @return an instance of {@link MimeMessage}
* @throws MessagingException
* @throws IOException
*/
public MimeMessage build() throws MessagingException, IOException {
return build(null);
}
/**
* Build a new {@link MimeMessage} instance from the provided details.
*
* @param messageId
* custom "Message-ID" to use, null to use auto-generated
* @return an instance of {@link MimeMessage}
* @throws MessagingException
* @throws IOException
*/
public MimeMessage build(final String messageId) throws MessagingException, IOException {
MimeMessage message = new MimeMessage(session) {
@Override
protected void updateMessageID() throws MessagingException {
if (isBlank(messageId)) {
super.updateMessageID();
} else {
this.setHeader("Message-ID", messageId);
}
}
};
message.setSubject(subject);
message.setRecipients(RecipientType.TO, InternetAddress.parse(Joiner.on(",").join(toRecipients)));
message.setRecipients(RecipientType.CC, InternetAddress.parse(Joiner.on(",").join(ccRecipients)));
message.setRecipients(RecipientType.BCC, InternetAddress.parse(Joiner.on(",").join(bccRecipients)));
message.setReplyTo(InternetAddress.parse(Joiner.on(",").join(replyRecipients)));
if (!isBlank(from)) message.setFrom(new InternetAddress(from));
if (!isBlank(sender)) message.setSender(new InternetAddress(sender));
for (String name : headers.keySet()) {
message.setHeader(name, headers.get(name));
}
if (textOnly) {
contents.get(0).apply(message);
return message;
}
Multipart mp = new MimeMultipart();
for (Content content : contents) {
MimeBodyPart part = new MimeBodyPart();
if (content.text == null) {
try {
URL link = new URL(content.file);
part.setDataHandler(new DataHandler(new URLDataSource(link)));
} catch (MalformedURLException e) {
part.attachFile(content.file);
}
part.setFileName(content.name);
if (content.cid != null) {
part.setContentID(content.cid);
}
if (content.inline) {
part.setDisposition(Part.INLINE);
} else {
part.setDisposition(Part.ATTACHMENT);
}
} else {
content.apply(part);
}
mp.addBodyPart(part);
}
message.setContent(mp);
return message;
}
/**
* Send the message with given send date.
*
* @param date
* send date, can be null
*
* @return sent {@link MimeMessage}
* @throws MessagingException
* @throws IOException
*/
public MimeMessage send(Date date) throws MessagingException, IOException {
final MimeMessage message = build();
try {
message.setSentDate(date);
} catch (Exception e) {
}
Transport.send(message);
return message;
}
/**
* Send the message.
*
* @return sent {@link MimeMessage}
* @throws MessagingException
* @throws IOException
*/
public MimeMessage send() throws MessagingException, IOException {
return send(new Date());
}
} |
package ly.count.android.sdk;
import android.content.Context;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
public class ConnectionQueue {
private CountlyStore store_;
private ExecutorService executor_;
private String appKey_;
private Context context_;
private String serverURL_;
private Future<?> connectionProcessorFuture_;
private DeviceId deviceId_;
private SSLContext sslContext_;
private Map<String, String> requestHeaderCustomValues;
// Getters are for unit testing
String getAppKey() {
return appKey_;
}
void setAppKey(final String appKey) {
appKey_ = appKey;
}
Context getContext() {
return context_;
}
void setContext(final Context context) {
context_ = context;
}
String getServerURL() {
return serverURL_;
}
void setServerURL(final String serverURL) {
serverURL_ = serverURL;
if (Countly.publicKeyPinCertificates == null && Countly.certificatePinCertificates == null) {
sslContext_ = null;
} else {
try {
TrustManager tm[] = { new CertificateTrustManager(Countly.publicKeyPinCertificates, Countly.certificatePinCertificates) };
sslContext_ = SSLContext.getInstance("TLS");
sslContext_.init(null, tm, null);
} catch (Throwable e) {
throw new IllegalStateException(e);
}
}
}
CountlyStore getCountlyStore() {
return store_;
}
void setCountlyStore(final CountlyStore countlyStore) {
store_ = countlyStore;
}
DeviceId getDeviceId() { return deviceId_; }
public void setDeviceId(DeviceId deviceId) {
this.deviceId_ = deviceId;
}
public void setRequestHeaderCustomValues(Map<String, String> headerCustomValues){
requestHeaderCustomValues = headerCustomValues;
}
void checkInternalState() {
if (context_ == null) {
throw new IllegalStateException("context has not been set");
}
if (appKey_ == null || appKey_.length() == 0) {
throw new IllegalStateException("app key has not been set");
}
if (store_ == null) {
throw new IllegalStateException("countly store has not been set");
}
if (serverURL_ == null || !Countly.isValidURL(serverURL_)) {
throw new IllegalStateException("server URL is not valid");
}
if (Countly.publicKeyPinCertificates != null && !serverURL_.startsWith("https")) {
throw new IllegalStateException("server must start with https once you specified public keys");
}
}
void beginSession() {
checkInternalState();
boolean dataAvailable = false;//will only send data if there is something valuable to send
String data = prepareCommonRequestData();
if(Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.sessions)) {
//add session data if consent given
data += "&begin_session=1"
+ "&metrics=" + DeviceInfo.getMetrics(context_);//can be only sent with begin session
dataAvailable = true;
}
CountlyStore cs = getCountlyStore();
String locationData = prepareLocationData(cs, true);
if(!locationData.isEmpty()){
data += locationData;
dataAvailable = true;
}
if(Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.attribution)) {
//add attribution data if consent given
if (Countly.sharedInstance().isAttributionEnabled) {
String cachedAdId = store_.getCachedAdvertisingId();
if (!cachedAdId.isEmpty()) {
data += "&aid=" + ConnectionProcessor.urlEncodeString("{\"adid\":\"" + cachedAdId + "\"}");
dataAvailable = true;
}
}
}
Countly.sharedInstance().isBeginSessionSent = true;
if(dataAvailable) {
store_.addConnection(data);
tick();
}
}
void updateSession(final int duration) {
checkInternalState();
if (duration > 0) {
boolean dataAvailable = false;//will only send data if there is something valuable to send
String data = prepareCommonRequestData();
if(Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.sessions)) {
data += "&session_duration=" + duration;
dataAvailable = true;
}
if(Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.attribution)) {
if (Countly.sharedInstance().isAttributionEnabled) {
String cachedAdId = store_.getCachedAdvertisingId();
if (!cachedAdId.isEmpty()) {
data += "&aid=" + ConnectionProcessor.urlEncodeString("{\"adid\":\"" + cachedAdId + "\"}");
dataAvailable = true;
}
}
}
if(dataAvailable) {
store_.addConnection(data);
tick();
}
}
}
public void changeDeviceId (String deviceId, final int duration) {
checkInternalState();
if(!Countly.sharedInstance().anyConsentGiven()){
//no consent set, aborting
return;
}
String data = prepareCommonRequestData();
if(Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.sessions)) {
data += "&session_duration=" + duration;
}
// !!!!! THIS SHOULD ALWAYS BE ADDED AS THE LAST FIELD, OTHERWISE MERGING BREAKS !!!!!
data += "&device_id=" + ConnectionProcessor.urlEncodeString(deviceId);
store_.addConnection(data);
tick();
}
public void tokenSession(String token, Countly.CountlyMessagingMode mode) {
checkInternalState();
if(!Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.push)){
return;
}
final String data = prepareCommonRequestData()
+ "&token_session=1"
+ "&android_token=" + token
+ "&test_mode=" + (mode == Countly.CountlyMessagingMode.TEST ? 2 : 0)
+ "&locale=" + DeviceInfo.getLocale();
// To ensure begin_session will be fully processed by the server before token_session
final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
worker.schedule(new Runnable() {
@Override
public void run() {
store_.addConnection(data);
tick();
}
}, 10, TimeUnit.SECONDS);
}
void endSession(final int duration) {
endSession(duration, null);
}
void endSession(final int duration, String deviceIdOverride) {
checkInternalState();
boolean dataAvailable = false;//will only send data if there is something valuable to send
String data = prepareCommonRequestData();
if(Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.sessions)) {
data += "&end_session=1";
if (duration > 0) {
data += "&session_duration=" + duration;
}
dataAvailable = true;
}
if (deviceIdOverride != null && Countly.sharedInstance().anyConsentGiven()) {
//if no consent is given, device ID override is not sent
data += "&override_id=" + ConnectionProcessor.urlEncodeString(deviceIdOverride);
dataAvailable = true;
}
if(dataAvailable) {
store_.addConnection(data);
tick();
}
}
/**
* Send user location
*/
void sendLocation() {
checkInternalState();
String data = prepareCommonRequestData();
CountlyStore cs = getCountlyStore();
data += prepareLocationData(cs, true);
store_.addConnection(data);
tick();
}
void sendUserData() {
checkInternalState();
if(!Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.users)){
return;
}
String userdata = UserData.getDataForRequest();
if(!userdata.equals("")){
String data = prepareCommonRequestData()
+ userdata;
store_.addConnection(data);
tick();
}
}
void sendReferrerData(String referrer) {
checkInternalState();
if(Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.attribution)) {
return;
}
if(referrer != null){
String data = prepareCommonRequestData()
+ referrer;
store_.addConnection(data);
tick();
}
}
void sendCrashReport(String error, boolean nonfatal) {
checkInternalState();
if(!Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.crashes)){
return;
}
//limit the size of the crash report to 10k characters
error = error.substring(0, Math.min(10000, error.length()));
final String data = prepareCommonRequestData()
+ "&crash=" + ConnectionProcessor.urlEncodeString(CrashDetails.getCrashData(context_, error, nonfatal));
store_.addConnection(data);
tick();
}
void recordEvents(final String events) {
checkInternalState();
///CONSENT FOR EVENTS IS CHECKED ON EVENT CREATION//
final String data = prepareCommonRequestData()
+ "&events=" + events;
store_.addConnection(data);
tick();
}
void sendConsentChanges(String formattedConsentChanges) {
checkInternalState();
final String data = prepareCommonRequestData()
+ "&consent=" + ConnectionProcessor.urlEncodeString(formattedConsentChanges);
store_.addConnection(data);
tick();
}
private String prepareCommonRequestData(){
return "app_key=" + appKey_
+ "×tamp=" + Countly.currentTimestampMs()
+ "&hour=" + Countly.currentHour()
+ "&dow=" + Countly.currentDayOfWeek()
+ "&tz=" + DeviceInfo.getTimezoneOffset()
+ "&sdk_version=" + Countly.COUNTLY_SDK_VERSION_STRING
+ "&sdk_name=" + Countly.COUNTLY_SDK_NAME;
}
private String prepareLocationData(CountlyStore cs, boolean canSendEmptyWithNoConsent){
String data = "";
if(canSendEmptyWithNoConsent && (cs.getLocationDisabled() || !Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.location))){
//if location is disabled or consent not given, send empty location info
//this way it is cleared server side and geoip is not used
//do this only if allowed
data += "&location=";
} else {
if(Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.location)) {
//location should be send, add all the fields we have
String location = cs.getLocation();
String city = cs.getLocationCity();
String country_code = cs.getLocationCountryCode();
String ip = cs.getLocationIpAddress();
if(location != null && !location.isEmpty()){
data += "&location=" + ConnectionProcessor.urlEncodeString(location);
}
if(city != null && !city.isEmpty()){
data += "&city=" + city;
}
if(country_code != null && !country_code.isEmpty()){
data += "&country_code=" + country_code;
}
if(ip != null && !ip.isEmpty()){
data += "&ip=" + ip;
}
}
}
return data;
}
protected String prepareRemoteConfigRequest(String keysInclude, String keysExclude){
String data = prepareCommonRequestData()
+ "&method=fetch_remote_config"
+ "&device_id=" + ConnectionProcessor.urlEncodeString(deviceId_.getId());
if(Countly.sharedInstance().getConsent(Countly.CountlyFeatureNames.sessions)) {
//add session data if consent given
data += "&metrics=" + DeviceInfo.getMetrics(context_);
}
CountlyStore cs = getCountlyStore();
String locationData = prepareLocationData(cs, true);
data += locationData;
//add key filters
if(keysInclude != null){
data += "&keys=" + ConnectionProcessor.urlEncodeString(keysInclude);
} else if(keysExclude != null) {
data += "&omit_keys=" + ConnectionProcessor.urlEncodeString(keysExclude);
}
return data;
}
/**
* Ensures that an executor has been created for ConnectionProcessor instances to be submitted to.
*/
void ensureExecutor() {
if (executor_ == null) {
executor_ = Executors.newSingleThreadExecutor();
}
}
/**
* Starts ConnectionProcessor instances running in the background to
* process the local connection queue data.
* Does nothing if there is connection queue data or if a ConnectionProcessor
* is already running.
*/
void tick() {
if (!store_.isEmptyConnections() && (connectionProcessorFuture_ == null || connectionProcessorFuture_.isDone())) {
ensureExecutor();
connectionProcessorFuture_ = executor_.submit(createConnectionProcessor());
}
}
public ConnectionProcessor createConnectionProcessor(){
return new ConnectionProcessor(serverURL_, store_, deviceId_, sslContext_, requestHeaderCustomValues);
}
// for unit testing
ExecutorService getExecutor() { return executor_; }
void setExecutor(final ExecutorService executor) { executor_ = executor; }
Future<?> getConnectionProcessorFuture() { return connectionProcessorFuture_; }
void setConnectionProcessorFuture(final Future<?> connectionProcessorFuture) { connectionProcessorFuture_ = connectionProcessorFuture; }
} |
package com.axelor.test;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Module;
import com.google.inject.servlet.RequestScoped;
import com.google.inject.servlet.RequestScoper;
import com.google.inject.servlet.ServletScopes;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.junit.runner.notification.RunNotifier;
import org.junit.runners.BlockJUnit4ClassRunner;
import org.junit.runners.model.InitializationError;
/**
* JUnit4 test runner that creates injector using the modules provided with {@link GuiceModules}
* configuration.
*
* <p>Here is a simple test:
*
* <pre>
*
* @RunWith(GuiceRunner.class)
* @GuiceModules({MyModule.class})
* public class MyTest {
*
* @Inject
* Foo foo;
*
* public void testFooInjected() {
* assertNotNull(foo);
* }
* }
*
* </pre>
*/
public class GuiceRunner extends BlockJUnit4ClassRunner {
private final Injector injector;
public GuiceRunner(Class<?> klass) throws InitializationError {
super(klass);
this.injector = Guice.createInjector(getModules(klass));
}
protected List<Module> getModules(Class<?> klass) throws InitializationError {
GuiceModules guiceModules = klass.getAnnotation(GuiceModules.class);
if (guiceModules == null) {
throw new InitializationError("No Guice modules specified.");
}
List<Module> modules = new ArrayList<Module>();
for (Class<? extends Module> c : guiceModules.value()) {
try {
modules.add(c.newInstance());
} catch (Exception e) {
throw new InitializationError(e);
}
}
modules.add(
new AbstractModule() {
@Override
protected void configure() {
bindScope(RequestScoped.class, ServletScopes.REQUEST);
}
});
return modules;
}
@Override
public void run(RunNotifier notifier) {
final RequestScoper scope = ServletScopes.scopeRequest(Collections.emptyMap());
try (RequestScoper.CloseableScope ignored = scope.open()) {
super.run(notifier);
}
}
@Override
public Object createTest() {
return injector.getInstance(getTestClass().getJavaClass());
}
/**
* Get the Guice injector.
*
* @return the injector
*/
protected Injector getInjector() {
return injector;
}
@Override
protected void validateZeroArgConstructor(List<Throwable> errors) {
// Guice can inject constroctor args
}
} |
package ly.count.android.sdk;
import android.content.Context;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class ConnectionQueue {
private CountlyStore store_;
private ExecutorService executor_;
private String appKey_;
private Context context_;
private String serverURL_;
private Future<?> connectionProcessorFuture_;
private DeviceId deviceId_;
// Getters are for unit testing
String getAppKey() {
return appKey_;
}
void setAppKey(final String appKey) {
appKey_ = appKey;
}
Context getContext() {
return context_;
}
void setContext(final Context context) {
context_ = context;
}
String getServerURL() {
return serverURL_;
}
void setServerURL(final String serverURL) {
serverURL_ = serverURL;
}
CountlyStore getCountlyStore() {
return store_;
}
void setCountlyStore(final CountlyStore countlyStore) {
store_ = countlyStore;
}
DeviceId getDeviceId() { return deviceId_; }
public void setDeviceId(DeviceId deviceId) {
this.deviceId_ = deviceId;
}
void checkInternalState() {
if (context_ == null) {
throw new IllegalStateException("context has not been set");
}
if (appKey_ == null || appKey_.length() == 0) {
throw new IllegalStateException("app key has not been set");
}
if (store_ == null) {
throw new IllegalStateException("countly store has not been set");
}
if (serverURL_ == null || !Countly.isValidURL(serverURL_)) {
throw new IllegalStateException("server URL is not valid");
}
}
void beginSession() {
checkInternalState();
final String data = "app_key=" + appKey_
+ "×tamp=" + Countly.currentTimestamp()
+ "&sdk_version=" + Countly.COUNTLY_SDK_VERSION_STRING
+ "&begin_session=1"
+ "&metrics=" + DeviceInfo.getMetrics(context_);
store_.addConnection(data);
tick();
}
void updateSession(final int duration) {
checkInternalState();
if (duration > 0) {
final String data = "app_key=" + appKey_
+ "×tamp=" + Countly.currentTimestamp()
+ "&session_duration=" + duration
+ "&location=" + getCountlyStore().getAndRemoveLocation();
store_.addConnection(data);
tick();
}
}
public void tokenSession(String token, Countly.CountlyMessagingMode mode) {
checkInternalState();
final String data = "app_key=" + appKey_
+ "&" + "timestamp=" + Countly.currentTimestamp()
+ "&" + "token_session=1"
+ "&" + "android_token=" + token
+ "&" + "test_mode=" + (mode == Countly.CountlyMessagingMode.TEST ? 2 : 0)
+ "&" + "locale=" + DeviceInfo.getLocale();
// To ensure begin_session will be fully processed by the server before token_session
final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
worker.schedule(new Runnable() {
@Override
public void run() {
store_.addConnection(data);
tick();
}
}, 10, TimeUnit.SECONDS);
}
void endSession(final int duration) {
checkInternalState();
String data = "app_key=" + appKey_
+ "×tamp=" + Countly.currentTimestamp()
+ "&end_session=1";
if (duration > 0) {
data += "&session_duration=" + duration;
}
store_.addConnection(data);
tick();
}
void sendUserData() {
checkInternalState();
String userdata = UserData.getDataForRequest();
if(!userdata.equals("")){
String data = "app_key=" + appKey_
+ "×tamp=" + Countly.currentTimestamp()
+ userdata;
store_.addConnection(data);
tick();
}
}
void sendReferrerData(String referrer) {
checkInternalState();
if(referrer != null){
String data = "app_key=" + appKey_
+ "×tamp=" + Countly.currentTimestamp()
+ referrer;
store_.addConnection(data);
tick();
}
}
void sendCrashReport(String error, boolean nonfatal) {
checkInternalState();
final String data = "app_key=" + appKey_
+ "×tamp=" + Countly.currentTimestamp()
+ "&sdk_version=" + Countly.COUNTLY_SDK_VERSION_STRING
+ "&crash=" + CrashDetails.getCrashData(context_, error, nonfatal);
store_.addConnection(data);
tick();
}
void recordEvents(final String events) {
checkInternalState();
final String data = "app_key=" + appKey_
+ "×tamp=" + Countly.currentTimestamp()
+ "&events=" + events;
store_.addConnection(data);
tick();
}
void recordLocation(final String events) {
checkInternalState();
final String data = "app_key=" + appKey_
+ "×tamp=" + Countly.currentTimestamp()
+ "&events=" + events;
store_.addConnection(data);
tick();
}
/**
* Ensures that an executor has been created for ConnectionProcessor instances to be submitted to.
*/
void ensureExecutor() {
if (executor_ == null) {
executor_ = Executors.newSingleThreadExecutor();
}
}
/**
* Starts ConnectionProcessor instances running in the background to
* process the local connection queue data.
* Does nothing if there is connection queue data or if a ConnectionProcessor
* is already running.
*/
void tick() {
if (!store_.isEmptyConnections() && (connectionProcessorFuture_ == null || connectionProcessorFuture_.isDone())) {
ensureExecutor();
connectionProcessorFuture_ = executor_.submit(new ConnectionProcessor(serverURL_, store_, deviceId_));
}
}
// for unit testing
ExecutorService getExecutor() { return executor_; }
void setExecutor(final ExecutorService executor) { executor_ = executor; }
Future<?> getConnectionProcessorFuture() { return connectionProcessorFuture_; }
void setConnectionProcessorFuture(final Future<?> connectionProcessorFuture) { connectionProcessorFuture_ = connectionProcessorFuture; }
} |
package edu.northwestern.bioinformatics.studycalendar.domain.auditing;
import org.hibernate.annotations.Type;
import java.util.Date;
import java.sql.Timestamp;
/**
* Subclass of core-commons' DataAuditInfo that aliases the "on" property as "time".
* This is so that it can be used in HQL queries ("on" is apparently a reserved word).
*
* @author Rhett Sutphin
*/
public class DataAuditInfo extends edu.nwu.bioinformatics.commons.DataAuditInfo {
public DataAuditInfo() { }
public DataAuditInfo(String by, String ip) {
super(by, ip);
}
public DataAuditInfo(String by, String ip, Date on) {
super(by, ip, on);
}
public static DataAuditInfo copy(edu.nwu.bioinformatics.commons.DataAuditInfo source) {
return new DataAuditInfo(
source.getBy(), source.getIp(), source.getOn()
);
}
@Type(type = "timestamp")
public Date getTime() {
return getOn();
}
public void setTime(Date on) {
setOn(on);
}
/* Have to duplicate other accessors so that it will work with annotations without
annotating the superclass. */
public String getUsername() { return super.getBy(); }
public void setUsername(String by) { super.setBy(by); }
public String getIp() { return super.getIp(); }
public void setIp(String ip) { super.setIp(ip); }
} |
package gov.nih.nci.cananolab.service.publication.impl;
import gov.nih.nci.cagrid.cananolab.client.CaNanoLabServiceClient;
import gov.nih.nci.cagrid.cqlquery.Association;
import gov.nih.nci.cagrid.cqlquery.Attribute;
import gov.nih.nci.cagrid.cqlquery.CQLQuery;
import gov.nih.nci.cagrid.cqlquery.Predicate;
import gov.nih.nci.cagrid.cqlquery.QueryModifier;
import gov.nih.nci.cagrid.cqlresultset.CQLQueryResults;
import gov.nih.nci.cagrid.data.utilities.CQLQueryResultsIterator;
import gov.nih.nci.cananolab.domain.common.Author;
import gov.nih.nci.cananolab.domain.common.Publication;
import gov.nih.nci.cananolab.domain.particle.NanoparticleSample;
import gov.nih.nci.cananolab.dto.common.PublicationBean;
import gov.nih.nci.cananolab.dto.particle.ParticleBean;
import gov.nih.nci.cananolab.exception.CaNanoLabSecurityException;
import gov.nih.nci.cananolab.exception.PublicationException;
import gov.nih.nci.cananolab.service.publication.PublicationService;
import gov.nih.nci.cananolab.service.publication.helper.PublicationServiceHelper;
import gov.nih.nci.cananolab.util.CaNanoLabComparators;
import gov.nih.nci.cananolab.util.CaNanoLabConstants;
import java.io.IOException;
import java.io.OutputStream;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import org.apache.log4j.Logger;
/**
* Remote implementation of PublicationService
*
* @author tanq
*
*/
public class PublicationServiceRemoteImpl implements PublicationService {
private static Logger logger = Logger
.getLogger(PublicationServiceRemoteImpl.class);
private CaNanoLabServiceClient gridClient;
public PublicationServiceRemoteImpl(String serviceUrl) throws Exception {
gridClient = new CaNanoLabServiceClient(serviceUrl);
}
/**
* Persist a new publication or update an existing publication
*
* @param publication
* @param particleNames
* @param fileData
* @param authors
*
* @throws Exception
*/
public void savePublication(Publication publication, String[] particleNames,
byte[] fileData, Collection<Author> authors) throws PublicationException {
throw new PublicationException("not implemented for grid service.");
}
public List<PublicationBean> findPublicationsBy(String title,
String category, String nanoparticleName,
String[] researchArea, String keywordsStr,
String pubMedId, String digitalObjectId, String authorsStr,
String[] nanoparticleEntityClassNames,
String[] otherNanoparticleTypes,
String[] functionalizingEntityClassNames,
String[] otherFunctionalizingEntityTypes,
String[] functionClassNames, String[] otherFunctionTypes)
throws PublicationException, CaNanoLabSecurityException {
List<PublicationBean> publicationBeans = new ArrayList<PublicationBean>();
try {
Publication[] publications = gridClient.getPublicationsBy(title, category,
nanoparticleName, researchArea, keywordsStr, pubMedId,
digitalObjectId, authorsStr, nanoparticleEntityClassNames,
otherNanoparticleTypes, functionalizingEntityClassNames,
otherFunctionalizingEntityTypes, functionClassNames, otherFunctionTypes);
if (publications != null) {
for (Publication publication : publications) {
loadParticleSamplesForPublication(publication);
publicationBeans.add(new PublicationBean(publication));
}
}
Collections.sort(publicationBeans,
new CaNanoLabComparators.PublicationBeanTitleComparator());
return publicationBeans;
} catch (RemoteException e) {
logger.error(CaNanoLabConstants.NODE_UNAVAILABLE, e);
//should show warning to user
//throw new DocumentException(CaNanoLabConstants.NODE_UNAVAILABLE, e);
return publicationBeans;
} catch (Exception e) {
String err = "Problem finding publication info.";
logger.error(err, e);
return publicationBeans;
//if may cause by grid version incompatible
//throw new DocumentException(err, e);
}
}
public Publication[] findPublicationsByParticleSampleId(String particleId)
throws PublicationException {
try {
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.Publication");
Association association = new Association();
association
.setName("gov.nih.nci.cananolab.domain.particle.NanoparticleSample");
association.setRoleName("nanoparticleSampleCollection");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(particleId);
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Publication");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(
results);
Publication publication = null;
List<Publication> publications = new ArrayList<Publication>();
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
publication = (Publication) obj;
publications.add(publication);
}
return publications.toArray(new Publication[0]);
} catch (RemoteException e) {
logger.error(CaNanoLabConstants.NODE_UNAVAILABLE, e);
//throw new DocumentException(CaNanoLabConstants.NODE_UNAVAILABLE, e);
return null;
} catch (Exception e) {
String err = "Error finding publications for particle.";
logger.error(err, e);
return null;
//if may cause by grid version incompatible
//throw new DocumentException(err, e);
}
}
private void loadParticleSamplesForPublication(Publication publication)
throws PublicationException {
try {
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.particle.NanoparticleSample");
Association association = new Association();
association.setName("gov.nih.nci.cananolab.domain.common.Publication");
association.setRoleName("publicationCollection");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(publication.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.particle.NanoparticleSample");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
NanoparticleSample particleSample = null;
publication
.setNanoparticleSampleCollection(new HashSet<NanoparticleSample>());
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
particleSample = (NanoparticleSample) obj;
publication.getNanoparticleSampleCollection().add(particleSample);
}
} catch (Exception e) {
String err = "Problem loading nanoparticle samples for the publication : "
+ publication.getId();
logger.error(err, e);
throw new PublicationException(err, e);
}
}
public void loadAuthorsForPublication(Publication publication)
throws PublicationException {
try {
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target
.setName("gov.nih.nci.cananolab.domain.common.Author");
Association association = new Association();
association.setName("gov.nih.nci.cananolab.domain.common.Publication");
association.setRoleName("publicationCollection");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(publication.getId().toString());
association.setAttribute(attribute);
target.setAssociation(association);
query.setTarget(target);
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Author");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
Author author = null;
publication.setAuthorCollection(new HashSet<Author>());
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
author = (Author) obj;
publication.getAuthorCollection().add(author);
}
// CQLQuery query = new CQLQuery();
// gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
// target
// .setName("gov.nih.nci.cananolab.domain.common.Author");
// Attribute attribute = new Attribute();
// attribute.setName("id");
// attribute.setPredicate(Predicate.EQUAL_TO);
// attribute.setValue("6881282");
// target.setAttribute(attribute);
// query.setTarget(target);
// CQLQueryResults results = gridClient.query(query);
// results
// .setTargetClassname("gov.nih.nci.cananolab.domain.common.Author");
// CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
// Author author = null;
// publication.setAuthorCollection(new HashSet<Author>());
// while (iter.hasNext()) {
// java.lang.Object obj = iter.next();
// author = (Author) obj;
// publication.getAuthorCollection().add(author);
} catch (Exception e) {
String err = "Problem loading authors for the publication : "
+ publication.getId();
logger.error(err, e);
throw new PublicationException(err, e);
}
}
public PublicationBean findPublicationById(String publicationId) throws PublicationException {
try {
Publication publication = findDomainPublicationById(publicationId);
PublicationBean publicationBean = new PublicationBean(publication);
return publicationBean;
} catch (Exception e) {
String err = "Problem finding the publication by id: " + publicationId;
logger.error(err, e);
throw new PublicationException(err, e);
}
}
public Publication findDomainPublicationById(String publicationId) throws PublicationException{
try {
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.Publication");
Attribute attribute = new Attribute();
attribute.setName("id");
attribute.setPredicate(Predicate.EQUAL_TO);
attribute.setValue(publicationId);
target.setAttribute(attribute);
query.setTarget(target);
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Publication");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
Publication publication = null;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
publication = (Publication) obj;
}
loadParticleSamplesForPublication(publication);
loadAuthorsForPublication(publication);
return publication;
} catch (RemoteException e) {
logger.error(CaNanoLabConstants.NODE_UNAVAILABLE, e);
throw new PublicationException(CaNanoLabConstants.NODE_UNAVAILABLE, e);
} catch (Exception e) {
String err = "Problem finding the publication by id: " + publicationId;
logger.error(err, e);
throw new PublicationException(err, e);
}
}
public void exportDetail(PublicationBean aPub, OutputStream out)
throws PublicationException{
try {
PublicationServiceHelper helper = new PublicationServiceHelper();
helper.exportDetail(aPub, out);
} catch (Exception e) {
String err = "error exporting detail view for "
+ aPub.getDomainFile().getTitle();
logger.error(err, e);
throw new PublicationException(err, e);
}
}
public int getNumberOfPublicPublications() throws PublicationException {
try {
CQLQuery query = new CQLQuery();
gov.nih.nci.cagrid.cqlquery.Object target = new gov.nih.nci.cagrid.cqlquery.Object();
target.setName("gov.nih.nci.cananolab.domain.common.Publication");
query.setTarget(target);
QueryModifier modifier = new QueryModifier();
modifier.setCountOnly(true);
query.setQueryModifier(modifier);
CQLQueryResults results = gridClient.query(query);
results
.setTargetClassname("gov.nih.nci.cananolab.domain.common.Publication");
CQLQueryResultsIterator iter = new CQLQueryResultsIterator(results);
int count = 0;
while (iter.hasNext()) {
java.lang.Object obj = iter.next();
count = ((Long) obj).intValue();
}
return count;
} catch (Exception e) {
String err = "Error finding counts of remote public publications.";
logger.error(err, e);
throw new PublicationException(err, e);
}
}
public void exportSummary(ParticleBean particleBean,
OutputStream out) throws IOException {
PublicationServiceHelper helper = new PublicationServiceHelper();
helper.exportSummary(particleBean, out);
}
public void removePublicationFromParticle(NanoparticleSample particle,
Long dataId) throws PublicationException{
throw new PublicationException("not implemented for grid service.");
}
} |
package org.basex.gui.text;
import static org.basex.gui.layout.BaseXKeys.*;
import static org.basex.util.Token.*;
import java.awt.*;
import java.awt.datatransfer.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.Timer;
import javax.swing.border.*;
import org.basex.core.*;
import org.basex.gui.*;
import org.basex.gui.GUIConstants.Fill;
import org.basex.gui.dialog.*;
import org.basex.gui.layout.*;
import org.basex.io.*;
import org.basex.util.*;
public class TextPanel extends BaseXPanel {
/** Delay for highlighting an error. */
private static final int ERROR_DELAY = 500;
/** Search direction. */
public enum SearchDir {
/** Current hit. */
CURRENT,
/** Next hit. */
FORWARD,
/** Previous hit. */
BACKWARD,
}
/** Editor action. */
public enum Action {
/** Check for changes; do nothing if input has not changed. */
CHECK,
/** Enforce parsing of input. */
PARSE,
/** Enforce execution of input. */
EXECUTE,
/** Enforce testing of input. */
TEST
}
/** Text editor. */
protected final TextEditor editor;
/** Undo history. */
public final History hist;
/** Search bar. */
protected SearchBar search;
/** Renderer reference. */
private final TextRenderer rend;
/** Scrollbar reference. */
private final BaseXScrollBar scroll;
/** Editable flag. */
private final boolean editable;
/** Link listener. */
private LinkListener linkListener;
/**
* Default constructor.
* @param edit editable flag
* @param win parent window
*/
public TextPanel(final boolean edit, final Window win) {
this(EMPTY, edit, win);
}
/**
* Default constructor.
* @param txt initial text
* @param edit editable flag
* @param win parent window
*/
public TextPanel(final byte[] txt, final boolean edit, final Window win) {
super(win);
editable = edit;
editor = new TextEditor(gui);
setFocusable(true);
setFocusTraversalKeysEnabled(!edit);
addMouseMotionListener(this);
addMouseWheelListener(this);
addComponentListener(this);
addMouseListener(this);
addKeyListener(this);
addFocusListener(new FocusAdapter() {
@Override
public void focusGained(final FocusEvent e) {
if(isEnabled()) caret(true);
}
@Override
public void focusLost(final FocusEvent e) {
caret(false);
rend.caret(false);
}
});
setFont(GUIConstants.dmfont);
layout(new BorderLayout());
scroll = new BaseXScrollBar(this);
rend = new TextRenderer(editor, scroll, editable, gui);
add(rend, BorderLayout.CENTER);
add(scroll, BorderLayout.EAST);
setText(txt);
hist = new History(edit ? editor.text() : null);
if(edit) {
setBackground(Color.white);
setBorder(new MatteBorder(1, 1, 0, 0, GUIConstants.color(6)));
} else {
mode(Fill.NONE);
}
new BaseXPopup(this, edit ?
new GUICommand[] {
new FindCmd(), new FindNextCmd(), new FindPrevCmd(), null, new GotoCmd(), null,
new UndoCmd(), new RedoCmd(), null,
new AllCmd(), new CutCmd(), new CopyCmd(), new PasteCmd(), new DelCmd() } :
new GUICommand[] {
new FindCmd(), new FindNextCmd(), new FindPrevCmd(), null, new GotoCmd(), null,
new AllCmd(), new CopyCmd() }
);
}
/**
* Sets the output text.
* @param t output text
*/
public void setText(final String t) {
setText(token(t));
}
/**
* Sets the output text.
* @param t output text
*/
public void setText(final byte[] t) {
setText(t, t.length);
resetError();
}
/**
* Returns a currently marked string if it does not extend over more than one line.
* @return search string or {@code null}
*/
public String searchString() {
final String string = editor.copy();
return string.isEmpty() || string.contains("\n") ? null : string;
}
/**
* Returns the line and column of the current caret position.
* @return line/column
*/
public final int[] pos() {
return rend.pos();
}
/**
* Sets the output text.
* @param t output text
* @param s text size
*/
public final void setText(final byte[] t, final int s) {
byte[] txt = t;
if(Token.contains(t, '\r')) {
// remove carriage returns
int ns = 0;
for(int r = 0; r < s; ++r) {
final byte b = t[r];
if(b != '\r') t[ns++] = b;
}
// new text is different...
txt = Arrays.copyOf(t, ns);
}
if(editor.text(txt)) {
if(hist != null) hist.store(txt, editor.pos(), 0);
}
componentResized(null);
}
/**
* Sets a syntax highlighter, based on the file format.
* @param file file reference
* @param opened indicates if file was opened from disk
*/
protected final void setSyntax(final IO file, final boolean opened) {
setSyntax(!opened || file.hasSuffix(IO.XQSUFFIXES) ? new SyntaxXQuery() :
file.hasSuffix(IO.JSONSUFFIX) ? new SyntaxJSON() :
file.hasSuffix(IO.JSSUFFIX) ? new SyntaxJS() :
file.hasSuffix(IO.XMLSUFFIXES) || file.hasSuffix(IO.HTMLSUFFIXES) ||
file.hasSuffix(IO.XSLSUFFIXES) || file.hasSuffix(IO.BXSSUFFIX) ?
new SyntaxXML() : Syntax.SIMPLE);
}
/**
* Returns the editable flag.
* @return boolean result
*/
public final boolean isEditable() {
return editable;
}
/**
* Sets a syntax highlighter.
* @param syntax syntax reference
*/
public final void setSyntax(final Syntax syntax) {
rend.setSyntax(syntax);
}
/**
* Sets the caret to the specified position. A text selection will be removed.
* @param pos caret position
*/
public final void setCaret(final int pos) {
editor.pos(pos);
cursorCode.invokeLater(1);
caret(true);
}
/**
* Returns the current text cursor.
* @return cursor position
*/
private int getCaret() {
return editor.pos();
}
/**
* Jumps to the end of the text.
*/
public final void scrollToEnd() {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
editor.pos(editor.size());
cursorCode.execute(2);
}
});
}
/**
* Returns the output text.
* @return output text
*/
public final byte[] getText() {
return editor.text();
}
/**
* Tests if text has been selected.
* @return result of check
*/
public final boolean selected() {
return editor.selected();
}
@Override
public final void setFont(final Font f) {
super.setFont(f);
if(rend != null) {
rend.setFont(f);
scrollCode.invokeLater(true);
}
}
/** Thread counter. */
private int errorID;
/**
* Removes the error marker.
*/
public final void resetError() {
++errorID;
editor.error(-1);
rend.repaint();
}
/**
* Sets the error marker.
* @param pos start of optional error mark
*/
public final void error(final int pos) {
final int eid = ++errorID;
editor.error(pos);
new Thread() {
@Override
public void run() {
Performance.sleep(ERROR_DELAY);
if(eid == errorID) rend.repaint();
}
}.start();
}
/**
* Adds or removes a comment.
*/
public void comment() {
final int caret = editor.pos();
if(editor.comment(rend.getSyntax())) hist.store(editor.text(), caret, editor.pos());
scrollCode.invokeLater(true);
}
/**
* Sorts text.
*/
public void sort() {
final DialogSort ds = new DialogSort(gui);
if(!ds.ok()) return;
final int caret = editor.pos();
if(editor.sort()) hist.store(editor.text(), caret, editor.pos());
scrollCode.invokeLater(true);
}
/**
* Formats the selected text.
*/
public void format() {
final int caret = editor.pos();
if(editor.format(rend.getSyntax())) hist.store(editor.text(), caret, editor.pos());
scrollCode.invokeLater(true);
}
@Override
public final void setEnabled(final boolean enabled) {
super.setEnabled(enabled);
rend.setEnabled(enabled);
scroll.setEnabled(enabled);
caret(enabled);
}
/**
* Selects the whole text.
*/
private void selectAll() {
editor.select(0, editor.size());
rend.repaint();
}
/**
* Installs a link listener.
* @param ll link listener
*/
public final void setLinkListener(final LinkListener ll) {
linkListener = ll;
}
/**
* Installs a search bar.
* @param s search bar
*/
final void setSearch(final SearchBar s) {
search = s;
}
/**
* Returns the search bar.
* @return search bar
*/
public final SearchBar getSearch() {
return search;
}
/**
* Performs a search.
* @param sc search context
* @param jump jump to next hit
*/
final void search(final SearchContext sc, final boolean jump) {
try {
rend.search(sc);
gui.status.setText(sc.search.isEmpty() ? Text.OK : Util.info(Text.STRINGS_FOUND_X, sc.nr()));
if(jump) jump(SearchDir.CURRENT, false);
} catch(final Exception ex) {
final String msg = Util.message(ex).replaceAll(Prop.NL + ".*", "");
gui.status.setError(Text.REGULAR_EXPR + Text.COLS + msg);
}
}
/**
* Replaces the text.
* @param rc replace context
*/
final void replace(final ReplaceContext rc) {
try {
final int[] select = rend.replace(rc);
if(rc.text != null) {
final boolean sel = editor.selected();
setText(rc.text);
editor.select(select[0], select[sel ? 1 : 0]);
release(Action.CHECK);
}
gui.status.setText(Util.info(Text.STRINGS_REPLACED));
} catch(final Exception ex) {
final String msg = Util.message(ex).replaceAll(Prop.NL + ".*", "");
gui.status.setError(Text.REGULAR_EXPR + Text.COLS + msg);
}
}
/**
* Jumps to the current, next or previous search string.
* @param dir search direction
* @param select select hit
*/
protected final void jump(final SearchDir dir, final boolean select) {
// updates the visible area
final int y = rend.jump(dir, select);
final int h = getHeight();
final int p = scroll.pos();
final int m = y + rend.fontHeight() * 3 - h;
if(y != -1 && (p < m || p > y)) scroll.pos(y - h / 2);
rend.repaint();
}
@Override
public final void mouseEntered(final MouseEvent e) {
gui.cursor(GUIConstants.CURSORTEXT);
}
@Override
public final void mouseExited(final MouseEvent e) {
gui.cursor(GUIConstants.CURSORARROW);
}
@Override
public final void mouseMoved(final MouseEvent e) {
if(linkListener == null) return;
final TextIterator iter = rend.jump(e.getPoint());
gui.cursor(iter.link() != null ? GUIConstants.CURSORHAND : GUIConstants.CURSORARROW);
}
@Override
public void mouseReleased(final MouseEvent e) {
if(linkListener == null) return;
if(SwingUtilities.isLeftMouseButton(e)) {
editor.endSelection();
// evaluate link
if(!editor.selected()) {
final TextIterator iter = rend.jump(e.getPoint());
final String link = iter.link();
if(link != null) linkListener.linkClicked(link);
}
}
}
@Override
public void mouseClicked(final MouseEvent e) {
if(!SwingUtilities.isMiddleMouseButton(e)) return;
new PasteCmd().execute(gui);
}
@Override
public final void mouseDragged(final MouseEvent e) {
if(!SwingUtilities.isLeftMouseButton(e)) return;
// selection mode
select(e.getPoint(), false);
final int y = Math.max(20, Math.min(e.getY(), getHeight() - 20));
if(y != e.getY()) scroll.pos(scroll.pos() + e.getY() - y);
}
@Override
public final void mousePressed(final MouseEvent e) {
if(!isEnabled() || !isFocusable()) return;
requestFocusInWindow();
caret(true);
if(SwingUtilities.isMiddleMouseButton(e)) copy();
final boolean shift = e.isShiftDown();
final boolean selected = editor.selected();
if(SwingUtilities.isLeftMouseButton(e)) {
final int c = e.getClickCount();
if(c == 1) {
// selection mode
if(shift) editor.startSelection(true);
select(e.getPoint(), !shift);
} else if(c == 2) {
editor.selectWord();
} else {
editor.selectLine();
}
} else if(!selected) {
select(e.getPoint(), true);
}
}
/**
* Selects the text at the specified position.
* @param point mouse position
* @param start states if selection has just been started
*/
private void select(final Point point, final boolean start) {
editor.select(rend.jump(point).pos(), start);
rend.repaint();
}
/**
* Invokes special keys.
* @param e key event
* @return {@code true} if special key was processed
*/
private boolean specialKey(final KeyEvent e) {
if(PREVTAB.is(e)) {
gui.editor.tab(false);
} else if(NEXTTAB.is(e)) {
gui.editor.tab(true);
} else if(CLOSETAB.is(e)) {
gui.editor.close(null);
} else if(search != null && ESCAPE.is(e)) {
search.deactivate(true);
} else {
return false;
}
e.consume();
return true;
}
@Override
public void keyPressed(final KeyEvent e) {
// ignore modifier keys
if(specialKey(e) || modifier(e)) return;
// re-animate cursor
caret(true);
// operations without cursor movement...
final int fh = rend.fontHeight();
if(SCROLLDOWN.is(e)) {
scroll.pos(scroll.pos() + fh);
return;
}
if(SCROLLUP.is(e)) {
scroll.pos(scroll.pos() - fh);
return;
}
// set cursor position
final boolean selected = editor.selected();
final int pos = editor.pos();
final boolean shift = e.isShiftDown();
boolean down = true, consumed = true;
// move caret
int lc = Integer.MIN_VALUE;
final byte[] txt = editor.text();
if(NEXTWORD.is(e)) {
editor.nextWord(shift);
} else if(PREVWORD.is(e)) {
editor.prevWord(shift);
down = false;
} else if(TEXTSTART.is(e)) {
editor.textStart(shift);
down = false;
} else if(TEXTEND.is(e)) {
editor.textEnd(shift);
} else if(LINESTART.is(e)) {
editor.lineStart(shift);
down = false;
} else if(LINEEND.is(e)) {
editor.lineEnd(shift);
} else if(PREVPAGE_RO.is(e) && !hist.active()) {
lc = editor.linesUp(getHeight() / fh, false, lastCol);
down = false;
} else if(NEXTPAGE_RO.is(e) && !hist.active()) {
lc = editor.linesDown(getHeight() / fh, false, lastCol);
} else if(PREVPAGE.is(e) && !sc(e)) {
lc = editor.linesUp(getHeight() / fh, shift, lastCol);
down = false;
} else if(NEXTPAGE.is(e) && !sc(e)) {
lc = editor.linesDown(getHeight() / fh, shift, lastCol);
} else if(NEXTLINE.is(e) && !MOVEDOWN.is(e)) {
lc = editor.linesDown(1, shift, lastCol);
} else if(PREVLINE.is(e) && !MOVEUP.is(e)) {
lc = editor.linesUp(1, shift, lastCol);
down = false;
} else if(NEXTCHAR.is(e)) {
editor.next(shift);
} else if(PREVCHAR.is(e)) {
editor.previous(shift);
down = false;
} else {
consumed = false;
}
lastCol = lc == Integer.MIN_VALUE ? -1 : lc;
// edit text
if(hist.active()) {
if(MOVEDOWN.is(e)) {
editor.move(true);
} else if(MOVEUP.is(e)) {
editor.move(false);
} else if(COMPLETE.is(e)) {
editor.complete();
} else if(DELLINE.is(e)) {
editor.deleteLine();
} else if(DELNEXTWORD.is(e)) {
editor.deleteNext(true);
} else if(DELLINEEND.is(e)) {
editor.deleteNext(false);
} else if(DELNEXT.is(e)) {
editor.delete();
} else if(DELPREVWORD.is(e)) {
editor.deletePrev(true);
down = false;
} else if(DELLINESTART.is(e)) {
editor.deletePrev(false);
down = false;
} else if(DELPREV.is(e)) {
editor.deletePrev();
down = false;
} else {
consumed = false;
}
}
if(consumed) e.consume();
final byte[] tmp = editor.text();
if(txt != tmp) {
// text has changed: add old text to history
hist.store(tmp, pos, editor.pos());
scrollCode.invokeLater(down);
} else if(pos != editor.pos() || selected != editor.selected()) {
// cursor position or selection state has changed
cursorCode.invokeLater(down ? 2 : 0);
}
}
/** Updates the scroll bar. */
private final GUICode scrollCode = new GUICode() {
@Override
public void execute(final Object down) {
rend.updateScrollbar();
cursorCode.execute((Boolean) down ? 2 : 0);
}
};
/** Updates the cursor position. */
private final GUICode cursorCode = new GUICode() {
@Override
public void execute(final Object algn) {
// updates the visible area
final int p = scroll.pos();
final int y = rend.cursorY();
final int m = y + rend.fontHeight() * 3 - getHeight();
if(p < m || p > y) {
final int align = (Integer) algn;
scroll.pos(align == 0 ? y : align == 1 ? y - getHeight() / 2 : m);
}
}
};
/** Last horizontal position. */
private int lastCol = -1;
@Override
public void keyTyped(final KeyEvent e) {
if(!hist.active() || control(e) || DELNEXT.is(e) || DELPREV.is(e) || ESCAPE.is(e)) return;
final int caret = editor.pos();
// remember if marked text is to be deleted
final StringBuilder sb = new StringBuilder(1).append(e.getKeyChar());
final boolean indent = TAB.is(e) && editor.indent(sb, e.isShiftDown());
// delete marked text
final boolean selected = editor.selected() && !indent;
if(selected) editor.delete();
final int move = ENTER.is(e) ? editor.enter(sb) : editor.add(sb, selected);
// refresh history and adjust cursor position
hist.store(editor.text(), caret, editor.pos());
if(move != 0) editor.pos(Math.min(editor.size(), caret + move));
// adjust text height
scrollCode.invokeLater(true);
e.consume();
}
/**
* Releases a key or mouse. Can be overwritten to react on events.
* @param action action
*/
@SuppressWarnings("unused")
protected void release(final Action action) { }
/**
* Copies the selected text to the clipboard.
* @return true if text was copied
*/
private boolean copy() {
final String txt = editor.copy();
if(txt.isEmpty()) return false;
// copy selection to clipboard
BaseXLayout.copy(txt);
return true;
}
/**
* Returns the clipboard text.
* @return text
*/
private static String clip() {
// copy selection to clipboard
final Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();
final Transferable tr = clip.getContents(null);
if(tr != null) for(final Object o : BaseXLayout.contents(tr)) return o.toString();
return null;
}
/**
* Finishes a command.
* @param old old cursor position; store entry to history if position != -1
*/
private void finish(final int old) {
if(old != -1) hist.store(editor.text(), old, editor.pos());
scrollCode.invokeLater(true);
release(Action.CHECK);
}
/** Text caret. */
private final Timer caretTimer = new Timer(500, new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
rend.caret(!rend.caret());
}
});
/**
* Stops an old text cursor thread and, if requested, starts a new one.
* @param start start/stop flag
*/
private void caret(final boolean start) {
caretTimer.stop();
if(start) caretTimer.start();
rend.caret(start);
}
@Override
public final void mouseWheelMoved(final MouseWheelEvent e) {
scroll.pos(scroll.pos() + e.getUnitsToScroll() * 20);
rend.repaint();
}
/** Calculation counter. */
private final GUICode resizeCode = new GUICode() {
@Override
public void execute(final Object arg) {
rend.updateScrollbar();
// update scrollbar to display value within valid range
scroll.pos(scroll.pos());
rend.repaint();
}
};
@Override
public final void componentResized(final ComponentEvent e) {
resizeCode.invokeLater();
}
/** Undo command. */
class UndoCmd extends GUIPopupCmd {
/** Constructor. */
UndoCmd() { super(Text.UNDO, UNDOSTEP); }
@Override
public void execute() {
if(!hist.active()) return;
final byte[] t = hist.prev();
if(t == null) return;
editor.text(t);
editor.pos(hist.caret());
finish(-1);
}
@Override
public boolean enabled(final GUI main) { return !hist.first(); }
}
/** Redo command. */
class RedoCmd extends GUIPopupCmd {
/** Constructor. */
RedoCmd() { super(Text.REDO, REDOSTEP); }
@Override
public void execute() {
if(!hist.active()) return;
final byte[] t = hist.next();
if(t == null) return;
editor.text(t);
editor.pos(hist.caret());
finish(-1);
}
@Override
public boolean enabled(final GUI main) { return !hist.last(); }
}
/** Cut command. */
class CutCmd extends GUIPopupCmd {
/** Constructor. */
CutCmd() { super(Text.CUT, CUT1, CUT2); }
@Override
public void execute() {
final int pos = editor.pos();
if(!copy()) return;
editor.delete();
finish(pos);
}
@Override
public boolean enabled(final GUI main) { return hist.active() && editor.selected(); }
}
/** Copy command. */
class CopyCmd extends GUIPopupCmd {
/** Constructor. */
CopyCmd() { super(Text.COPY, COPY1, COPY2); }
@Override
public void execute() { copy(); }
@Override
public boolean enabled(final GUI main) { return editor.selected(); }
}
/** Paste command. */
class PasteCmd extends GUIPopupCmd {
/** Constructor. */
PasteCmd() { super(Text.PASTE, PASTE1, PASTE2); }
@Override
public void execute() {
final int pos = editor.pos();
final String clip = clip();
if(clip == null) return;
if(editor.selected()) editor.delete();
editor.add(clip);
finish(pos);
}
@Override
public boolean enabled(final GUI main) { return hist.active() && clip() != null; }
}
/** Delete command. */
class DelCmd extends GUIPopupCmd {
/** Constructor. */
DelCmd() { super(Text.DELETE, DELNEXT); }
@Override
public void execute() {
final int pos = editor.pos();
editor.delete();
finish(pos);
}
@Override
public boolean enabled(final GUI main) { return hist.active() && editor.selected(); }
}
/** Select all command. */
class AllCmd extends GUIPopupCmd {
/** Constructor. */
AllCmd() { super(Text.SELECT_ALL, SELECTALL); }
@Override
public void execute() { selectAll(); }
}
/** Find next hit. */
class FindCmd extends GUIPopupCmd {
/** Constructor. */
FindCmd() { super(Text.FIND + Text.DOTS, FIND); }
@Override
public void execute() { search.activate(searchString(), true); }
@Override
public boolean enabled(final GUI main) { return search != null; }
}
/** Find next hit. */
class FindNextCmd extends GUIPopupCmd {
/** Constructor. */
FindNextCmd() { super(Text.FIND_NEXT, FINDNEXT1, FINDNEXT2); }
@Override
public void execute() { find(true); }
@Override
public boolean enabled(final GUI main) { return search != null; }
}
/** Find previous hit. */
class FindPrevCmd extends GUIPopupCmd {
/** Constructor. */
FindPrevCmd() { super(Text.FIND_PREVIOUS, FINDPREV1, FINDPREV2); }
@Override
public void execute() { find(false); }
@Override
public boolean enabled(final GUI main) { return search != null; }
}
/**
* Highlights the next/previous hit.
* @param next next/previous hit
*/
private void find(final boolean next) {
final boolean vis = search.isVisible();
search.activate(searchString(), false);
jump(vis ? next ? SearchDir.FORWARD : SearchDir.BACKWARD : SearchDir.CURRENT, true);
}
/** Go to line. */
class GotoCmd extends GUIPopupCmd {
/** Constructor. */
GotoCmd() { super(Text.GO_TO_LINE + Text.DOTS, GOTOLINE); }
@Override
public void execute() { gotoLine(); }
@Override
public boolean enabled(final GUI main) { return search != null; }
}
/**
* Jumps to a specific line.
*/
private void gotoLine() {
final byte[] last = editor.text();
final int ll = last.length;
final int cr = getCaret();
int l = 1;
for(int e = 0; e < ll && e < cr; e += cl(last, e)) {
if(last[e] == '\n') ++l;
}
final DialogLine dl = new DialogLine(gui, l);
if(!dl.ok()) return;
final int el = dl.line();
l = 1;
int p = 0;
for(int e = 0; e < ll && l < el; e += cl(last, e)) {
if(last[e] != '\n') continue;
p = e + 1;
++l;
}
setCaret(p);
gui.editor.posCode.invokeLater();
}
} |
package gov.nih.nci.ncicb.cadsr.umlmodelbrowser.struts.actions;
import gov.nih.nci.cadsr.domain.Context;
import gov.nih.nci.cadsr.domain.ObjectClass;
import gov.nih.nci.cadsr.umlproject.domain.Project;
import gov.nih.nci.cadsr.umlproject.domain.SemanticMetadata;
import gov.nih.nci.cadsr.umlproject.domain.SubProject;
import gov.nih.nci.cadsr.umlproject.domain.UMLAssociationMetadata;
import gov.nih.nci.cadsr.umlproject.domain.UMLAttributeMetadata;
import gov.nih.nci.cadsr.umlproject.domain.UMLClassMetadata;
import gov.nih.nci.cadsr.umlproject.domain.UMLPackageMetadata;
import gov.nih.nci.ncicb.cadsr.jsp.bean.PaginationBean;
import gov.nih.nci.ncicb.cadsr.service.UMLBrowserQueryService;
import gov.nih.nci.ncicb.cadsr.umlmodelbrowser.struts.common.UMLBrowserFormConstants;
import gov.nih.nci.ncicb.cadsr.util.BeanPropertyComparator;
import gov.nih.nci.ncicb.cadsr.util.UMLBrowserParams;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
public class UMLSearchAction extends BaseDispatchAction
{
protected static Log log = LogFactory.getLog(UMLSearchAction.class.getName());
public UMLSearchAction()
{
}
/**
* This Action forwards to the default umplbrowser home.
*
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
*
* @return
*
* @throws IOException
* @throws ServletException
*/
public ActionForward sendHome(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
removeSessionObject(request, UMLBrowserFormConstants.CLASS_SEARCH_RESULTS);
return mapping.findForward("umlbrowserHome");
}
/**
* This Action forwards to the default umplbrowser home.
*
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
*
* @return
*
* @throws IOException
* @throws ServletException
*/
public ActionForward initSearch(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
removeSessionObject(request, UMLBrowserFormConstants.CLASS_SEARCH_RESULTS);
//Set the lookup values in the session
setInitLookupValues(request);
setSessionObject(request, UMLBrowserFormConstants.SUBPROJECT_OPTIONS,
getSessionObject(request, UMLBrowserFormConstants.ALL_SUBPROJECTS ),true);
setSessionObject(request, UMLBrowserFormConstants.PACKAGE_OPTIONS,
getSessionObject(request, UMLBrowserFormConstants.ALL_PACKAGES ),true);
return mapping.findForward("umlSearch");
}
public ActionForward classSearch(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
DynaActionForm dynaForm = (DynaActionForm) form;
String resetCrumbs = (String) dynaForm.get(UMLBrowserFormConstants.RESET_CRUMBS);
UMLClassMetadata umlClass = this.populateClassFromForm(dynaForm);
this.findClassesLike(umlClass, request);
return mapping.findForward("umlSearch");
}
public ActionForward attributeSearch(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
// removeSessionObject(request, UMLBrowserFormConstants.CLASS_SEARCH_RESULTS);
DynaActionForm dynaForm = (DynaActionForm) form;
Collection<UMLAttributeMetadata> umlAttributes= new ArrayList();
UMLBrowserQueryService queryService = getAppServiceLocator().findQuerySerivce();
UMLAttributeMetadata umlAtt = new UMLAttributeMetadata();
String attName = ((String) dynaForm.get("attributeName")).trim();
if (attName !=null && attName.length()>0)
umlAtt.setName(attName );
UMLClassMetadata umlClass = this.populateClassFromForm(dynaForm);
if (umlClass != null)
umlAtt.setUMLClassMetadata(umlClass);
umlAttributes = queryService.findUmlAttributes(umlAtt);
setupSessionForAttributeResults(umlAttributes, request);
return mapping.findForward("showAttributes");
}
public ActionForward getAttributesForClass(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
int selectedClassIndex = Integer.parseInt(request.getParameter("selectedClassIndex"));
Collection umlClasses = (Collection) getSessionObject(request, UMLBrowserFormConstants.CLASS_SEARCH_RESULTS);
UMLClassMetadata umlClass =(UMLClassMetadata) umlClasses.toArray()[selectedClassIndex];
DynaActionForm dynaForm = (DynaActionForm) form;
Collection<UMLAttributeMetadata> umlAttributes= umlClass.getUMLAttributeMetadataCollection();
this.setupSessionForAttributeResults(umlAttributes, request);
dynaForm.set("className", umlClass.getName());
return mapping.findForward("showAttributes");
}
/**
* Sorts search results by fieldName
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
*
* @return
*
* @throws IOException
* @throws ServletException
*/
public ActionForward sortResult(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
//Set the lookup values in the session
DynaActionForm searchForm = (DynaActionForm) form;
String sortField = (String) searchForm.get("sortField");
Integer sortOrder = (Integer) searchForm.get("sortOrder");
List umlClasses = (List)getSessionObject(request,UMLBrowserFormConstants.CLASS_SEARCH_RESULTS);
//getLazyAssociationsForClass(umlClasses);
BeanPropertyComparator comparator = (BeanPropertyComparator)getSessionObject(request,UMLBrowserFormConstants.CLASS_SEARCH_RESULT_COMPARATOR);
comparator.setRelativePrimary(sortField);
comparator.setOrder(sortOrder.intValue());
//Initialize and add the PagenationBean to the Session
PaginationBean pb = new PaginationBean();
if (umlClasses != null) {
pb.setListSize(umlClasses.size());
}
Collections.sort(umlClasses,comparator);
setSessionObject(request, UMLBrowserFormConstants.CLASS_SEARCH_RESULTS_PAGINATION, pb,true);
setSessionObject(request, ANCHOR, "results",true);
return mapping.findForward(SUCCESS);
}
/**
* Sorts search results by fieldName
* @param mapping The ActionMapping used to select this instance.
* @param form The optional ActionForm bean for this request.
* @param request The HTTP Request we are processing.
* @param response The HTTP Response we are processing.
*
* @return
*
* @throws IOException
* @throws ServletException
*/
public ActionForward sortAttributes(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
//Set the lookup values in the session
DynaActionForm searchForm = (DynaActionForm) form;
String sortField = (String) searchForm.get("sortField");
Integer sortOrder = (Integer) searchForm.get("sortOrder");
List umlClasses = (List)getSessionObject(request, UMLBrowserFormConstants.CLASS_ATTRIBUTES);
BeanPropertyComparator comparator = (BeanPropertyComparator)getSessionObject(request,UMLBrowserFormConstants.ATTRIBUTE_SEARCH_RESULT_COMPARATOR);
comparator.setRelativePrimary(sortField);
comparator.setOrder(sortOrder.intValue());
//Initialize and add the PagenationBean to the Session
PaginationBean pb = new PaginationBean();
if (umlClasses != null) {
pb.setListSize(umlClasses.size());
}
Collections.sort(umlClasses,comparator);
setSessionObject(request, UMLBrowserFormConstants.ATTRIBUTE_SEARCH_RESULTS_PAGINATION, pb,true);
setSessionObject(request, ANCHOR, "results",true);
return mapping.findForward(SUCCESS);
}
private void findClassesLike (UMLClassMetadata umlClass, HttpServletRequest request ){
Collection<UMLClassMetadata> umlClasses = new ArrayList();
UMLBrowserQueryService queryService = getAppServiceLocator().findQuerySerivce();
umlClasses = queryService.findUmlClass(umlClass);
setupSessionForClassResults(umlClasses, request);
}
private void setupSessionForAttributeResults(Collection<UMLAttributeMetadata> umlAttributes, HttpServletRequest request){
setSessionObject(request, UMLBrowserFormConstants.CLASS_VIEW, false, true);
setSessionObject(request, UMLBrowserFormConstants.CLASS_ATTRIBUTES, umlAttributes,true);
PaginationBean pb = new PaginationBean();
if (umlAttributes != null) {
pb.setListSize(umlAttributes.size());
}
UMLAttributeMetadata anAttribute = null;
if(umlAttributes.size()>0) {
Object[] attArr = umlAttributes.toArray();
anAttribute=(UMLAttributeMetadata)attArr[0];
BeanPropertyComparator comparator = new BeanPropertyComparator(anAttribute.getClass());
comparator.setPrimary("name");
comparator.setOrder(comparator.ASCENDING);
Collections.sort((List)umlAttributes,comparator);
setSessionObject(request,UMLBrowserFormConstants.ATTRIBUTE_SEARCH_RESULT_COMPARATOR,comparator);
}
setSessionObject(request, UMLBrowserFormConstants.ATTRIBUTE_SEARCH_RESULTS_PAGINATION, pb,true);
}
private void setupSessionForClassResults(Collection umlClasses, HttpServletRequest request){
setSessionObject(request, UMLBrowserFormConstants.CLASS_SEARCH_RESULTS, umlClasses,true);
setSessionObject(request, UMLBrowserFormConstants.CLASS_VIEW, true, true);
PaginationBean pb = new PaginationBean();
if (umlClasses != null) {
pb.setListSize(umlClasses.size());
UMLClassMetadata aClass = null;
if(umlClasses.size()>0)
{
Object[] classArr = umlClasses.toArray();
aClass=(UMLClassMetadata)classArr[0];
BeanPropertyComparator comparator = new BeanPropertyComparator(aClass.getClass());
comparator.setPrimary("name");
comparator.setOrder(comparator.ASCENDING);
Collections.sort((List)umlClasses,comparator);
setSessionObject(request,UMLBrowserFormConstants.CLASS_SEARCH_RESULT_COMPARATOR,comparator);
//getLazyAssociationsForClass(umlClasses);
}
}
setSessionObject(request, UMLBrowserFormConstants.CLASS_SEARCH_RESULTS_PAGINATION, pb,true);
}
private UMLClassMetadata populateClassFromForm(DynaActionForm dynaForm) {
UMLClassMetadata umlClass = null;
String className = ((String) dynaForm.get("className")).trim();
if (className != null && className.length() >0) {
umlClass = new UMLClassMetadata();
umlClass.setName(className);
}
String projectId = ((String) dynaForm.get(UMLBrowserFormConstants.PROJECT_IDSEQ)).trim();
if (projectId != null && projectId.length() >0) {
if (umlClass == null)
umlClass = new UMLClassMetadata();
Project project = new Project();
project.setId(projectId);
umlClass.setProject(project);
}
UMLPackageMetadata packageMetadata = null;
String subprojectId = ((String) dynaForm.get(UMLBrowserFormConstants.SUB_PROJECT_IDSEQ)).trim();
if (projectId != null && subprojectId.length() >0) {
if (umlClass == null)
umlClass = new UMLClassMetadata();
SubProject subproject = new SubProject();
subproject.setId(subprojectId);
packageMetadata = new UMLPackageMetadata();
packageMetadata.setSubProject(subproject);
}
String packageId = ((String) dynaForm.get(UMLBrowserFormConstants.PACKAGE_IDSEQ)).trim();
if (packageId != null && packageId.length() >0) {
if (umlClass == null)
umlClass = new UMLClassMetadata();
if (packageMetadata == null)
packageMetadata = new UMLPackageMetadata();
packageMetadata.setId(packageId);
}
if (packageMetadata != null)
umlClass.setUMLPackageMetadata(packageMetadata);
return umlClass;
}
public ActionForward resetSubProjPkgOptions(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
DynaActionForm dynaForm = (DynaActionForm) form;
String projectId = ((String) dynaForm.get(UMLBrowserFormConstants.PROJECT_IDSEQ)).trim();
if (projectId == null || projectId.length() == 0) {
setSessionObject(request, UMLBrowserFormConstants.SUBPROJECT_OPTIONS,
getSessionObject(request, UMLBrowserFormConstants.ALL_SUBPROJECTS ),true);
setSessionObject(request, UMLBrowserFormConstants.PACKAGE_OPTIONS,
getSessionObject(request, UMLBrowserFormConstants.ALL_PACKAGES ),true);
} else {
Project project = setPackageOptionsForProjectId(request, projectId);
if (project != null ){
setSessionObject(request, UMLBrowserFormConstants.SUBPROJECT_OPTIONS,
project.getSubProjectCollection(), true);
}
}
Object classView = getSessionObject(request, UMLBrowserFormConstants.CLASS_VIEW);
String showClass = null;
if (classView != null)
showClass=classView.toString();
if (showClass == null || showClass.equalsIgnoreCase("true"))
return mapping.findForward("umlSearch");
return mapping.findForward("showAttributes");
}
public ActionForward resetPkgOptions(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
DynaActionForm dynaForm = (DynaActionForm) form;
String projectId = ((String) dynaForm.get(UMLBrowserFormConstants.PROJECT_IDSEQ)).trim();
String subprojId = ((String) dynaForm.get(UMLBrowserFormConstants.SUB_PROJECT_IDSEQ)).trim();
if (subprojId == null || subprojId.length() == 0) {
// if subProject is ALL, set package options by project
setPackageOptionsForProjectId(request, projectId);
} else {
SubProject subproject = null;
Collection<SubProject> allSubProjects = (Collection) getSessionObject(request, UMLBrowserFormConstants.ALL_SUBPROJECTS);
for (Iterator subprojIter =allSubProjects.iterator(); subprojIter.hasNext(); ) {
subproject = (SubProject) subprojIter.next();
if (subproject.getId().equalsIgnoreCase(subprojId))
break;
}
if (subproject != null ){
setSessionObject(request, UMLBrowserFormConstants.PACKAGE_OPTIONS,
subproject.getUMLPackageMetadataCollection(), true);
}
}
String showClass=(String) getSessionObject(request, UMLBrowserFormConstants.CLASS_VIEW);
if (showClass == null || showClass.equalsIgnoreCase("true"))
return mapping.findForward("umlSearch");
return mapping.findForward("showAttributes");
}
private Project setPackageOptionsForProjectId (HttpServletRequest request, String projectId){
Project project = null;
Collection<Project> allProjects = (Collection) getSessionObject(request, UMLBrowserFormConstants.ALL_PROJECTS);
for (Iterator projIter =allProjects.iterator(); projIter.hasNext(); ) {
project = (Project) projIter.next();
if (project.getId().equalsIgnoreCase(projectId))
break;
}
if (project != null ){
UMLBrowserQueryService queryService = getAppServiceLocator().findQuerySerivce();
setSessionObject(request, UMLBrowserFormConstants.PACKAGE_OPTIONS,
queryService.getAllPackageForProject(project),true);
}
return project;
}
public ActionForward treeClassSearch(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
String searchType = request.getParameter("P_PARAM_TYPE");
String searchId = request.getParameter("P_IDSEQ");
UMLBrowserQueryService queryService = getAppServiceLocator().findQuerySerivce();
Collection umlClasses = null;
if (searchType.equalsIgnoreCase("Class") ) {
UMLClassMetadata umlClass = new UMLClassMetadata();
umlClass.setId(searchId);
UMLAttributeMetadata umlAttribute = new UMLAttributeMetadata();
umlAttribute.setUMLClassMetadata(umlClass);
Collection umlAttributes = queryService.findUmlAttributes(umlAttribute);
setupSessionForAttributeResults(umlAttributes, request);
return mapping.findForward("showAttributes");
}
if (searchType.equalsIgnoreCase("Context") ) {
umlClasses = queryService.getClassesForContext(searchId);
}
if (searchType.equalsIgnoreCase("Project") ) {
UMLClassMetadata umlClass = new UMLClassMetadata();
Project project = new Project();
project.setId(searchId);
umlClass.setProject(project);
umlClasses = queryService.findUmlClass(umlClass);
}
if (searchType.equalsIgnoreCase("SubProject") ) {
UMLClassMetadata umlClass = new UMLClassMetadata();
SubProject subproject = new SubProject();
subproject.setId(searchId);
UMLPackageMetadata packageMetadata= new UMLPackageMetadata();
packageMetadata.setSubProject(subproject);
umlClass.setUMLPackageMetadata(packageMetadata);
umlClasses = queryService.findUmlClass(umlClass);
}
if (searchType.equalsIgnoreCase("Package") ) {
UMLClassMetadata umlClass = new UMLClassMetadata();
UMLPackageMetadata packageMetadata= new UMLPackageMetadata();
packageMetadata.setId(searchId);
umlClass.setUMLPackageMetadata(packageMetadata);
umlClasses = queryService.findUmlClass(umlClass);
}
setupSessionForClassResults(umlClasses, request);
return mapping.findForward("umlSearch");
}
private void getLazyAssociationsForClass(Collection classList)
{
if(classList==null) return;
int itemPerPage = UMLBrowserParams.getInstance().getItemPerPage();
int count = 0;
for (Iterator resultsIterator = classList.iterator();
resultsIterator.hasNext();) {
UMLClassMetadata returnedClass = (UMLClassMetadata) resultsIterator.next();
for (Iterator mdIterator = returnedClass.getSemanticMetadataCollection().iterator();
mdIterator.hasNext();) {
SemanticMetadata metaData = (SemanticMetadata) mdIterator.next();
System.out.println("concept Name: " + metaData.getConceptName());
}
}
++count;
if(itemPerPage<=count) return;
}
} |
package alien4cloud.paas.cloudify3.service;
import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.CREATE;
import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.CREATED;
import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.CREATING;
import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.DELETED;
import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.DELETING;
import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.STANDARD;
import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.START;
import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.STARTED;
import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.STARTING;
import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.STOP;
import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.STOPPED;
import static alien4cloud.paas.plan.ToscaNodeLifecycleConstants.STOPPING;
import static alien4cloud.utils.AlienUtils.safe;
import static org.alien4cloud.tosca.normative.constants.NormativeWorkflowNameConstants.INSTALL;
import static org.alien4cloud.tosca.normative.constants.NormativeWorkflowNameConstants.UNINSTALL;
import java.util.Map.Entry;
import java.util.Set;
import org.springframework.stereotype.Service;
import com.google.common.collect.Sets;
import alien4cloud.paas.model.PaaSNodeTemplate;
import alien4cloud.paas.model.PaaSRelationshipTemplate;
import alien4cloud.paas.plan.ToscaNodeLifecycleConstants;
import alien4cloud.paas.wf.AbstractActivity;
import alien4cloud.paas.wf.AbstractStep;
import alien4cloud.paas.wf.DelegateWorkflowActivity;
import alien4cloud.paas.wf.NodeActivityStep;
import alien4cloud.paas.wf.OperationCallActivity;
import alien4cloud.paas.wf.SetStateActivity;
import alien4cloud.paas.wf.Workflow;
import alien4cloud.paas.wf.util.WorkflowUtils;
import lombok.extern.slf4j.Slf4j;
/**
* This service is responsible for replacing the delegate operations of Service matched nodes by actual create and start operations.
*/
@Slf4j
@Service
public class ServiceDelegateWorkflowService {
/**
* Replace the service delegate workflow by a matching workflow:
*
* creating -> create() -> created -> start() -> started
* start operation requires all dependencies (based on relationship the service is source of) before being executed.
*
* @param serviceNode The node for which to inject the create operation.
* @param installWorkflow The install workflow for which to change the delegate operation.
*/
public void replaceInstallServiceDelegate(PaaSNodeTemplate serviceNode, Workflow installWorkflow) {
Set<String> stepDependencies = Sets.newHashSet();
for (PaaSRelationshipTemplate relationshipTemplate : serviceNode.getRelationshipTemplates()) {
if (serviceNode.getId().equals(relationshipTemplate.getSource())) {
// the start operation (used to trigger the add source and target) needs dependency on target started state.
String dependentStepId = getStartedStepId(relationshipTemplate.getTemplate().getTarget(), installWorkflow);
stepDependencies.add(dependentStepId);
}
}
// Replace the delegate activity by create and start operations.
for (Entry<String, AbstractStep> stepEntry : installWorkflow.getSteps().entrySet()) {
if (stepEntry.getValue() instanceof NodeActivityStep && serviceNode.getId().equals(((NodeActivityStep) stepEntry.getValue()).getNodeId())) {
NodeActivityStep nodeStep = (NodeActivityStep) stepEntry.getValue();
AbstractActivity activity = nodeStep.getActivity();
if (activity instanceof DelegateWorkflowActivity && INSTALL.equals(((DelegateWorkflowActivity) activity).getWorkflowName())) {
// Inject Creating set state step
NodeActivityStep creatingStep = WorkflowUtils.addStateStep(installWorkflow, serviceNode.getId(), CREATING);
NodeActivityStep createStep = WorkflowUtils.addOperationStep(installWorkflow, serviceNode.getId(), STANDARD, CREATE);
NodeActivityStep createdStep = WorkflowUtils.addStateStep(installWorkflow, serviceNode.getId(), CREATED);
NodeActivityStep startingStep = WorkflowUtils.addStateStep(installWorkflow, serviceNode.getId(), STARTING);
NodeActivityStep startStep = WorkflowUtils.addOperationStep(installWorkflow, serviceNode.getId(), STANDARD, START);
NodeActivityStep startedStep = WorkflowUtils.addStateStep(installWorkflow, serviceNode.getId(), STARTED);
// Re-wire the workflow
creatingStep.setPrecedingSteps(stepEntry.getValue().getPrecedingSteps());
for (String precederId : safe(creatingStep.getPrecedingSteps())) {
AbstractStep preceder = installWorkflow.getSteps().get(precederId);
preceder.getFollowingSteps().remove(stepEntry.getKey());
preceder.getFollowingSteps().add(creatingStep.getName());
}
creatingStep.setFollowingSteps(Sets.newHashSet(createStep.getName()));
createStep.setPrecedingSteps(Sets.newHashSet(creatingStep.getName()));
createStep.setFollowingSteps(Sets.newHashSet(createdStep.getName()));
createdStep.setPrecedingSteps(Sets.newHashSet(createStep.getName()));
createdStep.setFollowingSteps(Sets.newHashSet(startingStep.getName()));
startingStep.setPrecedingSteps(stepDependencies);
// Inject dependency follower (when node is source)
for (String precederId : startingStep.getPrecedingSteps()) {
AbstractStep preceder = installWorkflow.getSteps().get(precederId);
if (preceder.getFollowingSteps() == null) {
preceder.setFollowingSteps(Sets.newHashSet());
}
preceder.getFollowingSteps().add(startingStep.getName());
}
startingStep.getPrecedingSteps().add(createdStep.getName());
startingStep.setFollowingSteps(Sets.newHashSet(startStep.getName()));
startStep.setPrecedingSteps(Sets.newHashSet(startingStep.getName()));
startStep.setFollowingSteps(Sets.newHashSet(startedStep.getName()));
startedStep.setPrecedingSteps(Sets.newHashSet(startStep.getName()));
startedStep.setFollowingSteps(stepEntry.getValue().getFollowingSteps());
for (String followerId : safe(startedStep.getFollowingSteps())) {
AbstractStep follower = installWorkflow.getSteps().get(followerId);
follower.getPrecedingSteps().remove(stepEntry.getKey());
follower.getPrecedingSteps().add(startedStep.getName());
}
// Remove old step
installWorkflow.getSteps().remove(stepEntry.getKey());
return;
}
}
}
}
private String getStartedStepId(String nodeId, Workflow installWorkflow) {
for (Entry<String, AbstractStep> stepEntry : installWorkflow.getSteps().entrySet()) {
if (stepEntry.getValue() instanceof NodeActivityStep) {
NodeActivityStep nodeActivityStep = ((NodeActivityStep) stepEntry.getValue());
if (nodeId.equals(nodeActivityStep.getNodeId()) && nodeActivityStep.getActivity() instanceof SetStateActivity) {
SetStateActivity setStateActivity = (SetStateActivity) nodeActivityStep.getActivity();
if (CREATED.equals(setStateActivity.getStateName())) {
return stepEntry.getKey();
}
}
}
}
return null;
}
/**
* Replace the delegate operation of the service in the uninstall workflow by a simple:
* stopping -> stop() -> stopped -> deleting -> deleted
*
* @param serviceNode The service node for which to override the delegate operation.
* @param uninstallWorkflow The uninstall workflow in which to perform the override.
*/
public void replaceUnInstallServiceDelegate(PaaSNodeTemplate serviceNode, Workflow uninstallWorkflow) {
// Replace the delegate with the stopping, stop, deleted sequence
for (Entry<String, AbstractStep> stepEntry : uninstallWorkflow.getSteps().entrySet()) {
if (stepEntry.getValue() instanceof NodeActivityStep && serviceNode.getId().equals(((NodeActivityStep) stepEntry.getValue()).getNodeId())) {
NodeActivityStep nodeStep = (NodeActivityStep) stepEntry.getValue();
AbstractActivity activity = nodeStep.getActivity();
if (activity instanceof DelegateWorkflowActivity && UNINSTALL.equals(((DelegateWorkflowActivity) activity).getWorkflowName())) {
NodeActivityStep stoppingStep = WorkflowUtils.addStateStep(uninstallWorkflow, serviceNode.getId(), STOPPING);
NodeActivityStep stopStep = WorkflowUtils.addOperationStep(uninstallWorkflow, serviceNode.getId(), STANDARD, STOP);
NodeActivityStep stoppedStep = WorkflowUtils.addStateStep(uninstallWorkflow, serviceNode.getId(), STOPPED);
NodeActivityStep deletingStep = WorkflowUtils.addStateStep(uninstallWorkflow, serviceNode.getId(), DELETING);
NodeActivityStep deletedStep = WorkflowUtils.addStateStep(uninstallWorkflow, serviceNode.getId(), DELETED);
// Re-wire the workflow
stoppingStep.setPrecedingSteps(stepEntry.getValue().getPrecedingSteps());
for (String precederId : safe(stoppingStep.getPrecedingSteps())) {
AbstractStep preceder = uninstallWorkflow.getSteps().get(precederId);
preceder.getFollowingSteps().remove(stepEntry.getKey());
preceder.getFollowingSteps().add(stoppingStep.getName());
}
stoppingStep.setFollowingSteps(Sets.newHashSet(stopStep.getName()));
stopStep.setPrecedingSteps(Sets.newHashSet(stoppingStep.getName()));
stopStep.setFollowingSteps(Sets.newHashSet(stoppedStep.getName()));
stoppedStep.setPrecedingSteps(Sets.newHashSet(stopStep.getName()));
stoppedStep.setFollowingSteps(Sets.newHashSet(deletingStep.getName()));
deletingStep.setPrecedingSteps(Sets.newHashSet(stoppedStep.getName()));
deletingStep.setFollowingSteps(Sets.newHashSet(deletedStep.getName()));
deletedStep.setPrecedingSteps(Sets.newHashSet(deletingStep.getName()));
deletedStep.setFollowingSteps(stepEntry.getValue().getFollowingSteps());
for (String followerId : safe(deletedStep.getFollowingSteps())) {
AbstractStep follower = uninstallWorkflow.getSteps().get(followerId);
follower.getPrecedingSteps().remove(stepEntry.getKey());
follower.getPrecedingSteps().add(deletedStep.getName());
}
// Remove old step
uninstallWorkflow.getSteps().remove(stepEntry.getKey());
return;
}
}
}
}
} |
package ch.openech.frontend.estate;
import static ch.openech.model.estate.PlanningPermissionApplication.$;
import java.util.List;
import org.minimalj.backend.Backend;
import org.minimalj.frontend.Frontend;
import org.minimalj.frontend.action.Action;
import org.minimalj.frontend.action.ActionGroup;
import org.minimalj.frontend.form.Form;
import org.minimalj.frontend.page.HtmlPage;
import org.minimalj.frontend.page.TablePage.SimpleTablePageWithDetail;
import org.minimalj.repository.query.By;
import org.minimalj.util.StringUtils;
import ch.openech.model.estate.PlanningPermissionApplication;
import ch.openech.model.estate.PlanningPermissionApplicationEvent.SubmitPlanningPermissionApplication;
import ch.openech.model.estate.PlanningPermissionApplicationEvent.SubmitPlanningPermissionApplication.SubmitEventType;
import ch.openech.xml.write.EchSchema;
import ch.openech.xml.write.WriterEch0211;
public class PlanningPermissionApplicationTablePage extends SimpleTablePageWithDetail<PlanningPermissionApplication> {
public static final Object[] COLUMNS = new Object[] {
$.applicationType,
$.description,
$.locationAddress.street, $.locationAddress.houseNumber.houseNumber,
$.locationAddress.locality
};
public PlanningPermissionApplicationTablePage() {
super(COLUMNS);
}
// @Override
// public List<Action> getActions() {
// return actionGroup.getItems();
// @Override
// for (Action action : actionGroup.getItems()) {
@Override
protected Form<PlanningPermissionApplication> createForm(boolean editable) {
return new PlanningPermissionApplicationForm(editable);
}
@Override
protected List<PlanningPermissionApplication> load() {
return Backend.find(PlanningPermissionApplication.class, By.ALL);
}
@Override
protected DetailPage createDetailPage(PlanningPermissionApplication detail) {
return new PlanningPermissionApplicationPage(detail);
}
public class PlanningPermissionApplicationPage extends DetailPage {
private ActionGroup actionGroup;
public PlanningPermissionApplicationPage(PlanningPermissionApplication detail) {
super(detail);
actionGroup = new ActionGroup(null);
actionGroup.add(new DetailPageEditor());
actionGroup.addSeparator();
actionGroup.add(new SubmitPlanningPermissionApplicationEditor(detail));
}
@Override
public List<Action> getActions() {
return actionGroup.getItems();
}
}
// TODO remove
public class SubmitPlanningPermissionApplicationEditor extends Action {
private final PlanningPermissionApplication application;
public SubmitPlanningPermissionApplicationEditor(PlanningPermissionApplication application) {
this.application = application;
}
@Override
public void action() {
EchSchema schema = EchSchema.getNamespaceContext(211, "1.0");
WriterEch0211 writer = new WriterEch0211(schema);
String result;
try {
SubmitPlanningPermissionApplication object = new SubmitPlanningPermissionApplication();
object.eventType = SubmitEventType.submit;
object.planningPermissionApplication = application;
result = "<html><pre>" + StringUtils.escapeHTML(writer.submitPlanningPermissionApplication(object)) + "</pre></html>";
// result = writer.result();
} catch (Exception e) {
result = e.getMessage();
e.printStackTrace();
}
HtmlPage page = new HtmlPage(result, "Xml - Output");
Frontend.show(page);
}
}
} |
package fi.aalto.tripchain;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;
import org.json.JSONObject;
import com.google.android.gms.auth.GoogleAuthException;
import com.google.android.gms.auth.GoogleAuthUtil;
import com.google.android.gms.auth.UserRecoverableAuthException;
import com.google.android.gms.common.Scopes;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
public class LoginActivity extends Activity {
private static final String TAG = LoginActivity.class.getSimpleName();
private static final String SCOPE = Scopes.PROFILE;
private SharedPreferences preferences;
private static final int AUTHORIZATION_CODE = 1993;
private static final int ACCOUNT_CODE = 1601;
private volatile String accountName = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
preferences = getSharedPreferences(Configuration.SHARED_PREFERENCES,
MODE_MULTI_PROCESS);
String loginId = preferences.getString(Configuration.KEY_LOGIN_ID, null);
if (loginId != null) {
startMain();
return;
}
setContentView(R.layout.activity_login);
findViewById(R.id.sign_in_button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
chooseAccount(v);
}
});
}
public void chooseAccount(View _) {
Intent intent = AccountManager.newChooseAccountIntent(null, null,
new String[] { "com.google" }, false, null, null, null, null);
startActivityForResult(intent, ACCOUNT_CODE);
}
private void getUserId() {
final ProgressDialog dialog = ProgressDialog.show(this, "",
"Loading. Please wait...", true);
new AsyncTask<Void, Void, Boolean>() {
protected Boolean doInBackground(Void... _) {
try {
String token = GoogleAuthUtil.getToken(LoginActivity.this,
accountName, "oauth2:" + SCOPE);
URL url = new URL(
"https:
HttpURLConnection con = (HttpURLConnection) url
.openConnection();
int serverCode = con.getResponseCode();
// successful query
if (serverCode == 200) {
InputStream is = con.getInputStream();
String message = new Scanner(is, "UTF-8").useDelimiter(
"\\A").next();
JSONObject j = new JSONObject(message);
is.close();
Editor editor = preferences.edit();
editor.putString(Configuration.KEY_LOGIN_ID, j.getString("id"));
editor.commit();
GoogleAuthUtil.invalidateToken(LoginActivity.this, token);
return true;
// bad token, invalidate and get a new one
} else if (serverCode == 401) {
GoogleAuthUtil.invalidateToken(LoginActivity.this, token);
Log.e(TAG,
"Server auth error: "
+ new Scanner(con.getErrorStream(),
"UTF-8").useDelimiter("\\A")
.next());
// unknown error, do something else
} else {
Log.e(TAG, "Server returned the following error code: "
+ serverCode, null);
}
} catch (UserRecoverableAuthException e) {
startActivityForResult(e.getIntent(), AUTHORIZATION_CODE);
} catch (Exception e) {
Log.d(TAG, "failed to get user id", e);
}
return false;
}
protected void onPostExecute(Boolean success) {
Log.d(TAG, "Cancelling dialog.");
dialog.cancel();
if (success) {
Toast.makeText(LoginActivity.this,
"USER: " + preferences.getString(Configuration.KEY_LOGIN_ID, null),
Toast.LENGTH_SHORT).show();
startMain();
}
}
}.execute();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
Log.d(TAG, "onActivityResult");
if (resultCode != RESULT_OK) {
return;
}
if (requestCode == AUTHORIZATION_CODE) {
Log.d(TAG, "AUTHORIZATION_CODE");
} else if (requestCode == ACCOUNT_CODE) {
accountName = data
.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
Log.d(TAG, "ACCOUNT_CODE " + accountName);
}
getUserId();
}
private void startMain() {
Intent i = new Intent(getApplicationContext(), MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
finish();
}
} |
package org.jboss.as.server;
import static java.security.AccessController.doPrivileged;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.jboss.as.controller.AbstractControllerService;
import org.jboss.as.controller.BootContext;
import org.jboss.as.controller.ControlledProcessState;
import org.jboss.as.controller.ModelControllerServiceInitialization;
import org.jboss.as.controller.OperationStepHandler;
import org.jboss.as.controller.PathElement;
import org.jboss.as.controller.ProcessType;
import org.jboss.as.controller.ResourceDefinition;
import org.jboss.as.controller.RunningModeControl;
import org.jboss.as.controller.audit.ManagedAuditLogger;
import org.jboss.as.controller.descriptions.DescriptionProvider;
import org.jboss.as.controller.descriptions.ModelDescriptionConstants;
import org.jboss.as.controller.persistence.ConfigurationPersistenceException;
import org.jboss.as.controller.persistence.ExtensibleConfigurationPersister;
import org.jboss.as.controller.registry.ImmutableManagementResourceRegistration;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.as.controller.registry.Resource;
import org.jboss.as.controller.services.path.PathManager;
import org.jboss.as.controller.services.path.PathManagerService;
import org.jboss.as.domain.management.access.AccessAuthorizationResourceDefinition;
import org.jboss.as.platform.mbean.PlatformMBeanConstants;
import org.jboss.as.platform.mbean.RootPlatformMBeanResource;
import org.jboss.as.remoting.HttpListenerRegistryService;
import org.jboss.as.remoting.management.ManagementRemotingServices;
import org.jboss.as.repository.ContentRepository;
import org.jboss.as.server.controller.resources.ServerRootResourceDefinition;
import org.jboss.as.server.controller.resources.VersionModelInitializer;
import org.jboss.as.server.deployment.Attachments;
import org.jboss.as.server.deployment.ContentOverrideDeploymentUnitProcessor;
import org.jboss.as.server.deployment.DeploymentCompleteServiceProcessor;
import org.jboss.as.server.deployment.DeploymentMountProvider;
import org.jboss.as.server.deployment.DeploymentPhaseContext;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.DeploymentUnitProcessor;
import org.jboss.as.server.deployment.Phase;
import org.jboss.as.server.deployment.ServiceLoaderProcessor;
import org.jboss.as.server.deployment.SubDeploymentProcessor;
import org.jboss.as.server.deployment.annotation.AnnotationIndexProcessor;
import org.jboss.as.server.deployment.annotation.CleanupAnnotationIndexProcessor;
import org.jboss.as.server.deployment.annotation.CompositeIndexProcessor;
import org.jboss.as.server.deployment.dependencies.DeploymentDependenciesProcessor;
import org.jboss.as.server.deployment.integration.Seam2Processor;
import org.jboss.as.server.deployment.jbossallxml.JBossAllXMLParsingProcessor;
import org.jboss.as.server.deployment.module.ClassFileTransformerProcessor;
import org.jboss.as.server.deployment.module.DeploymentRootExplodedMountProcessor;
import org.jboss.as.server.deployment.module.DeploymentRootMountProcessor;
import org.jboss.as.server.deployment.module.DeploymentVisibilityProcessor;
import org.jboss.as.server.deployment.module.DriverDependenciesProcessor;
import org.jboss.as.server.deployment.module.ManifestAttachmentProcessor;
import org.jboss.as.server.deployment.module.ManifestClassPathProcessor;
import org.jboss.as.server.deployment.module.ManifestDependencyProcessor;
import org.jboss.as.server.deployment.module.ManifestExtensionListProcessor;
import org.jboss.as.server.deployment.module.ManifestExtensionNameProcessor;
import org.jboss.as.server.deployment.module.ModuleClassPathProcessor;
import org.jboss.as.server.deployment.module.ModuleDependencyProcessor;
import org.jboss.as.server.deployment.module.ModuleExtensionListProcessor;
import org.jboss.as.server.deployment.module.ModuleExtensionNameProcessor;
import org.jboss.as.server.deployment.module.ModuleIdentifierProcessor;
import org.jboss.as.server.deployment.module.ModuleSpecProcessor;
import org.jboss.as.server.deployment.module.ServerDependenciesProcessor;
import org.jboss.as.server.deployment.module.SubDeploymentDependencyProcessor;
import org.jboss.as.server.deployment.module.descriptor.DeploymentStructureDescriptorParser;
import org.jboss.as.server.deployment.reflect.CleanupReflectionIndexProcessor;
import org.jboss.as.server.deployment.reflect.InstallReflectionIndexProcessor;
import org.jboss.as.server.deployment.service.ServiceActivatorDependencyProcessor;
import org.jboss.as.server.deployment.service.ServiceActivatorProcessor;
import org.jboss.as.server.deploymentoverlay.service.DeploymentOverlayIndexService;
import org.jboss.as.server.moduleservice.ExtensionIndexService;
import org.jboss.as.server.moduleservice.ExternalModuleService;
import org.jboss.as.server.moduleservice.ServiceModuleLoader;
import org.jboss.as.server.services.security.AbstractVaultReader;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.Service;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.jboss.threads.JBossThreadFactory;
import org.wildfly.security.manager.GetAccessControlContextAction;
import org.wildfly.security.manager.WildFlySecurityManager;
/**
* Service for the {@link org.jboss.as.controller.ModelController} for an AS server instance.
*
* @author <a href="mailto:david.lloyd@redhat.com">David M. Lloyd</a>
*/
public final class ServerService extends AbstractControllerService {
private final InjectedValue<DeploymentMountProvider> injectedDeploymentRepository = new InjectedValue<DeploymentMountProvider>();
private final InjectedValue<ContentRepository> injectedContentRepository = new InjectedValue<ContentRepository>();
private final InjectedValue<ServiceModuleLoader> injectedModuleLoader = new InjectedValue<ServiceModuleLoader>();
private final InjectedValue<ExternalModuleService> injectedExternalModuleService = new InjectedValue<ExternalModuleService>();
private final InjectedValue<PathManager> injectedPathManagerService = new InjectedValue<PathManager>();
private final Bootstrap.Configuration configuration;
private final BootstrapListener bootstrapListener;
private final ControlledProcessState processState;
private final RunningModeControl runningModeControl;
private volatile ExtensibleConfigurationPersister extensibleConfigurationPersister;
private final AbstractVaultReader vaultReader;
private final DelegatingResourceDefinition rootResourceDefinition;
public static final String SERVER_NAME = "server";
/**
* Construct a new instance.
*
* @param configuration the bootstrap configuration
* @param prepareStep the prepare step to use
*/
private ServerService(final Bootstrap.Configuration configuration, final ControlledProcessState processState,
final OperationStepHandler prepareStep, final BootstrapListener bootstrapListener, final DelegatingResourceDefinition rootResourceDefinition,
final RunningModeControl runningModeControl, final AbstractVaultReader vaultReader, final ManagedAuditLogger auditLogger) {
super(getProcessType(configuration.getServerEnvironment()), runningModeControl, null, processState,
rootResourceDefinition, prepareStep, new RuntimeExpressionResolver(vaultReader), auditLogger);
this.configuration = configuration;
this.bootstrapListener = bootstrapListener;
this.processState = processState;
this.runningModeControl = runningModeControl;
this.vaultReader = vaultReader;
this.rootResourceDefinition = rootResourceDefinition;
}
static ProcessType getProcessType(ServerEnvironment serverEnvironment) {
if (serverEnvironment != null) {
switch (serverEnvironment.getLaunchType()) {
case DOMAIN:
return ProcessType.DOMAIN_SERVER;
case STANDALONE:
return ProcessType.STANDALONE_SERVER;
case EMBEDDED:
return ProcessType.EMBEDDED_SERVER;
case APPCLIENT:
return ProcessType.APPLICATION_CLIENT;
}
}
return ProcessType.EMBEDDED_SERVER;
}
/**
* Add this service to the given service target.
*
* @param serviceTarget the service target
* @param configuration the bootstrap configuration
*/
public static void addService(final ServiceTarget serviceTarget, final Bootstrap.Configuration configuration,
final ControlledProcessState processState, final BootstrapListener bootstrapListener,
final RunningModeControl runningModeControl, final AbstractVaultReader vaultReader, final ManagedAuditLogger auditLogger) {
final ThreadGroup threadGroup = new ThreadGroup("ServerService ThreadGroup");
final String namePattern = "ServerService Thread Pool
final ThreadFactory threadFactory = new JBossThreadFactory(threadGroup, Boolean.FALSE, null, namePattern, null, null, doPrivileged(GetAccessControlContextAction.getInstance()));
// TODO determine why QueuelessThreadPoolService makes boot take > 35 secs
// final QueuelessThreadPoolService serverExecutorService = new QueuelessThreadPoolService(Integer.MAX_VALUE, false, new TimeSpec(TimeUnit.SECONDS, 5));
// serverExecutorService.getThreadFactoryInjector().inject(threadFactory);
final ServerExecutorService serverExecutorService = new ServerExecutorService(threadFactory);
serviceTarget.addService(Services.JBOSS_SERVER_EXECUTOR, serverExecutorService)
.addAliases(ManagementRemotingServices.SHUTDOWN_EXECUTOR_NAME) // Use this executor for mgmt shutdown for now
.install();
DelegatingResourceDefinition rootResourceDefinition = new DelegatingResourceDefinition();
ServerService service = new ServerService(configuration, processState, null, bootstrapListener, rootResourceDefinition, runningModeControl, vaultReader, auditLogger);
ServiceBuilder<?> serviceBuilder = serviceTarget.addService(Services.JBOSS_SERVER_CONTROLLER, service);
serviceBuilder.addDependency(DeploymentMountProvider.SERVICE_NAME,DeploymentMountProvider.class, service.injectedDeploymentRepository);
serviceBuilder.addDependency(ContentRepository.SERVICE_NAME, ContentRepository.class, service.injectedContentRepository);
serviceBuilder.addDependency(Services.JBOSS_SERVICE_MODULE_LOADER, ServiceModuleLoader.class, service.injectedModuleLoader);
serviceBuilder.addDependency(Services.JBOSS_EXTERNAL_MODULE_SERVICE, ExternalModuleService.class,
service.injectedExternalModuleService);
serviceBuilder.addDependency(PathManagerService.SERVICE_NAME, PathManager.class, service.injectedPathManagerService);
if (configuration.getServerEnvironment().isAllowModelControllerExecutor()) {
serviceBuilder.addDependency(Services.JBOSS_SERVER_EXECUTOR, ExecutorService.class, service.getExecutorServiceInjector());
}
serviceBuilder.install();
}
public synchronized void start(final StartContext context) throws StartException {
ServerEnvironment serverEnvironment = configuration.getServerEnvironment();
if (runningModeControl.isReloaded()) {
}
Bootstrap.ConfigurationPersisterFactory configurationPersisterFactory = configuration.getConfigurationPersisterFactory();
extensibleConfigurationPersister = configurationPersisterFactory.createConfigurationPersister(serverEnvironment, getExecutorServiceInjector().getOptionalValue());
setConfigurationPersister(extensibleConfigurationPersister);
rootResourceDefinition.setDelegate(
new ServerRootResourceDefinition(injectedContentRepository.getValue(),
extensibleConfigurationPersister, configuration.getServerEnvironment(), processState,
runningModeControl, vaultReader, configuration.getExtensionRegistry(),
getExecutorServiceInjector().getOptionalValue() != null,
(PathManagerService)injectedPathManagerService.getValue(),
new DomainServerCommunicationServices.OperationIDUpdater() {
@Override
public void updateOperationID(final int operationID) {
DomainServerCommunicationServices.updateOperationID(operationID);
}
},
authorizer,
super.getAuditLogger()));
super.start(context);
}
protected void boot(final BootContext context) throws ConfigurationPersistenceException {
boolean ok;
try {
final ServerEnvironment serverEnvironment = configuration.getServerEnvironment();
final ServiceTarget serviceTarget = context.getServiceTarget();
final File[] extDirs = serverEnvironment.getJavaExtDirs();
final File[] newExtDirs = Arrays.copyOf(extDirs, extDirs.length + 1);
newExtDirs[extDirs.length] = new File(serverEnvironment.getServerBaseDir(), "lib/ext");
serviceTarget.addService(org.jboss.as.server.deployment.Services.JBOSS_DEPLOYMENT_EXTENSION_INDEX,
new ExtensionIndexService(newExtDirs)).setInitialMode(ServiceController.Mode.ON_DEMAND).install();
// Initialize controller extensions
runPerformControllerInitialization(context);
final DeploymentOverlayIndexService deploymentOverlayIndexService = new DeploymentOverlayIndexService();
context.getServiceTarget().addService(DeploymentOverlayIndexService.SERVICE_NAME, deploymentOverlayIndexService).install();
// Activate module loader
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.STRUCTURE, Phase.STRUCTURE_SERVICE_MODULE_LOADER, new DeploymentUnitProcessor() {
@Override
public void deploy(DeploymentPhaseContext phaseContext) throws DeploymentUnitProcessingException {
phaseContext.getDeploymentUnit().putAttachment(Attachments.SERVICE_MODULE_LOADER, injectedModuleLoader.getValue());
phaseContext.getDeploymentUnit().putAttachment(Attachments.EXTERNAL_MODULE_SERVICE, injectedExternalModuleService.getValue());
}
@Override
public void undeploy(DeploymentUnit context) {
context.removeAttachment(Attachments.SERVICE_MODULE_LOADER);
}
});
HttpListenerRegistryService.install(serviceTarget);
// Activate core processors for jar deployment
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.STRUCTURE, Phase.STRUCTURE_EXPLODED_MOUNT, new DeploymentRootExplodedMountProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.STRUCTURE, Phase.STRUCTURE_MOUNT, new DeploymentRootMountProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.STRUCTURE, Phase.STRUCTURE_MANIFEST, new ManifestAttachmentProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.STRUCTURE, Phase.STRUCTURE_ADDITIONAL_MANIFEST, new ManifestAttachmentProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.STRUCTURE, Phase.STRUCTURE_CONTENT_OVERRIDE, new ContentOverrideDeploymentUnitProcessor(deploymentOverlayIndexService));
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.STRUCTURE, Phase.STRUCTURE_SUB_DEPLOYMENT, new SubDeploymentProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.STRUCTURE, Phase.STRUCTURE_MODULE_IDENTIFIERS, new ModuleIdentifierProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.STRUCTURE, Phase.STRUCTURE_ANNOTATION_INDEX, new AnnotationIndexProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.STRUCTURE, Phase.STRUCTURE_PARSE_JBOSS_ALL_XML, new JBossAllXMLParsingProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.STRUCTURE, Phase.STRUCTURE_JBOSS_DEPLOYMENT_STRUCTURE, new DeploymentStructureDescriptorParser());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.STRUCTURE, Phase.STRUCTURE_CLASS_PATH, new ManifestClassPathProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.STRUCTURE, Phase.STRUCTURE_DEPLOYMENT_DEPENDENCIES, new DeploymentDependenciesProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.PARSE, Phase.PARSE_DEPENDENCIES_MANIFEST, new ManifestDependencyProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.PARSE, Phase.PARSE_COMPOSITE_ANNOTATION_INDEX, new CompositeIndexProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.PARSE, Phase.PARSE_EXTENSION_LIST, new ManifestExtensionListProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.PARSE, Phase.PARSE_EXTENSION_NAME, new ManifestExtensionNameProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.PARSE, Phase.PARSE_SERVICE_LOADER_DEPLOYMENT, new ServiceLoaderProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_MODULE, new ModuleDependencyProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_SAR_MODULE, new ServiceActivatorDependencyProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_CLASS_PATH, new ModuleClassPathProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_EXTENSION_LIST, new ModuleExtensionListProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_SUB_DEPLOYMENTS, new SubDeploymentDependencyProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_JDK, new ServerDependenciesProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_VISIBLE_MODULES, new DeploymentVisibilityProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_DRIVERS, new DriverDependenciesProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.CONFIGURE_MODULE, Phase.CONFIGURE_MODULE_SPEC, new ModuleSpecProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.POST_MODULE, Phase.POST_MODULE_INSTALL_EXTENSION, new ModuleExtensionNameProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.POST_MODULE, Phase.POST_MODULE_REFLECTION_INDEX, new InstallReflectionIndexProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.FIRST_MODULE_USE, Phase.FIRST_MODULE_USE_TRANSFORMER, new ClassFileTransformerProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.INSTALL, Phase.INSTALL_SERVICE_ACTIVATOR, new ServiceActivatorProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.INSTALL, Phase.INSTALL_DEPLOYMENT_COMPLETE_SERVICE, new DeploymentCompleteServiceProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.CLEANUP, Phase.CLEANUP_REFLECTION_INDEX, new CleanupReflectionIndexProcessor());
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.CLEANUP, Phase.CLEANUP_ANNOTATION_INDEX, new CleanupAnnotationIndexProcessor());
// Ext integration deployers
DeployerChainAddHandler.addDeploymentProcessor(SERVER_NAME, Phase.DEPENDENCIES, Phase.DEPENDENCIES_SEAM, new Seam2Processor(serviceTarget));
//jboss.xml parsers
DeploymentStructureDescriptorParser.registerJBossXMLParsers();
DeploymentDependenciesProcessor.registerJBossXMLParsers();
try {
// Boot but by default don't rollback on runtime failures
// TODO replace system property used by tests with something properly configurable for general use
// TODO search for uses of "jboss.unsupported.fail-boot-on-runtime-failure" in tests before changing this!!
boolean failOnRuntime = Boolean.valueOf(WildFlySecurityManager.getPropertyPrivileged("jboss.unsupported.fail-boot-on-runtime-failure", "false"));
ok = boot(extensibleConfigurationPersister.load(), failOnRuntime);
if (ok) {
finishBoot();
}
} finally {
DeployerChainAddHandler.INSTANCE.clearDeployerMap();
}
} catch (Exception e) {
ServerLogger.ROOT_LOGGER.caughtExceptionDuringBoot(e);
ok = false;
}
if (ok) {
// Trigger the started message
bootstrapListener.printBootStatistics();
} else {
// Die!
ServerLogger.ROOT_LOGGER.unsuccessfulBoot();
System.exit(1);
}
}
protected boolean boot(List<ModelNode> bootOperations, boolean rollbackOnRuntimeFailure) throws ConfigurationPersistenceException {
final List<ModelNode> operations = new ArrayList<ModelNode>(bootOperations);
operations.add(DeployerChainAddHandler.OPERATION);
return super.boot(operations, rollbackOnRuntimeFailure);
}
public void stop(final StopContext context) {
super.stop(context);
configuration.getExtensionRegistry().clear();
configuration.getServerEnvironment().resetProvidedProperties();
}
@Override
protected void initModel(Resource rootResource, ManagementResourceRegistration rootRegistration) {
// TODO maybe make creating of empty nodes part of the MNR description
Resource managementResource = Resource.Factory.create(); // TODO - Can we get a Resource direct from CoreManagementResourceDefinition?
rootResource.registerChild(PathElement.pathElement(ModelDescriptionConstants.CORE_SERVICE, ModelDescriptionConstants.MANAGEMENT), managementResource);
rootResource.registerChild(PathElement.pathElement(ModelDescriptionConstants.CORE_SERVICE, ModelDescriptionConstants.SERVICE_CONTAINER), Resource.Factory.create());
rootResource.registerChild(PathElement.pathElement(ModelDescriptionConstants.CORE_SERVICE, ModelDescriptionConstants.MODULE_LOADING), Resource.Factory.create());
managementResource.registerChild(PathElement.pathElement(ModelDescriptionConstants.ACCESS, ModelDescriptionConstants.AUTHORIZATION), AccessAuthorizationResourceDefinition.RESOURCE);
rootResource.registerChild(ServerEnvironmentResourceDescription.RESOURCE_PATH, Resource.Factory.create());
((PathManagerService)injectedPathManagerService.getValue()).addPathManagerResources(rootResource);
VersionModelInitializer.registerRootResource(rootResource, configuration.getServerEnvironment() != null ? configuration.getServerEnvironment().getProductConfig() : null);
// Platform MBeans
rootResource.registerChild(PlatformMBeanConstants.ROOT_PATH, new RootPlatformMBeanResource());
}
@Override
protected void performControllerInitialization(ServiceTarget target, Resource rootResource, ManagementResourceRegistration rootRegistration) {
final ServiceLoader<ModelControllerServiceInitialization> sl = ServiceLoader.load(ModelControllerServiceInitialization.class);
final Iterator<ModelControllerServiceInitialization> iterator = sl.iterator();
while(iterator.hasNext()) {
final ModelControllerServiceInitialization init = iterator.next();
init.initializeStandalone(target, rootRegistration, rootResource);
}
}
/** Temporary replacement for QueuelessThreadPoolService */
private static class ServerExecutorService implements Service<ExecutorService> {
private final ThreadFactory threadFactory;
private ExecutorService executorService;
private ServerExecutorService(ThreadFactory threadFactory) {
this.threadFactory = threadFactory;
}
@Override
public synchronized void start(StartContext context) throws StartException {
executorService = new ThreadPoolExecutor(0, Integer.MAX_VALUE, 20L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), threadFactory);
}
@Override
public synchronized void stop(final StopContext context) {
if (executorService != null) {
context.asynchronous();
Thread executorShutdown = new Thread(new Runnable() {
@Override
public void run() {
try {
executorService.shutdown();
} finally {
executorService = null;
context.complete();
}
}
}, "ServerExecutorService Shutdown Thread");
executorShutdown.start();
}
}
@Override
public synchronized ExecutorService getValue() throws IllegalStateException, IllegalArgumentException {
return executorService;
}
}
private static class DelegatingResourceDefinition implements ResourceDefinition {
private volatile ResourceDefinition delegate;
void setDelegate(ResourceDefinition delegate) {
this.delegate = delegate;
}
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
delegate.registerOperations(resourceRegistration);
}
@Override
public void registerChildren(ManagementResourceRegistration resourceRegistration) {
delegate.registerChildren(resourceRegistration);
}
@Override
public void registerAttributes(ManagementResourceRegistration resourceRegistration) {
delegate.registerAttributes(resourceRegistration);
}
@Override
public PathElement getPathElement() {
return delegate.getPathElement();
}
@Override
public DescriptionProvider getDescriptionProvider(ImmutableManagementResourceRegistration resourceRegistration) {
return delegate.getDescriptionProvider(resourceRegistration);
}
}
} |
package org.spine3.base;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.protobuf.Any;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Message;
import com.google.protobuf.Timestamp;
import org.spine3.protobuf.AnyPacker;
import org.spine3.protobuf.Timestamps;
import org.spine3.protobuf.TypeUrl;
import org.spine3.users.UserId;
import javax.annotation.Nullable;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.UUID;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Throwables.propagate;
import static org.spine3.protobuf.Timestamps.isBetween;
/**
* Utility class for working with {@link Event} objects.
*
* @author Mikhail Melnik
* @author Alexander Yevsyukov
*/
public class Events {
private Events() {
}
/** Compares two events by their timestamps. */
public static final Comparator<Event> EVENT_TIMESTAMP_COMPARATOR = new Comparator<Event>() {
@Override
public int compare(Event o1, Event o2) {
final Timestamp timestamp1 = getTimestamp(o1);
final Timestamp timestamp2 = getTimestamp(o2);
return Timestamps.compare(timestamp1, timestamp2);
}
};
/** Generates a new random UUID-based {@code EventId}. */
public static EventId generateId() {
final String value = UUID.randomUUID().toString();
return EventId.newBuilder().setUuid(value).build();
}
/**
* Sorts the given event record list by the event timestamps.
*
* @param events the event record list to sort
*/
public static void sort(List<Event> events) {
Collections.sort(events, EVENT_TIMESTAMP_COMPARATOR);
}
/** Obtains the timestamp of the event. */
public static Timestamp getTimestamp(Event event) {
final Timestamp result = event.getContext().getTimestamp();
return result;
}
/** Creates a new {@code Event} instance. */
@SuppressWarnings("OverloadedMethodsWithSameNumberOfParameters")
public static Event createEvent(Message event, EventContext context) {
return createEvent(AnyPacker.pack(event), context);
}
/** Creates a new {@code Event} instance. */
@SuppressWarnings("OverloadedMethodsWithSameNumberOfParameters")
public static Event createEvent(Any eventAny, EventContext context) {
final Event result = Event.newBuilder()
.setMessage(eventAny)
.setContext(context)
.build();
return result;
}
/**
* Creates {@code Event} instance for import or integration operations.
*
* @param event the event message
* @param producerId the ID of an entity which is generating the event
* @return event with data from an external source
*/
public static Event createImportEvent(Message event, Message producerId) {
final EventContext context = createImportEventContext(producerId);
final Event result = createEvent(event, context);
return result;
}
/**
* Extracts the event message from the passed event.
*
* @param event an event to get message from
*/
public static <M extends Message> M getMessage(Event event) {
final Any any = event.getMessage();
final M result = AnyPacker.unpack(any);
return result;
}
/**
* Obtains the actor user ID from the passed {@code EventContext}.
*
* <p>The 'actor' is the user who sent the command, which generated the event which context is
* passed to this method.
*
* <p>This is a convenience method for obtaining actor in event subscriber methods.
*/
public static UserId getActor(EventContext context) {
final CommandContext commandContext = checkNotNull(context).getCommandContext();
return commandContext.getActor();
}
/**
* Obtains event producer ID from the passed {@code EventContext} and casts it to the
* {@code <I>} type.
*
* @param context the event context to to get the event producer ID
* @param <I> the type of the producer ID wrapped in the passed {@code EventContext}
* @return producer ID
*/
public static <I> I getProducer(EventContext context) {
final Object aggregateId = Identifiers.idFromAny(context.getProducerId());
@SuppressWarnings("unchecked") // It is the caller's responsibility to know the type of the wrapped ID.
final I id = (I)aggregateId;
return id;
}
/**
* Creates {@code EventContext} instance for an event generated during data import.
*
* <p>The method does not set {@code CommandContext} because there was no command.
*
* <p>The {@code version} attribute is not populated either. It is the responsiblity of the
* target aggregate to populate the missing fields.
*
* @param producerId the ID of the producer which generates the event
* @return new instance of {@code EventContext} for the imported event
*/
public static EventContext createImportEventContext(Message producerId) {
checkNotNull(producerId);
final EventContext.Builder builder = EventContext.newBuilder()
.setEventId(generateId())
.setTimestamp(Timestamps.getCurrentTime())
.setProducerId(AnyPacker.pack(producerId));
return builder.build();
}
/** The predicate to filter event records after some point in time. */
public static class IsAfter implements Predicate<Event> {
private final Timestamp timestamp;
public IsAfter(Timestamp timestamp) {
this.timestamp = timestamp;
}
@Override
public boolean apply(@Nullable Event record) {
if (record == null) {
return false;
}
final Timestamp ts = getTimestamp(record);
final boolean result = Timestamps.compare(ts, this.timestamp) > 0;
return result;
}
}
/** The predicate to filter event records before some point in time. */
public static class IsBefore implements Predicate<Event> {
private final Timestamp timestamp;
public IsBefore(Timestamp timestamp) {
this.timestamp = timestamp;
}
@Override
public boolean apply(@Nullable Event record) {
if (record == null) {
return false;
}
final Timestamp ts = getTimestamp(record);
final boolean result = Timestamps.compare(ts, this.timestamp) < 0;
return result;
}
}
/** The predicate to filter event records within a given time range. */
public static class IsBetween implements Predicate<Event> {
private final Timestamp start;
private final Timestamp finish;
public IsBetween(Timestamp start, Timestamp finish) {
checkNotNull(start);
checkNotNull(finish);
checkArgument(Timestamps.compare(start, finish) < 0, "`start` must be before `finish`");
this.start = start;
this.finish = finish;
}
@Override
public boolean apply(@Nullable Event event) {
if (event == null) {
return false;
}
final Timestamp ts = getTimestamp(event);
final boolean result = isBetween(ts, start, finish);
return result;
}
}
/** Verifies if the enrichment is not disabled in the passed event. */
public static boolean isEnrichmentEnabled(Event event) {
final EventContext context = event.getContext();
final EventContext.EnrichmentModeCase mode = context.getEnrichmentModeCase();
final boolean isEnabled = mode != EventContext.EnrichmentModeCase.DO_NOT_ENRICH;
return isEnabled;
}
/**
* Returns all enrichments from the context.
*
* @param context a context to get enrichments from
* @return an optional of enrichments
*/
public static Optional<Enrichments> getEnrichments(EventContext context) {
final EventContext.EnrichmentModeCase mode = context.getEnrichmentModeCase();
if (mode == EventContext.EnrichmentModeCase.ENRICHMENTS) {
return Optional.of(context.getEnrichments());
}
return Optional.absent();
}
/**
* Return a specific enrichment from the context.
*
* @param enrichmentClass a class of the event enrichment
* @param context a context to get an enrichment from
* @param <E> a type of the event enrichment
* @return an optional of the enrichment
*/
public static <E extends Message> Optional<E> getEnrichment(Class<E> enrichmentClass, EventContext context) {
final Optional<Enrichments> value = getEnrichments(context);
if (!value.isPresent()) {
return Optional.absent();
}
final Enrichments enrichments = value.get();
final String typeName = TypeUrl.of(enrichmentClass)
.getTypeName();
final Any any = enrichments.getMapMap()
.get(typeName);
if (any == null) {
return Optional.absent();
}
final E result = unpack(enrichmentClass, any);
return Optional.fromNullable(result);
}
//TODO:2016-06-17:alexander.yevsyukov: Evaluate using this function instead of Messages.fromAny() in general.
// The below approach may already work.
private static <T extends Message> T unpack(Class<T> clazz, Any any) {
final T result;
try {
result = any.unpack(clazz);
return result;
} catch (InvalidProtocolBufferException e) {
throw propagate(e);
}
}
} |
package com.minelittlepony.client.render.entities.player;
import com.minelittlepony.client.MineLittlePony;
import com.minelittlepony.client.model.ClientPonyModel;
import com.minelittlepony.client.model.ModelWrapper;
import com.minelittlepony.client.render.DebugBoundingBoxRenderer;
import com.minelittlepony.client.render.IPonyRender;
import com.minelittlepony.client.render.RenderPony;
import com.minelittlepony.client.render.layer.LayerDJPon3Head;
import com.minelittlepony.client.render.layer.LayerEntityOnPonyShoulder;
import com.minelittlepony.client.render.layer.LayerGear;
import com.minelittlepony.client.render.layer.LayerHeldPonyItemMagical;
import com.minelittlepony.client.render.layer.LayerPonyArmor;
import com.minelittlepony.client.render.layer.LayerPonyCape;
import com.minelittlepony.client.render.layer.LayerPonyCustomHead;
import com.minelittlepony.client.render.layer.LayerPonyElytra;
import com.minelittlepony.pony.IPony;
import com.mojang.blaze3d.platform.GlStateManager;
import java.util.List;
import net.minecraft.block.BedBlock;
import net.minecraft.client.MinecraftClient;
import net.minecraft.client.network.AbstractClientPlayerEntity;
import net.minecraft.client.render.VisibleRegion;
import net.minecraft.client.render.entity.EntityRenderDispatcher;
import net.minecraft.client.render.entity.PlayerEntityRenderer;
import net.minecraft.client.render.entity.feature.FeatureRenderer;
import net.minecraft.client.render.entity.feature.StuckArrowsFeatureRenderer;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.util.AbsoluteHand;
import net.minecraft.util.Identifier;
public class RenderPonyPlayer extends PlayerEntityRenderer implements IPonyRender<AbstractClientPlayerEntity, ClientPonyModel<AbstractClientPlayerEntity>> {
protected final RenderPony<AbstractClientPlayerEntity, ClientPonyModel<AbstractClientPlayerEntity>> renderPony = new RenderPony<>(this);
public RenderPonyPlayer(EntityRenderDispatcher manager, boolean useSmallArms, ModelWrapper<AbstractClientPlayerEntity, ClientPonyModel<AbstractClientPlayerEntity>> model) {
super(manager, useSmallArms);
this.model = renderPony.setPonyModel(model);
addLayers();
}
protected void addLayers() {
features.clear();
addLayer(new LayerDJPon3Head<>(this));
addLayer(new LayerPonyArmor<>(this));
addFeature(new StuckArrowsFeatureRenderer<>(this));
addLayer(new LayerPonyCustomHead<>(this));
addLayer(new LayerPonyElytra<>(this));
addLayer(new LayerHeldPonyItemMagical<>(this));
addLayer(new LayerPonyCape<>(this));
addLayer(new LayerEntityOnPonyShoulder<>(renderManager, this));
addLayer(new LayerGear<>(this));
}
@SuppressWarnings({"unchecked", "rawtypes"})
protected boolean addLayer(FeatureRenderer<AbstractClientPlayerEntity, ? extends ClientPonyModel<AbstractClientPlayerEntity>> feature) {
return ((List)features).add(feature);
}
@Override
public float scaleAndTranslate(AbstractClientPlayerEntity player, float ticks) {
if (!player.hasVehicle() && !player.isSleeping()) {
float x = player.getWidth() / 2 * renderPony.getPony(player).getMetadata().getSize().getScaleFactor();
float y = 0;
if (player.isInSneakingPose()) {
// Sneaking makes the player 1/15th shorter.
// This should be compatible with height-changing mods.
y += player.getHeight() / 15;
}
super.postRender(player, 0, y, x, 0, ticks);
}
return super.scaleAndTranslate(player, ticks);
}
@Override
protected void scale(AbstractClientPlayerEntity player, float ticks) {
renderPony.preRenderCallback(player, ticks);
field_4673 = renderPony.getShadowScale();
if (player.hasVehicle()) {
GlStateManager.translated(0, player.getHeightOffset(), 0);
}
}
@Override
public void render(AbstractClientPlayerEntity entity, double xPosition, double yPosition, double zPosition, float yaw, float ticks) {
super.render(entity, xPosition, yPosition, zPosition, yaw, ticks);
DebugBoundingBoxRenderer.instance.render(renderPony.getPony(entity), entity, ticks);
}
@Override
public boolean isVisible(AbstractClientPlayerEntity entity, VisibleRegion camera, double camX, double camY, double camZ) {
if (entity.isSleeping() && entity == MinecraftClient.getInstance().player) {
return true;
}
return super.isVisible(entity, renderPony.getFrustrum(entity, camera), camX, camY, camZ);
}
@Override
protected void renderLabel(AbstractClientPlayerEntity entity, String name, double x, double y, double z, int maxDistance) {
if (entity.isSleeping()) {
if (entity.getSleepingPosition().isPresent() && entity.getEntityWorld().getBlockState(entity.getSleepingPosition().get()).getBlock() instanceof BedBlock) {
double bedRad = Math.toRadians(entity.getSleepingDirection().asRotation());
x += Math.cos(bedRad);
z -= Math.sin(bedRad);
}
}
super.renderLabel(entity, name, x, renderPony.getNamePlateYOffset(entity, y), z, maxDistance);
}
@Override
public void postRender(Entity player, double x, double y, double z, float yaw, float ticks) {
if (player.hasVehicle() && ((LivingEntity)player).isSleeping()) {
super.postRender(player, x, y, z, yaw, ticks);
}
}
@Override
public final void renderRightArm(AbstractClientPlayerEntity player) {
renderArm(player, AbsoluteHand.RIGHT);
}
@Override
public final void renderLeftArm(AbstractClientPlayerEntity player) {
renderArm(player, AbsoluteHand.LEFT);
}
protected void renderArm(AbstractClientPlayerEntity player, AbsoluteHand side) {
renderPony.updateModel(player);
bindEntityTexture(player);
GlStateManager.pushMatrix();
float reflect = side == AbsoluteHand.LEFT ? 1 : -1;
GlStateManager.translatef(reflect * -0.1F, -0.74F, 0);
if (side == AbsoluteHand.LEFT) {
super.renderLeftArm(player);
} else {
super.renderRightArm(player);
}
GlStateManager.popMatrix();
}
@Override
protected void setupTransforms(AbstractClientPlayerEntity player, float age, float yaw, float ticks) {
yaw = renderPony.getRenderYaw(player, yaw, ticks);
super.setupTransforms(player, age, yaw, ticks);
renderPony.applyPostureTransform(player, yaw, ticks);
}
@Override
public Identifier getTexture(AbstractClientPlayerEntity player) {
return renderPony.getPony(player).getTexture();
}
@Override
public ModelWrapper<AbstractClientPlayerEntity, ClientPonyModel<AbstractClientPlayerEntity>> getModelWrapper() {
return renderPony.playerModel;
}
@Override
public RenderPony<AbstractClientPlayerEntity, ClientPonyModel<AbstractClientPlayerEntity>> getInternalRenderer() {
return renderPony;
}
@Override
public Identifier findTexture(AbstractClientPlayerEntity entity) {
return getTexture(entity);
}
@Override
public IPony getEntityPony(AbstractClientPlayerEntity entity) {
return MineLittlePony.getInstance().getManager().getPony(entity);
}
} |
// ImarisHDFReader.java
package loci.formats.in;
import java.io.*;
import java.util.*;
import loci.formats.*;
public class ImarisHDFReader extends FormatReader {
// -- Constants --
private static final String NO_NETCDF_MSG =
"NetCDF is required to read Imaris 5.5 files. Please obtain " +
"the necessary JAR files from http://loci.wisc.edu/ome/formats.html";
// -- Static fields --
private static boolean noNetCDF = false;
private static ReflectedUniverse r = createReflectedUniverse();
private static ReflectedUniverse createReflectedUniverse() {
r = null;
try {
r = new ReflectedUniverse();
r.exec("import ucar.ma2.Array");
r.exec("import ucar.ma2.ArrayByte");
r.exec("import ucar.nc2.Attribute");
r.exec("import ucar.nc2.Group");
r.exec("import ucar.nc2.NetcdfFile");
}
catch (ReflectException exc) {
noNetCDF = true;
if (debug) LogTools.trace(exc);
}
return r;
}
// -- Fields --
private byte[][][] previousImage;
private int previousImageNumber;
private Vector channelParameters;
// -- Constructor --
/** Constructs a new Imaris HDF reader. */
public ImarisHDFReader() { super("Imaris 5.5 (HDF)", "ims"); }
// -- IFormatReader API methods --
/* @see loci.formats.IFormatReader#isThisType(byte[]) */
public boolean isThisType(byte[] block) {
return new String(block).indexOf("HDF") != -1;
}
/* @see loci.formats.IFormatReader#openBytes(int, byte[]) */
public byte[] openBytes(int no, byte[] buf)
throws FormatException, IOException
{
FormatTools.assertId(currentId, true, 1);
FormatTools.checkPlaneNumber(this, no);
FormatTools.checkBufferSize(this, buf.length);
int[] zct = FormatTools.getZCTCoords(this, no);
int[] oldZCT = previousImageNumber == -1 ? new int[] {-1, -1, -1} :
FormatTools.getZCTCoords(this, previousImageNumber);
if (zct[1] != oldZCT[1] || zct[2] != oldZCT[2]) {
try {
r.exec("ncfile = NetcdfFile.open(currentId)");
r.exec("g = ncfile.getRootGroup()");
findGroup("DataSet", "g", "g");
findGroup("ResolutionLevel_0", "g", "g");
findGroup("TimePoint_" + zct[2], "g", "g");
findGroup("Channel_" + zct[1], "g", "g");
r.setVar("name", "Data");
r.exec("var = g.findVariable(name)");
r.exec("pixelData = var.read()");
r.exec("data = pixelData.copyToNDJavaArray()");
previousImage = (byte[][][]) r.getVar("data");
}
catch (ReflectException exc) {
if (debug) LogTools.trace(exc);
return null;
}
}
previousImageNumber = no;
for (int y=0; y<core.sizeY[0]; y++) {
System.arraycopy(previousImage[zct[0]][y], 0, buf, y*core.sizeX[0],
core.sizeX[0]);
}
return buf;
}
// -- IFormatHandler API methods --
/* @see loci.formats.IFormatHandler#isThisType(String, boolean) */
public boolean isThisType(String name, boolean open) {
if (!super.isThisType(name, open)) return false;
if (!open) return true;
return checkBytes(name, 8);
}
/* @see loci.formats.IFormatReader#close() */
public void close() throws IOException {
super.close();
previousImageNumber = -1;
previousImage = null;
}
// -- Internal FormatReader API methods --
/* @see loci.formats.FormatReader#initFile(String) */
protected void initFile(String id) throws FormatException, IOException {
super.initFile(id);
if (noNetCDF) throw new FormatException(NO_NETCDF_MSG);
previousImageNumber = -1;
MetadataStore store = getMetadataStore();
store.setImage(currentId, null, null, null);
try {
r.setVar("currentId", id);
r.exec("ncfile = NetcdfFile.open(currentId)");
r.exec("root = ncfile.getRootGroup()");
}
catch (ReflectException exc) {
if (debug) LogTools.trace(exc);
}
getValue("root", "ImarisDataSet");
getValue("root", "ImarisVersion");
findGroup("DataSetInfo", "root", "dataSetInfo");
findGroup("DataSet", "root", "dataSet");
channelParameters = new Vector();
try {
List l = new Vector();
l.add(r.getVar("dataSetInfo"));
parseGroups(l);
}
catch (ReflectException exc) {
if (debug) LogTools.trace(exc);
}
core.currentOrder[0] = "XYZCT";
core.rgb[0] = false;
core.thumbSizeX[0] = 128;
core.thumbSizeY[0] = 128;
core.pixelType[0] = FormatTools.UINT8;
core.imageCount[0] = core.sizeZ[0] * core.sizeC[0] * core.sizeT[0];
core.orderCertain[0] = true;
core.littleEndian[0] = true;
core.interleaved[0] = false;
core.indexed[0] = false;
FormatTools.populatePixels(store, this);
for (int i=0; i<core.sizeC[0]; i++) {
String[] params = (String[]) channelParameters.get(i);
Float gainValue = null;
try { gainValue = new Float(params[0]); }
catch (NumberFormatException e) { }
catch (NullPointerException e) { }
Integer pinholeValue = null, emWaveValue = null, exWaveValue = null;
try { pinholeValue = new Integer(params[5]); }
catch (NumberFormatException e) { }
catch (NullPointerException e) { }
try { emWaveValue = new Integer(params[1]); }
catch (NumberFormatException e) { }
catch (NullPointerException e) { }
try { exWaveValue = new Integer(params[2]); }
catch (NumberFormatException e) { }
catch (NullPointerException e) { }
store.setLogicalChannel(i, params[6], null,
null, null, null, null, null, null, null, gainValue, null,
pinholeValue, null, params[7], null, null, null, null,
null, emWaveValue, exWaveValue, null, null, null);
Double minValue = null, maxValue = null;
try { minValue = new Double(params[4]); }
catch (NumberFormatException exc) { }
catch (NullPointerException exc) { }
try { maxValue = new Double(params[3]); }
catch (NumberFormatException exc) { }
catch (NullPointerException exc) { }
if (minValue != null && maxValue != null) {
store.setChannelGlobalMinMax(i, minValue, maxValue, null);
}
}
}
// -- Helper methods --
private String getValue(String group, String name) {
try {
r.setVar("name", name);
r.exec("attribute = " + group + ".findAttribute(name)");
if (r.getVar("attribute") == null) return null;
r.exec("isString = attribute.isString()");
if (!((Boolean) r.getVar("isString")).booleanValue()) return null;
r.exec("array = attribute.getValues()");
r.exec("s = array.copyTo1DJavaArray()");
Object[] s = (Object[]) r.getVar("s");
StringBuffer sb = new StringBuffer();
for (int i=0; i<s.length; i++) {
sb.append((String) s[i]);
}
String st = sb.toString();
if (name.equals("X")) {
core.sizeX[0] = Integer.parseInt(st.trim());
}
else if (name.equals("Y")) {
core.sizeY[0] = Integer.parseInt(st.trim());
}
else if (name.equals("Z")) {
core.sizeZ[0] = Integer.parseInt(st.trim());
}
else if (name.equals("FileTimePoints")) {
core.sizeT[0] = Integer.parseInt(st.trim());
}
else if (name.equals("FileTimePoints")) {
core.sizeT[0] = Integer.parseInt(st.trim());
}
if (st != null) addMeta(name, st);
return st;
}
catch (ReflectException exc) {
if (debug) LogTools.trace(exc);
}
return null;
}
private Object findGroup(String name, String parent, String store) {
try {
r.setVar("name", name);
r.exec(store + " = " + parent + ".findGroup(name)");
return r.getVar(store);
}
catch (ReflectException exc) {
if (debug) LogTools.trace(exc);
}
return null;
}
private void parseGroups(List groups) throws ReflectException {
for (int i=0; i<groups.size(); i++) {
r.setVar("group", groups.get(i));
r.exec("groupName = group.getName()");
String groupName = (String) r.getVar("groupName");
if (debug) LogTools.println("Parsing group: " + groupName);
r.exec("attributes = group.getAttributes()");
List l = (List) r.getVar("attributes");
String[] params = new String[8];
for (int j=0; j<l.size(); j++) {
r.setVar("attr", l.get(j));
r.exec("name = attr.getName()");
String name = (String) r.getVar("name");
String v = getValue("group", (String) r.getVar("name"));
if (groupName.startsWith("Channel_")) {
if (name.equals("Gain")) params[0] = v;
else if (name.equals("LSMEmissionWavelength")) params[1] = v;
else if (name.equals("LSMExcitationWavelength")) params[2] = v;
else if (name.equals("Max")) params[3] = v;
else if (name.equals("Min")) params[4] = v;
else if (name.equals("Pinhole")) params[5] = v;
else if (name.equals("Name")) params[6] = v;
else if (name.equals("MicroscopyMode")) params[7] = v;
}
}
if (groupName.indexOf("/Channel_") != -1) {
for (int j=0; j<6; j++) {
if (params[j] != null) {
if (params[j].indexOf(" ") != -1) {
params[j] = params[j].substring(params[j].indexOf(" ") + 1);
}
if (params[j].indexOf("-") != -1) {
int idx = params[j].indexOf("-");
float a = Float.parseFloat(params[j].substring(0, idx));
float b = Float.parseFloat(params[j].substring(idx + 1));
params[j] = "" + ((int) (b - a));
}
if (params[j].indexOf(".") != -1) {
params[j] = params[j].substring(0, params[j].indexOf("."));
}
}
}
channelParameters.add(params);
core.sizeC[0]++;
}
r.exec("groups = group.getGroups()");
parseGroups((List) r.getVar("groups"));
}
}
} |
package edu.harvard.iq.dataverse.engine.command.impl;
import edu.harvard.iq.dataverse.DataFile;
import edu.harvard.iq.dataverse.Dataset;
import edu.harvard.iq.dataverse.DatasetVersionUser;
import edu.harvard.iq.dataverse.DatasetField;
import edu.harvard.iq.dataverse.DatasetVersionUI;
import edu.harvard.iq.dataverse.RoleAssignment;
import edu.harvard.iq.dataverse.authorization.Permission;
import edu.harvard.iq.dataverse.authorization.users.User;
import edu.harvard.iq.dataverse.engine.command.AbstractCommand;
import edu.harvard.iq.dataverse.engine.command.CommandContext;
import edu.harvard.iq.dataverse.engine.command.RequiredPermissions;
import edu.harvard.iq.dataverse.engine.command.exception.CommandException;
import edu.harvard.iq.dataverse.engine.command.exception.IllegalCommandException;
import edu.harvard.iq.dataverse.settings.SettingsServiceBean;
import java.sql.Timestamp;
import java.util.Date;
import java.util.Iterator;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
/**
* Creates a {@link Dataset} in the passed {@link CommandContext}.
*
* @author michael
*/
@RequiredPermissions(Permission.AddDataset)
public class CreateDatasetCommand extends AbstractCommand<Dataset> {
private static final Logger logger = Logger.getLogger(CreateDatasetCommand.class.getCanonicalName());
private final Dataset theDataset;
private final boolean registrationRequired;
public CreateDatasetCommand(Dataset theDataset, User user) {
super(user, theDataset.getOwner());
this.theDataset = theDataset;
this.registrationRequired = false;
}
public CreateDatasetCommand(Dataset theDataset, User user, boolean registrationRequired) {
super(user, theDataset.getOwner());
this.theDataset = theDataset;
this.registrationRequired = registrationRequired;
}
@Override
public Dataset execute(CommandContext ctxt) throws CommandException {
// Test for duplicate identifier
if (!ctxt.datasets().isUniqueIdentifier(theDataset.getIdentifier(), theDataset.getProtocol(), theDataset.getAuthority(), theDataset.getDoiSeparator()) ) {
throw new IllegalCommandException(String.format("Dataset with identifier '%s', protocol '%s' and authority '%s' already exists",
theDataset.getIdentifier(), theDataset.getProtocol(), theDataset.getAuthority()),
this);
}
// validate
// @todo for now we run through an initFields method that creates empty fields for anything without a value
// that way they can be checked for required
theDataset.getEditVersion().setDatasetFields(theDataset.getEditVersion().initDatasetFields());
Set<ConstraintViolation> constraintViolations = theDataset.getEditVersion().validate();
if (!constraintViolations.isEmpty()) {
String validationFailedString = "Validation failed:";
for (ConstraintViolation constraintViolation : constraintViolations) {
validationFailedString += " " + constraintViolation.getMessage();
}
throw new IllegalCommandException(validationFailedString, this);
}
// FIXME - need to revisit this. Either
// theDataset.setCreator(getUser());
// if, at all, we decide to keep it.
theDataset.setCreateDate(new Timestamp(new Date().getTime()));
Iterator<DatasetField> dsfIt = theDataset.getEditVersion().getDatasetFields().iterator();
while (dsfIt.hasNext()) {
if (dsfIt.next().removeBlankDatasetFieldValues()) {
dsfIt.remove();
}
}
Iterator<DatasetField> dsfItSort = theDataset.getEditVersion().getDatasetFields().iterator();
while (dsfItSort.hasNext()) {
dsfItSort.next().setValueDisplayOrder();
}
Timestamp createDate = new Timestamp(new Date().getTime());
theDataset.getEditVersion().setCreateTime(createDate);
theDataset.getEditVersion().setLastUpdateTime(createDate);
theDataset.setModificationTime(createDate);
for (DataFile dataFile: theDataset.getFiles() ){
dataFile.setCreateDate(theDataset.getCreateDate());
}
String nonNullDefaultIfKeyNotFound = "";
String protocol = ctxt.settings().getValueForKey(SettingsServiceBean.Key.Protocol, nonNullDefaultIfKeyNotFound);
String doiProvider = ctxt.settings().getValueForKey(SettingsServiceBean.Key.DoiProvider, nonNullDefaultIfKeyNotFound);
if (protocol.equals("doi")
&& doiProvider.equals("EZID") && theDataset.getGlobalIdCreateTime() == null) {
String doiRetString = ctxt.doiEZId().createIdentifier(theDataset);
if (doiRetString.contains(theDataset.getIdentifier())) {
theDataset.setGlobalIdCreateTime(createDate);
}
}
if (registrationRequired && theDataset.getGlobalIdCreateTime() == null) {
throw new IllegalCommandException("Dataset could not be created. Registration failed", this);
}
Dataset savedDataset = ctxt.em().merge(theDataset);
// set the role to be default contributor role for its dataverse
ctxt.roles().save(new RoleAssignment(savedDataset.getOwner().getDefaultContributorRole(), getUser(), savedDataset));
try {
// TODO make async
String indexingResult = ctxt.index().indexDataset(savedDataset);
logger.log(Level.INFO, "during dataset save, indexing result was: {0}", indexingResult);
} catch ( RuntimeException e ) {
logger.log(Level.WARNING, "Exception while indexing:" + e.getMessage(), e);
}
DatasetVersionUser datasetVersionDataverseUser = new DatasetVersionUser();
datasetVersionDataverseUser.setUserIdentifier(getUser().getIdentifier());
datasetVersionDataverseUser.setDatasetVersion(savedDataset.getLatestVersion());
datasetVersionDataverseUser.setLastUpdateDate((Timestamp) createDate);
if (savedDataset.getLatestVersion().getId() == null){
logger.warning("CreateDatasetCommand: savedDataset version id is null");
} else {
datasetVersionDataverseUser.setDatasetversionid(savedDataset.getLatestVersion().getId().intValue());
}
ctxt.em().merge(datasetVersionDataverseUser);
return savedDataset;
}
@Override
public int hashCode() {
int hash = 7;
hash = 97 * hash + Objects.hashCode(this.theDataset);
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (!(obj instanceof CreateDatasetCommand)) {
return false;
}
final CreateDatasetCommand other = (CreateDatasetCommand) obj;
return Objects.equals(this.theDataset, other.theDataset);
}
@Override
public String toString() {
return "[DatasetCreate dataset:" + theDataset.getId() + "]";
}
} |
package in.twizmwaz.cardinal.module.modules.invisibleBlock;
import in.twizmwaz.cardinal.GameHandler;
import in.twizmwaz.cardinal.module.Module;
import org.bukkit.Bukkit;
import org.bukkit.Chunk;
import org.bukkit.Material;
import org.bukkit.block.Block;
import org.bukkit.block.BlockFace;
import org.bukkit.event.EventHandler;
import org.bukkit.event.HandlerList;
import org.bukkit.event.world.ChunkLoadEvent;
import org.bukkit.metadata.FixedMetadataValue;
public class InvisibleBlock implements Module {
protected InvisibleBlock() {
Bukkit.getScheduler().runTaskAsynchronously(GameHandler.getGameHandler().getPlugin(), new Runnable() {
@Override
public void run() {
for (Chunk chunk : GameHandler.getGameHandler().getMatchWorld().getLoadedChunks()) {
for (Block block36 : chunk.getBlocks(Material.getMaterial(36))) {
block36.setType(Material.AIR);
block36.setMetadata("block36", new FixedMetadataValue(GameHandler.getGameHandler().getPlugin(), true));
}
for (Block door : chunk.getBlocks(Material.IRON_DOOR_BLOCK)) {
if (door.getRelative(BlockFace.DOWN).getType() != Material.IRON_DOOR_BLOCK
&& door.getRelative(BlockFace.UP).getType() != Material.IRON_DOOR_BLOCK)
door.setType(Material.BARRIER);
}
}
}
});
}
@Override
public void unload() {
HandlerList.unregisterAll(this);
}
@EventHandler
public void onChunkLoad(ChunkLoadEvent event) {
final Chunk chunk = event.getChunk();
Bukkit.getScheduler().runTaskAsynchronously(GameHandler.getGameHandler().getPlugin(), new Runnable() {
@Override
public void run() {
for (Block block36 : chunk.getBlocks(Material.getMaterial(36))) {
block36.setType(Material.AIR);
block36.setMetadata("block36", new FixedMetadataValue(GameHandler.getGameHandler().getPlugin(), true));
}
for (Block door : chunk.getBlocks(Material.IRON_DOOR_BLOCK)) {
if (door.getRelative(BlockFace.DOWN).getType() != Material.IRON_DOOR_BLOCK
&& door.getRelative(BlockFace.UP).getType() != Material.IRON_DOOR_BLOCK)
door.setType(Material.BARRIER);
}
}
});
}
} |
package io.aif.language.token.separator;
import io.aif.language.common.settings.ISettings;
import java.util.List;
import java.util.Optional;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
class PredefinedTokenSeparatorExtractor implements ITokenSeparatorExtractor {
private final List<Character> separators;
PredefinedTokenSeparatorExtractor(ISettings settings) {
this.separators = Stream.of(settings.predefinedSeparators().split(""))
.map(it -> it.charAt(0)).collect(toList());
}
@Override
public Optional<List<Character>> extract(final String txt) {
return Optional.of(separators);
}
} |
package io.github.lukehutch.fastclasspathscanner.scanner;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner;
import io.github.lukehutch.fastclasspathscanner.FastClasspathScanner.ClassMatcher;
import io.github.lukehutch.fastclasspathscanner.classfileparser.ClassInfo;
import io.github.lukehutch.fastclasspathscanner.classfileparser.ClassInfo.ClassInfoUnlinked;
import io.github.lukehutch.fastclasspathscanner.classfileparser.ClassfileBinaryParser;
import io.github.lukehutch.fastclasspathscanner.classgraph.ClassGraphBuilder;
import io.github.lukehutch.fastclasspathscanner.classpath.ClasspathFinder;
import io.github.lukehutch.fastclasspathscanner.matchprocessor.StaticFinalFieldMatchProcessor;
import io.github.lukehutch.fastclasspathscanner.scanner.ScanSpec.ScanSpecPathMatch;
import io.github.lukehutch.fastclasspathscanner.utils.Log;
import io.github.lukehutch.fastclasspathscanner.utils.Log.DeferredLog;
public class RecursiveScanner {
/**
* The number of threads to use for parsing classfiles in parallel. Empirical testing shows that on a modern
* system with an SSD, NUM_THREADS = 5 is a good default. Raising the number of threads too high can actually
* hurt performance due to storage contention.
*/
private final int NUM_THREADS = 5;
/** The classpath finder. */
private final ClasspathFinder classpathFinder;
/** The scanspec (whitelisted and blacklisted packages, etc.). */
private final ScanSpec scanSpec;
/** The class matchers. */
private final ArrayList<ClassMatcher> classMatchers;
/** A map from class name to static final fields to match within the class. */
private final Map<String, HashSet<String>> classNameToStaticFinalFieldsToMatch;
/**
* A map from (className + "." + staticFinalFieldName) to StaticFinalFieldMatchProcessor(s) that should be
* called if that class name and static final field name is encountered with a static constant initializer
* during scan.
*/
private final Map<String, ArrayList<StaticFinalFieldMatchProcessor>>
fullyQualifiedFieldNameToStaticFinalFieldMatchProcessors;
/** A list of file path testers and match processor wrappers to use for file matching. */
private final List<FilePathTesterAndMatchProcessorWrapper> filePathTestersAndMatchProcessorWrappers =
new ArrayList<>();
/**
* The set of absolute directory/zipfile paths scanned (after symlink resolution), to prevent the same resource
* from being scanned twice.
*/
private final Set<String> previouslyScannedCanonicalPaths = new HashSet<>();
/**
* The set of relative file paths scanned (without symlink resolution), to allow for classpath masking of
* resources (only the first resource with a given relative path should be visible within the classpath, as per
* Java conventions).
*/
private final Set<String> previouslyScannedRelativePaths = new HashSet<>();
/** A map from class name to ClassInfo object for the class. */
private final Map<String, ClassInfo> classNameToClassInfo = new HashMap<>();
/** The class graph builder. */
private ClassGraphBuilder classGraphBuilder;
/** The total number of regular directories scanned. */
private final AtomicInteger numDirsScanned = new AtomicInteger();
/** The total number of jarfile-internal directories scanned. */
private final AtomicInteger numJarfileDirsScanned = new AtomicInteger();
/** The total number of regular files scanned. */
private final AtomicInteger numFilesScanned = new AtomicInteger();
/** The total number of jarfile-internal files scanned. */
private final AtomicInteger numJarfileFilesScanned = new AtomicInteger();
/** The total number of jarfiles scanned. */
private final AtomicInteger numJarfilesScanned = new AtomicInteger();
/** The total number of classfiles scanned. */
private final AtomicInteger numClassfilesScanned = new AtomicInteger();
/**
* The latest last-modified timestamp of any file, directory or sub-directory in the classpath, in millis since
* the Unix epoch. Does not consider timestamps inside zipfiles/jarfiles, but the timestamp of the zip/jarfile
* itself is considered.
*/
private long lastModified = 0;
/** An interface used to test whether a file's relative path matches a given specification. */
public static interface FilePathTester {
public boolean filePathMatches(final File classpathElt, final String relativePathStr);
}
/** An interface called when the corresponding FilePathTester returns true. */
public static interface FileMatchProcessorWrapper {
public void processMatch(final File classpathElt, final String relativePath, final InputStream inputStream,
final long fileSize) throws IOException;
}
private static class FilePathTesterAndMatchProcessorWrapper {
FilePathTester filePathTester;
FileMatchProcessorWrapper fileMatchProcessorWrapper;
public FilePathTesterAndMatchProcessorWrapper(final FilePathTester filePathTester,
final FileMatchProcessorWrapper fileMatchProcessorWrapper) {
this.filePathTester = filePathTester;
this.fileMatchProcessorWrapper = fileMatchProcessorWrapper;
}
}
public void addFilePathMatcher(final FilePathTester filePathTester,
final FileMatchProcessorWrapper fileMatchProcessorWrapper) {
filePathTestersAndMatchProcessorWrappers
.add(new FilePathTesterAndMatchProcessorWrapper(filePathTester, fileMatchProcessorWrapper));
}
/**
* Recursive classpath scanner. Pass in a specification of whitelisted packages/jars to scan and blacklisted
* packages/jars not to scan, where blacklisted entries are prefixed with the '-' character.
*
* Examples of values for scanSpecs:
*
* ["com.x"] => scans the package "com.x" and its sub-packages in all directories and jars on the classpath.
*
* ["com.x", "-com.x.y"] => scans "com.x" and all sub-packages except "com.x.y" in all directories and jars on
* the classpath.
*
* ["com.x", "-com.x.y", "jar:deploy.jar"] => scans "com.x" and all sub-packages except "com.x.y", but only
* looks in jars named "deploy.jar" on the classpath (i.e. whitelisting a "jar:" entry prevents non-jar entries
* from being searched). Note that only the leafname of a jarfile can be specified.
*
* ["com.x", "-jar:irrelevant.jar"] => scans "com.x" and all sub-packages in all directories and jars on the
* classpath *except* "irrelevant.jar" (i.e. blacklisting a jarfile doesn't prevent directories from being
* scanned the way that whitelisting a jarfile does).
*
* ["com.x", "jar:"] => scans "com.x" and all sub-packages, but only looks in jarfiles on the classpath, doesn't
* scan directories (i.e. all jars are whitelisted, and whitelisting jarfiles prevents non-jars (directories)
* from being scanned).
*
* ["com.x", "-jar:"] => scans "com.x" and all sub-packages, but only looks in directories on the classpath,
* doesn't scan jarfiles (i.e. all jars are blacklisted.)
*
* @param fullyQualifiedFieldNameToStaticFinalFieldMatchProcessors
*/
public RecursiveScanner(final ClasspathFinder classpathFinder, final ScanSpec scanSpec,
final ArrayList<ClassMatcher> classMatchers,
final Map<String, HashSet<String>> classNameToStaticFinalFieldsToMatch,
final Map<String, ArrayList<StaticFinalFieldMatchProcessor>>
fullyQualifiedFieldNameToStaticFinalFieldMatchProcessors) {
this.classpathFinder = classpathFinder;
this.scanSpec = scanSpec;
this.classMatchers = classMatchers;
this.classNameToStaticFinalFieldsToMatch = classNameToStaticFinalFieldsToMatch;
this.fullyQualifiedFieldNameToStaticFinalFieldMatchProcessors =
fullyQualifiedFieldNameToStaticFinalFieldMatchProcessors;
}
/** Class for calling ClassfileBinaryParser in parallel for all relative paths within a classpath element. */
private abstract class ClassfileBinaryParserCaller implements Callable<Void> {
final File classpathElt;
final Queue<String> relativePaths;
Queue<ClassInfoUnlinked> classInfoUnlinkedOut;
final DeferredLog log;
public ClassfileBinaryParserCaller(final File classpathElt, final Queue<String> relativePaths,
final Queue<ClassInfoUnlinked> classInfoUnlinkedOut, final DeferredLog log) {
this.classpathElt = classpathElt;
this.relativePaths = relativePaths;
this.classInfoUnlinkedOut = classInfoUnlinkedOut;
this.log = log;
}
@Override
public Void call() {
try {
for (String relativePath; (relativePath = relativePaths.poll()) != null;) {
final long fileStartTime = System.nanoTime();
// Get input stream from classpath element and relative path
try (InputStream inputStream = getInputStream(relativePath)) {
// Parse classpath binary format, creating a ClassInfoUnlinked object
final ClassInfoUnlinked thisClassInfoUnlinked = ClassfileBinaryParser
.readClassInfoFromClassfileHeader(relativePath, inputStream,
classNameToStaticFinalFieldsToMatch, scanSpec, log);
if (thisClassInfoUnlinked != null) {
classInfoUnlinkedOut.add(thisClassInfoUnlinked);
}
} catch (final IOException e) {
if (FastClasspathScanner.verbose) {
log.log(4, "Exception while trying to open " + relativePath + ": " + e);
}
}
if (FastClasspathScanner.verbose) {
log.log(6, "Parsed classfile " + relativePath, System.nanoTime() - fileStartTime);
}
}
} finally {
close();
}
return null;
}
protected abstract InputStream getInputStream(String relativePath) throws IOException;
protected void close() {
}
}
/** Dir/file handler. */
private class DirClassfileBinaryParserCaller extends ClassfileBinaryParserCaller {
public DirClassfileBinaryParserCaller(final File classpathElt, final Queue<String> relativePaths,
final Queue<ClassInfoUnlinked> classInfoUnlinkedOut, final DeferredLog log) throws IOException {
super(classpathElt, relativePaths, classInfoUnlinkedOut, log);
}
@Override
protected InputStream getInputStream(final String relativePath) throws IOException {
return new FileInputStream(classpathElt.getPath() + File.separator
+ (File.separatorChar == '/' ? relativePath : relativePath.replace('/', File.separatorChar)));
}
}
/** Jarfile handler. */
private class JarClassfileBinaryParserCaller extends ClassfileBinaryParserCaller {
private final ZipFile zipFile;
public JarClassfileBinaryParserCaller(final File classpathElt, final Queue<String> relativePaths,
final Queue<ClassInfoUnlinked> classInfoUnlinkedOut, final DeferredLog log) throws IOException {
super(classpathElt, relativePaths, classInfoUnlinkedOut, log);
zipFile = new ZipFile(classpathElt);
}
@Override
protected InputStream getInputStream(final String relativePath) throws IOException {
return zipFile.getInputStream(zipFile.getEntry(relativePath));
}
@Override
public void close() {
try {
zipFile.close();
} catch (final IOException e) {
// Ignore
}
}
}
/** Parse whitelisted classfiles in parallel, populating classNameToClassInfo with the results. */
private void parallelParseClassfiles(final File classpathElt, final Queue<String> relativePaths,
final ExecutorService executorService, final DeferredLog[] logs) {
final boolean isDir = classpathElt.isDirectory();
final Queue<ClassInfoUnlinked> classInfoUnlinked = new ConcurrentLinkedQueue<>();
final CompletionService<Void> completionService = new ExecutorCompletionService<>(executorService);
for (int threadIdx = 0; threadIdx < NUM_THREADS; threadIdx++) {
try {
final ClassfileBinaryParserCaller caller = isDir
? this.new DirClassfileBinaryParserCaller(classpathElt, relativePaths, classInfoUnlinked,
logs[threadIdx])
: this.new JarClassfileBinaryParserCaller(classpathElt, relativePaths, classInfoUnlinked,
logs[threadIdx]);
completionService.submit(caller);
} catch (final Exception e) {
Log.log(4, "Exception opening classpath element " + classpathElt + ": " + e);
}
}
for (int i = 0; i < NUM_THREADS; i++) {
logs[i].flush();
// Completion barrier
try {
completionService.take().get();
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
Log.log(4, "Exception processing classpath element " + classpathElt + ": " + e);
}
}
// Convert ClassInfoUnlinked to linked ClassInfo objects
for (final ClassInfoUnlinked c : classInfoUnlinked) {
c.link(classNameToClassInfo);
}
}
/**
* Return true if the canonical path (after resolving symlinks and getting absolute path) for this dir, jarfile
* or file hasn't been seen before during this scan.
*/
private boolean previouslyScanned(final File fileOrDir) {
try {
// Get canonical path (resolve symlinks, and make the path absolute), then see if this canonical path
// has been scanned before
return !previouslyScannedCanonicalPaths.add(fileOrDir.getCanonicalPath());
} catch (final IOException | SecurityException e) {
// If something goes wrong while getting the real path, just return true.
return true;
}
}
/**
* Return true if the relative path for this file hasn't been seen before during this scan (indicating that a
* resource at this path relative to the classpath hasn't been scanned).
*/
private boolean previouslyScanned(final String relativePath) {
return !previouslyScannedRelativePaths.add(relativePath);
}
/**
* Scan a directory for matching file path patterns.
*/
private void scanDir(final File classpathElt, final File dir, final int ignorePrefixLen,
boolean inWhitelistedPath, final boolean scanTimestampsOnly,
final Queue<String> classfileRelativePathsToScanOut) {
if (previouslyScanned(dir)) {
if (FastClasspathScanner.verbose) {
Log.log(3, "Reached duplicate directory, ignoring: " + dir);
}
return;
}
if (FastClasspathScanner.verbose) {
Log.log(3, "Scanning directory: " + dir);
}
updateLastModifiedTimestamp(dir.lastModified());
numDirsScanned.incrementAndGet();
final String dirPath = dir.getPath();
final String dirRelativePath = ignorePrefixLen > dirPath.length() ? "/"
: dirPath.substring(ignorePrefixLen).replace(File.separatorChar, '/') + "/";
final ScanSpecPathMatch matchStatus = scanSpec.pathWhitelistMatchStatus(dirRelativePath);
if (matchStatus == ScanSpecPathMatch.NOT_WITHIN_WHITELISTED_PATH
|| matchStatus == ScanSpecPathMatch.WITHIN_BLACKLISTED_PATH) {
// Reached a non-whitelisted or blacklisted path -- stop the recursive scan
if (FastClasspathScanner.verbose) {
Log.log(3, "Reached non-whitelisted (or blacklisted) directory: " + dirRelativePath);
}
return;
} else if (matchStatus == ScanSpecPathMatch.WITHIN_WHITELISTED_PATH) {
// Reached a whitelisted path -- can start scanning directories and files from this point
inWhitelistedPath = true;
}
final long startTime = System.nanoTime();
final File[] filesInDir = dir.listFiles();
if (filesInDir == null) {
if (FastClasspathScanner.verbose) {
Log.log(4, "Invalid directory " + dir);
}
return;
}
for (final File fileInDir : filesInDir) {
if (fileInDir.isDirectory()) {
if (inWhitelistedPath
|| matchStatus == ScanSpecPathMatch.ANCESTOR_OF_WHITELISTED_PATH) {
// Recurse into subdirectory
scanDir(classpathElt, fileInDir, ignorePrefixLen, inWhitelistedPath, scanTimestampsOnly,
classfileRelativePathsToScanOut);
}
} else if (fileInDir.isFile()) {
final String fileInDirRelativePath = dirRelativePath.isEmpty() || "/".equals(dirRelativePath)
? fileInDir.getName() : dirRelativePath + fileInDir.getName();
// Class can only be scanned if it's within a whitelisted path subtree, or if it is a classfile
// that has been specifically-whitelisted
if (!inWhitelistedPath && (matchStatus != ScanSpecPathMatch.AT_WHITELISTED_CLASS_PACKAGE
|| !scanSpec.isSpecificallyWhitelistedClass(fileInDirRelativePath))) {
// Ignore files that are siblings of specifically-whitelisted files, but that are not
// themselves specifically whitelisted
continue;
}
// Make sure file with same absolute path or same relative path hasn't been scanned before.
// (N.B. don't inline these two different calls to previouslyScanned() into a single expression
// using "||", because they have intentional side effects)
final boolean subFilePreviouslyScannedCanonical = previouslyScanned(fileInDir);
final boolean subFilePreviouslyScannedRelative = previouslyScanned(fileInDirRelativePath);
if (subFilePreviouslyScannedRelative || subFilePreviouslyScannedCanonical) {
if (FastClasspathScanner.verbose) {
Log.log(3, "Reached duplicate path, ignoring: " + fileInDirRelativePath);
}
continue;
}
if (FastClasspathScanner.verbose) {
Log.log(3, "Found whitelisted file: " + fileInDirRelativePath);
}
updateLastModifiedTimestamp(fileInDir.lastModified());
if (!scanTimestampsOnly) {
boolean matchedFile = false;
// Store relative paths of any classfiles encountered
if (fileInDirRelativePath.endsWith(".class")) {
matchedFile = true;
classfileRelativePathsToScanOut.add(fileInDirRelativePath);
numClassfilesScanned.incrementAndGet();
}
// Match file paths against path patterns
for (final FilePathTesterAndMatchProcessorWrapper fileMatcher :
filePathTestersAndMatchProcessorWrappers) {
if (fileMatcher.filePathTester.filePathMatches(classpathElt, fileInDirRelativePath)) {
// File's relative path matches.
try {
matchedFile = true;
final long fileStartTime = System.nanoTime();
try (FileInputStream inputStream = new FileInputStream(fileInDir)) {
fileMatcher.fileMatchProcessorWrapper.processMatch(classpathElt,
fileInDirRelativePath, inputStream, fileInDir.length());
}
if (FastClasspathScanner.verbose) {
Log.log(4, "Processed file match " + fileInDirRelativePath,
System.nanoTime() - fileStartTime);
}
} catch (final Exception e) {
if (FastClasspathScanner.verbose) {
Log.log(3, "Reached non-whitelisted (or blacklisted) file, ignoring: "
+ fileInDirRelativePath);
}
}
}
}
if (matchedFile) {
numFilesScanned.incrementAndGet();
}
}
}
}
if (FastClasspathScanner.verbose) {
Log.log(4, "Scanned directory " + dir + " and any subdirectories", System.nanoTime() - startTime);
}
}
/**
* Scan a zipfile for matching file path patterns.
*/
private void scanZipfile(final File classpathElt, final ZipFile zipFile,
final Queue<String> classfileRelativePathsToScanOut) {
if (FastClasspathScanner.verbose) {
Log.log(3, "Scanning jarfile: " + classpathElt);
}
final long startTime = System.nanoTime();
String prevParentRelativePath = null;
ScanSpecPathMatch prevParentMatchStatus = null;
for (final Enumeration<? extends ZipEntry> entries = zipFile.entries(); entries.hasMoreElements();) {
final long entryStartTime = System.nanoTime();
final ZipEntry zipEntry = entries.nextElement();
String relativePath = zipEntry.getName();
if (relativePath.startsWith("/")) {
// Shouldn't happen with the standard Java zipfile implementation (but just to be safe)
relativePath = relativePath.substring(1);
}
// Ignore directory entries, they are not needed
if (zipEntry.isDirectory()) {
if (prevParentMatchStatus == ScanSpecPathMatch.WITHIN_WHITELISTED_PATH) {
numJarfileDirsScanned.incrementAndGet();
if (FastClasspathScanner.verbose) {
numJarfileFilesScanned.incrementAndGet();
Log.log(4, "Reached jarfile-internal directory " + relativePath,
System.nanoTime() - entryStartTime);
}
}
continue;
}
// Only accept first instance of a given relative path within classpath.
if (previouslyScanned(relativePath)) {
if (FastClasspathScanner.verbose) {
Log.log(3, "Reached duplicate relative path, ignoring: " + relativePath);
}
continue;
}
// Get match status of the parent directory if this zipentry file's relative path
// (or reuse the last match status for speed, if the directory name hasn't changed).
final int lastSlashIdx = relativePath.lastIndexOf("/");
final String parentRelativePath = lastSlashIdx < 0 ? "/" : relativePath.substring(0, lastSlashIdx + 1);
final ScanSpecPathMatch parentMatchStatus =
prevParentRelativePath == null || !parentRelativePath.equals(prevParentRelativePath)
? scanSpec.pathWhitelistMatchStatus(parentRelativePath) : prevParentMatchStatus;
final boolean parentPathChanged = !parentRelativePath.equals(prevParentRelativePath);
prevParentRelativePath = parentRelativePath;
prevParentMatchStatus = parentMatchStatus;
// Class can only be scanned if it's within a whitelisted path subtree, or if it is a classfile
// that has been specifically-whitelisted
if (parentMatchStatus != ScanSpecPathMatch.WITHIN_WHITELISTED_PATH
&& (parentMatchStatus != ScanSpecPathMatch.AT_WHITELISTED_CLASS_PACKAGE
|| !scanSpec.isSpecificallyWhitelistedClass(relativePath))) {
if (FastClasspathScanner.verbose && parentPathChanged) {
Log.log(3, "Reached non-whitelisted (or blacklisted) file in jar, ignoring: "
+ parentRelativePath);
}
continue;
}
if (FastClasspathScanner.verbose) {
Log.log(3, "Found whitelisted file in jarfile: " + relativePath);
}
boolean matchedFile = false;
// Store relative paths of any classfiles encountered
if (relativePath.endsWith(".class")) {
matchedFile = true;
classfileRelativePathsToScanOut.add(relativePath);
numClassfilesScanned.incrementAndGet();
}
// Match file paths against path patterns
for (final FilePathTesterAndMatchProcessorWrapper fileMatcher :
filePathTestersAndMatchProcessorWrappers) {
if (fileMatcher.filePathTester.filePathMatches(classpathElt, relativePath)) {
// File's relative path matches.
try {
matchedFile = true;
final long fileStartTime = System.nanoTime();
try (InputStream inputStream = zipFile.getInputStream(zipEntry)) {
fileMatcher.fileMatchProcessorWrapper.processMatch(classpathElt, relativePath,
inputStream, zipEntry.getSize());
}
if (FastClasspathScanner.verbose) {
Log.log(4, "Processed file match " + relativePath, System.nanoTime() - fileStartTime);
}
} catch (final Exception e) {
if (FastClasspathScanner.verbose) {
Log.log(3, "Reached non-whitelisted (or blacklisted) file, ignoring: " + relativePath);
}
}
}
}
if (matchedFile) {
numJarfileFilesScanned.incrementAndGet();
}
}
if (FastClasspathScanner.verbose) {
Log.log(4, "Scanned jarfile " + classpathElt, System.nanoTime() - startTime);
}
}
/**
* Scan the classpath, and call any MatchProcessors on files or classes that match.
*
* @param scanTimestampsOnly
* If true, scans the classpath for matching files, and calls any match processors if a match is
* identified. If false, only scans timestamps of files.
*/
private synchronized void scan(final boolean scanTimestampsOnly) {
ExecutorService executorService = null;
try {
executorService = Executors.newFixedThreadPool(NUM_THREADS);
// Create one logger per thread, so that log output is not interleaved
final DeferredLog[] logs = new DeferredLog[NUM_THREADS];
for (int i = 0; i < NUM_THREADS; i++) {
logs[i] = new DeferredLog();
}
final List<File> uniqueClasspathElts = classpathFinder.getUniqueClasspathElements();
if (FastClasspathScanner.verbose) {
Log.log(1, "Starting scan" + (scanTimestampsOnly ? " (scanning classpath timestamps only)" : ""));
}
final Map<String, String> env = new HashMap<>();
env.put("create", "false");
previouslyScannedCanonicalPaths.clear();
previouslyScannedRelativePaths.clear();
numDirsScanned.set(0);
numFilesScanned.set(0);
numJarfileDirsScanned.set(0);
numJarfileFilesScanned.set(0);
numJarfilesScanned.set(0);
numClassfilesScanned.set(0);
if (!scanTimestampsOnly) {
classNameToClassInfo.clear();
}
// Iterate through path elements and recursively scan within each directory and jar for matching paths
final Queue<String> classfileRelativePathsToScan = new ConcurrentLinkedQueue<>();
for (final File classpathElt : uniqueClasspathElts) {
final String path = classpathElt.getPath();
final boolean isDirectory = classpathElt.isDirectory();
final boolean isFile = classpathElt.isFile();
if (!isDirectory && !isFile) {
if (FastClasspathScanner.verbose) {
Log.log(2, "Skipping non-file/non-dir on classpath: " + classpathElt);
}
continue;
}
final boolean isJar = isFile && ClasspathFinder.isJar(path);
if (isFile && !isJar) {
if (FastClasspathScanner.verbose) {
Log.log(2, "Skipping non-jar file on classpath: " + classpathElt);
}
continue;
}
if (previouslyScanned(classpathElt)) {
if (FastClasspathScanner.verbose) {
Log.log(3, "Reached duplicate classpath entry, ignoring: " + classpathElt);
}
continue;
}
if (FastClasspathScanner.verbose) {
Log.log(2, "Found " + (isDirectory ? "directory" : "jar") + " on classpath: " + path);
}
if (isDirectory && scanSpec.scanNonJars) {
// Scan within a directory (and recursively within its sub-directories)
// Scan dirs recursively, looking for matching paths; call FileMatchProcessors on any matches.
// Also store relative paths of all whitelisted classfiles in whitelistedClassfileRelativePaths.
scanDir(classpathElt, classpathElt, /* ignorePrefixLen = */ path.length() + 1,
/* inWhitelistedPath = */ false, scanTimestampsOnly, classfileRelativePathsToScan);
// Parse classfile binary format and populate classNameToClassInfo
parallelParseClassfiles(classpathElt, classfileRelativePathsToScan, executorService, logs);
} else if (isJar && scanSpec.scanJars) {
// Scan within a jar/zipfile
if (!scanSpec.jarIsWhitelisted(classpathElt.getName())) {
if (FastClasspathScanner.verbose) {
Log.log(3, "Skipping jarfile that did not match whitelist/blacklist criteria: "
+ classpathElt.getName());
}
continue;
}
// Use the timestamp of the jar/zipfile as the timestamp for all files,
// since the timestamps within the zip directory may be unreliable.
updateLastModifiedTimestamp(classpathElt.lastModified());
numJarfilesScanned.incrementAndGet();
if (!scanTimestampsOnly) {
// Don't actually scan the contents of the zipfile if we're only scanning timestamps,
// since only the timestamp of the zipfile itself will be used.
try (ZipFile zipFile = new ZipFile(classpathElt)) {
final long startTime = System.nanoTime();
scanZipfile(classpathElt, zipFile, classfileRelativePathsToScan);
if (FastClasspathScanner.verbose) {
Log.log(2, "Scanned jarfile " + classpathElt, System.nanoTime() - startTime);
}
} catch (final IOException e) {
// Ignore, can only be thrown by zipFile.close()
}
// Parse classfile binary format and populate classNameToClassInfo
parallelParseClassfiles(classpathElt, classfileRelativePathsToScan, executorService, logs);
}
} else {
if (FastClasspathScanner.verbose) {
Log.log(2, "Skipping classpath element: " + path);
}
}
}
// Build class graph
// After creating ClassInfo objects for each classfile, build the class graph, and run any
// MatchProcessors on matching classes.
if (!scanTimestampsOnly) {
// Build class, interface and annotation graph out of all the ClassInfo objects.
classGraphBuilder = new ClassGraphBuilder(classNameToClassInfo);
// Call any class, interface and annotation MatchProcessors
for (final ClassMatcher classMatcher : classMatchers) {
classMatcher.lookForMatches();
}
// Call static final field match processors on matching fields
for (final ClassInfo classInfo : classNameToClassInfo.values()) {
if (classInfo.fieldValues != null) {
for (final Entry<String, Object> ent : classInfo.fieldValues.entrySet()) {
final String fieldName = ent.getKey();
final Object constValue = ent.getValue();
final String fullyQualifiedFieldName = classInfo.className + "." + fieldName;
final ArrayList<StaticFinalFieldMatchProcessor> staticFinalFieldMatchProcessors =
fullyQualifiedFieldNameToStaticFinalFieldMatchProcessors
.get(fullyQualifiedFieldName);
if (staticFinalFieldMatchProcessors != null) {
if (FastClasspathScanner.verbose) {
Log.log(1, "Calling MatchProcessor for static final field "
+ classInfo.className + "." + fieldName + " = " + constValue);
}
for (final StaticFinalFieldMatchProcessor staticFinalFieldMatchProcessor :
staticFinalFieldMatchProcessors) {
staticFinalFieldMatchProcessor.processMatch(classInfo.className, fieldName,
constValue);
}
}
}
}
}
}
if (FastClasspathScanner.verbose) {
Log.log(1, "Number of resources scanned: directories: " + numDirsScanned.get() + "; files: "
+ numFilesScanned.get() + "; jarfiles: " + numJarfilesScanned.get()
+ "; jarfile-internal directories: " + numJarfileDirsScanned + "; jarfile-internal files: "
+ numJarfileFilesScanned + "; classfiles: " + numClassfilesScanned);
}
} finally {
if (executorService != null) {
try {
executorService.shutdown();
} catch (final Exception e) {
// Ignore
}
executorService = null;
}
}
}
/**
* Scan the classpath, and call any MatchProcessors on files or classes that match.
*
* @param scanTimestampsOnly
* If true, scans the classpath for matching files, and calls any match processors if a match is
* identified. If false, only scans timestamps of files.
*/
public void scan() {
scan(/* scanTimestampsOnly = */false);
}
/**
* Get the class, interface and annotation graph builder, containing the results of the last full scan, or null
* if a scan has not yet been completed.
*/
public ClassGraphBuilder getClassGraphBuilder() {
return classGraphBuilder;
}
/** Update the last modified timestamp, given the timestamp of a Path. */
private void updateLastModifiedTimestamp(final long fileLastModified) {
// Find max last modified timestamp, but don't accept values greater than the current time
lastModified = Math.max(lastModified, Math.min(System.currentTimeMillis(), fileLastModified));
}
/**
* Returns true if the classpath contents have been changed since scan() was last called. Only considers
* classpath prefixes whitelisted in the call to the constructor. Returns true if scan() has not yet been run.
* Much faster than standard classpath scanning, because only timestamps are checked, and jarfiles don't have to
* be opened.
*/
public boolean classpathContentsModifiedSinceScan() {
final long oldLastModified = this.lastModified;
if (oldLastModified == 0) {
return true;
} else {
scan(/* scanTimestampsOnly = */true);
final long newLastModified = this.lastModified;
return newLastModified > oldLastModified;
}
}
/**
* Returns the maximum "last modified" timestamp in the classpath (in epoch millis), or zero if scan() has not
* yet been called (or if nothing was found on the classpath).
*
* The returned timestamp should be less than the current system time if the timestamps of files on the
* classpath and the system time are accurate. Therefore, if anything changes on the classpath, this value
* should increase.
*/
public long classpathContentsLastModifiedTime() {
return this.lastModified;
}
} |
package link.infra.simpleprocessors.blocks.programmer;
import javax.annotation.Nullable;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import net.minecraftforge.items.ItemStackHandler;
import net.minecraftforge.items.SlotItemHandler;
public class ProgrammerContainer extends Container {
private ProgrammerTileEntity te;
private Slot processorSlot;
private boolean usable = true;
private ItemStackHandler inputStackHandler = new ItemStackHandler(1);
public ProgrammerContainer(IInventory playerInventory, ProgrammerTileEntity te) {
this.te = te;
addOwnSlots();
addPlayerSlots(playerInventory);
}
private void addPlayerSlots(IInventory playerInventory) {
// Slots for the main inventory
for (int row = 0; row < 3; ++row) {
for (int col = 0; col < 9; ++col) {
int x = 9 + col * 18;
int y = row * 18 + 70;
this.addSlotToContainer(new Slot(playerInventory, col + row * 9 + 10, x, y));
}
}
// Slots for the hotbar
for (int row = 0; row < 9; ++row) {
int x = 9 + row * 18;
int y = 58 + 70;
this.addSlotToContainer(new Slot(playerInventory, row, x, y));
}
}
private void addOwnSlots() {
processorSlot = new SlotItemHandler(inputStackHandler, 0, 146, 41);
addSlotToContainer(processorSlot);
}
@Nullable
@Override
public ItemStack transferStackInSlot(EntityPlayer playerIn, int index) {
ItemStack itemstack = ItemStack.EMPTY;
Slot slot = this.inventorySlots.get(index);
if (usable && slot != null && slot.getHasStack()) {
ItemStack itemstack1 = slot.getStack();
itemstack = itemstack1.copy();
if (index < 1) {
if (!this.mergeItemStack(itemstack1, 1, this.inventorySlots.size(), true)) {
return ItemStack.EMPTY;
}
} else if (!this.mergeItemStack(itemstack1, 0, 1, false)) {
return ItemStack.EMPTY;
}
if (itemstack1.isEmpty()) {
slot.putStack(ItemStack.EMPTY);
} else {
slot.onSlotChanged();
}
}
return itemstack;
}
@Override
public boolean canInteractWith(EntityPlayer playerIn) {
return te.canInteractWith(playerIn);
}
public void setUsable(boolean usable) {
this.usable = usable;
if (usable) {
processorSlot.xPos = 146;
} else {
processorSlot.xPos = -999; // make slot invisible
}
}
} |
package nl.tudelft.lifetiles.traverser.models;
import nl.tudelft.lifetiles.graph.models.Graph;
import nl.tudelft.lifetiles.graph.models.sequence.SegmentEmpty;
import nl.tudelft.lifetiles.graph.models.sequence.Sequence;
import nl.tudelft.lifetiles.graph.models.sequence.SequenceSegment;
import nl.tudelft.lifetiles.graph.view.Mutation;
/**
* Indicates mutations by traversing over all the vertices.
*
* @author Jos
*
*/
public class MutationIndicationTraverser {
/**
* Reference which is compared to determine the mutation types.
*/
private Sequence referenceVar;
/**
* Constructs a MutationIndicationTraverser.
*
* @param reference
* Reference which is compared to determine the mutation types.
*/
public MutationIndicationTraverser(final Sequence reference) {
referenceVar = reference;
}
/**
* Graph which is being traversed.
*/
private Graph<SequenceSegment> graphVar;
/**
* Traverses the graph and indicates the mutation types.
*
* @param graph
* The graph to traverse.
* @return the traversed graph.
*/
public final Graph<SequenceSegment> traverseGraph(
final Graph<SequenceSegment> graph) {
graphVar = graph;
traverseGraph();
return graphVar;
}
/**
* Traverse the graph and indicates the mutation types.
*
* @return traversed graph.
*/
public final Graph<SequenceSegment> traverseGraph() {
for (SequenceSegment vertex : graphVar.getAllVertices()) {
traverseVertex(vertex);
}
return graphVar;
}
/**
* Traverse a vertex in the copy of the graph and determines the mutation
* type of the mutation, if it has one.
*
* @param vertex
* Vertex in the graph to be traversed.
*/
private void traverseVertex(final SequenceSegment vertex) {
if (!vertex.getSources().contains(referenceVar)) {
Mutation mutation;
if (vertex.getContent() instanceof SegmentEmpty) {
mutation = Mutation.DELETION;
} else if (vertex.getReferenceStart() > vertex.getReferenceEnd()) {
mutation = Mutation.INSERTION;
} else {
mutation = Mutation.POLYMORPHISM;
}
vertex.setMutation(mutation);
}
}
} |
package org.jboss.forge.plugin.idea.ui.component;
import org.jboss.forge.addon.ui.input.InputComponent;
/**
* A factory for {@link ComponentBuilder} instances.
*
* @author <a href="mailto:ggastald@redhat.com">George Gastaldi</a>
*/
public enum ComponentBuilderRegistry
{
INSTANCE;
private ComponentBuilder[] componentBuilders = {
new CheckboxComponentBuilder(),
new ComboComponentBuilder(),
new RadioComponentBuilder(),
new TextBoxComponentBuilder(),
new PasswordComponentBuilder(),
new TextAreaComponentBuilder(),
new FileChooserComponentBuilder(),
new DirectoryChooserComponentBuilder(),
new JavaClassChooserComponentBuilder(),
new JavaPackageChooserComponentBuilder(),
new FallbackTextBoxComponentBuilder()};
public ComponentBuilder getBuilderFor(InputComponent<?, ?> input)
{
for (ComponentBuilder builder : componentBuilders)
{
if (builder.handles(input))
{
return builder;
}
}
throw new IllegalArgumentException(
"No UI component found for input type of "
+ input.getValueType()
);
}
} |
package org.spongepowered.common.mixin.core.item.inventory;
import net.minecraft.inventory.Container;
import net.minecraft.inventory.IContainerListener;
import net.minecraft.inventory.IInventory;
import net.minecraft.inventory.Slot;
import net.minecraft.item.ItemStack;
import org.spongepowered.api.item.inventory.ItemStackSnapshot;
import org.spongepowered.api.item.inventory.transaction.SlotTransaction;
import org.spongepowered.api.util.annotation.NonnullByDefault;
import org.spongepowered.asm.mixin.Implements;
import org.spongepowered.asm.mixin.Interface;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.common.interfaces.IMixinContainer;
import org.spongepowered.common.item.inventory.adapter.impl.MinecraftInventoryAdapter;
import org.spongepowered.common.item.inventory.adapter.impl.slots.SlotAdapter;
import org.spongepowered.common.item.inventory.lens.Fabric;
import org.spongepowered.common.item.inventory.lens.Lens;
import org.spongepowered.common.item.inventory.lens.SlotProvider;
import org.spongepowered.common.item.inventory.lens.impl.MinecraftFabric;
import org.spongepowered.common.item.inventory.lens.impl.collections.SlotCollection;
import org.spongepowered.common.item.inventory.util.ContainerUtil;
import java.util.ArrayList;
import java.util.List;
@NonnullByDefault
@Mixin(Container.class)
@Implements({@Interface(iface = MinecraftInventoryAdapter.class, prefix = "inventory")})
public abstract class MixinContainer implements org.spongepowered.api.item.inventory.Container, IMixinContainer {
@Shadow public List<Slot> inventorySlots;
@Shadow public List<ItemStack> inventoryItemStacks;
@Shadow public int windowId;
@Shadow protected List<IContainerListener> listeners;
@SuppressWarnings("rawtypes")
@Shadow
public abstract List getInventory();
@Shadow
public abstract Slot getSlot(int slotId);
private Container this$ = (Container) (Object) this;
private boolean captureInventory = false;
private List<SlotTransaction> capturedSlotTransactions = new ArrayList<>();
private Fabric<IInventory> fabric;
private SlotCollection slots;
private Lens<IInventory, ItemStack> lens;
private boolean initialized;
private void init() {
this.initialized = true;
this.fabric = MinecraftFabric.of(this$);
this.slots = ContainerUtil.countSlots(this$);
this.lens = ContainerUtil.getLens(this$, this.slots);
}
/**
* @author bloodmc
* @reason As we do not create a new player object on respawn, we
* need to update the client with changes if listener already
* exists.
*/
@SuppressWarnings("unchecked")
@Overwrite
public void addListener(IContainerListener listener) {
Container container = (Container) (Object) this;
if (this.listeners.contains(listener)) {
// Sponge start
listener.updateCraftingInventory(container, this.getInventory());
container.detectAndSendChanges();
// Sponge end
} else {
this.listeners.add(listener);
listener.updateCraftingInventory(container, this.getInventory());
container.detectAndSendChanges();
}
}
/**
* @author bloodmc
* @reason All player fabric changes that need to be synced to
* client flow through this method. Overwrite is used as no mod
* should be touching this method.
*
*/
@Overwrite
public void detectAndSendChanges() {
for (int i = 0; i < this.inventorySlots.size(); ++i) {
ItemStack itemstack = this.inventorySlots.get(i).getStack();
ItemStack itemstack1 = this.inventoryItemStacks.get(i);
if (!ItemStack.areItemStacksEqual(itemstack1, itemstack)) {
// Sponge start
if (this.captureInventory) {
ItemStackSnapshot originalItem = itemstack1 == null ? ItemStackSnapshot.NONE
: ((org.spongepowered.api.item.inventory.ItemStack) itemstack1).createSnapshot();
ItemStackSnapshot newItem = itemstack == null ? ItemStackSnapshot.NONE
: ((org.spongepowered.api.item.inventory.ItemStack) itemstack).createSnapshot();
SlotTransaction slotTransaction =
new SlotTransaction(new SlotAdapter(this.inventorySlots.get(i)), originalItem, newItem);
this.capturedSlotTransactions.add(slotTransaction);
}
// Sponge end
itemstack1 = itemstack == null ? null : itemstack.copy();
this.inventoryItemStacks.set(i, itemstack1);
for (int j = 0; j < this.listeners.size(); ++j) {
this.listeners.get(j).sendSlotContents((Container) (Object) this, i, itemstack1);
}
}
}
}
@Inject(method = "putStackInSlot", at = @At(value = "HEAD") )
public void onPutStackInSlot(int slotId, ItemStack itemstack, CallbackInfo ci) {
if (this.captureInventory) {
Slot slot = getSlot(slotId);
if (slot != null) {
ItemStackSnapshot originalItem = slot.getStack() == null ? ItemStackSnapshot.NONE
: ((org.spongepowered.api.item.inventory.ItemStack) slot.getStack()).createSnapshot();
ItemStackSnapshot newItem =
itemstack == null ? ItemStackSnapshot.NONE : ((org.spongepowered.api.item.inventory.ItemStack) itemstack).createSnapshot();
SlotTransaction slotTransaction = new SlotTransaction(new SlotAdapter(slot), originalItem, newItem);
this.capturedSlotTransactions.add(slotTransaction);
}
}
}
@Override
public boolean capturingInventory() {
return this.captureInventory;
}
@Override
public void setCaptureInventory(boolean flag) {
this.captureInventory = flag;
}
@Override
public List<SlotTransaction> getCapturedTransactions() {
return this.capturedSlotTransactions;
}
public SlotProvider<IInventory, ItemStack> inventory$getSlotProvider() {
if (!this.initialized) {
this.init();
}
return this.slots;
}
public Lens<IInventory, ItemStack> inventory$getRootLens() {
if (!this.initialized) {
this.init();
}
return this.lens;
}
public Fabric<IInventory> inventory$getInventory() {
if (!this.initialized) {
this.init();
}
return this.fabric;
}
} |
package org.spongepowered.common.mixin.core.item.inventory;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.Lists;
import net.minecraft.item.Item;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import org.spongepowered.api.data.DataContainer;
import org.spongepowered.api.data.DataTransactionBuilder;
import org.spongepowered.api.data.DataTransactionResult;
import org.spongepowered.api.data.DataView;
import org.spongepowered.api.data.MemoryDataContainer;
import org.spongepowered.api.data.key.Key;
import org.spongepowered.api.data.manipulator.DataManipulator;
import org.spongepowered.api.data.manipulator.mutable.DisplayNameData;
import org.spongepowered.api.data.merge.MergeFunction;
import org.spongepowered.api.data.value.BaseValue;
import org.spongepowered.api.data.value.mutable.Value;
import org.spongepowered.api.item.ItemType;
import org.spongepowered.api.item.inventory.ItemStack;
import org.spongepowered.api.item.inventory.ItemStackSnapshot;
import org.spongepowered.api.service.persistence.InvalidDataException;
import org.spongepowered.api.text.Text;
import org.spongepowered.api.text.TextBuilder;
import org.spongepowered.api.text.Texts;
import org.spongepowered.api.text.action.TextActions;
import org.spongepowered.api.text.translation.Translation;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfo;
import org.spongepowered.asm.mixin.injection.callback.CallbackInfoReturnable;
import org.spongepowered.common.data.util.DataQueries;
import org.spongepowered.common.data.util.DataUtil;
import org.spongepowered.common.data.util.NbtDataUtil;
import org.spongepowered.common.interfaces.data.IMixinCustomDataHolder;
import org.spongepowered.common.interfaces.item.IMixinItem;
import org.spongepowered.common.interfaces.item.IMixinItemStack;
import org.spongepowered.common.inventory.SpongeItemStackSnapshot;
import org.spongepowered.common.service.persistence.NbtTranslator;
import org.spongepowered.common.text.translation.SpongeTranslation;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.annotation.Nullable;
@Mixin(net.minecraft.item.ItemStack.class)
public abstract class MixinItemStack implements ItemStack, IMixinItemStack, IMixinCustomDataHolder {
@Shadow public int stackSize;
@Shadow public abstract void setItemDamage(int meta);
@Shadow public abstract void setTagCompound(NBTTagCompound compound);
@Shadow public abstract void setTagInfo(String key, NBTBase nbtBase);
@Shadow public abstract int getItemDamage();
@Shadow public abstract int getMaxStackSize();
@Shadow public abstract boolean hasTagCompound();
@Shadow public abstract NBTTagCompound getTagCompound();
@Shadow public abstract NBTTagCompound getSubCompound(String key, boolean create);
@Shadow public abstract NBTTagCompound writeToNBT(NBTTagCompound compound);
@Shadow(prefix = "shadow$")
public abstract net.minecraft.item.ItemStack shadow$copy();
@Shadow(prefix = "shadow$")
public abstract Item shadow$getItem();
@Inject(method = "writeToNBT", at = @At(value = "HEAD"))
private void onWrite(NBTTagCompound incoming, CallbackInfoReturnable<NBTTagCompound> info) {
if (this.hasManipulators()) {
writeToNbt(incoming);
}
}
@Inject(method = "readFromNBT", at = @At("RETURN"))
private void onRead(NBTTagCompound compound, CallbackInfo info) {
if (hasTagCompound() && getTagCompound().hasKey(NbtDataUtil.SPONGE_DATA, NbtDataUtil.TAG_COMPOUND)) {
readFromNbt(getTagCompound().getCompoundTag(NbtDataUtil.SPONGE_DATA));
}
}
@Inject(method = "copy", at = @At("RETURN"))
private void onCopy(CallbackInfoReturnable<net.minecraft.item.ItemStack> info) {
final net.minecraft.item.ItemStack itemStack = info.getReturnValue();
if (hasManipulators()) { // no manipulators? no problem.
for (DataManipulator<?, ?> manipulator : this.manipulators) {
((IMixinCustomDataHolder) itemStack).offerCustom(manipulator.copy(), MergeFunction.IGNORE_ALL);
}
}
}
@Inject(method = "splitStack", at = @At("RETURN"))
private void onSplit(int amount, CallbackInfoReturnable<net.minecraft.item.ItemStack> info) {
final net.minecraft.item.ItemStack itemStack = info.getReturnValue();
if (hasManipulators()) {
for (DataManipulator<?, ?> manipulator : this.manipulators) {
((IMixinCustomDataHolder) itemStack).offerCustom(manipulator.copy(), MergeFunction.IGNORE_ALL);
}
}
}
@Override
public ItemType getItem() {
return (ItemType) shadow$getItem();
}
@Override
public int getQuantity() {
return this.stackSize;
}
@Override
public void setQuantity(int quantity) throws IllegalArgumentException {
if (quantity > this.getMaxStackQuantity()) {
throw new IllegalArgumentException("Quantity (" + quantity + ") exceeded the maximum stack size (" + this.getMaxStackQuantity() + ")");
} else {
this.stackSize = quantity;
}
}
@Override
public int getMaxStackQuantity() {
return getMaxStackSize();
}
@Override
public boolean validateRawData(DataContainer container) {
return false;
}
@Override
public void setRawData(DataContainer container) throws InvalidDataException {
}
@Override
public ItemStack copy() {
return (ItemStack) shadow$copy();
}
@Override
public DataContainer toContainer() {
final DataContainer container = new MemoryDataContainer()
.set(DataQueries.ITEM_TYPE, this.getItem().getId())
.set(DataQueries.ITEM_COUNT, this.getQuantity())
.set(DataQueries.ITEM_DAMAGE_VALUE, this.getItemDamage());
if (hasTagCompound()) { // no tag? no data, simple as that.
final NBTTagCompound compound = (NBTTagCompound) getTagCompound().copy();
NbtDataUtil.filterSpongeCustomData(compound); // We must filter the custom data so it isn't stored twice
if (!compound.hasNoTags()) {
final DataContainer unsafeNbt = NbtTranslator.getInstance().translateFrom(compound);
container.set(DataQueries.UNSAFE_NBT, unsafeNbt);
}
}
final Collection<DataManipulator<?, ?>> manipulators = getContainers();
if (!manipulators.isEmpty()) {
container.set(DataQueries.DATA_MANIPULATORS, DataUtil.getSerializedManipulatorList(manipulators));
}
return container;
}
@Override
public Translation getTranslation() {
return new SpongeTranslation(shadow$getItem().getUnlocalizedName((net.minecraft.item.ItemStack) (Object) this) + ".name");
}
@Override
public Text toText() {
TextBuilder builder;
Optional<DisplayNameData> optName = get(DisplayNameData.class);
if (optName.isPresent()) {
Value<Text> displayName = optName.get().displayName();
if (displayName.exists()) {
builder = displayName.get().builder();
} else {
builder = Texts.builder(getTranslation());
}
} else {
builder = Texts.builder(getTranslation());
}
builder.onHover(TextActions.showItem(this));
return builder.build();
}
@Override
public ItemStackSnapshot createSnapshot() {
return new SpongeItemStackSnapshot(this);
}
@Override
public Collection<DataManipulator<?, ?>> getContainers() {
final List<DataManipulator<?, ?>> manipulators = Lists.newArrayList();
((IMixinItem) this.getItem()).getManipulatorsFor((net.minecraft.item.ItemStack) (Object) this, manipulators);
if (hasManipulators()) {
final List<DataManipulator<?, ?>> customManipulators = this.getCustomManipulators();
manipulators.addAll(customManipulators);
}
return manipulators;
}
@Override
public void readFromNbt(NBTTagCompound compound) {
if (compound.hasKey(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_LIST)) {
final NBTTagList list = compound.getTagList(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, NbtDataUtil.TAG_COMPOUND);
if (!list.hasNoTags()) {
compound.removeTag(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST);
final List<DataView> views = Lists.newArrayList();
for (int i = 0; i < list.tagCount(); i++) {
final NBTTagCompound dataCompound = list.getCompoundTagAt(i);
views.add(NbtTranslator.getInstance().translateFrom(dataCompound));
}
final List<DataManipulator<?, ?>> manipulators = DataUtil.deserializeManipulatorList(views);
for (DataManipulator<?, ?> manipulator : manipulators) {
offerCustom(manipulator, MergeFunction.IGNORE_ALL);
}
} else {
compound.removeTag(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST);
if (compound.hasNoTags()) {
getTagCompound().removeTag(NbtDataUtil.SPONGE_DATA);
return;
}
}
}
if (compound.hasNoTags()) {
getTagCompound().removeTag(NbtDataUtil.SPONGE_DATA);
if (getTagCompound().hasNoTags()) {
setTagCompound(null);
}
}
}
@Override
public void writeToNbt(NBTTagCompound compound) {
resyncCustomToTag();
}
private List<DataManipulator<?, ?>> manipulators = Lists.newArrayList();
@SuppressWarnings("rawtypes")
@Override
public DataTransactionResult offerCustom(DataManipulator<?, ?> manipulator, MergeFunction function) {
@Nullable DataManipulator<?, ?> existingManipulator = null;
for (DataManipulator<?, ?> existing : this.manipulators) {
if (manipulator.getClass().isInstance(existing)) {
existingManipulator = existing;
break;
}
}
final DataTransactionBuilder builder = DataTransactionBuilder.builder();
final DataManipulator<?, ?> newManipulator = checkNotNull(function.merge(existingManipulator, (DataManipulator) manipulator.copy()));
if (existingManipulator != null) {
builder.replace(existingManipulator.getValues());
this.manipulators.remove(existingManipulator);
}
this.manipulators.add(newManipulator);
resyncCustomToTag();
return builder.success(newManipulator.getValues())
.result(DataTransactionResult.Type.SUCCESS)
.build();
}
@SuppressWarnings("unchecked")
@Override
public <T extends DataManipulator<?, ?>> Optional<T> getCustom(Class<T> customClass) {
for (DataManipulator<?, ?> existing : this.manipulators) {
if (customClass.isInstance(existing)) {
return Optional.of((T) existing.copy());
}
}
return Optional.empty();
}
private void resyncCustomToTag() {
if (!this.manipulators.isEmpty()) {
final NBTTagList newList = new NBTTagList();
final List<DataView> manipulatorViews = DataUtil.getSerializedManipulatorList(this.getCustomManipulators());
for (DataView dataView : manipulatorViews) {
newList.appendTag(NbtTranslator.getInstance().translateData(dataView));
}
final NBTTagCompound spongeCompound = getSubCompound(NbtDataUtil.SPONGE_DATA, true);
spongeCompound.setTag(NbtDataUtil.CUSTOM_MANIPULATOR_TAG_LIST, newList);
} else {
if (hasTagCompound()) {
this.getTagCompound().removeTag(NbtDataUtil.SPONGE_DATA);
}
if (this.getTagCompound().hasNoTags()) {
this.setTagCompound(null);
}
}
}
@Override
public DataTransactionResult removeCustom(Class<? extends DataManipulator<?, ?>> customClass) {
@Nullable DataManipulator<?, ?> manipulator = null;
for (DataManipulator<?, ?> existing : this.manipulators) {
if (customClass.isInstance(existing)) {
manipulator = existing;
}
}
if (manipulator != null) {
this.manipulators.remove(manipulator);
resyncCustomToTag();
return DataTransactionBuilder.builder().replace(manipulator.getValues()).result(DataTransactionResult.Type.SUCCESS).build();
} else {
return DataTransactionBuilder.failNoData();
}
}
@Override
public boolean hasManipulators() {
return !this.manipulators.isEmpty();
}
@Override
public List<DataManipulator<?, ?>> getCustomManipulators() {
return this.manipulators.stream()
.map(DataManipulator::copy)
.collect(Collectors.toList());
}
@SuppressWarnings({"unchecked", "rawtypes"})
@Override
public <E> DataTransactionResult offerCustom(Key<? extends BaseValue<E>> key, E value) {
for (DataManipulator<?, ?> manipulator : this.manipulators) {
if (manipulator.supports(key)) {
final DataTransactionBuilder builder = DataTransactionBuilder.builder();
builder.replace(((Value) manipulator.getValue((Key) key).get()).asImmutable());
manipulator.set(key, value);
builder.success(((Value) manipulator.getValue((Key) key).get()).asImmutable());
resyncCustomToTag();
return builder.result(DataTransactionResult.Type.SUCCESS).build();
}
}
return DataTransactionBuilder.failNoData();
}
@Override
public DataTransactionResult removeCustom(Key<?> key) {
final Iterator<DataManipulator<?, ?>> iterator = this.manipulators.iterator();
while (iterator.hasNext()) {
final DataManipulator<?, ?> manipulator = iterator.next();
if (manipulator.getKeys().size() == 1 && manipulator.supports(key)) {
iterator.remove();
resyncCustomToTag();
return DataTransactionBuilder.builder()
.replace(manipulator.getValues())
.result(DataTransactionResult.Type.SUCCESS)
.build();
}
}
return DataTransactionBuilder.failNoData();
}
} |
package org.tigris.subversion.svnclientadapter.javahl;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import org.tigris.subversion.javahl.ClientException;
import org.tigris.subversion.javahl.Depth;
import org.tigris.subversion.javahl.Info;
import org.tigris.subversion.javahl.Info2;
import org.tigris.subversion.javahl.PromptUserPassword;
import org.tigris.subversion.javahl.PropertyData;
import org.tigris.subversion.javahl.Revision;
import org.tigris.subversion.javahl.RevisionKind;
import org.tigris.subversion.javahl.SVNClient;
import org.tigris.subversion.javahl.SVNClientInterface;
import org.tigris.subversion.javahl.Status;
import org.tigris.subversion.svnclientadapter.AbstractClientAdapter;
import org.tigris.subversion.svnclientadapter.ISVNAnnotations;
import org.tigris.subversion.svnclientadapter.ISVNDirEntry;
import org.tigris.subversion.svnclientadapter.ISVNInfo;
import org.tigris.subversion.svnclientadapter.ISVNLogMessage;
import org.tigris.subversion.svnclientadapter.ISVNNotifyListener;
import org.tigris.subversion.svnclientadapter.ISVNPromptUserPassword;
import org.tigris.subversion.svnclientadapter.ISVNProperty;
import org.tigris.subversion.svnclientadapter.ISVNStatus;
import org.tigris.subversion.svnclientadapter.SVNBaseDir;
import org.tigris.subversion.svnclientadapter.SVNClientException;
import org.tigris.subversion.svnclientadapter.SVNInfoUnversioned;
import org.tigris.subversion.svnclientadapter.SVNNodeKind;
import org.tigris.subversion.svnclientadapter.SVNNotificationHandler;
import org.tigris.subversion.svnclientadapter.SVNRevision;
import org.tigris.subversion.svnclientadapter.SVNScheduleKind;
import org.tigris.subversion.svnclientadapter.SVNStatusKind;
import org.tigris.subversion.svnclientadapter.SVNStatusUnversioned;
import org.tigris.subversion.svnclientadapter.SVNUrl;
import org.tigris.subversion.svnclientadapter.utils.Messages;
/**
* This is a base class for the JavaHL Adapter. It allows the JavaHL
* Adapter and the SVNKit Adapter to share most of their implementation.
*
* The SVNKit Adapter works by providing an implementation of the JavaHL
* SVNClientInterface.
*
*/
public abstract class AbstractJhlClientAdapter extends AbstractClientAdapter {
final protected static int SVN_ERR_WC_NOT_DIRECTORY = 155007;
protected SVNClientInterface svnClient;
protected JhlNotificationHandler notificationHandler;
public AbstractJhlClientAdapter() {
}
/**
* for users who want to directly use underlying javahl SVNClientInterface
* @return the SVNClientInterface instance
*/
public SVNClientInterface getSVNClient() {
return svnClient;
}
/**
* the default prompter : never prompts the user
*/
public static class DefaultPromptUserPassword implements PromptUserPassword {
public String askQuestion(String realm, String question, boolean showAnswer) {
return "";
}
public boolean askYesNo(String realm, String question, boolean yesIsDefault) {
return yesIsDefault;
}
public String getPassword() {
return "";
}
public String getUsername() {
return "";
}
public boolean prompt(String realm, String username) {
return false;
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#addNotifyListener(org.tigris.subversion.svnclientadapter.ISVNNotifyListener)
*/
public void addNotifyListener(ISVNNotifyListener listener) {
notificationHandler.add(listener);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#removeNotifyListener(org.tigris.subversion.svnclientadapter.ISVNNotifyListener)
*/
public void removeNotifyListener(ISVNNotifyListener listener) {
notificationHandler.remove(listener);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getNotificationHandler()
*/
public SVNNotificationHandler getNotificationHandler() {
return notificationHandler;
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#setUsername(java.lang.String)
*/
public void setUsername(String username) {
svnClient.username(username);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#setPassword(java.lang.String)
*/
public void setPassword(String password) {
notificationHandler.setCommand(ISVNNotifyListener.Command.UNDEFINED);
svnClient.password(password);
}
/**
* Register callback interface to supply username and password on demand
* @param prompt
*/
public void setPromptUserPassword(PromptUserPassword prompt) {
svnClient.setPrompt(prompt);
}
protected static String fileToSVNPath(File file, boolean canonical) {
// SVN need paths with '/' separators
if (canonical) {
try {
return file.getCanonicalPath().replace('\\', '/');
} catch (IOException e)
{
return null;
}
} else
return file.getPath().replace('\\', '/');
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#addFile(java.io.File)
*/
public void addFile(File file) throws SVNClientException {
try{
notificationHandler.setCommand(ISVNNotifyListener.Command.ADD);
notificationHandler.logCommandLine("add -N "+file.toString());
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(file));
svnClient.add(fileToSVNPath(file, false), false);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.subclipse.client.ISVNClientAdapter#addDirectory(java.io.File, boolean)
*/
public void addDirectory(File file, boolean recurse) throws SVNClientException {
addDirectory(file, recurse, false);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#addDirectory(java.io.File, boolean, boolean)
*/
public void addDirectory(File dir, boolean recurse, boolean force)
throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.ADD);
notificationHandler.logCommandLine(
"add"+
(recurse?"":" -N")+
(force?" --force":"")+
" "+dir.toString());
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(dir));
svnClient.add(fileToSVNPath(dir, false), recurse, force);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#checkout(org.tigris.subversion.svnclientadapter.SVNUrl, java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision, boolean)
*/
public void checkout(
SVNUrl moduleName,
File destPath,
SVNRevision revision,
boolean recurse)
throws SVNClientException {
try {
String url = moduleName.toString();
notificationHandler.setCommand(ISVNNotifyListener.Command.CHECKOUT);
notificationHandler.logCommandLine(
"checkout" +
(recurse?"":" -N") +
" -r "+revision.toString()+
" "+url + " --force");
notificationHandler.setBaseDir(new File("."));
boolean ignoreExternals = false;
boolean force = true;
svnClient.checkout(
url,
fileToSVNPath(destPath, false),
JhlConverter.convert(revision),
JhlConverter.convert(revision),
Depth.fromRecurse(recurse),
ignoreExternals,
force);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#commit(java.io.File[], java.lang.String, boolean)
*/
public long commit(File[] paths, String message, boolean recurse)
throws SVNClientException {
return commit(paths, message, recurse, false);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#commit(java.io.File[], java.lang.String, boolean, boolean)
*/
public long commit(File[] paths, String message, boolean recurse, boolean keepLocks)
throws SVNClientException {
try {
if (message == null)
message = "";
notificationHandler.setCommand(ISVNNotifyListener.Command.COMMIT);
String[] files = new String[paths.length];
String commandLine = "commit -m \""+message+"\"";
if (!recurse)
commandLine+=" -N";
if (keepLocks)
commandLine+=" --no-unlock";
for (int i = 0; i < paths.length; i++) {
files[i] = fileToSVNPath(paths[i], false);
commandLine+=" "+ files[i];
}
notificationHandler.logCommandLine(commandLine);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(paths));
long newRev = svnClient.commit(files, message, recurse, keepLocks);
if (newRev > 0)
notificationHandler.logCompleted("Committed revision " + newRev + ".");
return newRev;
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getList(org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision, boolean)
*/
public ISVNDirEntry[] getList(SVNUrl url, SVNRevision revision, boolean recurse)
throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.LS);
String commandLine = "list -r "+revision.toString()+(recurse?"-R":"")+" "+url.toString();
notificationHandler.logCommandLine(commandLine);
notificationHandler.setBaseDir(new File("."));
return JhlConverter.convert(svnClient.list(url.toString(), JhlConverter.convert(revision), recurse));
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getList(java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision, boolean)
*/
public ISVNDirEntry[] getList(File path, SVNRevision revision, boolean recurse)
throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.LS);
String target = fileToSVNPath(path, false);
String commandLine = "list -r "+revision.toString()+(recurse?"-R":"")+" "+path;
notificationHandler.logCommandLine(commandLine);
notificationHandler.setBaseDir(new File("."));
return JhlConverter.convert(svnClient.list(target, JhlConverter.convert(revision), recurse));
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/*
* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getDirEntry(org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision)
*/
public ISVNDirEntry getDirEntry(SVNUrl url, SVNRevision revision)
throws SVNClientException {
// list give the DirEntrys of the elements of a directory or the DirEntry
// of a file
ISVNDirEntry[] entries = getList(url.getParent(), revision,false);
String expectedPath = url.getLastPathSegment();
for (int i = 0; i < entries.length;i++) {
if (entries[i].getPath().equals(expectedPath)) {
return entries[i];
}
}
return null; // not found
}
/*
* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getDirEntry(java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision)
*/
public ISVNDirEntry getDirEntry(File path, SVNRevision revision)
throws SVNClientException {
// list give the DirEntrys of the elements of a directory or the DirEntry
// of a file
ISVNDirEntry[] entries = getList(path.getParentFile(), revision,false);
String expectedPath = path.getName();
for (int i = 0; i < entries.length;i++) {
if (entries[i].getPath().equals(expectedPath)) {
return entries[i];
}
}
return null; // not found
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getSingleStatus(java.io.File)
*/
public ISVNStatus getSingleStatus(File path)
throws SVNClientException {
return getStatus(new File[] {path})[0];
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getStatus(java.io.File[])
*/
public ISVNStatus[] getStatus(File[] path)
throws SVNClientException {
notificationHandler.setCommand(ISVNNotifyListener.Command.STATUS);
String filePathSVN[] = new String[path.length];
String commandLine = "status -N --no-ignore";
for (int i = 0; i < filePathSVN.length;i++) {
filePathSVN[i] = fileToSVNPath(path[i], false);
commandLine+=" "+filePathSVN[i];
}
notificationHandler.logCommandLine(commandLine);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
ISVNStatus[] statuses = new ISVNStatus[path.length];
for (int i = 0; i < filePathSVN.length;i++) {
try {
Status status = svnClient.singleStatus(filePathSVN[i], false);
if (status == null) {
statuses[i] = new SVNStatusUnversioned(path[i]);
} else {
statuses[i] = new JhlStatus(status);
}
} catch (ClientException e) {
if (e.getAprError() == SVN_ERR_WC_NOT_DIRECTORY) {
// when there is no .svn dir, an exception is thrown ...
statuses[i] = new SVNStatusUnversioned(path[i]);
} else
{
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
}
return statuses;
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getStatus(java.io.File, boolean, boolean)
*/
public ISVNStatus[] getStatus(File path, boolean descend, boolean getAll)
throws SVNClientException {
return getStatus(path, descend,getAll,false);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getStatus(java.io.File, boolean, boolean, boolean)
*/
public ISVNStatus[] getStatus(File path, boolean descend, boolean getAll, boolean contactServer) throws SVNClientException {
return getStatus(path, descend, getAll, contactServer, false);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getStatus(java.io.File, boolean, boolean, boolean, boolean)
*/
public ISVNStatus[] getStatus(File path, boolean descend, boolean getAll, boolean contactServer, boolean ignoreExternals) throws SVNClientException {
notificationHandler.setCommand(ISVNNotifyListener.Command.STATUS);
String filePathSVN = fileToSVNPath(path, false);
notificationHandler.logCommandLine("status " + (contactServer?"-u ":"")+ filePathSVN);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
try {
return processFolderStatuses(processExternalStatuses(JhlConverter.convert(
svnClient.status(
filePathSVN,
descend, // If descend is true, recurse fully, else do only immediate children.
contactServer, // If update is set, contact the repository and augment the status structures with information about out-of-dateness
getAll,getAll, // retrieve all entries; otherwise, retrieve only "interesting" entries (local mods and/or out-of-date).
ignoreExternals))), getAll, contactServer); // if yes the svn:externals will be ignored
} catch (ClientException e) {
if (e.getAprError() == SVN_ERR_WC_NOT_DIRECTORY) {
// when there is no .svn dir, an exception is thrown ...
return new ISVNStatus[] {new SVNStatusUnversioned(path)};
} else {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
}
/**
* Post-process svn:externals statuses.
* JavaHL answer two sort of statuses on externals:
* - when ignoreExternals is set to true during call to status(),
* the returned status has textStatus set to EXTERNAL, but the url is null.<br>
* - when ignoreExternals is set to false during call to status(),
* besides the "external + null" status, the second status with url and all fields is returned too,
* but this one has textStatus NORMAL.
*
* This methods unifies both statuses to be complete and has textStatus external.
* In case the first sort (when ignoreExternals true), the url is retrieved by call the info()
*/
protected JhlStatus[] processExternalStatuses(JhlStatus[] statuses) throws SVNClientException
{
//Collect indexes of external statuses
List externalStatusesIndexes = new ArrayList();
for (int i = 0; i < statuses.length; i++) {
if (SVNStatusKind.EXTERNAL.equals(statuses[i].getTextStatus())) {
externalStatusesIndexes.add(new Integer(i));
}
}
if (externalStatusesIndexes.isEmpty()) {
return statuses;
}
//Wrap the "second" externals so their textStatus is actually external
for (Iterator iter = externalStatusesIndexes.iterator(); iter.hasNext();) {
int index = ((Integer) iter.next()).intValue();
JhlStatus jhlStatus = statuses[index];
for (int i = 0; i < statuses.length; i++) {
if ((statuses[i].getPath() != null) && (statuses[i].getPath().equals(jhlStatus.getPath()))) {
statuses[i] = new JhlStatus.JhlStatusExternal(statuses[i]);
statuses[index] = statuses[i];
}
}
}
//Fill the missing urls
for (Iterator iter = externalStatusesIndexes.iterator(); iter.hasNext();) {
int index = ((Integer) iter.next()).intValue();
JhlStatus jhlStatus = statuses[index];
if ((jhlStatus.getUrlString() == null) || (jhlStatus.getUrlString().length() == 0)) {
ISVNInfo info = getInfoFromWorkingCopy(jhlStatus.getFile());
if (info != null) {
statuses[index] = new JhlStatus.JhlStatusExternal(jhlStatus, info.getUrlString());
}
}
}
return statuses;
}
/**
* Post-process statuses.
* Folders do not return proper lastChangedRevision information.
* this allows it to be populated via the svn info command
*/
protected ISVNStatus[] processFolderStatuses(JhlStatus[] statuses, boolean getAll, boolean contactServer) throws SVNClientException
{
if (!getAll || !contactServer)
return statuses;
//Fill the missing last changed info on folders from the file info in the array
List folders = new ArrayList();
for (int i = 0; i < statuses.length; i++) {
JhlStatus jhlStatus = statuses[i];
if (SVNNodeKind.DIR == jhlStatus.getNodeKind() && jhlStatus.getReposLastChangedRevision() == null) {
folders.add(jhlStatus);
}
}
for (int i = 0; i < statuses.length; i++) {
JhlStatus jhlStatus = statuses[i];
if (jhlStatus.getLastChangedRevision() != null) {
for (Iterator iter = folders.iterator(); iter.hasNext();) {
JhlStatus folder = (JhlStatus) iter.next();
if (jhlStatus.getUrlString().startsWith(folder.getUrlString() + "/")) {
if (folder.getLastChangedRevision() == null ||
folder.getLastChangedRevision().getNumber() < jhlStatus.getLastChangedRevision().getNumber()) {
folder.updateFromStatus(jhlStatus);
}
}
}
}
}
return statuses;
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#copy(java.io.File, java.io.File)
*/
public void copy(File srcPath, File destPath) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.COPY);
String src = fileToSVNPath(srcPath, false);
String dest = fileToSVNPath(destPath, false);
notificationHandler.logCommandLine("copy " + src + " " + dest);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(new File[] {srcPath,destPath }));
svnClient.copy(src, dest, "", Revision.WORKING);
// last two parameters are not used
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#copy(java.io.File, org.tigris.subversion.svnclientadapter.SVNUrl, java.lang.String)
*/
public void copy(File srcPath, SVNUrl destUrl, String message)
throws SVNClientException {
try {
if (message == null)
message = "";
notificationHandler.setCommand(ISVNNotifyListener.Command.COPY);
String src = fileToSVNPath(srcPath, false);
String dest = destUrl.toString();
notificationHandler.logCommandLine("copy " + src + " " + dest);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(srcPath));
svnClient.copy(src, dest, message, Revision.WORKING);
// last parameter is not used
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#copy(org.tigris.subversion.svnclientadapter.SVNUrl, java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision)
*/
public void copy(SVNUrl srcUrl, File destPath, SVNRevision revision)
throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.COPY);
String src = srcUrl.toString();
String dest = fileToSVNPath(destPath, false);
notificationHandler.logCommandLine("copy " + src + " " + dest);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(destPath));
svnClient.copy(src, dest, "", JhlConverter.convert(revision));
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#copy(org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNUrl, java.lang.String, org.tigris.subversion.svnclientadapter.SVNRevision)
*/
public void copy(
SVNUrl srcUrl,
SVNUrl destUrl,
String message,
SVNRevision revision)
throws SVNClientException {
try {
if (message == null)
message = "";
notificationHandler.setCommand(ISVNNotifyListener.Command.COPY);
String src = srcUrl.toString();
String dest = destUrl.toString();
notificationHandler.logCommandLine("copy -r" + revision.toString() + " " + src + " " + dest);
notificationHandler.setBaseDir();
svnClient.copy(src, dest, message, JhlConverter.convert(revision));
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#remove(org.tigris.subversion.svnclientadapter.SVNUrl[], java.lang.String)
*/
public void remove(SVNUrl url[], String message) throws SVNClientException {
try {
if (message == null)
message = "";
notificationHandler.setCommand(ISVNNotifyListener.Command.REMOVE);
String commandLine = "delete -m \""+message+"\"";
String targets[] = new String[url.length];
for (int i = 0; i < url.length;i++) {
targets[i] = url[i].toString();
commandLine += " "+targets[i];
}
notificationHandler.logCommandLine(commandLine);
notificationHandler.setBaseDir();
svnClient.remove(targets,message,false);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#remove(java.io.File[], boolean)
*/
public void remove(File file[], boolean force) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.REMOVE);
String commandLine = "delete"+(force?" --force":"");
String targets[] = new String[file.length];
for (int i = 0; i < file.length;i++) {
targets[i] = fileToSVNPath(file[i], false);
commandLine += " "+targets[i];
}
notificationHandler.logCommandLine(commandLine);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(file));
svnClient.remove(targets,"",force);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#doExport(org.tigris.subversion.svnclientadapter.SVNUrl, java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision, boolean)
*/
public void doExport(
SVNUrl srcUrl,
File destPath,
SVNRevision revision,
boolean force)
throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.EXPORT);
String src = srcUrl.toString();
String dest = fileToSVNPath(destPath, false);
notificationHandler.logCommandLine(
"export -r " + revision.toString() + ' ' + src + ' ' + dest);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(destPath));
svnClient.doExport(src, dest, JhlConverter.convert(revision), force);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#doExport(java.io.File, java.io.File, boolean)
*/
public void doExport(File srcPath, File destPath, boolean force)
throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.EXPORT);
String src = fileToSVNPath(srcPath, false);
String dest = fileToSVNPath(destPath, false);
notificationHandler.logCommandLine("export " + src + ' ' + dest);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(new File[]{srcPath,destPath }));
// in this case, revision is not used but must be valid
svnClient.doExport(src, dest, Revision.WORKING, force);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#doImport(java.io.File, org.tigris.subversion.svnclientadapter.SVNUrl, java.lang.String, boolean)
*/
public void doImport(
File path,
SVNUrl url,
String message,
boolean recurse)
throws SVNClientException {
try {
if (message == null)
message = "";
notificationHandler.setCommand(ISVNNotifyListener.Command.IMPORT);
String src = fileToSVNPath(path, false);
String dest = url.toString();
notificationHandler.logCommandLine(
"import -m \""
+ message
+ "\" "
+ (recurse ? "" : "-N ")
+ src
+ ' '
+ dest);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
svnClient.doImport(src, dest, message, recurse);
notificationHandler.logCompleted(Messages.bind("notify.import.complete"));
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#mkdir(org.tigris.subversion.svnclientadapter.SVNUrl, java.lang.String)
*/
public void mkdir(SVNUrl url, String message) throws SVNClientException {
try {
if (message == null)
message = "";
notificationHandler.setCommand(ISVNNotifyListener.Command.MKDIR);
String target = url.toString();
notificationHandler.logCommandLine(
"mkdir -m \""+message+"\" "+target);
notificationHandler.setBaseDir();
svnClient.mkdir(new String[] { target },message);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#mkdir(java.io.File)
*/
public void mkdir(File file) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.MKDIR);
String target = fileToSVNPath(file, false);
notificationHandler.logCommandLine(
"mkdir "+target);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(file));
svnClient.mkdir(new String[] { target },"");
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#move(java.io.File, java.io.File, boolean)
*/
public void move(File srcPath, File destPath, boolean force) throws SVNClientException {
// use force when you want to move file even if there are local modifications
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.MOVE);
String src = fileToSVNPath(srcPath, false);
String dest = fileToSVNPath(destPath, false);
notificationHandler.logCommandLine(
"move "+src+' '+dest);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(new File[] {srcPath, destPath}));
svnClient.move(src,dest,"",force);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#move(org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNUrl, java.lang.String, org.tigris.subversion.svnclientadapter.SVNRevision)
*/
public void move(
SVNUrl srcUrl,
SVNUrl destUrl,
String message,
SVNRevision revision)
throws SVNClientException {
try {
// NOTE: The revision arg is ignored as you cannot move
// a specific revision, only HEAD.
if (message == null)
message = "";
notificationHandler.setCommand(ISVNNotifyListener.Command.MOVE);
String src = srcUrl.toString();
String dest = destUrl.toString();
notificationHandler.logCommandLine(
"move -m \""
+ message
+ ' '
+ src
+ ' '
+ dest);
notificationHandler.setBaseDir();
svnClient.move(src, dest, message, false);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#update(java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision, boolean)
*/
public long update(File path, SVNRevision revision, boolean recurse)
throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.UPDATE);
String target = fileToSVNPath(path, false);
notificationHandler.logCommandLine(
"update -r "
+ revision.toString()
+ ' '
+ (recurse ? "" : "-N ")
+ target
+ " --force");
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
boolean ignoreExternals = false;
boolean force = true;
return svnClient.update(target, JhlConverter.convert(revision), Depth.fromRecurse(recurse),
ignoreExternals, force);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#update(java.io.File[], org.tigris.subversion.svnclientadapter.SVNRevision, boolean, boolean)
*/
public long[] update(File[] path, SVNRevision revision, boolean recurse, boolean ignoreExternals)
throws SVNClientException
{
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.UPDATE);
String[] targets = new String[path.length];
StringBuffer targetsString = new StringBuffer();
for (int i = 0; i < targets.length; i++) {
targets[i] = fileToSVNPath(path[i], false);
targetsString.append(targets[i]);
targetsString.append(" ");
}
notificationHandler.logCommandLine(
"update -r "
+ revision.toString()
+ ' '
+ (recurse ? "" : "-N ")
+ (ignoreExternals ? "--ignore-externals " : "")
+ targetsString.toString()
+ " --force");
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
notificationHandler.holdStats();
boolean force = true;
long[] rtnCode = svnClient.update(targets, JhlConverter.convert(revision), Depth.fromRecurse(recurse), ignoreExternals, force);
notificationHandler.releaseStats();
return rtnCode;
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#revert(java.io.File, boolean)
*/
public void revert(File path, boolean recurse) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.REVERT);
String target = fileToSVNPath(path, false);
notificationHandler.logCommandLine(
"revert "+
(recurse?"":"-N ")+
target);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
svnClient.revert(target,recurse);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/**
* @param logLevel
* @param filePath
*/
public static void enableLogging(int logLevel,File filePath) {
SVNClient.enableLogging(logLevel,fileToSVNPath(filePath, false));
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getContent(org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision)
*/
public InputStream getContent(SVNUrl url, SVNRevision revision)
throws SVNClientException {
try {
notificationHandler.setCommand(
ISVNNotifyListener.Command.CAT);
notificationHandler.logCommandLine(
"cat -r "
+ revision.toString()
+ " "
+ url.toString());
notificationHandler.setBaseDir();
byte[] contents = svnClient.fileContent(url.toString(), JhlConverter.convert(revision), Revision.HEAD);
InputStream input = new ByteArrayInputStream(contents);
return input;
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/*
* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getContent(java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision)
*/
public InputStream getContent(File path, SVNRevision revision)
throws SVNClientException {
try {
String target = fileToSVNPath(path, false);
notificationHandler.setCommand(
ISVNNotifyListener.Command.CAT);
notificationHandler.logCommandLine(
"cat -r "
+ revision.toString()
+ " "
+ target);
notificationHandler.setBaseDir();
if (revision.equals(SVNRevision.BASE)) {
// This is to work-around a JavaHL problem when trying to
// retrieve the base revision of a newly added file.
ISVNStatus status = getSingleStatus(path);
if (status.getTextStatus().equals(SVNStatusKind.ADDED))
return new ByteArrayInputStream(new byte[0]);
}
byte[] contents = svnClient.fileContent(target, JhlConverter.convert(revision));
InputStream input = new ByteArrayInputStream(contents);
return input;
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getProperties(java.io.File)
*/
public ISVNProperty[] getProperties(File path) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.PROPLIST);
String target = fileToSVNPath(path, false);
notificationHandler.logCommandLine(
"proplist "+ target);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
PropertyData[] propertiesData = svnClient.properties(target);
if (propertiesData == null) {
// no properties
return new JhlPropertyData[0];
}
JhlPropertyData[] svnProperties = new JhlPropertyData[propertiesData.length];
for (int i = 0; i < propertiesData.length;i++) {
svnProperties[i] = JhlPropertyData.newForFile(propertiesData[i]);
}
return svnProperties;
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getProperties(org.tigris.subversion.svnclientadapter.SVNUrl)
*/
public ISVNProperty[] getProperties(SVNUrl url) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.PROPLIST);
String target = url.toString();
notificationHandler.logCommandLine(
"proplist "+ target);
notificationHandler.setBaseDir();
PropertyData[] propertiesData = svnClient.properties(target);
if (propertiesData == null) {
// no properties
return new JhlPropertyData[0];
}
JhlPropertyData[] svnProperties = new JhlPropertyData[propertiesData.length];
for (int i = 0; i < propertiesData.length;i++) {
svnProperties[i] = JhlPropertyData.newForUrl(propertiesData[i]);
}
return svnProperties;
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#propertySet(java.io.File, java.lang.String, java.lang.String, boolean)
*/
public void propertySet(
File path,
String propertyName,
String propertyValue,
boolean recurse)
throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.PROPSET);
String target = fileToSVNPath(path, false);
notificationHandler.logCommandLine(
"propset "
+ (recurse?"-R ":"")
+ propertyName
+ " \""
+ propertyValue
+ "\" "
+ target);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
Set statusBefore = null;
if (recurse) {
statusBefore = new HashSet();
ISVNStatus[] statuses = getStatus(path,recurse,false);
for (int i = 0; i < statuses.length;i++) {
statusBefore.add(statuses[i].getFile().getAbsolutePath());
}
}
svnClient.propertySet(target, propertyName, propertyValue, recurse);
// there is no notification (Notify.notify is not called) when we set a property
// so we will do notification ourselves
if (recurse) {
ISVNStatus[] statuses = getStatus(path,recurse,false);
for (int i = 0; i < statuses.length;i++) {
String statusPath = statuses[i].getFile().getAbsolutePath();
notificationHandler.notifyListenersOfChange(statusPath);
statusBefore.remove(statusPath);
}
for (Iterator it = statusBefore.iterator(); it.hasNext();)
notificationHandler.notifyListenersOfChange((String)it.next());
} else {
notificationHandler.notifyListenersOfChange(path.getAbsolutePath());
}
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#propertySet(java.io.File, java.lang.String, java.io.File, boolean)
*/
public void propertySet(
File path,
String propertyName,
File propertyFile,
boolean recurse)
throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.PROPSET);
String target = fileToSVNPath(path, false);
notificationHandler.logCommandLine(
"propset "
+ (recurse?"-R ":"")
+ propertyName
+ "-F \""
+ propertyFile.toString()
+ "\" "
+ target);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
byte[] propertyBytes = new byte[(int) propertyFile.length()];
FileInputStream is = null;
try {
is = new FileInputStream(propertyFile);
is.read(propertyBytes);
}
catch (IOException ioe) {
throw new SVNClientException(ioe);
}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// ignore
}
}
}
Set statusBefore = null;
if (recurse) {
statusBefore = new HashSet();
ISVNStatus[] statuses = getStatus(path,recurse,false);
for (int i = 0; i < statuses.length;i++) {
statusBefore.add(statuses[i].getFile().getAbsolutePath());
}
}
svnClient.propertySet(target, propertyName, propertyBytes, recurse);
// there is no notification (Notify.notify is not called) when we set a property
// so we will do notification ourselves
if (recurse) {
ISVNStatus[] statuses = getStatus(path,recurse,false);
for (int i = 0; i < statuses.length;i++) {
String statusPath = statuses[i].getFile().getAbsolutePath();
notificationHandler.notifyListenersOfChange(statusPath);
statusBefore.remove(statusPath);
}
for (Iterator it = statusBefore.iterator(); it.hasNext();)
notificationHandler.notifyListenersOfChange((String)it.next());
} else {
notificationHandler.notifyListenersOfChange(path.getAbsolutePath());
}
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#propertyGet(java.io.File, java.lang.String)
*/
public ISVNProperty propertyGet(File path, String propertyName)
throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.PROPGET);
String target = fileToSVNPath(path, false);
notificationHandler.logCommandLine(
"propget " + propertyName + " " + target);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
PropertyData propData = svnClient.propertyGet(target, propertyName);
if (propData == null)
return null;
else
return JhlPropertyData.newForFile(propData);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#propertyGet(org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision, org.tigris.subversion.svnclientadapter.SVNRevision, java.lang.String)
*/
public ISVNProperty propertyGet(SVNUrl url, SVNRevision revision,
SVNRevision peg, String propertyName) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.PROPGET);
String target = url.toString();
String commandLine = "propget -r " + revision.toString() + " " +
propertyName + " " + target;
if (!peg.equals(SVNRevision.HEAD))
commandLine += "@" + peg.toString();
notificationHandler.logCommandLine(commandLine);
notificationHandler.setBaseDir();
PropertyData propData = svnClient.propertyGet(target, propertyName, JhlConverter.convert(revision),
JhlConverter.convert(peg));
if (propData == null)
return null;
else
return JhlPropertyData.newForUrl(propData);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#propertyDel(java.io.File, java.lang.String, boolean)
*/
public void propertyDel(File path, String propertyName,boolean recurse) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.PROPDEL);
String target = fileToSVNPath(path, false);
notificationHandler.logCommandLine("propdel "+propertyName+" "+target);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
Set statusBefore = null;
if (recurse) {
statusBefore = new HashSet();
ISVNStatus[] statuses = getStatus(path,recurse,false);
for (int i = 0; i < statuses.length;i++) {
statusBefore.add(statuses[i].getFile().getAbsolutePath());
}
}
// propertyRemove is on repository, this will be present on next version of javahl
// svnClient.propertyRemove(target, propertyName,recurse);
// @TODO : change this method when svnjavahl will be upgraded
// for now we use this workaround
PropertyData propData = svnClient.propertyGet(target,propertyName);
propData.remove(recurse);
// there is no notification (Notify.notify is not called) when we set a property
// so we will do notification ourselves
if (recurse) {
ISVNStatus[] statuses = getStatus(path,recurse,false);
for (int i = 0; i < statuses.length;i++) {
String statusPath = statuses[i].getFile().getAbsolutePath();
notificationHandler.notifyListenersOfChange(statusPath);
statusBefore.remove(statusPath);
}
for (Iterator it = statusBefore.iterator(); it.hasNext();)
notificationHandler.notifyListenersOfChange((String)it.next());
} else {
notificationHandler.notifyListenersOfChange(path.getAbsolutePath());
}
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#diff(java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision, java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision, java.io.File, boolean)
*/
public void diff(File oldPath, SVNRevision oldPathRevision,
File newPath, SVNRevision newPathRevision,
File outFile, boolean recurse) throws SVNClientException {
diff(oldPath, oldPathRevision, newPath, newPathRevision, outFile, recurse, true, false, false);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#diff(java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision, java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision, java.io.File, boolean, boolean, boolean, boolean)
*/
public void diff(File oldPath, SVNRevision oldPathRevision,
File newPath, SVNRevision newPathRevision,
File outFile, boolean recurse, boolean ignoreAncestry,
boolean noDiffDeleted, boolean force) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.DIFF);
if (oldPath == null)
oldPath = new File(".");
if (newPath == null)
newPath = oldPath;
if (oldPathRevision == null)
oldPathRevision = SVNRevision.BASE;
if (newPathRevision == null)
newPathRevision = SVNRevision.WORKING;
// we don't want canonical file path (otherwise the complete file name
// would be in the patch). This way the user can choose to use a relative
// path
String oldTarget = fileToSVNPath(oldPath, false);
String newTarget = fileToSVNPath(newPath, false);
String svnOutFile = fileToSVNPath(outFile, false);
String commandLine = "diff ";
if ( (oldPathRevision.getKind() != RevisionKind.base) ||
(newPathRevision.getKind() != RevisionKind.working) )
{
commandLine += "-r "+oldPathRevision.toString();
if (newPathRevision.getKind() != RevisionKind.working)
commandLine+= ":"+newPathRevision.toString();
commandLine += " ";
}
if (!oldPath.equals(new File(".")))
commandLine += "--old "+oldTarget+" ";
if (!newPath.equals(oldPath))
commandLine += "--new "+newTarget+" ";
notificationHandler.logCommandLine(commandLine);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(new File[]{oldPath,newPath}));
svnClient.diff(oldTarget,JhlConverter.convert(oldPathRevision),newTarget,JhlConverter.convert(newPathRevision), svnOutFile, recurse, ignoreAncestry, noDiffDeleted, force);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#diff(java.io.File, java.io.File, boolean)
*/
public void diff(File path, File outFile, boolean recurse) throws SVNClientException {
diff(path, null,null,null,outFile,recurse);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#diff(org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision, org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision, java.io.File, boolean)
*/
public void diff(SVNUrl oldUrl, SVNRevision oldUrlRevision,
SVNUrl newUrl, SVNRevision newUrlRevision,
File outFile, boolean recurse) throws SVNClientException {
diff(oldUrl, oldUrlRevision, newUrl, newUrlRevision, outFile, recurse, true, false, false);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#diff(org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision, org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision, java.io.File, boolean, boolean, boolean, boolean)
*/
public void diff(SVNUrl oldUrl, SVNRevision oldUrlRevision,
SVNUrl newUrl, SVNRevision newUrlRevision,
File outFile, boolean recurse, boolean ignoreAncestry,
boolean noDiffDeleted, boolean force) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.DIFF);
if (newUrl == null)
newUrl = oldUrl;
if (oldUrlRevision == null)
oldUrlRevision = SVNRevision.HEAD;
if (newUrlRevision == null)
newUrlRevision = SVNRevision.HEAD;
String svnOutFile = fileToSVNPath(outFile, false);
String commandLine = "diff ";
if ( (oldUrlRevision.getKind() != RevisionKind.head) ||
(newUrlRevision.getKind() != RevisionKind.head) )
{
commandLine += "-r "+oldUrlRevision.toString();
if (newUrlRevision.getKind() != RevisionKind.head)
commandLine+= ":"+newUrlRevision.toString();
commandLine += " ";
}
commandLine += oldUrl+" ";
if (!newUrl.equals(oldUrl))
commandLine += newUrl+" ";
notificationHandler.logCommandLine(commandLine);
notificationHandler.setBaseDir();
svnClient.diff(oldUrl.toString(),JhlConverter.convert(oldUrlRevision),newUrl.toString(),JhlConverter.convert(newUrlRevision), svnOutFile, recurse, ignoreAncestry, noDiffDeleted, force);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#diff(org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision, org.tigris.subversion.svnclientadapter.SVNRevision, java.io.File, boolean)
*/
public void diff(SVNUrl url, SVNRevision oldUrlRevision, SVNRevision newUrlRevision,
File outFile, boolean recurse) throws SVNClientException {
diff(url,oldUrlRevision,url,newUrlRevision,outFile,recurse);
}
private ISVNAnnotations annotate(String target, SVNRevision revisionStart, SVNRevision revisionEnd)
throws SVNClientException
{
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.ANNOTATE);
if(revisionStart == null)
revisionStart = new SVNRevision.Number(1);
if(revisionEnd == null)
revisionEnd = SVNRevision.HEAD;
String commandLine = "blame ";
commandLine = commandLine + "-r " + revisionEnd.toString() + " ";
commandLine = commandLine + target + "@HEAD";
notificationHandler.logCommandLine(commandLine);
notificationHandler.setBaseDir();
JhlAnnotations annotations = new JhlAnnotations();
svnClient.blame(target, Revision.HEAD, JhlConverter.convert(revisionStart), JhlConverter.convert(revisionEnd), annotations);
return annotations;
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#annotate(org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision, org.tigris.subversion.svnclientadapter.SVNRevision)
*/
public ISVNAnnotations annotate(SVNUrl url, SVNRevision revisionStart, SVNRevision revisionEnd)
throws SVNClientException
{
return annotate(url.toString(), revisionStart, revisionEnd);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#annotate(java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision, org.tigris.subversion.svnclientadapter.SVNRevision)
*/
public ISVNAnnotations annotate(File file, SVNRevision revisionStart, SVNRevision revisionEnd)
throws SVNClientException
{
String target = fileToSVNPath(file, false);
//If the file is an uncommitted rename/move, we have to refer to original/source, not the new copy.
ISVNInfo info = getInfoFromWorkingCopy(file);
if ((SVNScheduleKind.ADD == info.getSchedule()) && (info.getCopyUrl() != null)) {
target = info.getCopyUrl().toString();
}
return annotate(target, revisionStart, revisionEnd);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#resolved(java.io.File)
*/
public void resolved(File path)
throws SVNClientException
{
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.RESOLVED);
String target = fileToSVNPath(path, true);
notificationHandler.logCommandLine("resolved "+target);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
svnClient.resolved(target,false);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/*
* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#cancelOperation()
*/
public void cancelOperation() throws SVNClientException {
try {
svnClient.cancelOperation();
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getInfoFromWorkingCopy(java.io.File)
*/
public ISVNInfo getInfoFromWorkingCopy(File path) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.INFO);
String target = fileToSVNPath(path, false);
notificationHandler.logCommandLine("info "+target);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
Info info = svnClient.info(target);
if (info == null) {
return new SVNInfoUnversioned(path);
}
return new JhlInfo(path, info);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getInfo(java.io.File)
*/
public ISVNInfo getInfo(File path) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.INFO);
String target = fileToSVNPath(path, false);
notificationHandler.logCommandLine("info "+target);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
//Call the simple info() first to check whether the resource actually exists in repositiory.
//If yes, the call info2() later to get more data from the repository.
Info info = svnClient.info(target);
if (info == null) {
return new SVNInfoUnversioned(path);
} else if (info.getLastChangedRevision() == Revision.SVN_INVALID_REVNUM)
{
//Item is not in repository (yet or anymore ?)
return new JhlInfo(path, info);
}
Info2[] info2 = svnClient.info2(target, Revision.HEAD, Revision.HEAD, false);
if (info2 == null || info2.length == 0) {
return new SVNInfoUnversioned(path);
} else {
return new JhlInfo2(path,info2[0]);
}
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getInfo(org.tigris.subversion.svnclientadapter.SVNUrl)
*/
public ISVNInfo getInfo(SVNUrl url, SVNRevision revision, SVNRevision peg) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.INFO);
String target = url.toString();
notificationHandler.logCommandLine("info "+target);
// notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(url));
Info2[] info = svnClient.info2(target, JhlConverter.convert(revision), JhlConverter.convert(peg), false);
if (info == null || info.length == 0) {
return new SVNInfoUnversioned(null);
} else {
return new JhlInfo2(null, info[0]);
}
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/*
* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#switchUrl(org.tigris.subversion.svnclientadapter.SVNUrl, java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision, boolean)
*/
public void switchToUrl(File path, SVNUrl url, SVNRevision revision, boolean recurse) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.SWITCH);
String target = fileToSVNPath(path, false);
String commandLine = "switch --force "+url+" "+target+" "+"-r"+revision.toString();
if (!recurse) {
commandLine += " -N";
}
notificationHandler.logCommandLine(commandLine);
File baseDir = SVNBaseDir.getBaseDir(path);
notificationHandler.setBaseDir(baseDir);
boolean force = true;
svnClient.doSwitch(target, url.toString(),JhlConverter.convert(revision),Depth.fromRecurse(recurse), force);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#setConfigDirectory(java.io.File)
*/
public void setConfigDirectory(File dir) throws SVNClientException {
try {
svnClient.setConfigDirectory(fileToSVNPath(dir,false));
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#cleanup(java.io.File)
*/
public void cleanup(File path) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.CLEANUP);
String target = fileToSVNPath(path, false);
String commandLine = "cleanup " + target;
notificationHandler.logCommandLine(commandLine);
svnClient.cleanup(target);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#merge(org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision, org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision, java.io.File, boolean, boolean, boolean, boolean)
*/
public void merge(SVNUrl path1, SVNRevision revision1, SVNUrl path2,
SVNRevision revision2, File localPath, boolean force,
boolean recurse, boolean dryRun, boolean ignoreAncestry) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.MERGE);
String target = fileToSVNPath(localPath, false);
String commandLine = "merge";
boolean samePath = false;
if (!recurse) {
commandLine += " -N";
}
if (dryRun) {
commandLine += " --dry-run";
}
if (force) {
commandLine += " --force";
}
if (ignoreAncestry) {
commandLine += " --ignore-ancestry";
}
if (path1.toString().equals(path2.toString())) {
samePath = true;
commandLine += " -r" + revision1.toString() + ":" + revision2.toString() + " " + path1;
} else {
commandLine += " " + path1 + "@" + revision1.toString() + " " + path2 + "@" + revision2.toString();
}
commandLine += " " + target;
notificationHandler.logCommandLine(commandLine);
File baseDir = SVNBaseDir.getBaseDir(localPath);
notificationHandler.setBaseDir(baseDir);
if (samePath) {
Revision peg = JhlConverter.convert(revision2);
svnClient.merge(path1.toString(), peg, JhlConverter.convert(revision1), JhlConverter.convert(revision2), target, force, recurse, ignoreAncestry, dryRun );
} else
svnClient.merge(path1.toString(), JhlConverter.convert(revision1), path2.toString(), JhlConverter.convert(revision2), target, force, recurse, ignoreAncestry, dryRun );
if (dryRun)
notificationHandler.logCompleted("Dry-run merge complete.");
else
notificationHandler.logCompleted("Merge complete.");
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#addPasswordCallback(org.tigris.subversion.svnclientadapter.ISVNPromptUserPassword)
*/
public void addPasswordCallback(ISVNPromptUserPassword callback) {
if (callback != null) {
JhlPromptUserPassword prompt = new JhlPromptUserPassword(callback);
this.setPromptUserPassword(prompt);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#lock(org.tigris.subversion.svnclientadapter.SVNUrl[], java.lang.String, boolean)
*/
public void lock(SVNUrl[] uris, String comment, boolean force)
throws SVNClientException {
notImplementedYet();
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#unlock(org.tigris.subversion.svnclientadapter.SVNUrl[], boolean)
*/
public void unlock(SVNUrl[] uris, boolean force)
throws SVNClientException {
notImplementedYet();
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#lock(java.lang.String[], java.lang.String, boolean)
*/
public void lock(File[] paths, String comment, boolean force)
throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.LOCK);
String[] files = new String[paths.length];
String commandLine = "lock -m \""+comment+"\"";
if (force)
commandLine+=" --force";
for (int i = 0; i < paths.length; i++) {
files[i] = fileToSVNPath(paths[i], false);
commandLine+=" "+files[i];
}
notificationHandler.logCommandLine(commandLine);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(paths));
svnClient.lock(files, comment, force);
for (int i = 0; i < files.length; i++) {
notificationHandler.notifyListenersOfChange(files[i]);
}
} catch (ClientException e) {
notificationHandler.logException(e);
// throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#unlock(java.io.File[], boolean)
*/
public void unlock(File[] paths, boolean force) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.LOCK);
String[] files = new String[paths.length];
String commandLine = "unlock ";
if (force)
commandLine+=" --force";
for (int i = 0; i < paths.length; i++) {
files[i] = fileToSVNPath(paths[i], false);
commandLine+=" "+files[i];
}
notificationHandler.logCommandLine(commandLine);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(paths));
svnClient.unlock(files, force);
for (int i = 0; i < files.length; i++) {
notificationHandler.notifyListenersOfChange(files[i]);
}
} catch (ClientException e) {
notificationHandler.logException(e);
// throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#setRevProperty(org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision.Number, java.lang.String, java.lang.String, boolean)
*/
public void setRevProperty(SVNUrl url, SVNRevision.Number revisionNo, String propName, String propertyData, boolean force) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.PROPSET);
notificationHandler.logCommandLine(
"propset --revprop -r " + revisionNo.toString()
+ (force ? "--force " : "")
+ " \""
+ propName
+ "\" \""
+ propertyData
+ "\" "
+ url.toString());
notificationHandler.setBaseDir();
svnClient.setRevProperty(url.toString(), propName, Revision.getInstance(revisionNo.getNumber()), propertyData, true);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getAdminDirectoryName()
*/
public String getAdminDirectoryName() {
return svnClient.getAdminDirectoryName();
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#isAdminDirectory(java.lang.String)
*/
public boolean isAdminDirectory(String name) {
return svnClient.isAdminDirectory(name);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getLogMessages(java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision, org.tigris.subversion.svnclientadapter.SVNRevision, boolean)
*/
public ISVNLogMessage[] getLogMessages(File path,
SVNRevision revisionStart, SVNRevision revisionEnd,
boolean fetchChangePath) throws SVNClientException {
return this.getLogMessages(path, revisionStart, revisionEnd, false,
fetchChangePath);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getLogMessages(java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision, org.tigris.subversion.svnclientadapter.SVNRevision, boolean, boolean)
*/
public ISVNLogMessage[] getLogMessages(File path,
SVNRevision revisionStart, SVNRevision revisionEnd,
boolean stopOnCopy, boolean fetchChangePath)
throws SVNClientException {
return this.getLogMessages(path, revisionStart, revisionEnd,
stopOnCopy, fetchChangePath, 0);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getLogMessages(java.io.File, org.tigris.subversion.svnclientadapter.SVNRevision, org.tigris.subversion.svnclientadapter.SVNRevision, boolean, boolean, long)
*/
public ISVNLogMessage[] getLogMessages(File path,
SVNRevision revisionStart, SVNRevision revisionEnd,
boolean stopOnCopy, boolean fetchChangePath, long limit)
throws SVNClientException {
String target = fileToSVNPath(path, false);
//If the file is an uncommitted rename/move, we have to refer to original/source, not the new copy.
ISVNInfo info = getInfoFromWorkingCopy(path);
if ((SVNScheduleKind.ADD == info.getSchedule()) && (info.getCopyUrl() != null)) {
target = info.getCopyUrl().toString();
}
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
return this.getLogMessages(target, revisionStart, revisionEnd,
stopOnCopy, fetchChangePath, limit);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getLogMessages(org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision, org.tigris.subversion.svnclientadapter.SVNRevision, boolean)
*/
public ISVNLogMessage[] getLogMessages(SVNUrl url,
SVNRevision revisionStart, SVNRevision revisionEnd,
boolean fetchChangePath) throws SVNClientException {
String target = url.toString();
notificationHandler.setBaseDir();
return this.getLogMessages(target, revisionStart, revisionEnd, false,
fetchChangePath, 0);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getLogMessages(org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision, org.tigris.subversion.svnclientadapter.SVNRevision, org.tigris.subversion.svnclientadapter.SVNRevision, boolean, boolean, long)
*/
public ISVNLogMessage[] getLogMessages(SVNUrl url, SVNRevision pegRevision,
SVNRevision revisionStart, SVNRevision revisionEnd,
boolean stopOnCopy, boolean fetchChangePath, long limit)
throws SVNClientException {
//TODO pegRevision is ignored !
String target = url.toString();
notificationHandler.setBaseDir();
return this.getLogMessages(target, revisionStart, revisionEnd, stopOnCopy, fetchChangePath, limit);
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#getLogMessages(org.tigris.subversion.svnclientadapter.SVNUrl, java.lang.String[], org.tigris.subversion.svnclientadapter.SVNRevision, org.tigris.subversion.svnclientadapter.SVNRevision, boolean, boolean)
*/
public ISVNLogMessage[] getLogMessages(final SVNUrl url,
final String[] paths, SVNRevision revStart, SVNRevision revEnd,
boolean stopOnCopy, boolean fetchChangePath)
throws SVNClientException {
notImplementedYet();
return null;
}
private ISVNLogMessage[] getLogMessages(String target,
SVNRevision revisionStart, SVNRevision revisionEnd,
boolean stopOnCopy, boolean fetchChangePath, long limit)
throws SVNClientException {
try {
notificationHandler.setCommand(
ISVNNotifyListener.Command.LOG);
String logExtras = "";
if (stopOnCopy)
logExtras = logExtras + " --stop-on-copy";
if (limit > 0 )
logExtras = logExtras + " --limit " + limit;
notificationHandler.logCommandLine(
"log -r "
+ revisionStart.toString()
+ ":"
+ revisionEnd.toString()
+ " "
+ target
+ logExtras);
return JhlConverter.convert(
svnClient.logMessages(
target,
JhlConverter.convert(revisionStart),
JhlConverter.convert(revisionEnd),
stopOnCopy,
fetchChangePath,
limit));
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#relocate(java.lang.String, java.lang.String, java.lang.String, boolean)
*/
public void relocate(String from, String to, String path, boolean recurse)
throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.RELOCATE);
if (recurse)
notificationHandler.logCommandLine("switch --relocate "+ from + " " + to + " " + path);
else
notificationHandler.logCommandLine("switch --relocate -N"+ from + " " + to + " " + path);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(new File(path)));
svnClient.relocate(from, to, path, recurse);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
/* (non-Javadoc)
* @see org.tigris.subversion.svnclientadapter.ISVNClientAdapter#diff(java.io.File, org.tigris.subversion.svnclientadapter.SVNUrl, org.tigris.subversion.svnclientadapter.SVNRevision, java.io.File, boolean)
*/
public void diff(File path, SVNUrl url, SVNRevision urlRevision,
File outFile, boolean recurse) throws SVNClientException {
try {
notificationHandler.setCommand(ISVNNotifyListener.Command.DIFF);
// we don't want canonical file path (otherwise the complete file name
// would be in the patch). This way the user can choose to use a relative
// path
String wcPath = fileToSVNPath(path, false);
String svnOutFile = fileToSVNPath(outFile, false);
String commandLine = "diff --old " + wcPath + " ";
commandLine += "--new " + url.toString();
if (!urlRevision.equals(SVNRevision.HEAD))
commandLine += "@"+ urlRevision.toString();
notificationHandler.logCommandLine(commandLine);
notificationHandler.setBaseDir(SVNBaseDir.getBaseDir(path));
svnClient.diff(wcPath,Revision.WORKING,url.toString(),JhlConverter.convert(urlRevision), svnOutFile, recurse);
} catch (ClientException e) {
notificationHandler.logException(e);
throw new SVNClientException(e);
}
}
public void mkdir(SVNUrl url, boolean makeParents, String message)
throws SVNClientException {
if (makeParents) {
SVNUrl parent = url.getParent();
if (parent != null) {
ISVNInfo info = null;
try {
info = this.getInfo(parent);
} catch (SVNClientException e) {
if (e.getCause() instanceof ClientException) {
ClientException ce = (ClientException) e.getCause();
if (ce.getAprError() != 170000)
throw e;
}
}
if (info == null)
this.mkdir(parent, makeParents, message);
}
}
this.mkdir(url, message);
}
} |
package br.ufu.renova.scraper;
import java.io.Serializable;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Book implements Serializable {
public enum State {
INITIAL("", false),
RENEWED("", false),
INVALID_RENEW_DATE("O livro não pode ser renovado na data atual.", true),
REQUESTED("O livro foi solicitado.", true),
RENEW_LIMIT_REACHED("O limite de renovações do livro foi alcançado.", true);
public final String MSG;
public final boolean IS_ERROR_STATE;
State(String msg, boolean isErrorState) {
this.MSG = msg;
this.IS_ERROR_STATE = isErrorState;
}
}
private State state = State.INITIAL;
private String barcode;
private String title;
private String authors;
private Date expiration;
private String callNumber;
private String note;
private String status;
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
public String getCallNumber() {
return callNumber;
}
public void setCallNumber(String callNumber) {
this.callNumber = callNumber;
}
public Date getExpiration() {
return expiration;
}
public void setExpiration(Date expiration) {
this.expiration = expiration;
}
public String getAuthors() {
return authors;
}
public void setAuthors(String authors) {
this.authors = authors;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
public String toString() {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm");
return title + " - " + authors + " - " + dateFormat.format(expiration);
}
public State getState() {
return state;
}
public void setState(State state) {
this.state = state;
}
public int getNotificationId() {
return Integer.parseInt(barcode);
}
} |
package com.ogsdroid;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.StrictMode;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import com.ogs.ChatMessage;
import com.ogs.GameConnection;
import com.ogs.OGS;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Main3Activity extends AppCompatActivity {
private static final String TAG = "Main3Activity";
private GameConnection gameCon;
private String phase = "play";
private BoardView bv;
private Board board;
private String prefix = "";
private GameData gamedata = null;
private MediaPlayer clickSound;
private MediaPlayer passSound;
private int currentGameId;
private OGS ogs;
@Override
protected void onPostResume() {
super.onPostResume();
Log.d(TAG, "onPostResume"); |
package org.helioviewer.jhv.plugins.swek.config;
import java.util.ArrayList;
import java.util.List;
import javax.swing.Icon;
/**
* Describes a SWEK event type.
*
* @author Bram Bourgoignie (Bram.bourgoignie@oma.be)
*
*/
public class SWEKEventType {
/** The name of the event */
private String eventName;
/** List of suppliers of the event */
private List<SWEKSupplier> suppliers;
/** List of event specific parameters */
private List<SWEKParameter> parameterList;
/** Extension of the request interval for this event type */
private Long requestIntervalExtension;
/** Is the event type standard selected */
private boolean standardSelected;
/** On what should events be grouped on */
private SWEKParameter groupOn;
/** The coordinate system */
private String coordinateSystem;
/** The spatial region over which the event can be found */
private SWEKSpatialRegion spatialRegion;
/** The icon corresponding with the event type */
private Icon eventIcon;
/**
* Create a SWEKEvenType with an empty name, suppliers list, parameter list,
* not standard selected, grouped on nothing, no coordinate system, no
* spatial region and event icon null.
*/
public SWEKEventType() {
super();
eventName = "";
suppliers = new ArrayList<SWEKSupplier>();
parameterList = new ArrayList<SWEKParameter>();
requestIntervalExtension = 0L;
standardSelected = false;
groupOn = null;
coordinateSystem = "";
spatialRegion = new SWEKSpatialRegion();
eventIcon = null;
}
/**
* Creates an event type for the given event name, suppliers list, parameter
* list, request interval extension, standard selected indication, group on
* parameter, coordinate system and icon.
*
* @param eventName
* The name of the event
* @param suppliers
* The list of suppliers for this event type
* @param parameterList
* The list of parameters for this event
* @param requestIntervalExtension
* The extension of the requested interval
* @param standardSelected
* Is the event type standard selected
* @param groupOn
* On what are corresponding events grouped
* @param coordinateSystem
* The coordinate system
* @param eventIcon
* the icon of the event type
*/
public SWEKEventType(String eventName, List<SWEKSupplier> suppliers, List<SWEKParameter> parameterList, Long requestIntervalExtension,
boolean standardSelected, SWEKParameter groupOn, String coordinateSystem, Icon eventIcon) {
super();
this.eventName = eventName;
this.suppliers = suppliers;
this.parameterList = parameterList;
this.requestIntervalExtension = requestIntervalExtension;
this.standardSelected = standardSelected;
this.groupOn = groupOn;
this.coordinateSystem = coordinateSystem;
this.eventIcon = eventIcon;
}
/**
* Gives the name of the event type.
*
* @return the eventName
*/
public String getEventName() {
return eventName;
}
/**
* Sets the name of the event type.
*
* @param eventName
* the eventName to set
*/
public void setEventName(String eventName) {
this.eventName = eventName;
}
/**
* Gets the list of suppliers.
*
* @return the suppliers
*/
public List<SWEKSupplier> getSuppliers() {
return suppliers;
}
/**
* Sets the list of suppliers.
*
* @param suppliers
* the suppliers to set
*/
public void setSuppliers(List<SWEKSupplier> suppliers) {
this.suppliers = suppliers;
}
/**
* Get the list of event type specific parameters
*
* @return the parameterList
*/
public List<SWEKParameter> getParameterList() {
return parameterList;
}
/**
* Sets the list of event type specific parameters.
*
* @param parameterList
* the parameterList to set
*/
public void setParameterList(List<SWEKParameter> parameterList) {
this.parameterList = parameterList;
}
/**
* Gets the time extension of the requested time interval.
*
* @return the requestIntervalExtension
*/
public Long getRequestIntervalExtension() {
return requestIntervalExtension;
}
/**
* Sets the extension of the requested time interval.
*
* @param requestIntervalExtension
* the requestIntervalExtension to set
*/
public void setRequestIntervalExtension(Long requestIntervalExtension) {
this.requestIntervalExtension = requestIntervalExtension;
}
/**
* Is this event type standard selected.
*
* @return the standardSelected True if the event type is standard selected,
* false if not
*/
public boolean isStandardSelected() {
return standardSelected;
}
/**
* Sets the event type standard selected if true, not standard selected if
* false.
*
* @param standardSelected
* True if the event type is standart selected, false if not
*/
public void setStandardSelected(boolean standardSelected) {
this.standardSelected = standardSelected;
}
/**
* Gives the parameter on which corresponding events should be grouped.
*
* @return the groupOn
*/
public SWEKParameter getGroupOn() {
return groupOn;
}
/**
* Sets the parameter on which corresponding events should be grouped.
*
* @param groupOn
* the groupOn to set
*/
public void setGroupOn(SWEKParameter groupOn) {
this.groupOn = groupOn;
}
/**
* Gets the coordinate system.
*
* @return the coordinate system
*/
public String getCoordinateSystem() {
return coordinateSystem;
}
/**
* Sets the coordinate system.
*
* @param coordinateSystem
* the coordinate system
*/
public void setCoordinateSystem(String coordinateSystem) {
this.coordinateSystem = coordinateSystem;
}
/**
* Gets the spatial region for this event type.
*
* @return The spatial region
*/
public SWEKSpatialRegion getSpatialRegion() {
return spatialRegion;
}
/**
* Sets the spatial region for this event.
*
* @param spatialRegion
* The spatial region
*/
public void setSpatialRegion(SWEKSpatialRegion spatialRegion) {
this.spatialRegion = spatialRegion;
}
/**
* Contains this source the following parameter.
*
* @param name
* the name of the parameter
* @return true if the parameter is configured for this source, false if the
* parameter is not configured for this source
*/
public boolean containsParameter(String name) {
for (SWEKParameter parameter : parameterList) {
if (parameter.getParameterName().toLowerCase().equals(name.toLowerCase())) {
return true;
}
}
return false;
}
/**
* Gets a parameter from the event type.
*
* @param name
* the name of the parameter defined in the swek source
* @return the parameter if present in the event type, null if the parameter
* was not found.
*/
public SWEKParameter getParameter(String name) {
for (SWEKParameter parameter : parameterList) {
if (parameter.getParameterName().toLowerCase().equals(name.toLowerCase())) {
return parameter;
}
}
return null;
}
/**
* Gets the event icon.
*
* @return the icon of the event type
*/
public Icon getEventIcon() {
return eventIcon;
}
/**
* Sets the event icon.
*
* @param eventIcon
* the icon of the event type
*/
public void setEventIcon(Icon eventIcon) {
this.eventIcon = eventIcon;
}
} |
package org.wyona.yanel.impl.resources.image;
import org.wyona.yanel.core.Resource;
import org.wyona.yanel.core.api.attributes.ViewableV2;
import org.wyona.yanel.core.attributes.viewable.View;
import org.wyona.yanel.core.attributes.viewable.ViewDescriptor;
import org.wyona.yarep.core.Node;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import java.awt.image.BufferedImage;
import java.awt.image.AffineTransformOp;
import java.awt.geom.AffineTransform;
import javax.imageio.ImageIO;
/**
* Resource to scale (down) images (but only jpeg so far)
*/
public class ImageResource extends Resource implements ViewableV2 {
private static Logger log = LogManager.getLogger(ImageResource.class);
private String DEFAULT_CACHE_DIRECTORY = "/cached-images";
/**
* @see org.wyona.yanel.core.api.attributes.ViewableV2#exists()
*/
public boolean exists() throws Exception {
return getRealm().getRepository().existsNode(getPath());
}
/**
* @see org.wyona.yanel.core.api.attributes.ViewableV2#getSize()
*/
public long getSize() throws Exception {
// TODO Auto-generated method stub
return 0;
}
/**
* @see org.wyona.yanel.core.api.attributes.ViewableV2#getView(String)
*/
public View getView(String viewId) throws Exception {
if (!exists()) {
throw new org.wyona.yanel.core.ResourceNotFoundException("No such image: " + getPath());
}
BufferedImage sourceImg = ImageIO.read(getRealm().getRepository().getNode(getPath()).getInputStream());
int sourceWidth = sourceImg.getWidth();
int sourceHeight = sourceImg.getHeight();
if (log.isDebugEnabled()) log.debug("Source Width: " + sourceWidth + ", Source Height: " + sourceHeight);
int destWidth = getDestWidth();
int destHeight = getDestHeight();
if (log.isDebugEnabled()) log.debug(" Dest Width: " + destWidth + ", Dest Height: " + destHeight);
double scaleFactor = getScaleFactor(sourceWidth, sourceHeight, destWidth, destHeight); //(double) destHeight / (double) sourceHeight;
if (log.isDebugEnabled()) log.debug("Scale factor: " + scaleFactor);
Node cacheNode;
if (existsMoreRecentCacheNode()) {
//log.debug("Get image from cache...");
cacheNode = getCacheNode();
} else {
log.debug("Scale image and add scaled version to cache...");
cacheNode = createCacheNode();
ImageIO.write(scale(sourceImg, scaleFactor), "JPG", cacheNode.getOutputStream());
}
View view = new View();
view.setInputStream(cacheNode.getInputStream());
view.setMimeType("image/jpeg");
return view;
}
/**
* @see org.wyona.yanel.core.api.attributes.ViewableV2#getViewDescriptors()
*/
public ViewDescriptor[] getViewDescriptors() {
// TODO Auto-generated method stub
return null;
}
private static BufferedImage scale(BufferedImage orig, double scale) {
if (scale == 1.0) return orig; // same size ?
AffineTransform resizeDefinition = AffineTransform.getScaleInstance(scale, scale);
AffineTransformOp resizer = new AffineTransformOp(resizeDefinition, AffineTransformOp.TYPE_BILINEAR);
int width = (int) (orig.getWidth() * scale);
int height = (int) (orig.getHeight() * scale);
BufferedImage result = new BufferedImage(width, height, orig.getType());
resizer.filter(orig, result);
return result;
}
/**
* Get destination width
* @return TODO
*/
private int getDestWidth() throws Exception {
// TODO: Get destination width from query string: getEnvironment().getRequest().getParameter("width")
if (getResourceConfigProperty("width") != null) {
return new Integer(getResourceConfigProperty("width")).intValue();
} else {
log.debug("No destination width configured");
if (getResourceConfigProperty("height") != null) {
return -1;
} else {
throw new Exception("Neither height nor width configured!");
}
}
}
/**
* Get destination height
*/
private int getDestHeight() throws Exception {
// TODO: Get destination height from query string: getEnvironment().getRequest().getParameter("height")
if (getResourceConfigProperty("height") != null) {
return new Integer(getResourceConfigProperty("height")).intValue();
} else {
log.debug("No destination height configured");
if (getResourceConfigProperty("width") != null) {
return -1;
} else {
throw new Exception("Neither height nor width configured!");
}
}
}
/**
* Get scale factor
* @param sourceWidth TODO
*/
private double getScaleFactor(double sourceWidth, double sourceHeight, double destWidth, double destHeight) {
if (destWidth > 0 && destHeight <= 0) {
log.debug("Use width to calculate scale factor");
return (double) destWidth / (double) sourceWidth;
} else if (destWidth <= 0 && destHeight > 0) {
log.debug("Use height to calculate scale factor");
return (double) destHeight / (double) sourceHeight;
} else if (destWidth <= 0 && destHeight <= 0) {
log.error("Neither destination width nor height make sense to calculate scale factor, hence do not scale!");
return 1;
} else if (destWidth > 0 && destHeight > 0) {
log.warn("Width or height could be used, hence use height to calculate scale factor");
double destRatio = (double) destWidth / (double) destHeight;
double sourceRatio = (double) sourceWidth / (double) sourceHeight;
if (sourceRatio != destRatio) {
log.warn("Source (" + sourceRatio + ") and destination (" + destRatio + ") width/height ratio are NOT the same!");
}
return (double) destHeight / (double) sourceHeight;
} else {
log.error("We should never get here!");
return 1;
}
}
/**
* Create cache node
*/
private Node createCacheNode() throws Exception {
String cacheRootPath = getResourceConfigProperty("cache-root-path");
if (cacheRootPath == null) {
cacheRootPath = DEFAULT_CACHE_DIRECTORY;
log.warn("No cache root path configured within resource configuration. Use default '" + cacheRootPath + "'!");
}
Node cacheNode;
if (!getRealm().getRepository().existsNode(cacheRootPath + getPath())) {
cacheNode = org.wyona.yarep.util.YarepUtil.addNodes(getRealm().getRepository(), cacheRootPath + getPath(), org.wyona.yarep.core.NodeType.RESOURCE);
log.warn("Cached image did not exist yet, hence has been created: " + cacheNode.getPath());
} else {
cacheNode = getRealm().getRepository().getNode(cacheRootPath + getPath());
log.error("The cache already seems to exist: " + cacheNode.getPath());
}
return cacheNode;
}
/**
* Get cache node
*/
private Node getCacheNode() throws Exception {
String cacheRootPath = getResourceConfigProperty("cache-root-path");
if (cacheRootPath == null) {
cacheRootPath = DEFAULT_CACHE_DIRECTORY;
log.debug("No cache root path configured within resource configuration. Use default '" + cacheRootPath + "'!");
}
if (getRealm().getRepository().existsNode(cacheRootPath + getPath())) {
return getRealm().getRepository().getNode(cacheRootPath + getPath());
} else {
log.error("No such cache node: " + cacheRootPath + getPath());
return null;
}
}
/**
* Check whether cache node exists and if so, then compare last modified
* @return TODO
*/
private boolean existsMoreRecentCacheNode() throws Exception {
String cacheRootPath = getResourceConfigProperty("cache-root-path");
if (cacheRootPath == null) {
cacheRootPath = DEFAULT_CACHE_DIRECTORY;
log.debug("No cache root path configured within resource configuration. Use default '" + cacheRootPath + "'!");
}
if (getRealm().getRepository().existsNode(cacheRootPath + getPath())) {
long lastModifiedCacheNode = getRealm().getRepository().getNode(cacheRootPath + getPath()).getLastModified();
long lastModifiedOriginalNode = getRealm().getRepository().getNode(getPath()).getLastModified();
if (lastModifiedCacheNode > lastModifiedOriginalNode) {
//log.debug("Compare last modified: " + lastModifiedCacheNode + ", " + lastModifiedOriginalNode);
return true;
} else {
log.warn("Cached image seems to be out of date: " + cacheRootPath + getPath());
return false;
}
} else {
log.error("No such cache node: " + cacheRootPath + getPath());
return false;
}
}
} |
package cn.edu.zjnu.acm.judge.controller.submission;
import cn.edu.zjnu.acm.judge.Application;
import cn.edu.zjnu.acm.judge.config.JudgeConfiguration;
import cn.edu.zjnu.acm.judge.domain.Submission;
import cn.edu.zjnu.acm.judge.service.AccountService;
import cn.edu.zjnu.acm.judge.service.AccountServiceTest;
import cn.edu.zjnu.acm.judge.service.DeleteService;
import cn.edu.zjnu.acm.judge.service.MockDataService;
import cn.edu.zjnu.acm.judge.service.SubmissionService;
import cn.edu.zjnu.acm.judge.util.CopyHelper;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import lombok.extern.slf4j.Slf4j;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.env.Environment;
import org.springframework.http.MediaType;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import static org.hamcrest.Matchers.hasItemInArray;
import static org.junit.Assume.assumeThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.asyncDispatch;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.request;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
@AutoConfigureMockMvc(addFilters = false)
@RunWith(SpringRunner.class)
@Slf4j
@SpringBootTest(classes = Application.class)
@WebAppConfiguration
@WithMockUser(roles = "ADMIN")
public class RejudgeControllerTest {
@Autowired
private MockMvc mvc;
@Autowired
private MockDataService mockDataService;
@Autowired
private Environment environment;
@Autowired
private SubmissionService submissionService;
@Autowired
private JudgeConfiguration judgeConfiguration;
private Submission submission;
@Autowired
private AccountService accountService;
@Autowired
private DeleteService deleteService;
@Before
public void setUp() throws IOException, URISyntaxException {
submission = mockDataService.submission();
Path dataDir = judgeConfiguration.getDataDirectory(submission.getProblem());
CopyHelper.copy(Paths.get(RejudgeControllerTest.class.getResource("/sample/data").toURI()), dataDir, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
}
@After
public void tearDown() throws IOException {
if (submission != null) {
deleteService.delete(judgeConfiguration.getDataDirectory(submission.getProblem()));
submissionService.delete(submission.getId());
AccountServiceTest.delete(accountService, submission.getUser());
}
}
/**
* Test of rejudgeSolution method, of class RejudgeController.
*
* @see RejudgeController#rejudgeSolution(long)
*/
@Test
public void testRejudgeSolution() throws Exception {
assumeThat(environment.getActiveProfiles(), hasItemInArray("appveyor"));
log.info("rejudgeSolution");
long solutionId = submission.getId();
MvcResult result = mvc.perform(get("/admin/rejudge")
.accept(MediaType.TEXT_HTML, MediaType.APPLICATION_JSON)
.param("solution_id", Long.toString(solutionId)))
.andExpect(request().asyncStarted())
.andReturn();
mvc.perform(asyncDispatch(result))
.andExpect(status().isOk())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andReturn();
}
/**
* Test of rejudgeProblem method, of class RejudgeController.
*
* @see RejudgeController#rejudgeProblem(long)
*/
@Test
public void testRejudgeProblem() throws Exception {
log.info("rejudgeProblem");
long problem_id = 0;
MvcResult result = mvc.perform(get("/admin/rejudge")
.accept(MediaType.TEXT_HTML, MediaType.APPLICATION_JSON)
.param("problem_id", Long.toString(problem_id)))
.andExpect(status().isAccepted())
.andExpect(content().contentTypeCompatibleWith(MediaType.APPLICATION_JSON))
.andReturn();
}
} |
package edu.berkeley.path.beats.test.simulator.output;
import static org.junit.Assert.*;
import org.apache.log4j.Logger;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Vector;
import javax.xml.XMLConstants;
import javax.xml.stream.FactoryConfigurationError;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.transform.stax.StAXSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import edu.berkeley.path.beats.simulator.ObjectFactory;
import edu.berkeley.path.beats.simulator.Scenario;
import edu.berkeley.path.beats.simulator.SimulationSettings;
import edu.berkeley.path.beats.simulator.SiriusErrorLog;
import edu.berkeley.path.beats.simulator.SiriusException;
@RunWith(Parameterized.class)
public class XMLOutputWriterTest {
/** output file name prefix */
private static String OUT_PREFIX = "output_";
/** output file name suffix */
private static String OUT_SUFFIX = "_0.xml";
/** configuration file name suffix */
private static String CONF_SUFFIX = ".xml";
/** configuration (scenario) file */
private File conffile;
/** configuration (scenario) schema */
private static Schema ischema;
/** simulator output schema */
private static Schema oschema;
/**
* Loads scenario and simulator output schemas
* @throws SAXException
*/
@BeforeClass
public static void loadSchemas() throws SAXException {
SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
ClassLoader classLoader = XMLOutputWriterTest.class.getClassLoader();
ischema = factory.newSchema(classLoader.getResource("sirius.xsd"));
oschema = factory.newSchema(classLoader.getResource("sirius_output.xsd"));
}
/**
* Initializes testing environment
* @param conffile File the configuration file
*/
public XMLOutputWriterTest(File conffile) {
this.conffile = conffile;
}
* @return a Vector of configuration files <code>data/config/*.xml</code>
*/
@Parameters
public static Vector<Object[]> conffiles() {
File confdir = new File("data" + File.separator + "config");
File [] files = confdir.listFiles();
Vector<Object[]> res = new Vector<Object[]>(files.length);
for (File file : files) {
if (file.getName().endsWith(CONF_SUFFIX))
res.add(new Object[] {file});
}
return res;
}
private static Logger logger = Logger.getLogger(XMLOutputWriterTest.class);
/**
* Validates the configuration file, runs a simulation, validates the output.
* @throws IOException
* @throws SAXException
* @throws XMLStreamException
* @throws FactoryConfigurationError
* @throws SiriusException
*/
@Test
public void testOutputWriter() throws IOException, SAXException, XMLStreamException, FactoryConfigurationError, SiriusException {
logger.info("CONFIG: " + conffile.getPath());
validate(conffile, ischema);
String confname = conffile.getName();
logger.info("Config " + confname + " validated");
String out_prefix = OUT_PREFIX + confname.substring(0, confname.length() - CONF_SUFFIX.length()) + "_";
File outfile = File.createTempFile(out_prefix, OUT_SUFFIX);
runSirius(conffile.getPath(), outfile.getAbsolutePath());
logger.info("Simulation completed");
validate(outfile, oschema);
logger.info("Output validated");
outfile.delete();
logger.debug(outfile.getAbsolutePath() + " removed");
}
/**
* Validates an XML file
* @param xmlfile a File to be validated
* @param schema a Schema to validate against
* @throws FactoryConfigurationError
* @throws XMLStreamException
* @throws IOException
* @throws SAXException
* */
protected static void validate(File xmlfile, Schema schema) throws XMLStreamException, FactoryConfigurationError, SAXException, IOException {
Validator validator = schema.newValidator();
XMLStreamReader xmlsr = XMLInputFactory.newInstance().createXMLStreamReader(new FileInputStream(xmlfile));
validator.validate(new StAXSource(xmlsr));
}
/**
* Runs a simulation
* @param confpath String a configuration file path
* @param outpath String an output file path
* @throws SiriusException
*/
protected void runSirius(String confpath, String outpath) throws SiriusException {
// simulation settings
SimulationSettings simsettings = new SimulationSettings(SimulationSettings.defaults());
simsettings.setStartTime(0.0);
simsettings.setDuration(3600.0);
simsettings.setOutputDt(600.0);
// output writer properties
if (!outpath.endsWith(OUT_SUFFIX)) fail("Incorrect output file path: " + outpath);
Properties owr_props = new Properties();
owr_props.setProperty("prefix", outpath.substring(0, outpath.length() - OUT_SUFFIX.length()));
owr_props.setProperty("type", "xml");
// load the scenario
Scenario scenario = ObjectFactory.createAndLoadScenario(confpath);
if (null == scenario) fail("The scenario was not loaded");
// run the scenario
logger.info("Running a simulation");
scenario.run(simsettings, owr_props);
if (SiriusErrorLog.haserror()) {
SiriusErrorLog.print();
SiriusErrorLog.clearErrorMessage();
}
}
} |
package org.elasticsearch.watcher.actions.email.service;
import org.elasticsearch.common.collect.ImmutableMap;
import org.elasticsearch.test.ElasticsearchTestCase;
import org.junit.Test;
import static org.hamcrest.Matchers.equalTo;
public class HtmlSanitizeTests extends ElasticsearchTestCase {
@Test
public void test_HtmlSanitizer_onclick() {
String badHtml = "<button type=\"button\"" +
"onclick=\"document.getElementById('demo').innerHTML = Date()\">" +
"Click me to display Date and Time.</button>";
byte[] bytes = new byte[0];
String sanitizedHtml = Profile.sanitizeHtml(ImmutableMap.of("foo", (Attachment) new Attachment.Bytes("foo", bytes, "")), badHtml);
assertThat(sanitizedHtml, equalTo("Click me to display Date and Time."));
}
@Test
public void test_HtmlSanitizer_Nonattachment_img() {
String badHtml = "<img src=\"http://test.com/nastyimage.jpg\"/>This is a bad image";
byte[] bytes = new byte[0];
String sanitizedHtml = Profile.sanitizeHtml(ImmutableMap.of("foo", (Attachment) new Attachment.Bytes("foo", bytes, "")), badHtml);
assertThat(sanitizedHtml, equalTo("This is a bad image"));
}
@Test
public void test_HtmlSanitizer_Goodattachment_img() {
String goodHtml = "<img src=\"cid:foo\" />This is a good image";
byte[] bytes = new byte[0];
String sanitizedHtml = Profile.sanitizeHtml(ImmutableMap.of("foo", (Attachment) new Attachment.Bytes("foo", bytes, "")), goodHtml);
assertThat(sanitizedHtml, equalTo(goodHtml));
}
@Test
public void test_HtmlSanitizer_table() {
String goodHtml = "<table><tr><td>cell1</td><td>cell2</td></tr></table>";
byte[] bytes = new byte[0];
String sanitizedHtml = Profile.sanitizeHtml(ImmutableMap.of("foo", (Attachment) new Attachment.Bytes("foo", bytes, "")), goodHtml);
assertThat(sanitizedHtml, equalTo(goodHtml));
}
@Test
public void test_HtmlSanitizer_Badattachment_img() {
String goodHtml = "<img src=\"cid:bad\" />This is a bad image";
byte[] bytes = new byte[0];
String sanitizedHtml = Profile.sanitizeHtml(ImmutableMap.of("foo", (Attachment) new Attachment.Bytes("foo", bytes, "")), goodHtml);
assertThat(sanitizedHtml, equalTo("This is a bad image"));
}
@Test
public void test_HtmlSanitizer_Script() {
String badHtml = "<script>doSomethingNefarious()</script>This was a dangerous script";
byte[] bytes = new byte[0];
String sanitizedHtml = Profile.sanitizeHtml(ImmutableMap.of("foo", (Attachment) new Attachment.Bytes("foo", bytes, "")), badHtml);
assertThat(sanitizedHtml, equalTo("This was a dangerous script"));
}
@Test
public void test_HtmlSanitizer_FullHtmlWithMetaString() {
String needsSanitation = "<html><head></head><body><h1>Hello {{ctx.metadata.name}}</h1> meta <a href='https:
byte[] bytes = new byte[0];
String sanitizedHtml = Profile.sanitizeHtml(ImmutableMap.of("foo", (Attachment) new Attachment.Bytes("foo", bytes, "")), needsSanitation);
assertThat(sanitizedHtml, equalTo("<head></head><body><h1>Hello {{ctx.metadata.name}}</h1> meta <a href=\"https://www.google.com/search?q={{ctx.metadata.name}}\" rel=\"nofollow\">Testlink</a>meta</body>"));
}
} |
package org.jenkinsci.plugins.DependencyCheck;
import hudson.FilePath;
import hudson.model.Result;
import org.jenkinsci.plugins.workflow.cps.CpsFlowDefinition;
import org.jenkinsci.plugins.workflow.job.WorkflowJob;
import org.junit.Rule;
import org.junit.Test;
import org.jvnet.hudson.test.JenkinsRule;
import static org.junit.Assert.*;
public class DependencyCheckWorkflowTest {
@Rule
public JenkinsRule jenkinsRule = new JenkinsRule();
/**
* Run a workflow job using org.jenkinsci.plugins.DependencyCheck.DependencyCheckPublisher and check for success.
*/
//@Test
public void dependencyCheckPublisherWorkflowStep() throws Exception {
WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "dependencyCheckWorkPublisherWorkflowStep");
FilePath workspace = jenkinsRule.jenkins.getWorkspaceFor(job);
FilePath report = workspace.child("target").child("dependency-check-report.xml");
report.copyFrom(DependencyCheckWorkflowTest.class.getResourceAsStream("/org/jenkinsci/plugins/DependencyCheck/parser/dependency-check-report.xml"));
job.setDefinition(new CpsFlowDefinition(""
+ "node {\n"
+ " step([$class: 'DependencyCheckPublisher'])\n"
+ "}\n", true)
);
jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
//TODO
//DependencyCheckResultAction result = job.getLastBuild().getAction(DependencyCheckResultAction.class);
//assertTrue(result.getResult().getAnnotations().size() == 2);
}
/**
* Run a workflow job using DependencyCheckPublisher with a failing threshold of 0, so the given example file
* "/org/jenkinsci/plugins/DependencyCheck/parser/dependency-check-report2.xml" will make the build to fail.
*/
//@Test
public void dependencyCheckPublisherWorkflowStepSetLimits() throws Exception {
WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "dependencyCheckPublisherWorkflowStepSetLimits");
FilePath workspace = jenkinsRule.jenkins.getWorkspaceFor(job);
FilePath report = workspace.child("target").child("dependency-check-report.xml");
report.copyFrom(DependencyCheckWorkflowTest.class.getResourceAsStream("/org/jenkinsci/plugins/DependencyCheck/parser/dependency-check-report.xml"));
job.setDefinition(new CpsFlowDefinition(""
+ "node {\n"
+ " step([$class: 'DependencyCheckPublisher', pattern: '**/dependency-check-report.xml', failedTotalAll: '0', usePreviousBuildAsReference: false])\n"
+ "}\n", true)
);
jenkinsRule.assertBuildStatus(Result.FAILURE, job.scheduleBuild2(0).get());
//DependencyCheckResultAction result = job.getLastBuild().getAction(DependencyCheckResultAction.class);
//assertTrue(result.getResult().getAnnotations().size() == 2);
}
/**
* Run a workflow job using DependencyCheckPublisher with a unstable threshold of 0, so the given example file
* "/org/jenkinsci/plugins/DependencyCheck/parser/dependency-check-report2.xml" will make the build to fail.
*/
//@Test
public void dependencyCheckPublisherWorkflowStepFailure() throws Exception {
WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "dependencyCheckPublisherWorkflowStepFailure");
FilePath workspace = jenkinsRule.jenkins.getWorkspaceFor(job);
FilePath report = workspace.child("target").child("dependency-check-report.xml");
report.copyFrom(DependencyCheckWorkflowTest.class.getResourceAsStream("/org/jenkinsci/plugins/DependencyCheck/parser/dependency-check-report.xml"));
job.setDefinition(new CpsFlowDefinition(""
+ "node {\n"
+ " step([$class: 'DependencyCheckPublisher', pattern: '**/dependency-check-report.xml', unstableTotalAll: '0', usePreviousBuildAsReference: false])\n"
+ "}\n")
);
jenkinsRule.assertBuildStatus(Result.UNSTABLE, job.scheduleBuild2(0).get());
//DependencyCheckResultAction result = job.getLastBuild().getAction(DependencyCheckResultAction.class);
//assertTrue(result.getResult().getAnnotations().size() == 2);
}
} |
package org.sagebionetworks.web.unitclient.widget.googlemap;
import static org.junit.Assert.*;
import static org.mockito.Matchers.*;
import static org.mockito.Mockito.*;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.sagebionetworks.web.client.PortalGinInjector;
import org.sagebionetworks.web.client.RequestBuilderWrapper;
import org.sagebionetworks.web.client.SynapseJSNIUtils;
import org.sagebionetworks.web.client.utils.Callback;
import org.sagebionetworks.web.client.widget.entity.controller.SynapseAlert;
import org.sagebionetworks.web.client.widget.googlemap.GoogleMap;
import org.sagebionetworks.web.client.widget.googlemap.GoogleMapView;
import org.sagebionetworks.web.client.widget.lazyload.LazyLoadHelper;
import org.sagebionetworks.web.test.helper.RequestBuilderMockStubber;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.user.client.ui.Widget;
public class GoogleMapTest {
GoogleMap map;
@Mock
GoogleMapView mockView;
@Mock
SynapseJSNIUtils mockSynapseJSNIUtils;
@Mock
RequestBuilderWrapper mockRequestBuilder;
@Mock
SynapseAlert mockSynapseAlert;
@Mock
PortalGinInjector mockPortalGinInjector;
@Mock
LazyLoadHelper mockLazyLoadHelper;
@Mock
Response mockResponse;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
GoogleMap.isLoaded = true;
map = new GoogleMap(mockView, mockSynapseJSNIUtils, mockRequestBuilder, mockSynapseAlert, mockPortalGinInjector, mockLazyLoadHelper);
}
@Test
public void testConstruction() {
verify(mockView).setSynAlert(any(Widget.class));
verify(mockView).setPresenter(map);
}
private void simulateInView() {
ArgumentCaptor<Callback> captor = ArgumentCaptor.forClass(Callback.class);
verify(mockLazyLoadHelper).configure(captor.capture(), eq(mockView));
captor.getValue().invoke();
}
@Test
public void testConfigureNotLoaded() throws RequestException {
GoogleMap.isLoaded = false;
map.configure();
verify(mockLazyLoadHelper).setIsConfigured();
verifyZeroInteractions(mockRequestBuilder);
simulateInView();
//verify attempt to load
verify(mockRequestBuilder).configure(RequestBuilder.GET, GoogleMap.GOOGLE_MAP_URL);
verify(mockRequestBuilder).sendRequest(anyString(), any(RequestCallback.class));
}
@Test
public void testConfigure() throws RequestException {
map.configure();
when(mockResponse.getStatusCode()).thenReturn(Response.SC_OK);
String data = "map data";
when(mockResponse.getText()).thenReturn(data);
RequestBuilderMockStubber.callOnResponseReceived(null, mockResponse)
.when(mockRequestBuilder).sendRequest(anyString(), any(RequestCallback.class));
simulateInView();
//verify attempt to load all data
verify(mockRequestBuilder).configure(RequestBuilder.GET, GoogleMap.ALL_POINTS_URL);
verify(mockRequestBuilder).sendRequest(anyString(), any(RequestCallback.class));
verify(mockView).showMap(data);
}
@Test
public void testConfigureTeam() throws RequestException {
String teamId = "1234987";
map.configure(teamId);
when(mockResponse.getStatusCode()).thenReturn(Response.SC_OK);
String data = "map data";
when(mockResponse.getText()).thenReturn(data);
RequestBuilderMockStubber.callOnResponseReceived(null, mockResponse)
.when(mockRequestBuilder).sendRequest(anyString(), any(RequestCallback.class));
simulateInView();
//verify attempt to load team data
String expectedTeamMapDataUrl = GoogleMap.S3_PREFIX + teamId + ".json";
verify(mockRequestBuilder).configure(RequestBuilder.GET, expectedTeamMapDataUrl);
verify(mockRequestBuilder).sendRequest(anyString(), any(RequestCallback.class));
verify(mockView).showMap(data);
}
@Test
public void testFailedRequest() throws RequestException {
Exception ex = new Exception("failure to load");
RequestBuilderMockStubber.callOnError(null, ex)
.when(mockRequestBuilder).sendRequest(anyString(), any(RequestCallback.class));
map.configure();
simulateInView();
verify(mockSynapseAlert).handleException(ex);
}
} |
package stroom.explorer.server;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.stereotype.Component;
import stroom.servlet.HttpServletRequestHolder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Optional;
@Component
class ExplorerSessionImpl implements ExplorerSession, BeanFactoryAware {
private static final Logger LOGGER = LoggerFactory.getLogger(ExplorerSessionImpl.class);
private static final String MIN_EXPLORER_TREE_MODEL_BUILD_TIME = "MIN_EXPLORER_TREE_MODEL_BUILD_TIME";
private BeanFactory beanFactory;
@Override
public Optional<Long> getMinExplorerTreeModelBuildTime() {
final HttpServletRequest request = getRequest();
if (request == null) {
LOGGER.debug("Request holder has no current request");
return Optional.empty();
}
final HttpSession session = request.getSession();
final Object object = session.getAttribute(MIN_EXPLORER_TREE_MODEL_BUILD_TIME);
return Optional.ofNullable((Long) object);
}
@Override
public void setMinExplorerTreeModelBuildTime(final long buildTime) {
final HttpServletRequest request = getRequest();
if (request == null) {
LOGGER.debug("Request holder has no current request");
} else {
final HttpSession session = request.getSession();
session.setAttribute(MIN_EXPLORER_TREE_MODEL_BUILD_TIME, buildTime);
}
}
private HttpServletRequest getRequest() {
if (beanFactory != null) {
try {
final HttpServletRequestHolder holder = beanFactory.getBean(HttpServletRequestHolder.class);
if (holder != null) {
return holder.get();
}
} catch (final RuntimeException e) {
// Ignore.
}
}
return null;
}
@Override
public void setBeanFactory(final BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
} |
package com.jgeppert.jquery.div;
import com.jgeppert.jquery.selenium.JQueryIdleCondition;
import com.jgeppert.jquery.selenium.WebDriverFactory;
import com.jgeppert.jquery.junit.category.HtmlUnitCategory;
import com.jgeppert.jquery.junit.category.PhantomJSCategory;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
@RunWith(Parameterized.class)
@Category({HtmlUnitCategory.class})
public class DivTagIT {
@Parameterized.Parameters
public static Collection<Object[]> data() {
return Arrays.asList(new Object[][] {
{ "http://localhost:8080/regular" },
{ "http://localhost:8080/uncompressed" },
{ "http://localhost:8080/loadatonce" },
{ "http://localhost:8080/loadfromgoogle" }
});
}
private static final JQueryIdleCondition JQUERY_IDLE = new JQueryIdleCondition();
private String baseUrl;
private WebDriver driver;
public DivTagIT(final String baseUrl) {
this.baseUrl = baseUrl;
}
@Before
public void before() {
driver = WebDriverFactory.getWebDriver();
}
@After
public void after() {
driver.quit();
}
@Test
@Category({PhantomJSCategory.class})
public void testAjaxDiv() {
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get(baseUrl + "/div/ajax-div.action");
WebElement ajaxDiv = driver.findElement(By.id("ajaxdiv"));
wait.until(JQUERY_IDLE);
Assert.assertEquals("This is simple text from an ajax call.", ajaxDiv.getText());
}
@Test
public void testEvents() {
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get(baseUrl + "/div/events.action");
wait.until(JQUERY_IDLE);
wait.until(ExpectedConditions.alertIsPresent());
Alert alert = driver.switchTo().alert();
Assert.assertEquals("Before div", alert.getText());
alert.accept();
wait.until(JQUERY_IDLE);
wait.until(ExpectedConditions.alertIsPresent());
alert = driver.switchTo().alert();
Assert.assertEquals("Complete div", alert.getText());
alert.accept();
WebElement ajaxDiv = driver.findElement(By.id("ajaxdiv"));
Assert.assertEquals("This is simple text from an ajax call.", ajaxDiv.getText());
}
@Test
@Category({PhantomJSCategory.class})
public void testListenTopics() {
WebDriverWait wait = new WebDriverWait(driver, 30);
driver.get(baseUrl + "/div/listen-topics.action");
WebElement ajaxDiv = driver.findElement(By.id("ajaxdiv"));
WebElement topicsLink = driver.findElement(By.id("topicslink"));
Assert.assertEquals("ajax div", ajaxDiv.getText());
topicsLink.click();
wait.until(JQUERY_IDLE);
Assert.assertEquals("This is simple text from an ajax call.", ajaxDiv.getText());
}
} |
package com.fsck.k9.ui;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.DrawerLayout;
import android.util.TypedValue;
import android.view.View;
import com.fsck.k9.DI;
import com.fsck.k9.K9;
import com.fsck.k9.activity.MessageList;
import com.fsck.k9.mailstore.Folder;
import com.fsck.k9.ui.folders.FolderNameFormatter;
import com.fsck.k9.ui.settings.SettingsActivity;
import com.mikepenz.materialdrawer.Drawer;
import com.mikepenz.materialdrawer.Drawer.OnDrawerItemClickListener;
import com.mikepenz.materialdrawer.DrawerBuilder;
import com.mikepenz.materialdrawer.model.DividerDrawerItem;
import com.mikepenz.materialdrawer.model.PrimaryDrawerItem;
import com.mikepenz.materialdrawer.model.interfaces.IDrawerItem;
public class K9Drawer {
// Bit shift for identifiers of user folders items, to leave space for other items
private static final short DRAWER_FOLDER_SHIFT = 2;
private static final long DRAWER_ID_UNIFIED_INBOX = 0;
private static final long DRAWER_ID_PREFERENCES = 1;
private final FolderNameFormatter folderNameFormatter = DI.get(FolderNameFormatter.class);
private final Drawer drawer;
private final MessageList parent;
private int headerItemCount = 0;
private int iconFolderInboxResId;
private int iconFolderOutboxResId;
private int iconFolderSentResId;
private int iconFolderTrashResId;
private int iconFolderDraftsResId;
private int iconFolderArchiveResId;
private int iconFolderSpamResId;
private int iconFolderResId;
private final List<Long> userFolderDrawerIds = new ArrayList<>();
private String openedFolderServerId;
public K9Drawer(MessageList parent, Bundle savedInstanceState) {
this.parent = parent;
drawer = new DrawerBuilder()
.withActivity(parent)
.withDisplayBelowStatusBar(false)
.withTranslucentStatusBar(false)
.withDrawerLayout(R.layout.material_drawer_fits_not)
.withActionBarDrawerToggle(true)
.withOnDrawerItemClickListener(createItemClickListener())
.withOnDrawerListener(parent.createOnDrawerListener())
.withSavedInstance(savedInstanceState)
.build();
addHeaderItems();
addFooterItems();
initializeFolderIcons();
}
private void addHeaderItems() {
if (!K9.isHideSpecialAccounts()) {
drawer.addItems(new PrimaryDrawerItem()
.withName(R.string.integrated_inbox_title)
.withIcon(getResId(R.attr.iconUnifiedInbox))
.withIdentifier(DRAWER_ID_UNIFIED_INBOX),
new DividerDrawerItem());
headerItemCount += 2;
}
}
private void addFooterItems() {
drawer.addItems(new DividerDrawerItem(),
new PrimaryDrawerItem()
.withName(R.string.preferences_action)
.withIcon(getResId(R.attr.iconActionSettings))
.withIdentifier(DRAWER_ID_PREFERENCES)
.withSelectable(false));
}
private void initializeFolderIcons() {
iconFolderInboxResId = getResId(R.attr.iconFolderInbox);
iconFolderOutboxResId = getResId(R.attr.iconFolderOutbox);
iconFolderSentResId = getResId(R.attr.iconFolderSent);
iconFolderTrashResId = getResId(R.attr.iconFolderTrash);
iconFolderDraftsResId = getResId(R.attr.iconFolderDrafts);
iconFolderArchiveResId = getResId(R.attr.iconFolderArchive);
iconFolderSpamResId = getResId(R.attr.iconFolderSpam);
iconFolderResId = getResId(R.attr.iconFolder);
}
private int getResId(int resAttribute) {
TypedValue typedValue = new TypedValue();
boolean found = parent.getTheme().resolveAttribute(resAttribute, typedValue, true);
if (!found) {
throw new AssertionError("Couldn't find resource with attribute " + resAttribute);
}
return typedValue.resourceId;
}
private int getFolderIcon(Folder folder) {
switch (folder.getType()) {
case INBOX: return iconFolderInboxResId;
case OUTBOX: return iconFolderOutboxResId;
case SENT: return iconFolderSentResId;
case TRASH: return iconFolderTrashResId;
case DRAFTS: return iconFolderDraftsResId;
case ARCHIVE: return iconFolderArchiveResId;
case SPAM: return iconFolderSpamResId;
default: return iconFolderResId;
}
}
private String getFolderDisplayName(Folder folder) {
return folderNameFormatter.displayName(folder);
}
private OnDrawerItemClickListener createItemClickListener() {
return new OnDrawerItemClickListener() {
@Override
public boolean onItemClick(View view, int position, IDrawerItem drawerItem) {
long id = drawerItem.getIdentifier();
if (id == DRAWER_ID_UNIFIED_INBOX) {
parent.openUnifiedInbox();
return false;
} else if (id == DRAWER_ID_PREFERENCES) {
SettingsActivity.launch(parent);
return false;
}
Folder folder = (Folder) drawerItem.getTag();
parent.openFolder(folder.getServerId());
return false;
}
};
}
public void setUserFolders(@Nullable List<Folder> folders) {
clearUserFolders();
if (folders == null) {
return;
}
long openedFolderDrawerId = -1;
for (int i = folders.size() - 1; i >= 0; i
Folder folder = folders.get(i);
long drawerId = folder.getId() << DRAWER_FOLDER_SHIFT;
drawer.addItemAtPosition(new PrimaryDrawerItem()
.withIcon(getFolderIcon(folder))
.withIdentifier(drawerId)
.withTag(folder)
.withName(getFolderDisplayName(folder)),
headerItemCount);
userFolderDrawerIds.add(drawerId);
if (folder.getServerId().equals(openedFolderServerId)) {
openedFolderDrawerId = drawerId;
}
}
if (openedFolderDrawerId != -1) {
drawer.setSelection(openedFolderDrawerId, false);
}
}
private void clearUserFolders() {
for (long drawerId : userFolderDrawerIds) {
drawer.removeItem(drawerId);
}
userFolderDrawerIds.clear();
}
public void selectFolder(String folderServerId) {
openedFolderServerId = folderServerId;
for (long drawerId : userFolderDrawerIds) {
Folder folder = (Folder) drawer.getDrawerItem(drawerId).getTag();
if (folder.getServerId().equals(folderServerId)) {
drawer.setSelection(drawerId, false);
return;
}
}
}
public void selectUnifiedInbox() {
drawer.setSelection(DRAWER_ID_UNIFIED_INBOX, false);
}
public DrawerLayout getLayout() {
return drawer.getDrawerLayout();
}
public boolean isOpen() {
return drawer.isDrawerOpen();
}
public void open() {
drawer.openDrawer();
}
public void close() {
drawer.closeDrawer();
}
public void lock() {
drawer.getDrawerLayout().setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
}
public void unlock() {
drawer.getDrawerLayout().setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
}
} |
package eu.ydp.empiria.player.client.module.sourcelist.view;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.List;
import java.util.Map;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.runners.MockitoJUnitRunner;
import org.mockito.stubbing.Answer;
import com.google.common.collect.BiMap;
import com.google.common.collect.Lists;
import com.google.gwt.event.dom.client.DragDropEventBase;
import com.google.gwt.junit.GWTMockUtilities;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.inject.Provider;
import eu.ydp.empiria.player.client.gin.factory.TouchReservationFactory;
import eu.ydp.empiria.player.client.module.sourcelist.presenter.SourceListPresenter;
import eu.ydp.empiria.player.client.test.utils.ReflectionsUtils;
import eu.ydp.empiria.player.client.util.dom.drag.DragDataObject;
import eu.ydp.empiria.player.client.util.events.dragdrop.DragDropEventTypes;
@RunWith(MockitoJUnitRunner.class)
public class SourceListViewImplTest {
@Mock
private SourceListPresenter sourceListPresenter;
@Mock private TouchReservationFactory touchReservationFactory;
@Mock private Provider<SourceListViewItem> sourceListViewItemProvider;
@Mock private SourceListViewItem viewItem;
@InjectMocks
private SourceListViewImpl instance;
private final List<String> allIds = Lists.newArrayList("a","b","c","d","e","f");
private FlowPanel items;
@BeforeClass
public static void disarm() {
GWTMockUtilities.disarm();
}
@AfterClass
public static void rearm() {
GWTMockUtilities.restore();
}
@Before
public void before() {
when(sourceListViewItemProvider.get()).then(new Answer<SourceListViewItem>() {
@Override
public SourceListViewItem answer(InvocationOnMock invocation) throws Throwable {
return mock(SourceListViewItem.class);
}
});
items = mock(FlowPanel.class);
instance.items = items;
}
private void addItems(){
for(String id : allIds){
instance.createItem(id, id);
}
}
@Test
public void testDisableItems() throws Exception {
ReflectionsUtils reflectionsUtils = new ReflectionsUtils();
BiMap<String,SourceListViewItem> itemIdToItemCollection = (BiMap<String, SourceListViewItem>) reflectionsUtils.getValueFromFiledInObject("itemIdToItemCollection", instance);
addItems();
instance.disableItems(true);
for (SourceListViewItem item : itemIdToItemCollection.values()) {
verify(item).setDisableDrag(eq(true));
}
instance.disableItems(false);
for (SourceListViewItem item : itemIdToItemCollection.values()) {
verify(item).setDisableDrag(eq(false));
}
}
@Test
public void testOnDragEventDragStart() throws Exception {
String itemContent = "itemContent";
String itemId = "item";
doReturn(viewItem).when(sourceListViewItemProvider).get();
SourceListPresenter sourceListPresenter = mock(SourceListPresenter.class);
String json = "{}";
DragDataObject dataObject = mock(DragDataObject.class);
doReturn(json).when(dataObject).toJSON();
when(sourceListPresenter.getDragDataObject(anyString())).thenReturn(dataObject);
DragDropEventBase event = mock(DragDropEventBase.class);
instance.createItem(itemId, itemContent);
instance.setSourceListPresenter(sourceListPresenter);
instance.onDragEvent(DragDropEventTypes.DRAG_START, viewItem, event);
verify(event).setData(eq("json"), eq(json));
verify(sourceListPresenter).onDragEvent(eq(DragDropEventTypes.DRAG_START), eq(itemId));
}
@Test
public void testOnDragEvent() throws Exception {
addItems();
DragDropEventBase event = mock(DragDropEventBase.class);
ReflectionsUtils reflectionsUtils = new ReflectionsUtils();
BiMap<String, SourceListViewItem> itemIdToItemCollection = (BiMap<String, SourceListViewItem>) reflectionsUtils.getValueFromFiledInObject(
"itemIdToItemCollection", instance);
instance.setSourceListPresenter(sourceListPresenter);
for (Map.Entry<String, SourceListViewItem> item : itemIdToItemCollection.entrySet()) {
for (DragDropEventTypes type : DragDropEventTypes.values()) {
if (type != DragDropEventTypes.DRAG_START) {
instance.onDragEvent(type, item.getValue(), event);
verify(event, times(0)).setData(eq("json"), anyString());
verify(sourceListPresenter).onDragEvent(eq(type), eq(item.getKey()));
}
}
}
}
@Test
public void testGetItemValue() throws Exception {
ReflectionsUtils reflectionsUtils = new ReflectionsUtils();
BiMap<String,SourceListViewItem> itemIdToItemCollection = (BiMap<String, SourceListViewItem>) reflectionsUtils.getValueFromFiledInObject("itemIdToItemCollection", instance);
addItems();
for(String id: allIds){
instance.getItemValue(id);
}
for (SourceListViewItem item : itemIdToItemCollection.values()) {
verify(item).getItemContent();
}
}
@Test
public void testCreateItem() throws Exception {
String itemContent = "itemContent";
String itemId = "item";
doReturn(viewItem).when(sourceListViewItemProvider).get();
instance.createItem(itemId, itemContent);
verify(sourceListViewItemProvider).get();
verify(items).add(eq(sourceListViewItemProvider.get()));
verify(sourceListViewItemProvider.get()).setSourceListView(eq(instance));
verify(sourceListViewItemProvider.get()).createAndBindUi(eq(itemContent));
}
@Test
public void testHideItem() throws Exception {
ReflectionsUtils reflectionsUtils = new ReflectionsUtils();
BiMap<String,SourceListViewItem> itemIdToItemCollection = (BiMap<String, SourceListViewItem>) reflectionsUtils.getValueFromFiledInObject("itemIdToItemCollection", instance);
addItems();
instance.hideItem("a");
SourceListViewItem viewItem = itemIdToItemCollection.get("a");
verify(viewItem).hide();
allIds.remove("a");
for(String id: allIds){
viewItem = itemIdToItemCollection.get(id);
verify(viewItem,times(0)).hide();
}
}
@Test
public void testHideItemIdNotPresent() throws Exception {
ReflectionsUtils reflectionsUtils = new ReflectionsUtils();
BiMap<String,SourceListViewItem> itemIdToItemCollection = (BiMap<String, SourceListViewItem>) reflectionsUtils.getValueFromFiledInObject("itemIdToItemCollection", instance);
addItems();
instance.hideItem("aa");
for(String id: allIds){
viewItem = itemIdToItemCollection.get(id);
verify(viewItem,times(0)).hide();
}
}
@Test
public void testShowItem() throws Exception {
ReflectionsUtils reflectionsUtils = new ReflectionsUtils();
BiMap<String,SourceListViewItem> itemIdToItemCollection = (BiMap<String, SourceListViewItem>) reflectionsUtils.getValueFromFiledInObject("itemIdToItemCollection", instance);
addItems();
instance.showItem("a");
SourceListViewItem viewItem = itemIdToItemCollection.get("a");
verify(viewItem).show();
allIds.remove("a");
for(String id: allIds){
viewItem = itemIdToItemCollection.get(id);
verify(viewItem,times(0)).show();
}
}
@Test
public void testShowItemIdNotPresent() throws Exception {
ReflectionsUtils reflectionsUtils = new ReflectionsUtils();
BiMap<String,SourceListViewItem> itemIdToItemCollection = (BiMap<String, SourceListViewItem>) reflectionsUtils.getValueFromFiledInObject("itemIdToItemCollection", instance);
addItems();
instance.showItem("aa");
for(String id: allIds){
viewItem = itemIdToItemCollection.get(id);
verify(viewItem,times(0)).show();
}
}
@Test
public void testLockForDragDrop() throws Exception {
ReflectionsUtils reflectionsUtils = new ReflectionsUtils();
BiMap<String, SourceListViewItem> itemIdToItemCollection = (BiMap<String, SourceListViewItem>) reflectionsUtils.getValueFromFiledInObject(
"itemIdToItemCollection", instance);
addItems();
instance.lockItemForDragDrop("a");
viewItem = itemIdToItemCollection.get("a");
verify(viewItem).lockForDragDrop();
for (String id : allIds) {
if (!id.equals("a")) {
viewItem = itemIdToItemCollection.get(id);
verify(viewItem, times(0)).lockForDragDrop();
verify(viewItem, times(0)).unlockForDragDrop();
}
}
}
@Test
public void testUnlockForDragDrop() throws Exception {
ReflectionsUtils reflectionsUtils = new ReflectionsUtils();
BiMap<String, SourceListViewItem> itemIdToItemCollection = (BiMap<String, SourceListViewItem>) reflectionsUtils.getValueFromFiledInObject(
"itemIdToItemCollection", instance);
addItems();
instance.unlockItemForDragDrop("a");
viewItem = itemIdToItemCollection.get("a");
verify(viewItem).unlockForDragDrop();
for (String id : allIds) {
if (!id.equals("a")) {
viewItem = itemIdToItemCollection.get(id);
verify(viewItem, times(0)).unlockForDragDrop();
verify(viewItem, times(0)).lockForDragDrop();
}
}
}
} |
package org.codehaus.groovy.grails.orm.hibernate;
import groovy.lang.GroovyClassLoader;
import groovy.lang.GroovyObject;
import groovy.lang.MissingMethodException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsDomainClass;
import org.codehaus.groovy.grails.commons.spring.SpringConfig;
import org.codehaus.groovy.grails.orm.hibernate.exceptions.GrailsQueryException;
import org.codehaus.groovy.grails.orm.hibernate.metaclass.FindByPersistentMethod;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import org.springmodules.beans.factory.drivers.xml.XmlApplicationContextDriver;
public class PersistentMethodTests extends AbstractDependencyInjectionSpringContextTests {
protected GrailsApplication grailsApplication = null;
/**
* @param grailsApplication The grailsApplication to set.
*/
public void setGrailsApplication(GrailsApplication grailsApplication) {
this.grailsApplication = grailsApplication;
}
protected String[] getConfigLocations() {
return new String[] { "org/codehaus/groovy/grails/orm/hibernate/grails-persistent-method-tests.xml" };
}
public void testMethodSignatures() {
FindByPersistentMethod findBy = new FindByPersistentMethod( grailsApplication,null,new GroovyClassLoader());
assertTrue(findBy.isMethodMatch("findByFirstName"));
assertTrue(findBy.isMethodMatch("findByFirstNameAndLastName"));
assertFalse(findBy.isMethodMatch("rubbish"));
}
public void testSavePersistentMethod() {
// init spring config
GrailsDomainClass domainClass = this.grailsApplication.getGrailsDomainClass("org.codehaus.groovy.grails.orm.hibernate.PersistentMethodTestClass");
GroovyObject obj = domainClass.newInstance();
obj.setProperty( "id", new Long(1) );
obj.setProperty( "firstName", "fred" );
obj.setProperty( "lastName", "flintstone" );
obj.invokeMethod("save", null);
}
public void testValidatePersistentMethod() {
// init spring config
GrailsDomainClass domainClass = this.grailsApplication.getGrailsDomainClass("org.codehaus.groovy.grails.orm.hibernate.PersistentMethodTestClass");
GroovyObject obj = domainClass.newInstance();
obj.setProperty( "id", new Long(1) );
obj.setProperty( "firstName", "fr" );
obj.setProperty( "lastName", "flintstone" );
obj.invokeMethod("validate", null);
List errors = (List)obj.getProperty("errors");
assertNotNull(errors);
assertEquals(1, errors.size());
}
public void testFindByPersistentMethods() {
GrailsDomainClass domainClass = this.grailsApplication.getGrailsDomainClass("org.codehaus.groovy.grails.orm.hibernate.PersistentMethodTestClass");
GroovyObject obj = domainClass.newInstance();
obj.setProperty( "id", new Long(1) );
obj.setProperty( "firstName", "fred" );
obj.setProperty( "lastName", "flintstone" );
obj.setProperty( "age", new Integer(45));
obj.invokeMethod("save", null);
GroovyObject obj2 = domainClass.newInstance();
obj2.setProperty( "id", new Long(2) );
obj2.setProperty( "firstName", "wilma" );
obj2.setProperty( "lastName", "flintstone" );
obj2.setProperty( "age", new Integer(42));
obj2.invokeMethod("save", null);
GroovyObject obj3 = domainClass.newInstance();
obj3.setProperty( "id", new Long(3) );
obj3.setProperty( "firstName", "dino" );
obj3.setProperty( "lastName", "dinosaur" );
obj3.setProperty( "age", new Integer(12));
obj3.invokeMethod("save", null);
Object returnValue = obj.getMetaClass().invokeStaticMethod(obj, "findAllByFirstName", new Object[] { "fred" });
assertNotNull(returnValue);
assertTrue(returnValue instanceof List);
List returnList = (List)returnValue;
assertEquals(1, returnList.size());
returnValue = obj.getMetaClass().invokeStaticMethod(obj, "findAllByFirstNameAndLastName", new Object[] { "fred", "flintstone" });
assertNotNull(returnValue);
assertTrue(returnValue instanceof List);
returnList = (List)returnValue;
assertEquals(1, returnList.size());
/*returnValue = obj.getMetaClass().invokeStaticMethod(obj, "findByFirstNameOrLastName", new Object[] { "fred", "flintstone" });
assertNotNull(returnValue);
assertTrue(returnValue instanceof List);
returnList = (List)returnValue;
assertEquals(2, returnList.size());*/
returnList = (List)obj.getMetaClass().invokeStaticMethod(obj, "findAllByFirstNameNotEqual", new Object[] { "fred" });
assertEquals(2, returnList.size());
obj = (GroovyObject)returnList.get(0);
obj2 = (GroovyObject)returnList.get(1);
assertFalse("fred".equals( obj.getProperty("firstName")));
assertFalse("fred".equals( obj2.getProperty("firstName")));
returnList = (List)obj.getMetaClass().invokeStaticMethod(obj, "findAllByAgeLessThan", new Object[] { new Integer(20) });
assertEquals(1, returnList.size());
obj = (GroovyObject)returnList.get(0);
assertEquals("dino", obj.getProperty("firstName"));
returnList = (List)obj.getMetaClass().invokeStaticMethod(obj, "findAllByAgeGreaterThan", new Object[] { new Integer(20) });
assertEquals(2, returnList.size());
returnList = (List)obj.getMetaClass().invokeStaticMethod(obj, "findAllByAgeGreaterThanAndLastName", new Object[] { new Integer(20), "flintstone" });
assertEquals(2, returnList.size());
returnList = (List)obj.getMetaClass().invokeStaticMethod(obj, "findAllByLastNameLike", new Object[] { "flint%" });
assertEquals(2, returnList.size());
returnList = (List)obj.getMetaClass().invokeStaticMethod(obj, "findAllByAgeBetween", new Object[] { new Integer(10), new Integer(43) });
assertEquals(2, returnList.size());
Map queryMap = new HashMap();
queryMap.put("firstName", "wilma");
queryMap.put("lastName", "flintstone");
returnValue = obj.getMetaClass().invokeStaticMethod(obj, "findWhere", new Object[] { queryMap });
assertNotNull(returnValue);
// now lets test out some junk and make sure we get errors!
try {
returnList = (List)obj.getMetaClass().invokeStaticMethod(obj, "findAllByLastNameLike", new Object[] { new Boolean(false) });
fail("Should have thrown an exception for invalid arguments");
}
catch(MissingMethodException mme) {
//great!
}
// and the wrong number of arguments!
try {
returnList = (List)obj.getMetaClass().invokeStaticMethod(obj, "findAllByAgeBetween", new Object[] { new Integer(10) });
fail("Should have thrown an exception for invalid argument count");
}
catch(MissingMethodException mme) {
//great!
}
}
public void testGetPersistentMethod() {
GrailsDomainClass domainClass = this.grailsApplication.getGrailsDomainClass("org.codehaus.groovy.grails.orm.hibernate.PersistentMethodTestClass");
GroovyObject obj = domainClass.newInstance();
obj.setProperty( "id", new Long(1) );
obj.setProperty( "firstName", "fred" );
obj.setProperty( "lastName", "flintstone" );
obj.invokeMethod("save", null);
GroovyObject obj2 = domainClass.newInstance();
obj2.setProperty( "id", new Long(2) );
obj2.setProperty( "firstName", "wilma" );
obj2.setProperty( "lastName", "flintstone" );
obj2.invokeMethod("save", null);
// get wilma by id
Object returnValue = obj.getMetaClass().invokeStaticMethod(obj, "get", new Object[] { new Long(2) });
assertNotNull(returnValue);
assertEquals(returnValue.getClass(),domainClass.getClazz());
}
public void testFindAllPersistentMethod() {
GrailsDomainClass domainClass = this.grailsApplication.getGrailsDomainClass("org.codehaus.groovy.grails.orm.hibernate.PersistentMethodTestClass");
GroovyObject obj = domainClass.newInstance();
obj.setProperty( "id", new Long(1) );
obj.setProperty( "firstName", "fred" );
obj.setProperty( "lastName", "flintstone" );
obj.invokeMethod("save", null);
GroovyObject obj2 = domainClass.newInstance();
obj2.setProperty( "id", new Long(2) );
obj2.setProperty( "firstName", "wilma" );
obj2.setProperty( "lastName", "flintstone" );
obj2.invokeMethod("save", null);
// test find with a query
Object returnValue = obj.getMetaClass().invokeStaticMethod(obj, "findAll", new Object[] { "from org.codehaus.groovy.grails.orm.hibernate.PersistentMethodTestClass" });
assertNotNull(returnValue);
assertEquals(ArrayList.class,returnValue.getClass());
List listResult = (List)returnValue;
assertEquals(2, listResult.size());
// test find with query and args
List args = new ArrayList();
args.add( "wilma" );
returnValue = obj.getMetaClass().invokeStaticMethod(obj, "findAll", new Object[] { "from org.codehaus.groovy.grails.orm.hibernate.PersistentMethodTestClass as p where p.firstName = ?", args });
assertNotNull(returnValue);
assertEquals(ArrayList.class,returnValue.getClass());
listResult = (List)returnValue;
assertEquals(1, listResult.size());
// test find by example
GroovyObject example = domainClass.newInstance();
example.setProperty( "firstName", "fred" );
returnValue = obj.getMetaClass().invokeStaticMethod(obj, "findAll", new Object[] { example });
assertNotNull(returnValue);
assertEquals(ArrayList.class,returnValue.getClass());
listResult = (List)returnValue;
assertEquals(1, listResult.size());
// test invalid query
try {
returnValue = obj.getMetaClass().invokeStaticMethod(obj, "findAll", new Object[] { "from RubbishClass"});
fail("Should have thrown grails query exception");
}
catch(GrailsQueryException gqe) {
//expected
}
}
public void testListPersistentMethods() {
GrailsDomainClass domainClass = this.grailsApplication.getGrailsDomainClass("org.codehaus.groovy.grails.orm.hibernate.PersistentMethodTestClass");
GroovyObject obj = domainClass.newInstance();
obj.setProperty( "id", new Long(1) );
obj.setProperty( "firstName", "fred" );
obj.setProperty( "lastName", "flintstone" );
obj.invokeMethod("save", null);
GroovyObject obj2 = domainClass.newInstance();
obj2.setProperty( "id", new Long(2) );
obj2.setProperty( "firstName", "wilma" );
obj2.setProperty( "lastName", "flintstone" );
obj2.invokeMethod("save", null);
GroovyObject obj3 = domainClass.newInstance();
obj3.setProperty( "id", new Long(3) );
obj3.setProperty( "firstName", "dino" );
obj3.setProperty( "lastName", "dinosaur" );
obj3.invokeMethod("save", null);
// test plain list
Object returnValue = obj.getMetaClass().invokeStaticMethod(obj,"list", null);
assertNotNull(returnValue);
assertTrue(returnValue instanceof List);
List returnList = (List)returnValue;
assertEquals(3, returnList.size());
// test list with max value
Map argsMap = new HashMap();
argsMap.put("max",new Integer(1));
returnValue = obj.getMetaClass().invokeStaticMethod(obj,"list", new Object[]{ argsMap });
assertNotNull(returnValue);
assertTrue(returnValue instanceof List);
returnList = (List)returnValue;
assertEquals(1, returnList.size());
// test list with order by
returnValue = obj.getMetaClass().invokeStaticMethod(obj,"listOrderByFirstName", new Object[]{});
assertNotNull(returnValue);
assertTrue(returnValue instanceof List);
returnList = (List)returnValue;
obj = (GroovyObject)returnList.get(0);
obj2 = (GroovyObject)returnList.get(1);
assertEquals("dino", obj.getProperty("firstName"));
assertEquals("fred", obj2.getProperty("firstName"));
}
protected void onSetUp() throws Exception {
SpringConfig springConfig = new SpringConfig(grailsApplication);
ConfigurableApplicationContext appCtx = (ConfigurableApplicationContext)
new XmlApplicationContextDriver().getApplicationContext(
springConfig.getBeanReferences(), super.applicationContext);
System.out.println("Loaded app context: " + appCtx.getDisplayName());
super.onSetUp();
}
} |
package org.apache.tika.parser.ner.grobid;
import org.apache.cxf.jaxrs.client.WebClient;
import org.apache.tika.parser.ner.NERecogniser;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.IOException;
import java.util.*;
public class GrobidNERecogniser implements NERecogniser{
private static final Logger LOG = LoggerFactory.getLogger(GrobidNERecogniser.class);
private static boolean available = false;
private static final String GROBID_REST_HOST = "http://localhost:8080";
private String restHostUrlStr;
/*
* Useful Entities from Grobid NER
*/
public static final Set<String> ENTITY_TYPES = new HashSet<String>(){{
add("MEASUREMENT_NUMBERS");
add("MEASUREMENT_UNITS");
add("MEASUREMENTS");
add("NORMALIZED_MEASUREMENTS");
add("MEASUREMENT_TYPES");
}};
public GrobidNERecogniser(){
try {
String restHostUrlStr="";
try {
restHostUrlStr = readRestUrl();
} catch (IOException e) {
e.printStackTrace();
}
if (restHostUrlStr == null || restHostUrlStr.equals("")) {
this.restHostUrlStr = GROBID_REST_HOST;
} else {
this.restHostUrlStr = restHostUrlStr;
}
Response response = WebClient.create(restHostUrlStr).accept(MediaType.APPLICATION_JSON).get();
int responseCode = response.getStatus();
if(responseCode == 200){
available = true;
}
else{
LOG.info("Grobid REST Server is not running");
}
}
catch (Exception e) {
LOG.info(e.getMessage(), e);
}
}
/**
* Reads the GROBID REST URL from the properties file
* returns the GROBID REST URL
*/
private static String readRestUrl() throws IOException {
Properties grobidProperties = new Properties();
grobidProperties.load(GrobidNERecogniser.class.getResourceAsStream("GrobidServer.properties"));
return grobidProperties.getProperty("grobid.server.url");
}
/**
* Reads the GROBID REST Endpoint from the properties file
* returns the GROBID REST Endpoint
*/
private static String readRestEndpoint() throws IOException {
Properties grobidProperties = new Properties();
grobidProperties.load(GrobidNERecogniser.class.getResourceAsStream("GrobidServer.properties"));
return grobidProperties.getProperty("grobid.endpoint.text");
}
/**
* @return {@code true} if server endpoint is available.
* returns {@code false} if server endpoint is not avaliable for service.
*/
public boolean isAvailable() {
return available;
}
/**
* Gets set of entity types recognised by this recogniser
* @return set of entity classes/types
*/
public Set<String> getEntityTypes() {
return ENTITY_TYPES;
}
/**
* Converts JSON Object to JSON Array
* @return a JSON array
*/
public JSONArray convertToJSONArray(JSONObject obj, String key){
JSONArray jsonArray = new JSONArray();
try{
jsonArray = (JSONArray) obj.get(key);
}
catch(Exception e){
LOG.info(e.getMessage(), e);
}
return jsonArray;
}
/**
* Parses a JSON String and converts it to a JSON Object
* @return a JSON Object
*/
public JSONObject convertToJSONObject(String jsonString){
JSONParser parser = new JSONParser();
JSONObject jsonObject = new JSONObject();
try{
jsonObject = (JSONObject) parser.parse(jsonString);
}
catch(Exception e){
LOG.info(e.getMessage(), e);
}
return jsonObject;
}
/**
* recognises names of entities in the text
* @param text text which possibly contains names
* @return map of entity type -> set of names
*/
public Map<String, Set<String>> recognise(String text) {
Map<String, Set<String>> entities = new HashMap<String,Set<String>>();
Set<String> measurementNumberSet = new HashSet<String>();
Set<String> unitSet = new HashSet<String>();
Set<String> measurementSet = new HashSet<String>();
Set<String> normalizedMeasurementSet = new HashSet<String>();
Set<String> measurementTypeSet = new HashSet<String>();
try {
String url = restHostUrlStr + readRestEndpoint();
Response response = WebClient.create(url).accept(MediaType.APPLICATION_JSON).post("text=" + text);
int responseCode = response.getStatus();
if (responseCode == 200) {
String result = response.readEntity(String.class);
JSONObject jsonObject = convertToJSONObject(result);
JSONArray measurements = convertToJSONArray(jsonObject, "measurements");
for(int i=0; i<measurements.size(); i++){
StringBuffer measurementString = new StringBuffer();
StringBuffer normalizedMeasurementString = new StringBuffer();
JSONObject quantity = (JSONObject) convertToJSONObject(measurements.get(i).toString()).get("quantity");
if(quantity!=null) {
if (quantity.containsKey("rawValue")) {
String measurementNumber = (String) convertToJSONObject(quantity.toString()).get("rawValue");
measurementString.append(measurementNumber);
measurementString.append(" ");
measurementNumberSet.add(measurementNumber);
}
if (quantity.containsKey("normalizedQuantity")) {
String normalizedMeasurementNumber = convertToJSONObject(quantity.toString()).get("normalizedQuantity").toString();
normalizedMeasurementString.append(normalizedMeasurementNumber);
normalizedMeasurementString.append(" ");
}
if (quantity.containsKey("type")) {
String measurementType = (String) convertToJSONObject(quantity.toString()).get("type");
measurementTypeSet.add(measurementType);
}
JSONObject jsonObj = (JSONObject) convertToJSONObject(quantity.toString());
if (jsonObj.containsKey("rawUnit")) {
JSONObject rawUnit = (JSONObject) jsonObj.get("rawUnit");
String unitName = (String) convertToJSONObject(rawUnit.toString()).get("name");
unitSet.add(unitName);
measurementString.append(unitName);
}
if (jsonObj.containsKey("normalizedUnit")) {
JSONObject normalizedUnit = (JSONObject) jsonObj.get("normalizedUnit");
String normalizedUnitName = (String) convertToJSONObject(normalizedUnit.toString()).get("name");
normalizedMeasurementString.append(normalizedUnitName);
}
if (!measurementString.toString().equals("")) {
measurementSet.add(measurementString.toString());
}
if (!normalizedMeasurementString.toString().equals("")) {
normalizedMeasurementSet.add(normalizedMeasurementString.toString());
}
}
}
entities.put("MEASUREMENT_NUMBERS",measurementNumberSet);
entities.put("MEASUREMENT_UNITS",unitSet);
entities.put("MEASUREMENTS",measurementSet);
entities.put("NORMALIZED_MEASUREMENTS",normalizedMeasurementSet);
entities.put("MEASUREMENT_TYPES",measurementTypeSet);
}
}
catch (Exception e) {
LOG.info(e.getMessage(), e);
}
ENTITY_TYPES.clear();
ENTITY_TYPES.addAll(entities.keySet());
return entities;
}
} |
package org.wildfly.extension.undertow.filters;
import io.undertow.Handlers;
import io.undertow.UndertowOptions;
import io.undertow.client.UndertowClient;
import io.undertow.predicate.PredicateParser;
import io.undertow.protocols.ssl.UndertowXnioSsl;
import org.jboss.as.controller.OperationContext;
import org.jboss.as.controller.OperationFailedException;
import org.jboss.as.domain.management.SecurityRealm;
import org.jboss.as.network.SocketBinding;
import org.jboss.dmr.ModelNode;
import org.jboss.msc.service.ServiceBuilder;
import org.jboss.msc.service.ServiceController;
import org.jboss.msc.service.ServiceTarget;
import org.jboss.msc.service.StartContext;
import org.jboss.msc.service.StartException;
import org.jboss.msc.service.StopContext;
import org.jboss.msc.value.InjectedValue;
import org.wildfly.extension.io.IOServices;
import org.wildfly.extension.undertow.UndertowService;
import org.wildfly.extension.undertow.logging.UndertowLogger;
import org.xnio.OptionMap;
import org.xnio.Options;
import org.xnio.XnioWorker;
import io.undertow.predicate.Predicate;
import io.undertow.server.HttpHandler;
import io.undertow.server.HttpServerExchange;
import io.undertow.server.handlers.PredicateHandler;
import io.undertow.server.handlers.proxy.mod_cluster.MCMPConfig;
import io.undertow.server.handlers.proxy.mod_cluster.ModCluster;
import org.xnio.ssl.XnioSsl;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.net.InetAddress;
/**
* filter service for the mod cluster frontend. This requires various injections, and as a result can't use the
* standard filter service
*
* @author Stuart Douglas
*/
public class ModClusterService extends FilterService {
private final InjectedValue<XnioWorker> workerInjectedValue = new InjectedValue<>();
private final InjectedValue<SocketBinding> managementSocketBinding = new InjectedValue<>();
private final InjectedValue<SocketBinding> advertiseSocketBinding = new InjectedValue<>();
private final InjectedValue<SecurityRealm> securityRealm = new InjectedValue<>();
private final long healthCheckInterval;
private final int maxRequestTime;
private final long removeBrokenNodes;
private final int advertiseFrequency;
private final String advertisePath;
private final String advertiseProtocol;
private final String securityKey;
private final Predicate managementAccessPredicate;
private final int connectionsPerThread;
private final int cachedConnections;
private final int connectionIdleTimeout;
private final int requestQueueSize;
private final boolean useAlias;
private final boolean enableHttp2;
private ModCluster modCluster;
private MCMPConfig config;
ModClusterService(ModelNode model, long healthCheckInterval, int maxRequestTime, long removeBrokenNodes, int advertiseFrequency, String advertisePath, String advertiseProtocol, String securityKey, Predicate managementAccessPredicate, int connectionsPerThread, int cachedConnections, int connectionIdleTimeout, int requestQueueSize, boolean useAlias, boolean enableHttp2) {
super(ModClusterDefinition.INSTANCE, model);
this.healthCheckInterval = healthCheckInterval;
this.maxRequestTime = maxRequestTime;
this.removeBrokenNodes = removeBrokenNodes;
this.advertiseFrequency = advertiseFrequency;
this.advertisePath = advertisePath;
this.advertiseProtocol = advertiseProtocol;
this.securityKey = securityKey;
this.managementAccessPredicate = managementAccessPredicate;
this.connectionsPerThread = connectionsPerThread;
this.cachedConnections = cachedConnections;
this.connectionIdleTimeout = connectionIdleTimeout;
this.requestQueueSize = requestQueueSize;
this.useAlias = useAlias;
this.enableHttp2 = enableHttp2;
}
@Override
public synchronized void start(StartContext context) throws StartException {
super.start(context);
SecurityRealm realm = securityRealm.getOptionalValue();
//TODO: SSL support for the client
//TODO: wire up idle timeout when new version of undertow arrives
final ModCluster.Builder modClusterBuilder;
final XnioWorker worker = workerInjectedValue.getValue();
if(realm == null) {
modClusterBuilder = ModCluster.builder(worker);
} else {
SSLContext sslContext = realm.getSSLContext();
OptionMap.Builder builder = OptionMap.builder();
builder.set(Options.USE_DIRECT_BUFFERS, true);
OptionMap combined = builder.getMap();
XnioSsl xnioSsl = new UndertowXnioSsl(worker.getXnio(), combined, sslContext);
modClusterBuilder = ModCluster.builder(worker, UndertowClient.getInstance(), xnioSsl);
}
if(enableHttp2) {
modClusterBuilder.setClientOptions(OptionMap.create(UndertowOptions.ENABLE_HTTP2, true));
}
modClusterBuilder.setHealthCheckInterval(healthCheckInterval)
.setMaxRequestTime(maxRequestTime)
.setCacheConnections(cachedConnections)
.setQueueNewRequests(requestQueueSize > 0)
.setRequestQueueSize(requestQueueSize)
.setRemoveBrokenNodes(removeBrokenNodes)
.setTtl(connectionIdleTimeout)
.setMaxConnections(connectionsPerThread)
.setUseAlias(useAlias);
modCluster = modClusterBuilder
.build();
MCMPConfig.Builder builder = MCMPConfig.builder();
InetAddress multicastAddress = advertiseSocketBinding.getValue().getMulticastAddress();
if(multicastAddress == null) {
throw UndertowLogger.ROOT_LOGGER.advertiseSocketBindingRequiresMulticastAddress();
}
if(advertiseFrequency > 0) {
builder.enableAdvertise()
.setAdvertiseAddress(advertiseSocketBinding.getValue().getSocketAddress().getAddress().getHostAddress())
.setAdvertiseGroup(multicastAddress.getHostAddress())
.setAdvertisePort(advertiseSocketBinding.getValue().getPort())
.setAdvertiseFrequency(advertiseFrequency)
.setPath(advertisePath)
.setProtocol(advertiseProtocol)
.setSecurityKey(securityKey);
}
builder.setManagementHost(managementSocketBinding.getValue().getSocketAddress().getHostName());
builder.setManagementPort(managementSocketBinding.getValue().getSocketAddress().getPort());
config = builder.build();
if(advertiseFrequency > 0) {
try {
modCluster.advertise(config);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
modCluster.start();
}
@Override
public synchronized void stop(StopContext context) {
super.stop(context);
modCluster.stop();
modCluster = null;
config = null;
}
@Override
public HttpHandler createHttpHandler(Predicate predicate, final HttpHandler next) {
//this is a bit of a hack at the moment. Basically we only want to create a single mod_cluster instance
//not matter how many filter refs use it, also mod_cluster at this point has no way
//to specify the next handler. To get around this we invoke the mod_proxy handler
//and then if it has not dispatched or handled the request then we know that we can
//just pass it on to the next handler
final HttpHandler proxyHandler = modCluster.getProxyHandler();
final HttpHandler realNext = new HttpHandler() {
@Override
public void handleRequest(HttpServerExchange exchange) throws Exception {
proxyHandler.handleRequest(exchange);
if(!exchange.isDispatched() && !exchange.isComplete()) {
exchange.setStatusCode(200);
next.handleRequest(exchange);
}
}
};
final HttpHandler mcmp = managementAccessPredicate != null ? Handlers.predicate(managementAccessPredicate, config.create(modCluster, realNext), next) : config.create(modCluster, realNext);
UndertowLogger.ROOT_LOGGER.debug("HttpHandler for mod_cluster MCMP created.");
if (predicate != null) {
return new PredicateHandler(predicate, mcmp, next);
} else {
return mcmp;
}
}
static ServiceController<FilterService> install(String name, ServiceTarget serviceTarget, ModelNode model, OperationContext operationContext) throws OperationFailedException {
String securityKey = null;
ModelNode securityKeyNode = ModClusterDefinition.SECURITY_KEY.resolveModelAttribute(operationContext, model);
if(securityKeyNode.isDefined()) {
securityKey = securityKeyNode.asString();
}
String managementAccessPredicateString = null;
ModelNode managementAccessPredicateNode = ModClusterDefinition.MANAGEMENT_ACCESS_PREDICATE.resolveModelAttribute(operationContext, model);
if(managementAccessPredicateNode.isDefined()) {
managementAccessPredicateString = managementAccessPredicateNode.asString();
}
Predicate managementAccessPredicate = null;
if(managementAccessPredicateString != null) {
managementAccessPredicate = PredicateParser.parse(managementAccessPredicateString, ModClusterService.class.getClassLoader());
}
final ModelNode securityRealm = ModClusterDefinition.SECURITY_REALM.resolveModelAttribute(operationContext, model);
ModClusterService service = new ModClusterService(model,
ModClusterDefinition.HEALTH_CHECK_INTERVAL.resolveModelAttribute(operationContext, model).asInt(),
ModClusterDefinition.MAX_REQUEST_TIME.resolveModelAttribute(operationContext, model).asInt(),
ModClusterDefinition.BROKEN_NODE_TIMEOUT.resolveModelAttribute(operationContext, model).asInt(),
ModClusterDefinition.ADVERTISE_FREQUENCY.resolveModelAttribute(operationContext, model).asInt(),
ModClusterDefinition.ADVERTISE_PATH.resolveModelAttribute(operationContext, model).asString(),
ModClusterDefinition.ADVERTISE_PROTOCOL.resolveModelAttribute(operationContext, model).asString(),
securityKey, managementAccessPredicate,
ModClusterDefinition.CONNECTIONS_PER_THREAD.resolveModelAttribute(operationContext, model).asInt(),
ModClusterDefinition.CACHED_CONNECTIONS_PER_THREAD.resolveModelAttribute(operationContext, model).asInt(),
ModClusterDefinition.CONNECTION_IDLE_TIMEOUT.resolveModelAttribute(operationContext, model).asInt(),
ModClusterDefinition.REQUEST_QUEUE_SIZE.resolveModelAttribute(operationContext, model).asInt(),
ModClusterDefinition.USE_ALIAS.resolveModelAttribute(operationContext, model).asBoolean(),
ModClusterDefinition.ENABLE_HTTP2.resolveModelAttribute(operationContext, model).asBoolean());
ServiceBuilder<FilterService> builder = serviceTarget.addService(UndertowService.FILTER.append(name), service);
builder.addDependency(SocketBinding.JBOSS_BINDING_NAME.append(ModClusterDefinition.MANAGEMENT_SOCKET_BINDING.resolveModelAttribute(operationContext, model).asString()), SocketBinding.class, service.managementSocketBinding);
builder.addDependency(SocketBinding.JBOSS_BINDING_NAME.append(ModClusterDefinition.ADVERTISE_SOCKET_BINDING.resolveModelAttribute(operationContext, model).asString()), SocketBinding.class, service.advertiseSocketBinding);
builder.addDependency(IOServices.WORKER.append(ModClusterDefinition.WORKER.resolveModelAttribute(operationContext, model).asString()), XnioWorker.class, service.workerInjectedValue);
if(securityRealm.isDefined()) {
SecurityRealm.ServiceUtil.addDependency(builder, service.securityRealm, securityRealm.asString(), false);
}
return builder.install();
}
public ModCluster getModCluster() {
return modCluster;
}
} |
package nl.fontys.sofa.limo.view.custom.procedure;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JTextField;
import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;
import nl.fontys.sofa.limo.api.dao.ProcedureCategoryDAO;
import nl.fontys.sofa.limo.domain.component.procedure.Procedure;
import nl.fontys.sofa.limo.domain.component.procedure.TimeType;
import nl.fontys.sofa.limo.domain.component.procedure.value.SingleValue;
import nl.fontys.sofa.limo.domain.component.procedure.value.Value;
import nl.fontys.sofa.limo.view.custom.table.DragNDropTable;
import nl.fontys.sofa.limo.view.custom.table.DragNDropTableModel;
import nl.fontys.sofa.limo.view.util.LIMOResourceBundle;
public class AddProcedureDialog extends JDialog implements ActionListener {
private JButton saveButton, cancelButton, addTimeButton, addCostButton, addCotwoButton;
private JTextField nameTextField, costTextField, timeTextField, cotwoTextField;
private JComboBox timeTypeCombobox, categoryCombobox;
private Value timeValue, costValue, cotwoValue;
private Procedure newProcedure;
private final DragNDropTable table;
private final CellConstraints cc;
public AddProcedureDialog(ProcedureCategoryDAO procedureCategoryDao, DragNDropTable dragNDropTable) {
this.table = dragNDropTable;
cc = new CellConstraints();
//LAYOUT
FormLayout layout = new FormLayout("5px, pref, 5px, pref, pref:grow, 5px, pref, 5px",
"5px, pref, 5px, pref, 5px, pref, 5px, pref, 5px, pref, 5px, pref, 5px, pref, 5px");
this.setLayout(layout);
//COMPONENTS
initComponents(procedureCategoryDao.findAll().toArray());
//ADD COMPONENTS
addComponents();
//ADD COMPONENTS TO LISTENER
cancelButton.addActionListener(this);
saveButton.addActionListener(this);
addCostButton.addActionListener(this);
addTimeButton.addActionListener(this);
addCotwoButton.addActionListener(this);
//DIALOG OPTIONS
this.setSize(250, 300);
this.setModal(true);
this.setAlwaysOnTop(true);
Toolkit toolkit = Toolkit.getDefaultToolkit();
Dimension screenSize = toolkit.getScreenSize();
int x = (screenSize.width - this.getWidth()) / 2;
int y = (screenSize.height - this.getHeight()) / 2;
this.setLocation(x, y);
this.setTitle(LIMOResourceBundle.getString("PROCEDURES"));
}
/**
* Initializes the components.
*
* @param categories the categories that gets used in the categoryCombobox.
*/
private void initComponents(Object[] categories) {
nameTextField = new JTextField();
categoryCombobox = new JComboBox(categories);
categoryCombobox.insertItemAt("costs not accounted", 0);
categoryCombobox.setSelectedIndex(0);
timeTypeCombobox = new JComboBox(TimeType.values());
timeValue = new SingleValue(0.0);
timeTextField = new JTextField(timeValue.toString());
timeTextField.setEditable(false);
addTimeButton = new JButton("...");
costValue = new SingleValue(0.0);
costTextField = new JTextField(costValue.toString());
costTextField.setEditable(false);
addCostButton = new JButton("...");
cotwoValue = new SingleValue(0.0);
cotwoTextField = new JTextField(costValue.toString());
cotwoTextField.setEditable(false);
addCotwoButton = new JButton("...");
saveButton = new JButton(LIMOResourceBundle.getString("SAVE"));
cancelButton = new JButton(LIMOResourceBundle.getString("CANCEL"));
}
/**
* Adds the component to the dialog.
*/
private void addComponents() {
this.add(new JLabel(LIMOResourceBundle.getString("NAME")), cc.xy(2, 2));
this.add(nameTextField, cc.xyw(4, 2, 2));
this.add(new JLabel(LIMOResourceBundle.getString("CATEGORY")), cc.xy(2, 4));
this.add(categoryCombobox, cc.xyw(4, 4, 2));
this.add(new JLabel(LIMOResourceBundle.getString("TIME_TYPE")), cc.xy(2, 6));
this.add(timeTypeCombobox, cc.xyw(4, 6, 2));
this.add(new JLabel(LIMOResourceBundle.getString("TIME_COST")), cc.xy(2, 8));
this.add(timeTextField, cc.xyw(4, 8, 2));
this.add(addTimeButton, cc.xy(7, 8));
this.add(new JLabel(LIMOResourceBundle.getString("MONEY_COST")), cc.xy(2, 10));
this.add(costTextField, cc.xyw(4, 10, 2));
this.add(addCostButton, cc.xy(7, 10));
this.add(new JLabel(LIMOResourceBundle.getString("CO2")), cc.xy(2, 12));
this.add(cotwoTextField, cc.xyw(4, 12, 2));
this.add(addCotwoButton, cc.xy(7, 12));
this.add(saveButton, cc.xy(2, 14));
this.add(cancelButton, cc.xy(4, 14));
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(addCostButton)) {
EditValueDialog editValueDialog = new EditValueDialog(costValue, new EditValueDialogListener() {
@Override
public void newValue(Value changedValue) {
if (costValue != null) {
costValue = changedValue;
costTextField.setText(costValue.toString());
AddProcedureDialog.this.revalidate();
AddProcedureDialog.this.repaint();
}
}
});
editValueDialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
editValueDialog.setVisible(true);
}
if (e.getSource().equals(addTimeButton)) {
EditValueDialog editValueDialog = new EditValueDialog(timeValue, new EditValueDialogListener() {
@Override
public void newValue(Value changedValue) {
if (timeValue != null) {
timeValue = changedValue;
timeTextField.setText(timeValue.toString());
AddProcedureDialog.this.revalidate();
AddProcedureDialog.this.repaint();
}
}
});
editValueDialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
editValueDialog.setVisible(true);
}
if (e.getSource().equals(addCotwoButton)) {
EditValueDialog editValueDialog = new EditValueDialog(cotwoValue, new EditValueDialogListener() {
@Override
public void newValue(Value changedValue) {
if (cotwoValue != null) {
cotwoValue = changedValue;
cotwoTextField.setText(cotwoValue.toString());
AddProcedureDialog.this.revalidate();
AddProcedureDialog.this.repaint();
}
}
});
editValueDialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
editValueDialog.setVisible(true);
}
if (e.getSource().equals(cancelButton)) {
this.dispose();
}
if (e.getSource().equals(saveButton)) {
actionSave();
}
}
/**
* This method represents the action that happens when the save button was
* pressed. It validates the model and closes the dialog if everythin is
* valid.
*/
private void actionSave() {
if (isValidProcedure()) {
String name = nameTextField.getText();
String category = "";
try {
category = categoryCombobox.getSelectedItem().toString();
} catch (Exception ex) {
System.out.println(Arrays.toString(ex.getStackTrace()));
}
TimeType timeType = (TimeType) timeTypeCombobox.getSelectedItem();
newProcedure = new Procedure(name, category, costValue, timeValue, timeType, cotwoValue);
List<Object> newRow = new ArrayList<>();
newRow.add(newProcedure.getName());
newRow.add(newProcedure.getCategory());
newRow.add(newProcedure.getTime());
newRow.add(newProcedure.getTimeType());
newRow.add(newProcedure.getCost());
newRow.add(newProcedure.getCotwo());
((DragNDropTableModel) table.getModel()).addRow(newRow);
((DragNDropTableModel) table.getModel()).fireTableDataChanged();
table.revalidate();
table.repaint();
this.dispose();
}
}
/**
* Checks if the model is valid. Returns true if it is and false if it is
* not.
*
* @return True if the model is valid, false if not.
*/
private boolean isValidProcedure() {
return !(nameTextField.getText().equals("") || nameTextField.getText().equals("") || costTextField.getText().equals(""));
}
public interface EditValueDialogListener {
/**
* Handles what happens when a new value for a procedure got specified.
*
* @param value The new value for a procedure.
*/
void newValue(Value value);
}
} |
package nl.fontys.sofa.limo.view.custom.procedure;
import com.jgoodies.forms.layout.CellConstraints;
import com.jgoodies.forms.layout.FormLayout;
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.BoxLayout;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.SwingConstants;
import static javax.swing.WindowConstants.DISPOSE_ON_CLOSE;
import javax.swing.table.DefaultTableCellRenderer;
import nl.fontys.sofa.limo.api.dao.ProcedureCategoryDAO;
import nl.fontys.sofa.limo.api.service.provider.EventService;
import nl.fontys.sofa.limo.api.service.provider.ProcedureService;
import nl.fontys.sofa.limo.domain.component.event.Event;
import nl.fontys.sofa.limo.domain.component.procedure.Procedure;
import nl.fontys.sofa.limo.domain.component.procedure.ProcedureCategory;
import nl.fontys.sofa.limo.domain.component.procedure.TimeType;
import nl.fontys.sofa.limo.domain.component.procedure.value.Value;
import nl.fontys.sofa.limo.view.custom.table.DragNDropTable;
import nl.fontys.sofa.limo.view.custom.table.DragNDropTableModel;
import nl.fontys.sofa.limo.view.util.IconUtil;
import nl.fontys.sofa.limo.view.util.LIMOResourceBundle;
import org.openide.util.Lookup;
public class ProcedureComponent extends JPanel implements ActionListener, MouseListener {
protected DragNDropTable table;
protected DragNDropTableModel model;
protected JButton addButton, newButton, deleteButton;
protected ProcedureCategoryDAO procedureCategoryDao;
protected Value changedValue;
protected JComboBox procedureCategoryCheckbox, timeTypesCheckbox;
protected DefaultComboBoxModel procedureComboBoxModel;
protected JComboBox<Procedure> proceduresComboBox;
private ProcedureService service;
private List<Procedure> allProcedures;
/**
* Creates a new ProcedureComponent with an empty table.
*/
public ProcedureComponent() {
this(new ArrayList<>());
}
/**
* Creates a new ProcedureComponent with a given list of procedures.
*
* @param procedures The procedures that have to be displayed in the table.
*/
public ProcedureComponent(List<Procedure> procedures) {
procedureCategoryDao = Lookup.getDefault().lookup(ProcedureCategoryDAO.class);
initProcedureService();
proceduresComboBox = new JComboBox();
setLayout(new GridBagLayout());
GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.HORIZONTAL;
c.weightx = 0.2;
c.gridx = 0;
c.gridy = 0;
c.gridwidth = 1;
add(new JLabel(LIMOResourceBundle.getString("PROCEDURE")), c);
c.weightx = 0.7;
c.gridx = 1;
c.gridy = 0;
add(proceduresComboBox, c);
DragNDropTableModel tableModel;
JPanel panel = new JPanel(new BorderLayout());
tableModel = new DragNDropTableModel(
new String[]{}, new ArrayList<>(), new Class[]{});
table = new DragNDropTable(tableModel);
initProceduresTable(procedures);
JScrollPane scrollPane = new JScrollPane(table);
panel.add(scrollPane, BorderLayout.CENTER);
addButton = new JButton(new ImageIcon(IconUtil.getIcon(IconUtil.UI_ICON.VALID)));
newButton = new JButton(new ImageIcon(IconUtil.getIcon(IconUtil.UI_ICON.ADD)));
deleteButton = new JButton(new ImageIcon(IconUtil.getIcon(IconUtil.UI_ICON.TRASH)));
JPanel panelLeft = new JPanel();
panelLeft.setLayout(new BoxLayout(panelLeft, BoxLayout.Y_AXIS));
panelLeft.add(addButton);
panelLeft.add(newButton);
panelLeft.add(deleteButton);
panel.add(panelLeft, BorderLayout.EAST);
c.weightx = 1;
c.gridx = 0;
c.gridy = 1;
c.gridwidth = 5;
add(panel, c);
addButton.addActionListener(this);
newButton.addActionListener(this);
deleteButton.addActionListener(this);
table.addMouseListener(this);
setVisible(true);
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource().equals(deleteButton)) {
int rowToDelete = table.getSelectedRow();
if (rowToDelete > -1) {
deleteProcedure(rowToDelete);
}
} else if (e.getSource().equals(newButton)) {
addProcedure();
}
}
@Override
public void mouseClicked(MouseEvent e) {
if (e.getSource().equals(table)) {
if (e.getClickCount() > 1) {
editProcedure();
}
}
}
/**
* Returns a list with all procedures present in the table.
*
* @return A list with all procedures that are in the table at the moment.
*/
public List<Procedure> getActiveTableState() {
List<List<Object>> values = ((DragNDropTableModel) table.getModel()).getValues();
ArrayList<Procedure> procedures = new ArrayList<>();
values.stream().map((value) -> {
Procedure p = new Procedure();
p.setName((String) value.get(0));
if (value.get(1) instanceof ProcedureCategory) {
p.setCategory(((ProcedureCategory) value.get(1)).getName());
} else { //If a procedure category is displayed in the Procedure wizard, it is represented by a String instead of a ProcedureCategory object
p.setCategory((String) value.get(1));
}
p.setTime((Value) value.get(2));
p.setTimeType((TimeType) value.get(3));
p.setCost((Value) value.get(4));
p.setCotwo((Value) value.get(5));
return p;
}).forEach((p) -> {
procedures.add(p);
});
return procedures;
}
/**
* Sets the table to a new procedure list.
*
* @param procedures The new list of procedures that has to be used.
*/
public void setProcedureTable(List<Procedure> procedures) {
initProceduresTable(procedures);
model.fireTableDataChanged();
revalidate();
repaint();
}
/**
* Handles the adding of a procedure via a dialog.
*/
protected void addProcedure() {
AddProcedureDialog addProcedureDialog = new AddProcedureDialog(procedureCategoryDao, table, deleteButton);
addProcedureDialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
addProcedureDialog.setVisible(true);
checkButtonsState();
}
/**
* Deletes the specified row. Does nothing if the row is out of scope.
*
* @param row The row that has to be deleted.
*/
protected void deleteProcedure(int row) {
if (table.getRowCount() > 1) {
((DragNDropTableModel) table.getModel()).removeRow(row);
revalidate();
repaint();
deleteButton.setEnabled(table.getRowCount() > 1);
}
checkButtonsState();
}
/**
* Handles the editing of the specified row.
*/
protected void editProcedure() {
if (table.getSelectedColumn() == 2 || table.getSelectedColumn() == 4 || table.getSelectedColumn() == 5) {
changedValue = (Value) table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
Object valueAt = table.getValueAt(table.getSelectedRow(), table.getSelectedColumn());
EditValueDialog editValueDialog = new EditValueDialog((Value) valueAt, (Value value) -> {
changedValue = value;
table.setValueAt(value, table.getSelectedRow(), table.getSelectedColumn());
ProcedureComponent.this.revalidate();
ProcedureComponent.this.repaint();
});
editValueDialog.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
editValueDialog.setVisible(true);
}
}
// <editor-fold desc="UNUSED LISTENER METHODS" defaultstate="collapsed">
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
}
@Override
public void mouseExited(MouseEvent e) {
}
//</editor-fold>
/**
* Initializes the procedure table with the given list of procedures.
*
* @param procedures The list of procedures that has to be used in the
* table.
*/
private void initProceduresTable(List<Procedure> procedures) {
List<List<Object>> valueList = new ArrayList<>();
if (procedures != null) {
procedures.stream().map((p) -> {
ArrayList<Object> procedure = new ArrayList<>();
procedure.add(p.getName());
procedure.add(p.getCategory());
procedure.add(p.getTime());
procedure.add(p.getTimeType());
procedure.add(p.getCost());
procedure.add(p.getCotwo());
return procedure;
}).forEach((procedure) -> {
valueList.add(procedure);
});
}
model = new DragNDropTableModel(new String[]{LIMOResourceBundle.getString("PROCEDURE"), LIMOResourceBundle.getString("CATEGORY"), LIMOResourceBundle.getString("TIME_COST"), LIMOResourceBundle.getString("TIME_TYPE"), LIMOResourceBundle.getString("MONEY_COST"), LIMOResourceBundle.getString("CO2")},
valueList, new Class[]{String.class, String.class, Value.class, TimeType.class, Value.class, Value.class});
table.setModel(model);
DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment(SwingConstants.RIGHT);
table.getColumnModel().getColumn(2).setCellRenderer(rightRenderer);
table.getColumnModel().getColumn(4).setCellRenderer(rightRenderer);
table.getColumnModel().getColumn(5).setCellRenderer(rightRenderer);
DefaultTableCellRenderer middleRenderer = new DefaultTableCellRenderer();
middleRenderer.setHorizontalAlignment(SwingConstants.CENTER);
table.getColumnModel().getColumn(3).setCellRenderer(middleRenderer);
try {
procedureCategoryCheckbox = new JComboBox(procedureCategoryDao.findAll().toArray());
table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(procedureCategoryCheckbox));
} catch (Exception e) {
procedureCategoryCheckbox = new JComboBox(new ProcedureCategory[]{});
table.getColumnModel().getColumn(1).setCellEditor(new DefaultCellEditor(procedureCategoryCheckbox));
}
timeTypesCheckbox = new JComboBox(TimeType.values());
table.getColumnModel().getColumn(3).setCellEditor(new DefaultCellEditor(timeTypesCheckbox));
}
protected void checkButtonsState() {
addButton.setEnabled(proceduresComboBox.getModel().getSize() > 0);
}
private void initProcedureService() {
service = Lookup.getDefault().lookup(ProcedureService.class);
allProcedures = service.findAll();
}
} |
package org.project.neutrino.nfvo.vim.test;
import org.junit.*;
import org.junit.rules.ExpectedException;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.project.neutrino.nfvo.catalogue.mano.common.DeploymentFlavour;
import org.project.neutrino.nfvo.catalogue.mano.common.VNFDeploymentFlavour;
import org.project.neutrino.nfvo.catalogue.mano.descriptor.VirtualDeploymentUnit;
import org.project.neutrino.nfvo.catalogue.mano.record.Status;
import org.project.neutrino.nfvo.catalogue.mano.record.VirtualNetworkFunctionRecord;
import org.project.neutrino.nfvo.catalogue.nfvo.NFVImage;
import org.project.neutrino.nfvo.catalogue.nfvo.Server;
import org.project.neutrino.nfvo.catalogue.nfvo.VimInstance;
import org.project.neutrino.nfvo.common.exceptions.VimException;
import org.project.neutrino.nfvo.vim.AmazonVIM;
import org.project.neutrino.nfvo.vim.OpenstackVIM;
import org.project.neutrino.nfvo.vim.TestVIM;
import org.project.neutrino.nfvo.vim_interfaces.vim.Vim;
import org.project.neutrino.nfvo.vim_interfaces.vim.VimBroker;
import org.project.neutrino.nfvo.vim_interfaces.client_interfaces.ClientInterfaces;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestExecutionListeners;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.support.DependencyInjectionTestExecutionListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import static org.mockito.Matchers.anyList;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.when;
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners( {DependencyInjectionTestExecutionListener.class} )
@ContextConfiguration(classes = {ApplicationTest.class})
@TestPropertySource(properties = { "mocked_id=1234567890", "port: 4242" })
public class VimTestSuiteClass {
/**
* TODO add all other tests
*/
@Autowired
private Environment environment;
@Mock
ClientInterfaces clientInterfaces;
@InjectMocks
OpenstackVIM openstackVIM;
@Autowired
private ConfigurableApplicationContext context;
@Autowired
private VimBroker vimBroker;
@Rule
public ExpectedException exception = ExpectedException.none();
private Logger log = LoggerFactory.getLogger(this.getClass());
@Before
public void init(){
MockitoAnnotations.initMocks(this);
}
@Test
public void testVimBrokers(){
Assert.assertNotNull(vimBroker);
Vim testVIM = vimBroker.getVim("test");
Assert.assertEquals(testVIM.getClass(), TestVIM.class);
Vim openstackVIM = vimBroker.getVim("openstack");
Assert.assertEquals(openstackVIM.getClass(), OpenstackVIM.class);
Assert.assertEquals(vimBroker.getVim("amazon").getClass(), AmazonVIM.class);
exception.expect(UnsupportedOperationException.class);
vimBroker.getVim("throw_exception");
}
@Ignore
@Test
public void testVimOpenstack() throws VimException {
VirtualDeploymentUnit vdu = createVDU();
VirtualNetworkFunctionRecord vnfr = createVNFR();
ArrayList<String> networks = new ArrayList<>();
networks.add("network1");
ArrayList<String> secGroups = new ArrayList<>();
secGroups.add("secGroup1");
Server server = new Server();
server.setExtId(environment.getProperty("mocked_id"));
when(clientInterfaces.launchInstanceAndWait(anyString(), anyString(), anyString(), anyString(), anyList(), anyList(), anyString())).thenReturn(server);
try {
Future<String> id = openstackVIM.allocate(vdu, vnfr);
String expectedId = id.get();
log.debug(expectedId + " == " + environment.getProperty("mocked_id"));
Assert.assertEquals(expectedId, environment.getProperty("mocked_id"));
Assert.assertEquals(vdu.getHostname(), vnfr.getName() + "-" + vdu.getId().substring((vdu.getId().length()-5), vdu.getId().length()-1));
} catch (VimException e) {
e.printStackTrace();
Assert.fail();
} catch (InterruptedException e) {
e.printStackTrace();
Assert.fail();
} catch (ExecutionException e) {
e.printStackTrace();
Assert.fail();
}
vdu.getVm_image().remove(0);
exception.expect(VimException.class);
openstackVIM.allocate(vdu, vnfr);
}
@Test
@Ignore
public void testVimAmazon(){}
@Test
@Ignore
public void testVimTest(){}
@Test
@Ignore
public void testOpenstackClient(){}
private VirtualNetworkFunctionRecord createVNFR(){
VirtualNetworkFunctionRecord vnfr = new VirtualNetworkFunctionRecord();
vnfr.setName("testVnfr");
vnfr.setStatus(Status.INITIAILZED);
vnfr.setAudit_log("audit_log");
vnfr.setDescriptor_reference("test_dr");
VNFDeploymentFlavour deployment_flavour = new VNFDeploymentFlavour();
deployment_flavour.setFlavour_key("m1.small");
vnfr.setDeployment_flavour_key("m1.small");
return vnfr;
}
private VirtualDeploymentUnit createVDU() {
VirtualDeploymentUnit vdu = new VirtualDeploymentUnit();
VimInstance vimInstance = new VimInstance();
vimInstance.setName("mock_vim_instance");
vimInstance.setImages(new ArrayList<NFVImage>() {{
NFVImage nfvImage = new NFVImage();
nfvImage.setName("image_1234");
nfvImage.setExtId("ext_id");
add(nfvImage);
}});
vdu.setVimInstance(vimInstance);
Set<String> monitoring_parameter = new HashSet<>();
monitoring_parameter.add("parameter_1");
monitoring_parameter.add("parameter_2");
monitoring_parameter.add("parameter_3");
vdu.setMonitoring_parameter(monitoring_parameter);
vdu.setComputation_requirement("computation_requirement");
Set<String> vm_images = new HashSet<>();
vm_images.add("image_1234");
vdu.setVm_image(vm_images);
vimInstance.setFlavours(new ArrayList<DeploymentFlavour>());
DeploymentFlavour deploymentFlavour = new DeploymentFlavour();
deploymentFlavour.setExtId("ext_id");
deploymentFlavour.setFlavour_key("m1.small");
vimInstance.getFlavours().add(deploymentFlavour);
return vdu;
}
} |
package com.thoughtworks.xstream.converters.reflection;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
public class FieldDictionary {
private static final Map keyedByFieldNameCache = new TreeMap();
private static final Map keyedByFieldKeyCache = new TreeMap();
public Iterator serializableFieldsFor(Class cls) {
return buildMap(cls, true).values().iterator();
}
public Field field(Class cls, String name, Class definedIn) {
Map fields = buildMap(cls, definedIn != null);
Field field = (Field) fields.get(definedIn != null ? (Object) new FieldKey(name, definedIn, 0) : (Object) name);
if (field == null) {
throw new ObjectAccessException("No such field " + cls.getName() + "." + name);
} else {
return field;
}
}
private Map buildMap(Class cls, boolean tupleKeyed) {
final String clsName = cls.getName();
if (!keyedByFieldNameCache.containsKey(clsName)) {
final Map keyedByFieldName = new TreeMap();
final Map keyedByFieldKey = new OrderRetainingMap();
while (!Object.class.equals(cls)) {
Field[] fields = cls.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
if (field.getName().startsWith("this$")) {
continue;
}
field.setAccessible(true);
if (!keyedByFieldName.containsKey(field.getName())) {
keyedByFieldName.put(field.getName(), field);
}
keyedByFieldKey.put(new FieldKey(field.getName(), field.getDeclaringClass(), i), field);
}
cls = cls.getSuperclass();
}
keyedByFieldNameCache.put(clsName, keyedByFieldName);
keyedByFieldKeyCache.put(clsName, keyedByFieldKey);
}
return (Map) (tupleKeyed ? keyedByFieldKeyCache.get(clsName) : keyedByFieldNameCache.get(clsName));
}
private static class FieldKey {
private String fieldName;
private Class declaringClass;
private Integer depth;
private int order;
public FieldKey(String fieldName, Class declaringClass, int order) {
this.fieldName = fieldName;
this.declaringClass = declaringClass;
this.order = order;
Class c = declaringClass;
int i = 0;
while (c.getSuperclass() != null) {
i++;
c = c.getSuperclass();
}
depth = new Integer(i);
}
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof FieldKey)) return false;
final FieldKey fieldKey = (FieldKey) o;
if (declaringClass != null ? !declaringClass.equals(fieldKey.declaringClass) : fieldKey.declaringClass != null) return false;
if (fieldName != null ? !fieldName.equals(fieldKey.fieldName) : fieldKey.fieldName != null) return false;
return true;
}
public int hashCode() {
int result;
result = (fieldName != null ? fieldName.hashCode() : 0);
result = 29 * result + (declaringClass != null ? declaringClass.hashCode() : 0);
return result;
}
public String toString() {
return "FieldKey{" +
"order=" + order +
", depth=" + depth +
", declaringClass=" + declaringClass +
", fieldName='" + fieldName + "'" +
"}";
}
}
private static class OrderRetainingMap extends HashMap {
private List valueOrder = new ArrayList();
public Object put(Object key, Object value) {
valueOrder.add(value);
return super.put(key, value);
}
public Collection values() {
return Collections.unmodifiableList(valueOrder);
}
}
} |
package de.fau.cs.mad.yasme.android.ui.fragments;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnKeyListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import de.fau.cs.mad.yasme.android.R;
import de.fau.cs.mad.yasme.android.asyncTasks.server.GetProfilePictureTask;
import de.fau.cs.mad.yasme.android.asyncTasks.server.SetProfileDataTask;
import de.fau.cs.mad.yasme.android.asyncTasks.server.UploadProfilePictureTask;
import de.fau.cs.mad.yasme.android.controller.FragmentObservable;
import de.fau.cs.mad.yasme.android.controller.Log;
import de.fau.cs.mad.yasme.android.controller.NotifiableFragment;
import de.fau.cs.mad.yasme.android.controller.ObservableRegistry;
import de.fau.cs.mad.yasme.android.controller.Sanitizer;
import de.fau.cs.mad.yasme.android.entities.User;
import de.fau.cs.mad.yasme.android.storage.PictureManager;
import de.fau.cs.mad.yasme.android.ui.AbstractYasmeActivity;
import de.fau.cs.mad.yasme.android.ui.ChatAdapter;
public class OwnProfileFragment extends Fragment implements View.OnClickListener, NotifiableFragment<Drawable> {
private EditText name;
private ImageView profilePictureView;
private TextView initial;
private OnOwnProfileFragmentInteractionListener mListener;
User self;
AbstractYasmeActivity activity;
private static int RESULT_LOAD_IMAGE = 1;
public OwnProfileFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Register at observer
Log.d(this.getClass().getSimpleName(), "Try to get OwnProfileObservable");
FragmentObservable<OwnProfileFragment, Drawable> obs = ObservableRegistry.getObservable(OwnProfileFragment.class);
Log.d(this.getClass().getSimpleName(), "... successful");
obs.register(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
activity = (AbstractYasmeActivity) getActivity();
self = activity.getSelfUser();
View layout = inflater.inflate(R.layout.fragment_own_profile, container, false);
TextView email = (TextView) layout.findViewById(R.id.own_profile_email);
TextView id = (TextView) layout.findViewById(R.id.own_profile_id);
initial = (TextView) layout.findViewById(R.id.own_profile_picture_text);
profilePictureView = (ImageView) layout.findViewById(R.id.own_profile_picture);
profilePictureView.setOnClickListener(this);
name = (EditText) layout.findViewById(R.id.own_profile_header);
name.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event isn't a key-down event on the "enter" button, skip this.
if (!((event.getAction() == KeyEvent.ACTION_DOWN) && (keyCode == KeyEvent.KEYCODE_ENTER)))
return false;
AbstractYasmeActivity activity = (AbstractYasmeActivity) getActivity();
// Hide virtual keyboard
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(name.getWindowToken(), 0);
// Set Focus away from edittext
name.setFocusable(false);
name.setFocusableInTouchMode(true);
// Save name in android device
Sanitizer sanitizer = new Sanitizer();
String oldName = name.getText().toString();
String newName = sanitizer.sanitize(oldName);
if(!oldName.equals(newName)) {
Toast.makeText(getActivity(), getString(R.string.illegal_characters) + ": " + sanitizer.getRegex(), Toast.LENGTH_LONG).show();
name.setText(newName);
}
new SetProfileDataTask(new User(newName, activity.getUserMail(), -1)).execute();
return true;
}
});
name.setText(self.getName());
email.setText(self.getEmail());
id.setText("" + self.getId());
self.setProfilePicture(activity.getOwnProfilePicture());
BitmapDrawable pic = null;
if (self.getProfilePicture() != null) {
int width = 300;
int height = 300;
Log.e(this.getClass().getSimpleName(), "Width: " + width + " Height: " + height);
pic = new BitmapDrawable(getResources(), PictureManager.INSTANCE
.getPicture(self, height, width));
Log.d(this.getClass().getSimpleName(), "Try to load Picture from: " + self.getProfilePicture());
}
if (pic == null) {
// Show nice profile picture
Log.d(this.getClass().getSimpleName(), "using standard picture");
profilePictureView.setBackgroundColor(ChatAdapter.CONTACT_DUMMY_COLORS_ARGB
[(int) self.getId() % ChatAdapter.CONTACT_DUMMY_COLORS_ARGB.length]);
if (self.getName() != null && !self.getName().isEmpty()) {
initial.setText(self.getName().substring(0, 1).toUpperCase());
}
// Load profile image into profilePictureView from server as AsyncTask if available
new GetProfilePictureTask(getClass()).execute(self.getId());
} else {
notifyFragment(pic);
Log.d(this.getClass().getSimpleName(), "successful loaded picture");
}
return layout;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (OnOwnProfileFragmentInteractionListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener");
}
}
@Override
public void onDetach() {
super.onDetach();
mListener = null;
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.own_profile_picture:
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);
break;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getActivity().getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
//store own image on device
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(picturePath, options);
// Calculate inSampleSize
options.inSampleSize = PictureManager.INSTANCE.calculateInSampleSize(options, 500, 500);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap newProfilePicture = BitmapFactory.decodeFile(picturePath, options);
String path = "";
try {
path = PictureManager.INSTANCE.storePicture(self, newProfilePicture);
} catch (IOException e) {
Log.e(this.getClass().getSimpleName(), e.getMessage());
return;
}
activity.setOwnProfilePicture(path);
// set picture
notifyFragment(new BitmapDrawable(getResources(), newProfilePicture));
// Upload picture as AsyncTask
new UploadProfilePictureTask(newProfilePicture).execute();
}
}
@Override
public void notifyFragment(Drawable value) {
initial.setVisibility(View.GONE);
profilePictureView.setBackgroundColor(Color.TRANSPARENT);
profilePictureView.setImageDrawable(value);
}
public interface OnOwnProfileFragmentInteractionListener {
public void onOwnProfileFragmentInteraction(String s);
}
} |
package org.hyperic.sigar;
/**
* Flag constants for network related ops.
*/
public class NetFlags {
private NetFlags () { }
/**
* value of unknown or non-existent hardware address
*/
public final static String NULL_HWADDR = "00:00:00:00:00:00";
public static final String ANY_ADDR = "0.0.0.0";
public static final String ANY_ADDR_V6 = "::";
public static final String LOOPBACK_HOSTNAME = "localhost";
public static final String LOOPBACK_ADDRESS = "127.0.0.1";
public static final String LOOPBACK_ADDRESS_V6 = "::1";
/**
* interface is up
*/
public final static int IFF_UP = 0x1;
/**
* broadcast address valid
*/
public final static int IFF_BROADCAST = 0x2;
/**
* debugging is on
*/
public final static int IFF_DEBUG = 0x4;
/**
* is a loopback net
*/
public final static int IFF_LOOPBACK = 0x8;
/**
* interface has a point-to-point link
*/
public final static int IFF_POINTOPOINT = 0x10;
/**
* avoid use of trailers
*/
public final static int IFF_NOTRAILERS = 0x20;
/**
* interface is running
*/
public final static int IFF_RUNNING = 0x40;
/**
* no ARP protocol
*/
public final static int IFF_NOARP = 0x80;
/**
* receive all packets
*/
public final static int IFF_PROMISC = 0x100;
/**
* receive all multicast packets
*/
public final static int IFF_ALLMULTI = 0x200;
/**
* supports multicast
*/
public final static int IFF_MULTICAST = 0x800;
public final static int IFF_SLAVE = 0x1000;
/**
* Master of a load balancer
*/
public static final int IFF_MASTER = 0x2000;
/**
* Dialup device with changing addresses
*/
public static final int IFF_DYNAMIC = 0x4000;
public static final int RTF_UP = 0x1;
public static final int RTF_GATEWAY = 0x2;
public static final int RTF_HOST = 0x4;
public final static int CONN_CLIENT = 0x01;
public final static int CONN_SERVER = 0x02;
public final static int CONN_TCP = 0x10;
public final static int CONN_UDP = 0x20;
public final static int CONN_RAW = 0x40;
public final static int CONN_UNIX = 0x80;
public final static int CONN_PROTOCOLS =
NetFlags.CONN_TCP | NetFlags.CONN_UDP |
NetFlags.CONN_RAW | NetFlags.CONN_UNIX;
public static final int TCP_ESTABLISHED = 1;
public static final int TCP_SYN_SENT = 2;
public static final int TCP_SYN_RECV = 3;
public static final int TCP_FIN_WAIT1 = 4;
public static final int TCP_FIN_WAIT2 = 5;
public static final int TCP_TIME_WAIT = 6;
public static final int TCP_CLOSE = 7;
public static final int TCP_CLOSE_WAIT = 8;
public static final int TCP_LAST_ACK = 9;
public static final int TCP_LISTEN = 10;
public static final int TCP_CLOSING = 11;
public static final int TCP_IDLE = 12;
public static final int TCP_BOUND = 13;
public static final int TCP_UNKNOWN = 14;
public static int getConnectionProtocol(String protocol)
throws SigarException {
if (protocol.equals("tcp")) {
return NetFlags.CONN_TCP;
}
else if (protocol.equals("udp")) {
return NetFlags.CONN_UDP;
}
else if (protocol.equals("raw")) {
return NetFlags.CONN_RAW;
}
else if (protocol.equals("unix")) {
return NetFlags.CONN_UNIX;
}
String msg = "Protocol '" + protocol + "' not supported";
throw new SigarException(msg);
}
/**
* @param flags network interface flags.
* @return String representation of network interface flags.
* @see org.hyperic.sigar.NetInterfaceConfig#getFlags
*/
public static native String getIfFlagsString(long flags);
/**
* @param network interface ipv6 address scope.
* @return String representation of ipv6 address scope.
* @see org.hyperic.sigar.NetInterfaceConfig#getScope6
*/
public static native String getScopeString(int scope);
public static boolean isAnyAddress(String address) {
return
(address == null) ||
address.equals(ANY_ADDR) ||
address.equals(ANY_ADDR_V6);
}
public static boolean isLoopback(String address) {
return
address.equals(LOOPBACK_HOSTNAME) ||
address.equals(LOOPBACK_ADDRESS) ||
address.equals(LOOPBACK_ADDRESS_V6);
}
} |
package org.xdi.oxauth.load.benchmark;
import org.testng.Reporter;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Listeners;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.xdi.oxauth.BaseTest;
import org.xdi.oxauth.client.*;
import org.xdi.oxauth.load.benchmark.suite.BenchmarkTestListener;
import org.xdi.oxauth.load.benchmark.suite.BenchmarkTestSuiteListener;
import org.xdi.oxauth.model.common.Prompt;
import org.xdi.oxauth.model.common.ResponseType;
import org.xdi.oxauth.model.register.ApplicationType;
import org.xdi.oxauth.model.util.StringUtils;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
/**
* @author Yuriy Movchan
* @author Javier Rojas Blum
* @version June 19, 2015
*/
@Listeners({BenchmarkTestSuiteListener.class, BenchmarkTestListener.class})
public class BenchmarkRequestAuthorization extends BaseTest {
private String clientId;
private String redirectUri;
@Parameters({"userId", "userSecret", "redirectUris"})
@BeforeClass
public void registerClient(final String userId, final String userSecret, String redirectUris) throws Exception {
Reporter.log("Register client", true);
List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE, ResponseType.ID_TOKEN);
List<String> redirectUrisList = StringUtils.spaceSeparatedToList(redirectUris);
RegisterRequest registerRequest = new RegisterRequest(ApplicationType.WEB, "oxAuth benchmark test app", redirectUrisList);
registerRequest.setResponseTypes(responseTypes);
RegisterClient registerClient = new RegisterClient(registrationEndpoint);
registerClient.setRequest(registerRequest);
RegisterResponse registerResponse = registerClient.exec();
assertEquals(registerResponse.getStatus(), 200, "Unexpected response code: " + registerResponse.getEntity());
assertNotNull(registerResponse.getClientId());
assertNotNull(registerResponse.getClientSecret());
assertNotNull(registerResponse.getRegistrationAccessToken());
assertNotNull(registerResponse.getClientIdIssuedAt());
assertNotNull(registerResponse.getClientSecretExpiresAt());
this.clientId = registerResponse.getClientId();
this.redirectUri = redirectUrisList.get(0);
}
@Parameters({"userId", "userSecret"})
@Test(invocationCount = 1000, threadPoolSize = 10)
public void testAuthorization1(final String userId, final String userSecret) throws Exception {
testAuthorizationImpl(userId, userSecret, this.redirectUri, this.clientId);
}
@Parameters({"userId", "userSecret"})
@Test(invocationCount = 1000, threadPoolSize = 10, dependsOnMethods = {"testAuthorization1"})
public void testAuthorization2(final String userId, final String userSecret) throws Exception {
testAuthorizationImpl(userId, userSecret, this.redirectUri, this.clientId);
}
@Parameters({"userId", "userSecret"})
@Test(invocationCount = 500, threadPoolSize = 2, dependsOnMethods = {"testAuthorization2"})
public void testAuthorization3(final String userId, final String userSecret) throws Exception {
testAuthorizationImpl(userId, userSecret, this.redirectUri, this.clientId);
}
private void testAuthorizationImpl(final String userId, final String userSecret, String redirectUri, String clientId) {
List<ResponseType> responseTypes = Arrays.asList(ResponseType.CODE, ResponseType.ID_TOKEN);
List<String> scopes = Arrays.asList("openid", "profile", "address", "email", "user_name");
String state = UUID.randomUUID().toString();
String nonce = UUID.randomUUID().toString();
AuthorizationRequest authorizationRequest = new AuthorizationRequest(responseTypes, clientId, scopes, redirectUri, null);
authorizationRequest.setAuthUsername(userId);
authorizationRequest.setAuthPassword(userSecret);
authorizationRequest.setState(state);
authorizationRequest.setNonce(nonce);
authorizationRequest.getPrompts().add(Prompt.NONE);
AuthorizeClient authorizeClient = new AuthorizeClient(this.authorizationEndpoint);
authorizeClient.setRequest(authorizationRequest);
AuthorizationResponse response = authorizeClient.exec();
assertEquals(response.getStatus(), 302, "Unexpected response code: " + response.getEntity());
assertNotNull(response.getLocation(), "The location is null");
assertNotNull(response.getCode(), "The authorization code is null");
assertNotNull(response.getIdToken(), "The id_token is null");
assertNotNull(response.getState(), "The state is null");
assertNotNull(response.getScope(), "The scope is null");
}
} |
package com.example.ssteeve.dpdandroidtest;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.example.ssteeve.dpd_android.DPDObject;
import com.example.ssteeve.dpd_android.DPDQuery;
import com.example.ssteeve.dpd_android.DPDUser;
import com.example.ssteeve.dpd_android.MappableResponseCallBack;
import com.example.ssteeve.dpd_android.QueryCondition;
import com.example.ssteeve.dpd_android.ResponseCallBack;
import org.json.JSONException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import okhttp3.Call;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
List<User> users = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
login();
//createUser();
//updateUser();
//logout();
}
void login() {
try {
DPDUser.login("users", "dpd-android", "dpd-android", User.class, new MappableResponseCallBack() {
@Override
public void onResponse(List<DPDObject> response) {
if (response != null) {
users = (List<User>)(List<?>) response;
}
}
@Override
public void onFailure(Call call, Response response, Exception e) {
Log.d(this.getClass().getSimpleName(), "error occured");
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
void createUser() {
try {
DPDUser.createUser("users", "dpdAndroid", "dpdAndroi", User.class, new MappableResponseCallBack() {
@Override
public void onResponse(List<DPDObject> response) {
Log.d(this.getClass().getSimpleName(), "User created successfully");
}
@Override
public void onFailure(Call call, Response response, Exception e) {
Log.d(this.getClass().getSimpleName(), "Failed to create user");
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
void updateUser() {
try {
User user = (User) DPDUser.getInstance().currentUser(User.class);
user.firstName = "John";
user.lastName = "Doe";
user.updateObject("users", User.class, new MappableResponseCallBack() {
@Override
public void onResponse(List<DPDObject> response) {
Log.d(this.getClass().getSimpleName(), "User updated successfully");
}
@Override
public void onFailure(Call call, Response response, Exception e) {
Log.d(this.getClass().getSimpleName(), "Failed to update user");
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
void loadStroe() {
DPDQuery query = new DPDQuery(QueryCondition.LESS_THAN, null, null, null, "zip", "60012", null);
query.findMappableObject("stores", Store.class, new MappableResponseCallBack() {
@Override
public void onResponse(List<DPDObject> response) {
Log.d(this.getClass().getSimpleName(), "response");
}
@Override
public void onFailure(Call call, Response response, Exception e) {
Log.d(this.getClass().getSimpleName(), "error occured");
}
});
}
void logout() {
DPDUser.logout(new ResponseCallBack() {
@Override
public void onResponse(String response) {
Log.d(this.getClass().getSimpleName(), response);
}
@Override
public void onFailure(Call call, Response response, Exception e) {
Log.d(this.getClass().getSimpleName(), "Failed to logout");
}
});
}
} |
package nl.fontys.limo.simulation.task;
import nl.fontys.limo.simulation.result.SimulationResult;
import nl.fontys.sofa.limo.domain.component.SupplyChain;
import nl.fontys.sofa.limo.domain.component.hub.Hub;
import nl.fontys.sofa.limo.domain.component.leg.Leg;
import nl.fontys.sofa.limo.domain.component.procedure.Procedure;
import nl.fontys.sofa.limo.domain.component.procedure.ProcedureResponsibilityDirection;
import nl.fontys.sofa.limo.domain.component.procedure.TimeType;
import nl.fontys.sofa.limo.domain.component.procedure.value.RangeValue;
import org.junit.Assert;
import org.junit.Test;
public class SimulationTest {
private Simulation simulation;
private final SupplyChain supplyChain;
public SimulationTest() {
supplyChain = new SupplyChain();
simulation = new Simulation(supplyChain, 5);
Hub start = new Hub();
start.addProcedure(new Procedure("loading", "mandatory", new RangeValue(3000, 4000), new RangeValue(3, 4), TimeType.HOURS, ProcedureResponsibilityDirection.INPUT));
//start.addEvent(new Event());
Hub end = new Hub();
end.addProcedure(new Procedure("unloading", "mandatory", new RangeValue(2000, 3000), new RangeValue(2, 3), TimeType.HOURS, ProcedureResponsibilityDirection.OUTPUT));
Leg leg = new Leg();
leg.setNext(end);
start.setNext(leg);
supplyChain.setStart(start);
}
@Test
public void testGetProgress() {
double progress = simulation.getProgress();
Assert.assertEquals(0, progress, 0.000001);
}
@Test
public void testGetResult() {
SimulationResult result = simulation.getResult();
Assert.assertEquals(0, result.getTotalCosts().getMax(), 0.000001);
Assert.assertEquals(0, result.getTotalDelays().getMax(), 0.000001);
Assert.assertEquals(0, result.getTotalExtraCosts().getMax(), 0.000001);
Assert.assertEquals(0, result.getTotalLeadTimes().getMax(), 0.000001);
}
@Test
public void testRun() {
// simulation.run();
// while (simulation.getProgress() != 1) {
// SimulationResult result = simulation.getResult();
// Assert.assertNotNull(result);
// DataEntry totalCosts = result.getTotalCosts();
// Assert.assertEquals(5000, totalCosts.getMin(), 0.000001);
// Assert.assertEquals(7000, totalCosts.getMax(), 0.000001);
// Assert.assertTrue(totalCosts.getAvg() > 5000);
// Assert.assertTrue(totalCosts.getAvg() < 7000);
// DataEntry totalDelays = result.getTotalDelays();
// DataEntry totalExtraCosts = result.getTotalExtraCosts();
// DataEntry totalLeadTimes = result.getTotalLeadTimes();
}
@Test
public void testTaskFinished() {
// simulation.taskFinished(Task.EMPTY);
}
} |
package org.jetbrains.plugins.scala.testingSupport.scalaTest;
import org.jetbrains.plugins.scala.testingSupport.TestRunnerUtil;
import org.scalatest.*;
import org.scalatest.tools.Runner;
import scala.None$;
import scala.Option;
import scala.Some$;
import scala.collection.immutable.Map;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLDecoder;
import java.util.*;
import java.util.jar.JarFile;
/**
* @author Alexander Podkhalyuzin
*/
public class ScalaTestRunner {
private static final String reporterQualName = "org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestReporter";
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
try {
if (isScalaTest2())
runScalaTest2(args);
else
runScalaTest1(args);
} catch (Throwable ignore) {
ignore.printStackTrace();
}
System.exit(0);
}
private static boolean isScalaTest2() {
try {
ScalaTestRunner.class.getClassLoader().loadClass("org.scalatest.events.Location");
return true;
}
catch(ClassNotFoundException e) {
return false;
}
}
private static void runScalaTest2(String[] args) throws IOException {
ArrayList<String> argsArray = new ArrayList<String>();
HashSet<String> classes = new HashSet<String>();
HashMap<String, Set<String>> failedTestMap = new HashMap<String, Set<String>>();
boolean failedUsed = false;
String testName = "";
boolean showProgressMessages = true;
boolean useVersionFromOptions = false;
boolean isOlderScalaVersionFromOptions = false;
int i = 0;
String[] newArgs = TestRunnerUtil.getNewArgs(args);
while (i < newArgs.length) {
if (newArgs[i].equals("-s")) {
++i;
while (i < newArgs.length && !newArgs[i].startsWith("-")) {
classes.add(newArgs[i]);
++i;
}
} else if (newArgs[i].equals("-testName")) {
++i;
testName = newArgs[i];
++i;
} else if (newArgs[i].equals("-showProgressMessages")) {
++i;
showProgressMessages = Boolean.parseBoolean(newArgs[i]);
++i;
} else if (newArgs[i].equals("-failedTests")) {
failedUsed = true;
++i;
while (i < newArgs.length && !newArgs[i].startsWith("-")) {
String failedClassName = newArgs[i];
String failedTestName = newArgs[i + 1];
Set<String> testSet = failedTestMap.get(failedClassName);
if (testSet == null)
testSet = new HashSet<String>();
testSet.add(failedTestName);
failedTestMap.put(failedClassName, testSet);
i += 2;
}
} else if (newArgs[i].startsWith("-setScalaTestVersion=")) {
useVersionFromOptions = true;
isOlderScalaVersionFromOptions = isOlderScalaVersionFromOptions(newArgs[i]);
++i;
} else if (newArgs[i].equals("-C")) {
if (useVersionFromOptions) {
argsArray.add(isOlderScalaVersionFromOptions ? "-r" : newArgs[i]);
} else {
argsArray.add(isOlderScalaTestVersion() ? "-r" : newArgs[i]);
}
if (i + 1 < newArgs.length) argsArray.add(newArgs[i + 1] + "WithLocation");
i += 2;
} else {
argsArray.add(newArgs[i]);
++i;
}
}
TestRunnerUtil.configureReporter(reporterQualName, showProgressMessages);
if (failedUsed) {
// TODO: How to support -s -i -t here, to support rerunning nested suite's test.
for (java.util.Map.Entry<String, Set<String>> entry : failedTestMap.entrySet()) {
argsArray.add("-s");
argsArray.add(entry.getKey());
for (String failedTestName : entry.getValue()) {
argsArray.add("-t");
argsArray.add(failedTestName);
}
}
} else if (testName.equals("")) {
for (String clazz : classes) {
argsArray.add("-s");
argsArray.add(clazz);
}
} else {
String[] testNames = testName.split(";");
for (String clazz : classes) {
for (String tn : Arrays.asList(testNames)) {
// Should encounter problem if the suite class does not have the specified test name.
argsArray.add("-s");
argsArray.add(clazz);
argsArray.add("-t");
argsArray.add(tn);
}
}
}
Runner.run(argsArray.toArray(new String[argsArray.size()]));
}
private static void runScalaTest1(String[] args) throws ClassNotFoundException, IllegalAccessException, InstantiationException, NoSuchMethodException, InvocationTargetException, IOException {
ArrayList<String> argsArray = new ArrayList<String>();
ArrayList<String> classes = new ArrayList<String>();
ArrayList<String> failedTests = new ArrayList<String>();
boolean failedUsed = false;
String testName = "";
boolean showProgressMessages = true;
boolean useVersionFromOptions = false;
boolean isOlderScalaVersionFromOptions = false;
int i = 0;
int classIndex = 0;
String[] newArgs = TestRunnerUtil.getNewArgs(args);
while (i < newArgs.length) {
if (newArgs[i].equals("-s")) {
argsArray.add(newArgs[i]);
++i;
argsArray.add("empty");
classIndex = i;
while (i < newArgs.length && !newArgs[i].startsWith("-")) {
classes.add(newArgs[i]);
++i;
}
} else if (newArgs[i].equals("-testName")) {
++i;
testName = newArgs[i];
++i;
} else if (newArgs[i].equals("-showProgressMessages")) {
++i;
showProgressMessages = Boolean.parseBoolean(newArgs[i]);
++i;
} else if (newArgs[i].equals("-failedTests")) {
failedUsed = true;
++i;
while (i < newArgs.length && !newArgs[i].startsWith("-")) {
failedTests.add(newArgs[i]);
++i;
}
} else if (newArgs[i].startsWith("-setScalaTestVersion=")) {
useVersionFromOptions = true;
isOlderScalaVersionFromOptions = isOlderScalaVersionFromOptions(newArgs[i]);
++i;
} else if (newArgs[i].equals("-C")) {
if (useVersionFromOptions) {
argsArray.add(isOlderScalaVersionFromOptions ? "-r" : newArgs[i]);
} else {
argsArray.add(isOlderScalaTestVersion() ? "-r" : newArgs[i]);
}
if (i + 1 < newArgs.length) argsArray.add(newArgs[i + 1]);
i += 2;
} else {
argsArray.add(newArgs[i]);
++i;
}
}
String[] arga = argsArray.toArray(new String[argsArray.size()]);
if (failedUsed) {
i = 0;
while (i + 1 < failedTests.size()) {
TestRunnerUtil.configureReporter(reporterQualName, showProgressMessages);
runSingleTest(failedTests.get(i + 1), failedTests.get(i));
i += 2;
}
} else if (testName.equals("")) {
for (String clazz : classes) {
arga[classIndex] = clazz;
TestRunnerUtil.configureReporter(reporterQualName, showProgressMessages);
Runner.run(arga);
}
} else {
String[] testNames = testName.split(";");
for (String clazz : classes) {
for (String tn : Arrays.asList(testNames)) {
TestRunnerUtil.configureReporter(reporterQualName, showProgressMessages);
runSingleTest(tn, clazz);
}
}
}
}
private static void runSingleTest(String testName, String clazz) throws IllegalAccessException,
InstantiationException, ClassNotFoundException, NoSuchMethodException, InvocationTargetException {
try {
Class<?> aClass = ScalaTestRunner.class.getClassLoader().loadClass(clazz);
Suite suite = (Suite) aClass.newInstance();
String reporterQualName = "org.jetbrains.plugins.scala.testingSupport.scalaTest.ScalaTestReporter";
Class<?> reporterClass = ScalaTestRunner.class.getClassLoader().
loadClass(reporterQualName);
Reporter reporter = (Reporter) reporterClass.newInstance();
Class<?> suiteClass = Class.forName("org.scalatest.Suite");
Method method = suiteClass.getMethod("run", Option.class, Reporter.class, Stopper.class, org.scalatest.Filter.class,
Map.class, Option.class, Tracker.class);
// This stopper could be used to request stop to runner
Stopper stopper = new Stopper() {
private volatile boolean stopRequested = false;
public boolean apply() {
return stopRequested();
}
public boolean stopRequested() {
return stopRequested;
}
public void requestStop() {
stopRequested = true;
}
};
method.invoke(suite, Some$.MODULE$.apply(testName), reporter, stopper, Filter$.MODULE$.getClass().getMethod("apply").invoke(Filter$.MODULE$),
scala.collection.immutable.Map$.MODULE$.empty(), None$.MODULE$, Tracker.class.getConstructor().newInstance());
}
catch(Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
private static boolean isOlderScalaTestVersion() {
try {
Class<?> suiteClass = Class.forName("org.scalatest.Suite");
URL location = suiteClass.getResource('/' + suiteClass.getName().replace('.', '/') + ".class");
String path = location.getPath();
String jarPath = path.substring(5, path.indexOf("!"));
JarFile jar = new JarFile(URLDecoder.decode(jarPath, "UTF-8"));
String version = jar.getManifest().getMainAttributes().getValue("Bundle-Version");
return parseVersion(version);
} catch (IOException e) {
return true;
} catch (ClassNotFoundException e) {
return true;
}
}
private static boolean isOlderScalaVersionFromOptions(String arg) {
if (arg.indexOf("=") + 1 < arg.length()) {
String version = arg.substring(arg.indexOf("=") + 1);
return parseVersion(version);
} else {
return true;
}
}
private static boolean parseVersion(String version) {
try {
if (version != null && !version.isEmpty()) {
String[] nums = version.split("\\.");
if (nums.length >= 2) {
if (Integer.parseInt(nums[0]) == 1 && Integer.parseInt(nums[1]) >= 8) {
return false;
} else if (Integer.parseInt(nums[0]) == 2 && Integer.parseInt(nums[1]) >= 0) {
return false;
} else if (Integer.parseInt(nums[0]) == 3 && Integer.parseInt(nums[1]) >= 0) {
return false;
}
}
}
} catch (NumberFormatException e) {
return true;
}
return true;
}
} |
package com.groupon.seleniumgridextras.grid;
import com.google.gson.JsonObject;
import com.groupon.seleniumgridextras.ExecuteCommand;
import com.groupon.seleniumgridextras.config.Config;
import com.groupon.seleniumgridextras.config.GridNode;
import com.groupon.seleniumgridextras.config.GridNode.GridNodeConfiguration;
import com.groupon.seleniumgridextras.config.RuntimeConfig;
import com.groupon.seleniumgridextras.utilities.json.JsonCodec;
import com.groupon.seleniumgridextras.utilities.json.JsonResponseBuilder;
import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import java.io.File;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.ArrayList;
public class GridStarter {
private static Logger logger = Logger.getLogger(GridStarter.class);
public static String[] getOsSpecificHubStartCommand(String configFile, Boolean windows) {
List<String> command = new ArrayList<String>();
command.add(getJavaExe());
if(RuntimeConfig.getConfig().getGridJvmXOptions() != "") {
List<String> options = new ArrayList<String>(Arrays.asList(RuntimeConfig.getConfig().getGridJvmXOptions().split(" ")));
for(String option : options) {
command.add(option);
}
}
if(RuntimeConfig.getConfig().getGridJvmOptions() != "") {
List<String> options = new ArrayList<String>(Arrays.asList(RuntimeConfig.getConfig().getGridJvmOptions().split(" ")));
for(String option : options) {
command.add(option);
}
}
String cp = getGridExtrasJarFilePath();
List<String> additionalClassPathItems = RuntimeConfig.getConfig().getAdditionalHubConfig();
for(String additionalJarPath : additionalClassPathItems) {
cp += RuntimeConfig.getOS().getPathSeparator() + additionalJarPath;
}
String jarPath = RuntimeConfig.getOS().getPathSeparator() + getCurrentWebDriverJarPath(RuntimeConfig.getConfig());
cp += jarPath;
command.add("-cp");
command.add(cp);
String classPath = getWebdriverVersion(RuntimeConfig.getConfig()).startsWith("3.") ? "org.openqa.grid.selenium.GridLauncherV3" : "org.openqa.grid.selenium.GridLauncher";
command.add(classPath);
command.add("-role");
command.add("hub");
String logFile = configFile.replace("json", "log");
command.add("-log");
command.add("log" + RuntimeConfig.getOS().getFileSeparator() + logFile);
command.add("-hubConfig");
command.add(configFile);
logger.info("Hub Start Command: \n\n" + Arrays.toString(command.toArray(new String[0])));
return command.toArray(new String[0]);
}
public static JsonObject startAllNodes(JsonResponseBuilder jsonResponseBuilder) {
for (List<String> command : getStartCommandsForNodes(
RuntimeConfig.getOS().isWindows(),
RuntimeConfig.getConfig())) {
logger.info(command);
try {
JsonObject startResponse = startOneNode(command);
logger.info(startResponse);
if (!startResponse.get(JsonCodec.EXIT_CODE).toString().equals("0")) {
jsonResponseBuilder
.addKeyValues(JsonCodec
.ERROR,
"Error running " + startResponse.get(JsonCodec.ERROR).toString());
}
} catch (Exception e) {
jsonResponseBuilder
.addKeyValues(JsonCodec.ERROR, "Error running " + command);
jsonResponseBuilder
.addKeyValues(JsonCodec.ERROR, e.toString());
e.printStackTrace();
}
}
return jsonResponseBuilder.getJson();
}
public static JsonObject startAllHubs(JsonResponseBuilder jsonResponseBuilder) {
for (String configFile : RuntimeConfig.getConfig().getHubConfigFiles()) {
String command[] = getOsSpecificHubStartCommand(configFile, RuntimeConfig.getOS().isWindows());
logger.info(command);
try {
JsonObject startResponse = ExecuteCommand.execRuntime(command, false);
logger.info(startResponse);
if (!startResponse.get(JsonCodec.EXIT_CODE).toString().equals("0")) {
jsonResponseBuilder
.addKeyValues(JsonCodec.ERROR, "Error running " + startResponse.get(JsonCodec.ERROR).toString());
}
} catch (Exception e) {
jsonResponseBuilder
.addKeyValues(JsonCodec.ERROR, "Error running " + command);
jsonResponseBuilder
.addKeyValues(JsonCodec.ERROR, e.toString());
e.printStackTrace();
}
}
return jsonResponseBuilder.getJson();
}
public static JsonObject startOneNode(List<String> command) {
logger.info("Hub Start Command: \n\n" + Arrays.toString(command.toArray(new String[0])));
return ExecuteCommand.execRuntime(command.toArray(new String[0]), false);
}
public static List<List<String>> getStartCommandsForNodes(Boolean isWindows, Config config) {
List<List<String>> commands = new LinkedList<List<String>>();
List<String> configFiles = RuntimeConfig.getConfig().getNodeConfigFiles();
for (String configFile : configFiles) {
List<String>
backgroundCommand =
getBackgroundStartCommandForNode(getNodeStartCommand(configFile, isWindows, config),
configFile.replace("json", "log"),
isWindows);
commands.add(backgroundCommand);
}
logger.info("Node Start Command: \n\n" + String.valueOf(commands));
return commands;
}
protected static List<String> getBackgroundStartCommandForWebNode(List<String> command, String logFile) {
String logFileFullPath = "log" + RuntimeConfig.getOS().getFileSeparator() + logFile;
command.add("-log");
command.add(logFileFullPath);
return command;
}
protected static List<String> getBackgroundStartCommandForAppiumNode(List<String> command, String logFile) {
String workingDirectory = System.getProperty("user.dir");
String logFileFullPath = workingDirectory + RuntimeConfig.getOS().getFileSeparator() + "log" +
RuntimeConfig.getOS().getFileSeparator() + logFile;
command.add("--log");
command.add(logFileFullPath);
return command;
}
protected static List<String> getBackgroundStartCommandForNode(List<String> command, String logFile,
Boolean isWindows) {
if (logFile.startsWith("appium")) {
command = getBackgroundStartCommandForAppiumNode(command, logFile);
} else {
command = getBackgroundStartCommandForWebNode(command, logFile);
}
if (isWindows) {
String batchFile = logFile.replace("log", "bat");
StringBuilder sb = new StringBuilder();
for(String part : command) {
sb.append(part + " ");
}
writeBatchFile(batchFile, sb.toString());
return new ArrayList<String> ( Arrays.asList ( "cmd", "/C", "start" , "/MIN" , batchFile ) );
} else {
return command;
}
}
protected static List<String> getWebNodeStartCommand(String configFile, Boolean windows, Config config) {
List<String> command = new ArrayList<String>();
command.add(getJavaExe());
if(config.getGridJvmXOptions() != "") {
List<String> options = new ArrayList<String>(Arrays.asList(RuntimeConfig.getConfig().getGridJvmXOptions().split(" ")));
for(String option : options) {
command.add(option);
}
}
if(config.getGridJvmOptions() != "") {
List<String> options = new ArrayList<String>(Arrays.asList(RuntimeConfig.getConfig().getGridJvmOptions().split(" ")));
for(String option : options) {
command.add(option);
}
}
if (windows) {
command.add(getIEDriverExecutionPathParam(config));
command.add(getEdgeDriverExecutionPathParam(config));
}
command.add(getChromeDriverExecutionPathParam(config));
command.add(getGeckoDriverExecutionPathParam(config));
command.add("-cp");
String cp = getGridExtrasJarFilePath();
List<String> additionalClassPathItems = config.getAdditionalNodeConfig();
for(String additionalJarPath : additionalClassPathItems) {
cp += RuntimeConfig.getOS().getPathSeparator() + additionalJarPath;
}
cp += RuntimeConfig.getOS().getPathSeparator() + getCurrentWebDriverJarPath(config);
command.add(cp);
String classPath = getWebdriverVersion(config).startsWith("3.") ? "org.openqa.grid.selenium.GridLauncherV3" : "org.openqa.grid.selenium.GridLauncher";
command.add(classPath);
command.add("-role");
command.add("node");
if (RuntimeConfig.getHostIp() != null && RuntimeConfig.getOS().getHostName() == null) {
command.add("-host");
command.add(RuntimeConfig.getHostIp());
} else if ((RuntimeConfig.getOS().getHostName() != null) &&
!getWebdriverVersion(config).startsWith("3.")) { // Exception in thread "main" com.beust.jcommander.ParameterException: Unknown option: -friendlyHostName
command.add("-friendlyHostName");
command.add(RuntimeConfig.getOS().getHostName());
}
command.add("-nodeConfig");
command.add(configFile);
return command;
}
protected static List<String> getAppiumNodeStartCommand(String configFile, Config runtimeConfig) {
List<String> command = new ArrayList<String>();
if(!getWebdriverVersion(runtimeConfig).startsWith("3.")) {
GridNodeConfiguration config = GridNode.loadFromFile(configFile, false).getConfiguration();
command.add(config.getAppiumStartCommand());
command.add("-p");
command.add(config.getPort() + "");
} else {
GridNode node = GridNode.loadFromFile(configFile, true);
command.add(node.getAppiumStartCommand());
command.add("-p");
command.add(node.getPort() + "");
}
String workingDirectory = System.getProperty("user.dir");
String configFileFullPath = workingDirectory + RuntimeConfig.getOS().getFileSeparator() + configFile;
command.add("--log-timestamp");
command.add("--nodeconfig");
command.add(configFileFullPath);
return command;
}
protected static List<String> getNodeStartCommand(String configFile, Boolean windows, Config config) {
if (configFile.startsWith("appium")) {
return getAppiumNodeStartCommand(configFile, config);
} else {
return getWebNodeStartCommand(configFile, windows, config);
}
}
protected static String getIEDriverExecutionPathParam(Config config) {
if (RuntimeConfig.getOS().isWindows()) { //TODO: Clean this conditional up and test!!!
return String.format("-Dwebdriver.ie.driver=%s", config.getIEdriver().getExecutablePath());
} else {
return "";
}
}
public static String getEdgeDriverExecutionPathParam(Config config) {
return String.format("-Dwebdriver.edge.driver=\"%s\"", config.getEdgeDriver().getExecutablePath());
}
protected static String getChromeDriverExecutionPathParam(Config config) {
return String.format("-Dwebdriver.chrome.driver=%s", config.getChromeDriver().getExecutablePath());
}
protected static String getGeckoDriverExecutionPathParam(Config config) {
return String.format("-Dwebdriver.gecko.driver=%s", config.getGeckoDriver().getExecutablePath());
}
protected static String buildBackgroundStartCommand(String command, Boolean windows) {
String backgroundCommand;
final String batchFile = "start_hub.bat";
if (windows) {
writeBatchFile(batchFile, command);
backgroundCommand =
"start " + batchFile;
} else {
backgroundCommand = command;
}
return backgroundCommand;
}
protected static String getGridExtrasJarFilePath() {
return RuntimeConfig.getSeleniumGridExtrasJarFile().getAbsolutePath();
}
protected static String getCurrentWebDriverJarPath(Config config) {
return config.getWebdriver().getExecutablePath();
}
protected static String getWebdriverVersion(Config config) {
return config.getWebdriver().getVersion();
}
protected static String getWebdriverHome() {
return RuntimeConfig.getConfig().getWebdriver().getDirectory();
}
private static void writeBatchFile(String filename, String input) {
File file = new File(filename);
try {
FileUtils.writeStringToFile(file, input);
} catch (Exception error) {
logger.fatal("Could not write default config file, exit with error " + error.toString());
System.exit(1);
}
}
private static String getJavaExe() {
if (RuntimeConfig.getOS().isWindows()) {
return "java";
} else {
String javaHome = System.getProperty("java.home");
File f = new File(javaHome);
f = new File(f, "bin");
f = new File(f, "java");
return f.getAbsolutePath();
}
}
} |
package com.hubspot.singularity.client;
import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import javax.inject.Provider;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.fasterxml.jackson.core.type.TypeReference;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMap.Builder;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import com.hubspot.horizon.HttpClient;
import com.hubspot.horizon.HttpRequest;
import com.hubspot.horizon.HttpRequest.Method;
import com.hubspot.horizon.HttpResponse;
import com.hubspot.mesos.json.MesosFileChunkObject;
import com.hubspot.singularity.ExtendedTaskState;
import com.hubspot.singularity.MachineState;
import com.hubspot.singularity.OrderDirection;
import com.hubspot.singularity.SingularityAction;
import com.hubspot.singularity.SingularityAuthorizationScope;
import com.hubspot.singularity.SingularityClientCredentials;
import com.hubspot.singularity.SingularityCreateResult;
import com.hubspot.singularity.SingularityDeleteResult;
import com.hubspot.singularity.SingularityDeploy;
import com.hubspot.singularity.SingularityDeployHistory;
import com.hubspot.singularity.SingularityDeployKey;
import com.hubspot.singularity.SingularityDeployUpdate;
import com.hubspot.singularity.SingularityDisabledAction;
import com.hubspot.singularity.SingularityDisasterType;
import com.hubspot.singularity.SingularityDisastersData;
import com.hubspot.singularity.SingularityPaginatedResponse;
import com.hubspot.singularity.SingularityPendingRequest;
import com.hubspot.singularity.SingularityPendingRequestParent;
import com.hubspot.singularity.SingularityPendingTaskId;
import com.hubspot.singularity.SingularityPriorityFreezeParent;
import com.hubspot.singularity.SingularityRack;
import com.hubspot.singularity.SingularityRequest;
import com.hubspot.singularity.SingularityRequestCleanup;
import com.hubspot.singularity.SingularityRequestGroup;
import com.hubspot.singularity.SingularityRequestHistory;
import com.hubspot.singularity.SingularityRequestParent;
import com.hubspot.singularity.SingularityS3Log;
import com.hubspot.singularity.SingularitySandbox;
import com.hubspot.singularity.SingularitySlave;
import com.hubspot.singularity.SingularityState;
import com.hubspot.singularity.SingularityTask;
import com.hubspot.singularity.SingularityTaskCleanupResult;
import com.hubspot.singularity.SingularityTaskHistory;
import com.hubspot.singularity.SingularityTaskHistoryUpdate;
import com.hubspot.singularity.SingularityTaskId;
import com.hubspot.singularity.SingularityTaskIdHistory;
import com.hubspot.singularity.SingularityTaskReconciliationStatistics;
import com.hubspot.singularity.SingularityTaskRequest;
import com.hubspot.singularity.SingularityUpdatePendingDeployRequest;
import com.hubspot.singularity.SingularityWebhook;
import com.hubspot.singularity.api.SingularityBounceRequest;
import com.hubspot.singularity.api.SingularityDeleteRequestRequest;
import com.hubspot.singularity.api.SingularityDeployRequest;
import com.hubspot.singularity.api.SingularityDisabledActionRequest;
import com.hubspot.singularity.api.SingularityExitCooldownRequest;
import com.hubspot.singularity.api.SingularityKillTaskRequest;
import com.hubspot.singularity.api.SingularityMachineChangeRequest;
import com.hubspot.singularity.api.SingularityPauseRequest;
import com.hubspot.singularity.api.SingularityPriorityFreeze;
import com.hubspot.singularity.api.SingularityRunNowRequest;
import com.hubspot.singularity.api.SingularityScaleRequest;
import com.hubspot.singularity.api.SingularityUnpauseRequest;
public class SingularityClient {
private static final Logger LOG = LoggerFactory.getLogger(SingularityClient.class);
private static final String AUTH_CHECK_FORMAT = "http://%s/%s/auth/%s/auth-check/%s";
private static final String STATE_FORMAT = "http://%s/%s/state";
private static final String TASK_RECONCILIATION_FORMAT = STATE_FORMAT + "/task-reconciliation";
private static final String RACKS_FORMAT = "http://%s/%s/racks";
private static final String RACKS_DECOMISSION_FORMAT = RACKS_FORMAT + "/rack/%s/decommission";
private static final String RACKS_FREEZE_FORMAT = RACKS_FORMAT + "/rack/%s/freeze";
private static final String RACKS_ACTIVATE_FORMAT = RACKS_FORMAT + "/rack/%s/activate";
private static final String RACKS_DELETE_FORMAT = RACKS_FORMAT + "/rack/%s";
private static final String SLAVES_FORMAT = "http://%s/%s/slaves";
private static final String SLAVE_DETAIL_FORMAT = SLAVES_FORMAT + "/slave/%s/details";
private static final String SLAVES_DECOMISSION_FORMAT = SLAVES_FORMAT + "/slave/%s/decommission";
private static final String SLAVES_FREEZE_FORMAT = SLAVES_FORMAT + "/slave/%s/freeze";
private static final String SLAVES_ACTIVATE_FORMAT = SLAVES_FORMAT + "/slave/%s/activate";
private static final String SLAVES_DELETE_FORMAT = SLAVES_FORMAT + "/slave/%s";
private static final String INACTIVE_SLAVES_FORMAT = "http://%s/%s/inactive";
private static final String TASKS_FORMAT = "http://%s/%s/tasks";
private static final String TASKS_KILL_TASK_FORMAT = TASKS_FORMAT + "/task/%s";
private static final String TASKS_GET_ACTIVE_FORMAT = TASKS_FORMAT + "/active";
private static final String TASKS_GET_ACTIVE_ON_SLAVE_FORMAT = TASKS_FORMAT + "/active/slave/%s";
private static final String TASKS_GET_SCHEDULED_FORMAT = TASKS_FORMAT + "/scheduled";
private static final String TASKS_GET_SCHEDULED_IDS_FORMAT = TASKS_GET_SCHEDULED_FORMAT + "/ids";
private static final String HISTORY_FORMAT = "http://%s/%s/history";
private static final String TASKS_HISTORY_FORMAT = HISTORY_FORMAT + "/tasks";
private static final String TASKS_HISTORY_WITHMETADATA_FORMAT = HISTORY_FORMAT + "/tasks/withmetadata";
private static final String TASK_HISTORY_FORMAT = HISTORY_FORMAT + "/task/%s";
private static final String REQUEST_HISTORY_FORMAT = HISTORY_FORMAT + "/request/%s/requests";
private static final String TASK_HISTORY_BY_RUN_ID_FORMAT = HISTORY_FORMAT + "/request/%s/run/%s";
private static final String REQUEST_ACTIVE_TASKS_HISTORY_FORMAT = HISTORY_FORMAT + "/request/%s/tasks/active";
private static final String REQUEST_INACTIVE_TASKS_HISTORY_FORMAT = HISTORY_FORMAT + "/request/%s/tasks";
private static final String REQUEST_DEPLOY_HISTORY_FORMAT = HISTORY_FORMAT + "/request/%s/deploy/%s";
private static final String REQUESTS_FORMAT = "http://%s/%s/requests";
private static final String REQUESTS_GET_ACTIVE_FORMAT = REQUESTS_FORMAT + "/active";
private static final String REQUESTS_GET_PAUSED_FORMAT = REQUESTS_FORMAT + "/paused";
private static final String REQUESTS_GET_COOLDOWN_FORMAT = REQUESTS_FORMAT + "/cooldown";
private static final String REQUESTS_GET_PENDING_FORMAT = REQUESTS_FORMAT + "/queued/pending";
private static final String REQUESTS_GET_CLEANUP_FORMAT = REQUESTS_FORMAT + "/queued/cleanup";
private static final String REQUEST_GROUPS_FORMAT = "http://%s/%s/groups";
private static final String REQUEST_GROUP_FORMAT = REQUEST_GROUPS_FORMAT + "/group/%s";
private static final String REQUEST_GET_FORMAT = REQUESTS_FORMAT + "/request/%s";
private static final String REQUEST_CREATE_OR_UPDATE_FORMAT = REQUESTS_FORMAT;
private static final String REQUEST_BY_RUN_ID_FORMAT = REQUEST_GET_FORMAT + "/run/%s";
private static final String REQUEST_DELETE_ACTIVE_FORMAT = REQUESTS_FORMAT + "/request/%s";
private static final String REQUEST_BOUNCE_FORMAT = REQUESTS_FORMAT + "/request/%s/bounce";
private static final String REQUEST_PAUSE_FORMAT = REQUESTS_FORMAT + "/request/%s/pause";
private static final String REQUEST_UNPAUSE_FORMAT = REQUESTS_FORMAT + "/request/%s/unpause";
private static final String REQUEST_SCALE_FORMAT = REQUESTS_FORMAT + "/request/%s/scale";
private static final String REQUEST_RUN_FORMAT = REQUESTS_FORMAT + "/request/%s/run";
private static final String REQUEST_EXIT_COOLDOWN_FORMAT = REQUESTS_FORMAT + "/request/%s/exit-cooldown";
private static final String DEPLOYS_FORMAT = "http://%s/%s/deploys";
private static final String DELETE_DEPLOY_FORMAT = DEPLOYS_FORMAT + "/deploy/%s/request/%s";
private static final String UPDATE_DEPLOY_FORMAT = DEPLOYS_FORMAT + "/update";
private static final String WEBHOOKS_FORMAT = "http://%s/%s/webhooks";
private static final String WEBHOOKS_DELETE_FORMAT = WEBHOOKS_FORMAT;
private static final String WEBHOOKS_GET_QUEUED_DEPLOY_UPDATES_FORMAT = WEBHOOKS_FORMAT + "/deploy";
private static final String WEBHOOKS_GET_QUEUED_REQUEST_UPDATES_FORMAT = WEBHOOKS_FORMAT + "/request";
private static final String WEBHOOKS_GET_QUEUED_TASK_UPDATES_FORMAT = WEBHOOKS_FORMAT + "/task";
private static final String SANDBOX_FORMAT = "http://%s/%s/sandbox";
private static final String SANDBOX_BROWSE_FORMAT = SANDBOX_FORMAT + "/%s/browse";
private static final String SANDBOX_READ_FILE_FORMAT = SANDBOX_FORMAT + "/%s/read";
private static final String S3_LOG_FORMAT = "http://%s/%s/logs";
private static final String S3_LOG_GET_TASK_LOGS = S3_LOG_FORMAT + "/task/%s";
private static final String S3_LOG_GET_REQUEST_LOGS = S3_LOG_FORMAT + "/request/%s";
private static final String S3_LOG_GET_DEPLOY_LOGS = S3_LOG_FORMAT + "/request/%s/deploy/%s";
private static final String DISASTERS_FORMAT = "http://%s/%s/disasters";
private static final String DISASTER_STATS_FORMAT = DISASTERS_FORMAT + "/stats";
private static final String ACTIVE_DISASTERS_FORMAT = DISASTERS_FORMAT + "/active";
private static final String DISABLE_AUTOMATED_ACTIONS_FORMAT = DISASTERS_FORMAT + "/disable";
private static final String ENABLE_AUTOMATED_ACTIONS_FORMAT = DISASTERS_FORMAT + "/enable";
private static final String DISASTER_FORMAT = DISASTERS_FORMAT + "/active/%s";
private static final String DISABLED_ACTIONS_FORMAT = DISASTERS_FORMAT + "/disabled-actions";
private static final String DISABLED_ACTION_FORMAT = DISASTERS_FORMAT + "/disabled-actions/%s";
private static final String PRIORITY_FORMAT = "http://%s/%s/priority";
private static final String PRIORITY_FREEZE_FORMAT = PRIORITY_FORMAT + "/freeze";
private static final TypeReference<Collection<SingularityRequestParent>> REQUESTS_COLLECTION = new TypeReference<Collection<SingularityRequestParent>>() {};
private static final TypeReference<Collection<SingularityPendingRequest>> PENDING_REQUESTS_COLLECTION = new TypeReference<Collection<SingularityPendingRequest>>() {};
private static final TypeReference<Collection<SingularityRequestCleanup>> CLEANUP_REQUESTS_COLLECTION = new TypeReference<Collection<SingularityRequestCleanup>>() {};
private static final TypeReference<Collection<SingularityTask>> TASKS_COLLECTION = new TypeReference<Collection<SingularityTask>>() {};
private static final TypeReference<Collection<SingularityTaskIdHistory>> TASKID_HISTORY_COLLECTION = new TypeReference<Collection<SingularityTaskIdHistory>>() {};
private static final TypeReference<Collection<SingularityRack>> RACKS_COLLECTION = new TypeReference<Collection<SingularityRack>>() {};
private static final TypeReference<Collection<SingularitySlave>> SLAVES_COLLECTION = new TypeReference<Collection<SingularitySlave>>() {};
private static final TypeReference<Collection<SingularityWebhook>> WEBHOOKS_COLLECTION = new TypeReference<Collection<SingularityWebhook>>() {};
private static final TypeReference<Collection<SingularityDeployUpdate>> DEPLOY_UPDATES_COLLECTION = new TypeReference<Collection<SingularityDeployUpdate>>() {};
private static final TypeReference<Collection<SingularityRequestHistory>> REQUEST_UPDATES_COLLECTION = new TypeReference<Collection<SingularityRequestHistory>>() {};
private static final TypeReference<Collection<SingularityTaskHistoryUpdate>> TASK_UPDATES_COLLECTION = new TypeReference<Collection<SingularityTaskHistoryUpdate>>() {};
private static final TypeReference<Collection<SingularityTaskRequest>> TASKS_REQUEST_COLLECTION = new TypeReference<Collection<SingularityTaskRequest>>() {};
private static final TypeReference<Collection<SingularityPendingTaskId>> PENDING_TASK_ID_COLLECTION = new TypeReference<Collection<SingularityPendingTaskId>>() {};
private static final TypeReference<Collection<SingularityS3Log>> S3_LOG_COLLECTION = new TypeReference<Collection<SingularityS3Log>>() {};
private static final TypeReference<Collection<SingularityRequestHistory>> REQUEST_HISTORY_COLLECTION = new TypeReference<Collection<SingularityRequestHistory>>() {};
private static final TypeReference<Collection<SingularityRequestGroup>> REQUEST_GROUP_COLLECTION = new TypeReference<Collection<SingularityRequestGroup>>() {};
private static final TypeReference<Collection<SingularityDisasterType>> DISASTERS_COLLECTION = new TypeReference<Collection<SingularityDisasterType>>() {};
private static final TypeReference<Collection<SingularityDisabledAction>> DISABLED_ACTIONS_COLLECTION = new TypeReference<Collection<SingularityDisabledAction>>() {};
private static final TypeReference<SingularityPaginatedResponse<SingularityTaskIdHistory>> PAGINATED_HISTORY = new TypeReference<SingularityPaginatedResponse<SingularityTaskIdHistory>>() {};
private static final TypeReference<Collection<String>> STRING_COLLECTION = new TypeReference<Collection<String>>() {};
private final Random random;
private final Provider<List<String>> hostsProvider;
private final String contextPath;
private final HttpClient httpClient;
private final Optional<SingularityClientCredentials> credentials;
@Inject
@Deprecated
public SingularityClient(@Named(SingularityClientModule.CONTEXT_PATH) String contextPath, @Named(SingularityClientModule.HTTP_CLIENT_NAME) HttpClient httpClient, @Named(SingularityClientModule.HOSTS_PROPERTY_NAME) String hosts) {
this(contextPath, httpClient, Arrays.asList(hosts.split(",")), Optional.<SingularityClientCredentials>absent());
}
public SingularityClient(String contextPath, HttpClient httpClient, List<String> hosts, Optional<SingularityClientCredentials> credentials) {
this(contextPath, httpClient, ProviderUtils.<List<String>>of(ImmutableList.copyOf(hosts)), credentials);
}
public SingularityClient(String contextPath, HttpClient httpClient, Provider<List<String>> hostsProvider, Optional<SingularityClientCredentials> credentials) {
this.httpClient = httpClient;
this.contextPath = contextPath;
this.hostsProvider = hostsProvider;
this.random = new Random();
this.credentials = credentials;
}
private String getHost() {
final List<String> hosts = hostsProvider.get();
return hosts.get(random.nextInt(hosts.size()));
}
private void checkResponse(String type, HttpResponse response) {
if (response.isError()) {
throw fail(type, response);
}
}
private SingularityClientException fail(String type, HttpResponse response) {
String body = "";
try {
body = response.getAsString();
} catch (Exception e) {
LOG.warn("Unable to read body", e);
}
String uri = "";
try {
uri = response.getRequest().getUrl().toString();
} catch (Exception e) {
LOG.warn("Unable to read uri", e);
}
throw new SingularityClientException(String.format("Failed '%s' action on Singularity (%s) - code: %s, %s", type, uri, response.getStatusCode(), body), response.getStatusCode());
}
private <T> Optional<T> getSingle(String uri, String type, String id, Class<T> clazz) {
return getSingleWithParams(uri, type, id, Optional.<Map<String, Object>>absent(), clazz);
}
private <T> Optional<T> getSingleWithParams(String uri, String type, String id, Optional<Map<String, Object>> queryParams, Class<T> clazz) {
final long start = System.currentTimeMillis();
HttpResponse response = executeGetSingleWithParams(uri, type, id, queryParams);
if (response.getStatusCode() == 404) {
return Optional.absent();
}
checkResponse(type, response);
LOG.info("Got {} {} in {}ms", type, id, System.currentTimeMillis() - start);
return Optional.fromNullable(response.getAs(clazz));
}
private <T> Optional<T> getSingleWithParams(String uri, String type, String id, Optional<Map<String, Object>> queryParams, TypeReference<T> typeReference) {
final long start = System.currentTimeMillis();
HttpResponse response = executeGetSingleWithParams(uri, type, id, queryParams);
if (response.getStatusCode() == 404) {
return Optional.absent();
}
checkResponse(type, response);
LOG.info("Got {} {} in {}ms", type, id, System.currentTimeMillis() - start);
return Optional.fromNullable(response.getAs(typeReference));
}
private HttpResponse executeGetSingleWithParams(String uri, String type, String id, Optional<Map<String, Object>> queryParams) {
checkNotNull(id, String.format("Provide a %s id", type));
LOG.info("Getting {} {} from {}", type, id, uri);
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
.setUrl(uri);
if (queryParams.isPresent()) {
addQueryParams(requestBuilder, queryParams.get());
}
addCredentials(requestBuilder);
return httpClient.execute(requestBuilder.build());
}
private <T> Collection<T> getCollection(String uri, String type, TypeReference<Collection<T>> typeReference) {
return getCollectionWithParams(uri, type, Optional.<Map<String, Object>>absent(), typeReference);
}
private <T> Collection<T> getCollectionWithParams(String uri, String type, Optional<Map<String, Object>> queryParams, TypeReference<Collection<T>> typeReference) {
LOG.info("Getting all {} from {}", type, uri);
final long start = System.currentTimeMillis();
HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
.setUrl(uri);
if (queryParams.isPresent()) {
addQueryParams(requestBuilder, queryParams.get());
}
addCredentials(requestBuilder);
HttpResponse response = httpClient.execute(requestBuilder.build());
if (response.getStatusCode() == 404) {
return ImmutableList.of();
}
checkResponse(type, response);
LOG.info("Got {} in {}ms", type, System.currentTimeMillis() - start);
return response.getAs(typeReference);
}
private void addQueryParams(HttpRequest.Builder requestBuilder, Map<String, Object> queryParams) {
for (Entry<String, Object> queryParamEntry : queryParams.entrySet()) {
if (queryParamEntry.getValue() instanceof String) {
requestBuilder.setQueryParam(queryParamEntry.getKey()).to((String) queryParamEntry.getValue());
} else if (queryParamEntry.getValue() instanceof Integer) {
requestBuilder.setQueryParam(queryParamEntry.getKey()).to((Integer) queryParamEntry.getValue());
} else if (queryParamEntry.getValue() instanceof Long) {
requestBuilder.setQueryParam(queryParamEntry.getKey()).to((Long) queryParamEntry.getValue());
} else if (queryParamEntry.getValue() instanceof Boolean) {
requestBuilder.setQueryParam(queryParamEntry.getKey()).to((Boolean) queryParamEntry.getValue());
} else {
throw new RuntimeException(String.format("The type '%s' of query param %s is not supported. Only String, long, int and boolean values are supported",
queryParamEntry.getValue().getClass().getName(), queryParamEntry.getKey()));
}
}
}
private void addCredentials(HttpRequest.Builder requestBuilder) {
if (credentials.isPresent()) {
requestBuilder.addHeader(credentials.get().getHeaderName(), credentials.get().getToken());
}
}
private <T> void delete(String uri, String type, String id) {
delete(uri, type, id, Optional.absent());
}
private <T> void delete(String uri, String type, String id, Optional<?> body) {
delete(uri, type, id, body, Optional.<Class<T>> absent());
}
private <T> Optional<T> delete(String uri, String type, String id, Optional<?> body, Optional<Class<T>> clazz) {
LOG.info("Deleting {} {} from {}", type, id, uri);
final long start = System.currentTimeMillis();
HttpRequest.Builder request = HttpRequest.newBuilder().setUrl(uri).setMethod(Method.DELETE);
if (body.isPresent()) {
request.setBody(body.get());
}
addCredentials(request);
HttpResponse response = httpClient.execute(request.build());
if (response.getStatusCode() == 404) {
LOG.info("{} ({}) was not found", type, id);
return Optional.absent();
}
checkResponse(type, response);
LOG.info("Deleted {} ({}) from Singularity in %sms", type, id, System.currentTimeMillis() - start);
if (clazz.isPresent()) {
return Optional.of(response.getAs(clazz.get()));
}
return Optional.absent();
}
private <T> Optional<T> deleteWithParams(String uri, String type, String id, Optional<?> body, Optional<Map<String, Object>> queryParams, Optional<Class<T>> clazz) {
LOG.info("Deleting {} {} from {}", type, id, uri);
final long start = System.currentTimeMillis();
HttpRequest.Builder request = HttpRequest.newBuilder().setUrl(uri).setMethod(Method.DELETE);
if (body.isPresent()) {
request.setBody(body.get());
}
if (queryParams.isPresent()) {
addQueryParams(request, queryParams.get());
}
addCredentials(request);
HttpResponse response = httpClient.execute(request.build());
if (response.getStatusCode() == 404) {
LOG.info("{} ({}) was not found", type, id);
return Optional.absent();
}
checkResponse(type, response);
LOG.info("Deleted {} ({}) from Singularity in %sms", type, id, System.currentTimeMillis() - start);
if (clazz.isPresent()) {
return Optional.of(response.getAs(clazz.get()));
}
return Optional.absent();
}
private HttpResponse put(String uri, String type, Optional<?> body) {
return executeRequest(uri, type, body, Method.PUT, Optional.absent());
}
private <T> Optional<T> post(String uri, String type, Optional<?> body, Optional<Class<T>> clazz) {
try {
HttpResponse response = executeRequest(uri, type, body, Method.POST, Optional.absent());
if (clazz.isPresent()) {
return Optional.of(response.getAs(clazz.get()));
}
} catch (Exception e) {
LOG.warn("Http post failed", e);
}
return Optional.<T>absent();
}
private HttpResponse postWithParams(String uri, String type, Optional<?> body, Optional<Map<String, Object>> queryParams) {
return executeRequest(uri, type, body, Method.POST, queryParams);
}
private HttpResponse post(String uri, String type, Optional<?> body) {
return executeRequest(uri, type, body, Method.POST, Optional.absent());
}
private HttpResponse executeRequest(String uri, String type, Optional<?> body, Method method, Optional<Map<String, Object>> queryParams) {
final long start = System.currentTimeMillis();
HttpRequest.Builder request = HttpRequest.newBuilder().setUrl(uri).setMethod(method);
if (body.isPresent()) {
request.setBody(body.get());
}
if (queryParams.isPresent()) {
addQueryParams(request, queryParams.get());
}
addCredentials(request);
HttpResponse response = httpClient.execute(request.build());
checkResponse(type, response);
LOG.info("Successfully {}ed {} in {}ms", method, type, System.currentTimeMillis() - start);
return response;
}
// GLOBAL
public SingularityState getState(Optional<Boolean> skipCache, Optional<Boolean> includeRequestIds) {
final String uri = String.format(STATE_FORMAT, getHost(), contextPath);
LOG.info("Fetching state from {}", uri);
final long start = System.currentTimeMillis();
HttpRequest.Builder request = HttpRequest.newBuilder().setUrl(uri);
if (skipCache.isPresent()) {
request.setQueryParam("skipCache").to(skipCache.get());
}
if (includeRequestIds.isPresent()) {
request.setQueryParam("includeRequestIds").to(includeRequestIds.get());
}
addCredentials(request);
HttpResponse response = httpClient.execute(request.build());
checkResponse("state", response);
LOG.info("Got state in {}ms", System.currentTimeMillis() - start);
return response.getAs(SingularityState.class);
}
public Optional<SingularityTaskReconciliationStatistics> getTaskReconciliationStatistics() {
final String uri = String.format(TASK_RECONCILIATION_FORMAT, getHost(), contextPath);
LOG.info("Fetch task reconciliation statistics from {}", uri);
final long start = System.currentTimeMillis();
HttpRequest.Builder request = HttpRequest.newBuilder().setUrl(uri);
addCredentials(request);
HttpResponse response = httpClient.execute(request.build());
if (response.getStatusCode() == 404) {
return Optional.absent();
}
checkResponse("task reconciliation statistics", response);
LOG.info("Got task reconciliation statistics in {}ms", System.currentTimeMillis() - start);
return Optional.of(response.getAs(SingularityTaskReconciliationStatistics.class));
}
// ACTIONS ON A SINGLE SINGULARITY REQUEST
public Optional<SingularityRequestParent> getSingularityRequest(String requestId) {
final String singularityApiRequestUri = String.format(REQUEST_GET_FORMAT, getHost(), contextPath, requestId);
return getSingle(singularityApiRequestUri, "request", requestId, SingularityRequestParent.class);
}
public Optional<SingularityTaskId> getTaskByRunIdForRequest(String requestId, String runId) {
final String singularityApiRequestUri = String.format(REQUEST_BY_RUN_ID_FORMAT, getHost(), contextPath, requestId, runId);
return getSingle(singularityApiRequestUri, "requestByRunId", runId, SingularityTaskId.class);
}
public void createOrUpdateSingularityRequest(SingularityRequest request) {
checkNotNull(request.getId(), "A posted Singularity Request must have an id");
final String requestUri = String.format(REQUEST_CREATE_OR_UPDATE_FORMAT, getHost(), contextPath);
post(requestUri, String.format("request %s", request.getId()), Optional.of(request));
}
/**
* Delete a singularity request .
* If the deletion is successful the deleted singularity request is returned.
* If the request to be deleted is not found {code Optional.absent()} is returned
* If an error occurs during deletion an exception is returned
* If the singularity request to be deleted is paused the deletion will fail with an exception
* If you want to delete a paused singularity request use the provided {@link SingularityClient#deletePausedSingularityRequest}
*
* @param requestId
* the id of the singularity request to delete
* @param user
* the ...
* @return
* the singularity request that was deleted
*/
public Optional<SingularityRequest> deleteSingularityRequest(String requestId, Optional<SingularityDeleteRequestRequest> deleteRequest) {
final String requestUri = String.format(REQUEST_DELETE_ACTIVE_FORMAT, getHost(), contextPath, requestId);
return delete(requestUri, "active request", requestId, deleteRequest, Optional.of(SingularityRequest.class));
}
public void pauseSingularityRequest(String requestId, Optional<SingularityPauseRequest> pauseRequest) {
final String requestUri = String.format(REQUEST_PAUSE_FORMAT, getHost(), contextPath, requestId);
post(requestUri, String.format("pause of request %s", requestId), pauseRequest);
}
public void unpauseSingularityRequest(String requestId, Optional<SingularityUnpauseRequest> unpauseRequest) {
final String requestUri = String.format(REQUEST_UNPAUSE_FORMAT, getHost(), contextPath, requestId);
post(requestUri, String.format("unpause of request %s", requestId), unpauseRequest);
}
public void scaleSingularityRequest(String requestId, SingularityScaleRequest scaleRequest) {
final String requestUri = String.format(REQUEST_SCALE_FORMAT, getHost(), contextPath, requestId);
put(requestUri, String.format("Scale of Request %s", requestId), Optional.of(scaleRequest));
}
public SingularityPendingRequestParent runSingularityRequest(String requestId, Optional<SingularityRunNowRequest> runNowRequest) {
final String requestUri = String.format(REQUEST_RUN_FORMAT, getHost(), contextPath, requestId);
final HttpResponse response = post(requestUri, String.format("run of request %s", requestId), runNowRequest);
return response.getAs(SingularityPendingRequestParent.class);
}
public void bounceSingularityRequest(String requestId, Optional<SingularityBounceRequest> bounceOptions) {
final String requestUri = String.format(REQUEST_BOUNCE_FORMAT, getHost(), contextPath, requestId);
post(requestUri, String.format("bounce of request %s", requestId), bounceOptions);
}
public void exitCooldown(String requestId, Optional<SingularityExitCooldownRequest> exitCooldownRequest) {
final String requestUri = String.format(REQUEST_EXIT_COOLDOWN_FORMAT, getHost(), contextPath, requestId);
post(requestUri, String.format("exit cooldown of request %s", requestId), exitCooldownRequest);
}
// ACTIONS ON A DEPLOY FOR A SINGULARITY REQUEST
public SingularityRequestParent createDeployForSingularityRequest(String requestId, SingularityDeploy pendingDeploy, Optional<Boolean> deployUnpause, Optional<String> message) {
return createDeployForSingularityRequest(requestId, pendingDeploy, deployUnpause, message, Optional.<SingularityRequest>absent());
}
public SingularityRequestParent createDeployForSingularityRequest(String requestId, SingularityDeploy pendingDeploy, Optional<Boolean> deployUnpause, Optional<String> message, Optional<SingularityRequest> updatedRequest) {
final String requestUri = String.format(DEPLOYS_FORMAT, getHost(), contextPath);
HttpResponse response = post(requestUri, String.format("new deploy %s", new SingularityDeployKey(requestId, pendingDeploy.getId())),
Optional.of(new SingularityDeployRequest(pendingDeploy, deployUnpause, message, updatedRequest)));
return getAndLogRequestAndDeployStatus(response.getAs(SingularityRequestParent.class));
}
private SingularityRequestParent getAndLogRequestAndDeployStatus(SingularityRequestParent singularityRequestParent) {
String activeDeployId = singularityRequestParent.getActiveDeploy().isPresent() ? singularityRequestParent.getActiveDeploy().get().getId() : "No Active Deploy";
String pendingDeployId = singularityRequestParent.getPendingDeploy().isPresent() ? singularityRequestParent.getPendingDeploy().get().getId() : "No Pending deploy";
LOG.info("Deploy status: Singularity request {} -> pending deploy: '{}', active deploy: '{}'", singularityRequestParent.getRequest().getId(), pendingDeployId, activeDeployId);
return singularityRequestParent;
}
public SingularityRequestParent cancelPendingDeployForSingularityRequest(String requestId, String deployId) {
final String requestUri = String.format(DELETE_DEPLOY_FORMAT, getHost(), contextPath, deployId, requestId);
SingularityRequestParent singularityRequestParent = delete(requestUri, "pending deploy", new SingularityDeployKey(requestId, deployId).getId(), Optional.absent(),
Optional.of(SingularityRequestParent.class)).get();
return getAndLogRequestAndDeployStatus(singularityRequestParent);
}
public SingularityRequestParent updateIncrementalDeployInstanceCount(SingularityUpdatePendingDeployRequest updateRequest) {
final String requestUri = String.format(UPDATE_DEPLOY_FORMAT, getHost(), contextPath);
HttpResponse response = post(requestUri, String.format("update deploy %s", new SingularityDeployKey(updateRequest.getRequestId(), updateRequest.getDeployId())),
Optional.of(updateRequest));
return getAndLogRequestAndDeployStatus(response.getAs(SingularityRequestParent.class));
}
/**
* Get all singularity requests that their state is either ACTIVE, PAUSED or COOLDOWN
*
* For the requests that are pending to become ACTIVE use:
* {@link SingularityClient#getPendingSingularityRequests()}
*
* For the requests that are cleaning up use:
* {@link SingularityClient#getCleanupSingularityRequests()}
*
*
* Use {@link SingularityClient#getActiveSingularityRequests()}, {@link SingularityClient#getPausedSingularityRequests()},
* {@link SingularityClient#getCoolDownSingularityRequests()} respectively to get only the ACTIVE, PAUSED or COOLDOWN requests.
*
* @return
* returns all the [ACTIVE, PAUSED, COOLDOWN] {@link SingularityRequestParent} instances.
*
*/
public Collection<SingularityRequestParent> getSingularityRequests() {
final String requestUri = String.format(REQUESTS_FORMAT, getHost(), contextPath);
return getCollection(requestUri, "[ACTIVE, PAUSED, COOLDOWN] requests", REQUESTS_COLLECTION);
}
/**
* Get all requests that their state is ACTIVE
*
* @return
* All ACTIVE {@link SingularityRequestParent} instances
*/
public Collection<SingularityRequestParent> getActiveSingularityRequests() {
final String requestUri = String.format(REQUESTS_GET_ACTIVE_FORMAT, getHost(), contextPath);
return getCollection(requestUri, "ACTIVE requests", REQUESTS_COLLECTION);
}
/**
* Get all requests that their state is PAUSED
* ACTIVE requests are paused by users, which is equivalent to stop their tasks from running without undeploying them
*
* @return
* All PAUSED {@link SingularityRequestParent} instances
*/
public Collection<SingularityRequestParent> getPausedSingularityRequests() {
final String requestUri = String.format(REQUESTS_GET_PAUSED_FORMAT, getHost(), contextPath);
return getCollection(requestUri, "PAUSED requests", REQUESTS_COLLECTION);
}
/**
* Get all requests that has been set to a COOLDOWN state by singularity
*
* @return
* All {@link SingularityRequestParent} instances that their state is COOLDOWN
*/
public Collection<SingularityRequestParent> getCoolDownSingularityRequests() {
final String requestUri = String.format(REQUESTS_GET_COOLDOWN_FORMAT, getHost(), contextPath);
return getCollection(requestUri, "COOLDOWN requests", REQUESTS_COLLECTION);
}
/**
* Get all requests that are pending to become ACTIVE
*
* @return
* A collection of {@link SingularityPendingRequest} instances that hold information about the singularity requests that are pending to become ACTIVE
*/
public Collection<SingularityPendingRequest> getPendingSingularityRequests() {
final String requestUri = String.format(REQUESTS_GET_PENDING_FORMAT, getHost(), contextPath);
return getCollection(requestUri, "pending requests", PENDING_REQUESTS_COLLECTION);
}
/**
* Get all requests that are cleaning up
* Requests that are cleaning up are those that have been marked for removal and their tasks are being stopped/removed
* before they are being removed. So after their have been cleaned up, these request cease to exist in Singularity.
*
* @return
* A collection of {@link SingularityRequestCleanup} instances that hold information about all singularity requests
* that are marked for deletion and are currently cleaning up.
*/
public Collection<SingularityRequestCleanup> getCleanupSingularityRequests() {
final String requestUri = String.format(REQUESTS_GET_CLEANUP_FORMAT, getHost(), contextPath);
return getCollection(requestUri, "cleaning requests", CLEANUP_REQUESTS_COLLECTION);
}
// SINGULARITY TASK COLLECTIONS
// ACTIVE TASKS
public Collection<SingularityTask> getActiveTasks() {
final String requestUri = String.format(TASKS_GET_ACTIVE_FORMAT, getHost(), contextPath);
return getCollection(requestUri, "active tasks", TASKS_COLLECTION);
}
public Collection<SingularityTask> getActiveTasksOnSlave(final String slaveId) {
final String requestUri = String.format(TASKS_GET_ACTIVE_ON_SLAVE_FORMAT, getHost(), contextPath, slaveId);
return getCollection(requestUri, String.format("active tasks on slave %s", slaveId), TASKS_COLLECTION);
}
public Optional<SingularityTaskCleanupResult> killTask(String taskId, Optional<SingularityKillTaskRequest> killTaskRequest) {
final String requestUri = String.format(TASKS_KILL_TASK_FORMAT, getHost(), contextPath, taskId);
return delete(requestUri, "task", taskId, killTaskRequest, Optional.of(SingularityTaskCleanupResult.class));
}
// SCHEDULED TASKS
public Collection<SingularityTaskRequest> getScheduledTasks() {
final String requestUri = String.format(TASKS_GET_SCHEDULED_FORMAT, getHost(), contextPath);
return getCollection(requestUri, "scheduled tasks", TASKS_REQUEST_COLLECTION);
}
public Collection<SingularityPendingTaskId> getScheduledTaskIds() {
final String requestUri = String.format(TASKS_GET_SCHEDULED_IDS_FORMAT, getHost(), contextPath);
return getCollection(requestUri, "scheduled task ids", PENDING_TASK_ID_COLLECTION);
}
// RACKS
private Collection<SingularityRack> getRacks(Optional<MachineState> rackState) {
final String requestUri = String.format(RACKS_FORMAT, getHost(), contextPath);
Optional<Map<String, Object>> maybeQueryParams = Optional.<Map<String, Object>>absent();
String type = "racks";
if (rackState.isPresent()) {
maybeQueryParams = Optional.<Map<String, Object>>of(ImmutableMap.<String, Object>of("state", rackState.get().toString()));
type = String.format("%s racks", rackState.get().toString());
}
return getCollectionWithParams(requestUri, type, maybeQueryParams, RACKS_COLLECTION);
}
@Deprecated
public void decomissionRack(String rackId) {
decommissionRack(rackId, Optional.<SingularityMachineChangeRequest>absent());
}
public void decommissionRack(String rackId, Optional<SingularityMachineChangeRequest> machineChangeRequest) {
final String requestUri = String.format(RACKS_DECOMISSION_FORMAT, getHost(), contextPath, rackId);
post(requestUri, String.format("decomission rack %s", rackId), machineChangeRequest.or(Optional.of(new SingularityMachineChangeRequest(Optional.<String>absent()))));
}
public void freezeRack(String rackId, Optional<SingularityMachineChangeRequest> machineChangeRequest) {
final String requestUri = String.format(RACKS_FREEZE_FORMAT, getHost(), contextPath, rackId);
post(requestUri, String.format("freeze rack %s", rackId), machineChangeRequest.or(Optional.of(new SingularityMachineChangeRequest(Optional.<String>absent()))));
}
public void activateRack(String rackId, Optional<SingularityMachineChangeRequest> machineChangeRequest) {
final String requestUri = String.format(RACKS_ACTIVATE_FORMAT, getHost(), contextPath, rackId);
post(requestUri, String.format("decommission rack %s", rackId), machineChangeRequest.or(Optional.of(new SingularityMachineChangeRequest(Optional.<String>absent()))));
}
public void deleteRack(String rackId) {
final String requestUri = String.format(RACKS_DELETE_FORMAT, getHost(), contextPath, rackId);
delete(requestUri, "dead rack", rackId);
}
// SLAVES
/**
* Retrieve the list of all known slaves, optionally filtering by a particular slave state
*
* @param slaveState
* Optionally specify a particular state to filter slaves by
* @return
* A collection of {@link SingularitySlave}
*/
public Collection<SingularitySlave> getSlaves(Optional<MachineState> slaveState) {
final String requestUri = String.format(SLAVES_FORMAT, getHost(), contextPath);
Optional<Map<String, Object>> maybeQueryParams = Optional.<Map<String, Object>>absent();
String type = "slaves";
if (slaveState.isPresent()) {
maybeQueryParams = Optional.<Map<String, Object>>of(ImmutableMap.<String, Object>of("state", slaveState.get().toString()));
type = String.format("%s slaves", slaveState.get().toString());
}
return getCollectionWithParams(requestUri, type, maybeQueryParams, SLAVES_COLLECTION);
}
public Optional<SingularitySlave> getSlave(String slaveId) {
final String requestUri = String.format(SLAVE_DETAIL_FORMAT, getHost(), contextPath, slaveId);
return getSingle(requestUri, "slave", slaveId, SingularitySlave.class);
}
@Deprecated
public void decomissionSlave(String slaveId) {
decommissionSlave(slaveId, Optional.<SingularityMachineChangeRequest>absent());
}
public void decommissionSlave(String slaveId, Optional<SingularityMachineChangeRequest> machineChangeRequest) {
final String requestUri = String.format(SLAVES_DECOMISSION_FORMAT, getHost(), contextPath, slaveId);
post(requestUri, String.format("decommission slave %s", slaveId), machineChangeRequest.or(Optional.of(new SingularityMachineChangeRequest(Optional.<String>absent()))));
}
public void freezeSlave(String slaveId, Optional<SingularityMachineChangeRequest> machineChangeRequest) {
final String requestUri = String.format(SLAVES_FREEZE_FORMAT, getHost(), contextPath, slaveId);
post(requestUri, String.format("freeze slave %s", slaveId), machineChangeRequest.or(Optional.of(new SingularityMachineChangeRequest(Optional.<String>absent()))));
}
public void activateSlave(String slaveId, Optional<SingularityMachineChangeRequest> machineChangeRequest) {
final String requestUri = String.format(SLAVES_ACTIVATE_FORMAT, getHost(), contextPath, slaveId);
post(requestUri, String.format("activate slave %s", slaveId), machineChangeRequest.or(Optional.of(new SingularityMachineChangeRequest(Optional.<String>absent()))));
}
public void deleteSlave(String slaveId) {
final String requestUri = String.format(SLAVES_DELETE_FORMAT, getHost(), contextPath, slaveId);
delete(requestUri, "deleting slave", slaveId);
}
// REQUEST HISTORY
/**
* Retrieve a paged list of updates for a particular {@link SingularityRequest}
*
* @param requestId
* Request ID to look up
* @param count
* Number of items to return per page
* @param page
* Which page of items to return
* @return
* A list of {@link SingularityRequestHistory}
*/
public Collection<SingularityRequestHistory> getHistoryForRequest(String requestId, Optional<Integer> count, Optional<Integer> page) {
final String requestUri = String.format(REQUEST_HISTORY_FORMAT, getHost(), contextPath, requestId);
Optional<Map<String, Object>> maybeQueryParams = Optional.<Map<String, Object>>absent();
ImmutableMap.Builder<String, Object> queryParamsBuilder = ImmutableMap.<String, Object>builder();
if (count.isPresent() ) {
queryParamsBuilder.put("count", count.get());
}
if (page.isPresent()) {
queryParamsBuilder.put("page", page.get());
}
Map<String, Object> queryParams = queryParamsBuilder.build();
if (!queryParams.isEmpty()) {
maybeQueryParams = Optional.of(queryParams);
}
return getCollectionWithParams(requestUri, "request history", maybeQueryParams, REQUEST_HISTORY_COLLECTION);
}
// Inactive/Bad Slaves
public Collection<String> getInactiveSlaves() {
final String requestUri = String.format(INACTIVE_SLAVES_FORMAT, getHost(), contextPath);
return getCollection(requestUri, "inactiveSlaves", STRING_COLLECTION);
}
public void markSlaveAsInactive(String host) {
final String requestUri = String.format(INACTIVE_SLAVES_FORMAT, getHost(), contextPath);
Map<String, Object> params = new HashMap<>();
params.put("host", host);
postWithParams(requestUri, "deactivateSlave", Optional.absent(), Optional.of(params));
}
public void clearInactiveSlave(String host) {
final String requestUri = String.format(INACTIVE_SLAVES_FORMAT, getHost(), contextPath);
Map<String, Object> params = new HashMap<>();
params.put("host", host);
deleteWithParams(requestUri, "clearInactiveSlave", host, Optional.absent(), Optional.of(params), Optional.of(HttpResponse.class));
}
// TASK HISTORY
public Optional<SingularityTaskHistory> getHistoryForTask(String taskId) {
final String requestUri = String.format(TASK_HISTORY_FORMAT, getHost(), contextPath, taskId);
return getSingle(requestUri, "task history", taskId, SingularityTaskHistory.class);
}
public Collection<SingularityTaskIdHistory> getActiveTaskHistoryForRequest(String requestId) {
final String requestUri = String.format(REQUEST_ACTIVE_TASKS_HISTORY_FORMAT, getHost(), contextPath, requestId);
final String type = String.format("active task history for %s", requestId);
return getCollection(requestUri, type, TASKID_HISTORY_COLLECTION);
}
public Collection<SingularityTaskIdHistory> getInactiveTaskHistoryForRequest(String requestId) {
return getInactiveTaskHistoryForRequest(requestId, 100, 1);
}
public Collection<SingularityTaskIdHistory> getInactiveTaskHistoryForRequest(String requestId, int count, int page) {
return getInactiveTaskHistoryForRequest(requestId, count, page, Optional.<String>absent(), Optional.<String>absent(), Optional.<ExtendedTaskState>absent(), Optional.<Long>absent(), Optional.<Long>absent(), Optional.<Long>absent(), Optional.<Long>absent(), Optional.<OrderDirection>absent());
}
public Collection<SingularityTaskIdHistory> getInactiveTaskHistoryForRequest(String requestId, int count, int page, Optional<String> host, Optional<String> runId,
Optional<ExtendedTaskState> lastTaskStatus, Optional<Long> startedBefore, Optional<Long> startedAfter, Optional<Long> updatedBefore, Optional<Long> updatedAfter,
Optional<OrderDirection> orderDirection) {
final String requestUri = String.format(REQUEST_INACTIVE_TASKS_HISTORY_FORMAT, getHost(), contextPath, requestId);
final String type = String.format("inactive (failed, killed, lost) task history for request %s", requestId);
Map<String, Object> params = taskSearchParams(Optional.of(requestId), Optional.<String>absent(), runId, host, lastTaskStatus, startedBefore, startedAfter, updatedBefore, updatedAfter, orderDirection, count, page);
return getCollectionWithParams(requestUri, type, Optional.of(params), TASKID_HISTORY_COLLECTION);
}
public Optional<SingularityDeployHistory> getHistoryForRequestDeploy(String requestId, String deployId) {
final String requestUri = String.format(REQUEST_DEPLOY_HISTORY_FORMAT, getHost(), contextPath, requestId, deployId);
return getSingle(requestUri, "deploy history", new SingularityDeployKey(requestId, deployId).getId(), SingularityDeployHistory.class);
}
public Optional<SingularityTaskIdHistory> getHistoryForTask(String requestId, String runId) {
final String requestUri = String.format(TASK_HISTORY_BY_RUN_ID_FORMAT, getHost(), contextPath, requestId, runId);
return getSingle(requestUri, "task history", requestId, SingularityTaskIdHistory.class);
}
public Collection<SingularityTaskIdHistory> getTaskHistory(Optional<String> requestId, Optional<String> deployId, Optional<String> runId, Optional<String> host,
Optional<ExtendedTaskState> lastTaskStatus, Optional<Long> startedBefore, Optional<Long> startedAfter, Optional<Long> updatedBefore,
Optional<Long> updatedAfter, Optional<OrderDirection> orderDirection, Integer count, Integer page) {
final String requestUri = String.format(TASKS_HISTORY_FORMAT, getHost(), contextPath);
Map<String, Object> params = taskSearchParams(requestId, deployId, runId, host, lastTaskStatus, startedBefore, startedAfter, updatedBefore, updatedAfter, orderDirection, count, page);
return getCollectionWithParams(requestUri, "task id history", Optional.of(params), TASKID_HISTORY_COLLECTION);
}
public Optional<SingularityPaginatedResponse<SingularityTaskIdHistory>> getTaskHistoryWithMetadata(Optional<String> requestId, Optional<String> deployId, Optional<String> runId, Optional<String> host,
Optional<ExtendedTaskState> lastTaskStatus, Optional<Long> startedBefore, Optional<Long> startedAfter, Optional<Long> updatedBefore,
Optional<Long> updatedAfter, Optional<OrderDirection> orderDirection, Integer count, Integer page) {
final String requestUri = String.format(TASKS_HISTORY_WITHMETADATA_FORMAT, getHost(), contextPath);
Map<String, Object> params = taskSearchParams(requestId, deployId, runId, host, lastTaskStatus, startedBefore, startedAfter, updatedBefore, updatedAfter, orderDirection, count, page);
return getSingleWithParams(requestUri, "task id history with metadata", "", Optional.of(params), PAGINATED_HISTORY);
}
private Map<String, Object> taskSearchParams(Optional<String> requestId, Optional<String> deployId, Optional<String> runId, Optional<String> host,
Optional<ExtendedTaskState> lastTaskStatus, Optional<Long> startedBefore, Optional<Long> startedAfter, Optional<Long> updatedBefore,
Optional<Long> updatedAfter, Optional<OrderDirection> orderDirection, Integer count, Integer page) {
Map<String, Object> params = new HashMap<>();
if (requestId.isPresent()) {
params.put("requestId", requestId.get());
}
if (deployId.isPresent()) {
params.put("deployId", deployId.get());
}
if (runId.isPresent()) {
params.put("runId", runId.get());
}
if (host.isPresent()) {
params.put("host", host.get());
}
if (lastTaskStatus.isPresent()) {
params.put("lastTaskStatus", lastTaskStatus.get().toString());
}
if (startedBefore.isPresent()) {
params.put("startedBefore", startedBefore.get());
}
if (startedAfter.isPresent()) {
params.put("startedAfter", startedAfter.get());
}
if (updatedBefore.isPresent()) {
params.put("updatedBefore", updatedBefore.get());
}
if (updatedAfter.isPresent()) {
params.put("updatedAfter", updatedAfter.get());
}
if (orderDirection.isPresent()) {
params.put("orderDirection", orderDirection.get().toString());
}
params.put("count", count);
params.put("page", page);
return params;
}
// WEBHOOKS
public Optional<SingularityCreateResult> addWebhook(SingularityWebhook webhook) {
final String requestUri = String.format(WEBHOOKS_FORMAT, getHost(), contextPath);
return post(requestUri, String.format("webhook %s", webhook.getUri()), Optional.of(webhook), Optional.of(SingularityCreateResult.class));
}
public Optional<SingularityDeleteResult> deleteWebhook(String webhookId) {
final String requestUri = String.format(WEBHOOKS_DELETE_FORMAT, getHost(), contextPath);
Builder<String, Object> queryParamBuider = ImmutableMap.<String, Object>builder().put("webhookId", webhookId);
return deleteWithParams(requestUri, String.format("webhook with id %s", webhookId), webhookId, Optional.absent(), Optional.<Map<String,Object>>of(queryParamBuider.build()), Optional.of(SingularityDeleteResult.class));
}
public Collection<SingularityWebhook> getActiveWebhook() {
final String requestUri = String.format(WEBHOOKS_FORMAT, getHost(), contextPath);
return getCollection(requestUri, "active webhooks", WEBHOOKS_COLLECTION);
}
public Collection<SingularityDeployUpdate> getQueuedDeployUpdates(String webhookId) {
final String requestUri = String.format(WEBHOOKS_GET_QUEUED_DEPLOY_UPDATES_FORMAT, getHost(), contextPath);
Builder<String, Object> queryParamBuider = ImmutableMap.<String, Object>builder().put("webhookId", webhookId);
return getCollectionWithParams(requestUri, "deploy updates", Optional.<Map<String,Object>>of(queryParamBuider.build()), DEPLOY_UPDATES_COLLECTION);
}
public Collection<SingularityRequestHistory> getQueuedRequestUpdates(String webhookId) {
final String requestUri = String.format(WEBHOOKS_GET_QUEUED_REQUEST_UPDATES_FORMAT, getHost(), contextPath);
Builder<String, Object> queryParamBuider = ImmutableMap.<String, Object>builder().put("webhookId", webhookId);
return getCollectionWithParams(requestUri, "request updates", Optional.<Map<String,Object>>of(queryParamBuider.build()), REQUEST_UPDATES_COLLECTION);
}
public Collection<SingularityTaskHistoryUpdate> getQueuedTaskUpdates(String webhookId) {
final String requestUri = String.format(WEBHOOKS_GET_QUEUED_TASK_UPDATES_FORMAT, getHost(), contextPath);
Builder<String, Object> queryParamBuider = ImmutableMap.<String, Object>builder().put("webhookId", webhookId);
return getCollectionWithParams(requestUri, "request updates", Optional.<Map<String,Object>>of(queryParamBuider.build()), TASK_UPDATES_COLLECTION);
}
// SANDBOX
/**
* Retrieve information about a specific task's sandbox
*
* @param taskId
* The task ID to browse
* @param path
* The path to browse from.
* if not specified it will browse from the sandbox root.
* @return
* A {@link SingularitySandbox} object that captures the information for the path to a specific task's Mesos sandbox
*/
public Optional<SingularitySandbox> browseTaskSandBox(String taskId, String path) {
final String requestUrl = String.format(SANDBOX_BROWSE_FORMAT, getHost(), contextPath, taskId);
return getSingleWithParams(requestUrl, "browse sandbox for task", taskId, Optional.<Map<String, Object>>of(ImmutableMap.<String, Object>of("path", path)), SingularitySandbox.class);
}
/**
* Retrieve part of the contents of a file in a specific task's sandbox.
*
* @param taskId
* The task ID of the sandbox to read from
* @param path
* The path to the file to be read. Relative to the sandbox root (without a leading slash)
* @param grep
* Optional string to grep for
* @param offset
* Byte offset to start reading from
* @param length
* Maximum number of bytes to read
* @return
* A {@link MesosFileChunkObject} that contains the requested partial file contents
*/
public Optional<MesosFileChunkObject> readSandBoxFile(String taskId, String path, Optional<String> grep, Optional<Long> offset, Optional<Long> length) {
final String requestUrl = String.format(SANDBOX_READ_FILE_FORMAT, getHost(), contextPath, taskId);
Builder<String, Object> queryParamBuider = ImmutableMap.<String, Object>builder().put("path", path);
if (grep.isPresent()) {
queryParamBuider.put("grep", grep.get());
}
if (offset.isPresent()) {
queryParamBuider.put("offset", offset.get());
}
if (length.isPresent()) {
queryParamBuider.put("length", length.get());
}
return getSingleWithParams(requestUrl, "Read sandbox file for task", taskId, Optional.<Map<String, Object>>of(queryParamBuider.build()), MesosFileChunkObject.class);
}
// S3 LOGS
/**
* Retrieve the list of logs stored in S3 for a specific task
*
* @param taskId
* The task ID to search for
*
* @return
* A collection of {@link SingularityS3Log}
*/
public Collection<SingularityS3Log> getTaskLogs(String taskId) {
final String requestUri = String.format(S3_LOG_GET_TASK_LOGS, getHost(), contextPath, taskId);
final String type = String.format("S3 logs for task %s", taskId);
return getCollection(requestUri, type, S3_LOG_COLLECTION);
}
/**
* Retrieve the list of logs stored in S3 for a specific request
*
* @param requestId
* The request ID to search for
*
* @return
* A collection of {@link SingularityS3Log}
*/
public Collection<SingularityS3Log> getRequestLogs(String requestId) {
final String requestUri = String.format(S3_LOG_GET_REQUEST_LOGS, getHost(), contextPath, requestId);
final String type = String.format("S3 logs for request %s", requestId);
return getCollection(requestUri, type, S3_LOG_COLLECTION);
}
/**
* Retrieve the list of logs stored in S3 for a specific deploy if a singularity request
*
* @param requestId
* The request ID to search for
* @param deployId
* The deploy ID (within the specified request) to search for
*
* @return
* A collection of {@link SingularityS3Log}
*/
public Collection<SingularityS3Log> getDeployLogs(String requestId, String deployId) {
final String requestUri = String.format(S3_LOG_GET_DEPLOY_LOGS, getHost(), contextPath, requestId, deployId);
final String type = String.format("S3 logs for deploy %s of request %s", deployId, requestId);
return getCollection(requestUri, type, S3_LOG_COLLECTION);
}
public Collection<SingularityRequestGroup> getRequestGroups() {
final String requestUri = String.format(REQUEST_GROUPS_FORMAT, getHost(), contextPath);
return getCollection(requestUri, "request groups", REQUEST_GROUP_COLLECTION);
}
public Optional<SingularityRequestGroup> getRequestGroup(String requestGroupId) {
final String requestUri = String.format(REQUEST_GROUP_FORMAT, getHost(), contextPath, requestGroupId);
return getSingle(requestUri, "request group", requestGroupId, SingularityRequestGroup.class);
}
public Optional<SingularityRequestGroup> saveRequestGroup(SingularityRequestGroup requestGroup) {
final String requestUri = String.format(REQUEST_GROUPS_FORMAT, getHost(), contextPath);
return post(requestUri, "request group", Optional.of(requestGroup), Optional.of(SingularityRequestGroup.class));
}
public void deleteRequestGroup(String requestGroupId) {
final String requestUri = String.format(REQUEST_GROUP_FORMAT, getHost(), contextPath, requestGroupId);
delete(requestUri, "request group", requestGroupId);
}
// DISASTERS
public Optional<SingularityDisastersData> getDisasterStats() {
final String requestUri = String.format(DISASTER_STATS_FORMAT, getHost(), contextPath);
return getSingle(requestUri, "disaster stats", "", SingularityDisastersData.class);
}
public Collection<SingularityDisasterType> getActiveDisasters() {
final String requestUri = String.format(ACTIVE_DISASTERS_FORMAT, getHost(), contextPath);
return getCollection(requestUri, "active disasters", DISASTERS_COLLECTION);
}
public void disableAutomatedDisasterCreation() {
final String requestUri = String.format(DISABLE_AUTOMATED_ACTIONS_FORMAT, getHost(), contextPath);
post(requestUri, "disable automated disasters", Optional.absent());
}
public void enableAutomatedDisasterCreation() {
final String requestUri = String.format(ENABLE_AUTOMATED_ACTIONS_FORMAT, getHost(), contextPath);
post(requestUri, "enable automated disasters", Optional.absent());
}
public void removeDisaster(SingularityDisasterType disasterType) {
final String requestUri = String.format(DISASTER_FORMAT, getHost(), contextPath, disasterType);
delete(requestUri, "remove disaster", disasterType.toString());
}
public void activateDisaster(SingularityDisasterType disasterType) {
final String requestUri = String.format(DISASTER_FORMAT, getHost(), contextPath, disasterType);
post(requestUri, "activate disaster", Optional.absent());
}
public Collection<SingularityDisabledAction> getDisabledActions() {
final String requestUri = String.format(DISABLED_ACTIONS_FORMAT, getHost(), contextPath);
return getCollection(requestUri, "disabled actions", DISABLED_ACTIONS_COLLECTION);
}
public void disableAction(SingularityAction action, Optional<SingularityDisabledActionRequest> request) {
final String requestUri = String.format(DISABLED_ACTION_FORMAT, getHost(), contextPath, action);
post(requestUri, "disable action", request);
}
public void enableAction(SingularityAction action) {
final String requestUri = String.format(DISABLED_ACTION_FORMAT, getHost(), contextPath, action);
delete(requestUri, "disable action", action.toString());
}
// PRIORITY
public Optional<SingularityPriorityFreezeParent> getActivePriorityFreeze() {
final String requestUri = String.format(PRIORITY_FREEZE_FORMAT, getHost(), contextPath);
return getSingle(requestUri, "priority freeze", "", SingularityPriorityFreezeParent.class);
}
public Optional<SingularityPriorityFreezeParent> createPriorityFreeze(SingularityPriorityFreeze priorityFreezeRequest) {
final String requestUri = String.format(PRIORITY_FREEZE_FORMAT, getHost(), contextPath);
return post(requestUri, "priority freeze", Optional.of(priorityFreezeRequest), Optional.of(SingularityPriorityFreezeParent.class));
}
public void deletePriorityFreeze() {
final String requestUri = String.format(PRIORITY_FREEZE_FORMAT, getHost(), contextPath);
delete(requestUri, "priority freeze", "");
}
// Auth
public boolean isUserAuthorized(String requestId, String userId, SingularityAuthorizationScope scope) {
final String requestUri = String.format(AUTH_CHECK_FORMAT, getHost(), contextPath, requestId, userId);
Map<String, Object> params = new HashMap<>();
params.put("scope", scope.name());
HttpResponse response = executeGetSingleWithParams(requestUri, "auth check", "", Optional.of(params));
return response.isSuccess();
}
} |
package ch.epfl.sweng.swissaffinity.events;
import java.io.Serializable;
import java.net.URL;
import ch.epfl.sweng.swissaffinity.utilities.Address;
import ch.epfl.sweng.swissaffinity.utilities.Location;
/**
* Representation of an establishment for an event to take place in.
*/
public class Establishment implements Serializable {
/**
* Type of establishment.
*/
public enum Type implements Serializable {
BAR("bar"),
RESTAURANT("restaurant"),
HOTEL("hotel");
private final String mType;
Type(String type) {
mType = type;
}
/**
* Getter for the string representation of the type.
*
* @return its type
*/
public String get() {
return mType;
}
/**
* Getter for the type of an establishment.
*
* @param type the type in string format.
*
* @return
*/
public Type getType(String type) {
for (Type t : Type.values()) {
if (t.mType.equalsIgnoreCase(type)) {
return t;
}
}
return null;
}
}
private final int mId;
private final String mName;
private final Type mType;
private final Address mAddress;
private final String mPhoneNumber;
private final String mDescription; // nullable
private final URL mUrl; // nullable
private final int mMaxSeats; // nullable
private final String mLogoPath; // nullable
private final Location mLocation;
/**
* Constructor for an establishment.
*
* @param id its unique id.
* @param name its name.
* @param type its type {@link Type}
* @param address its address {@link Address}
* @param phoneNumber its phone number
* @param description the description of the establishment.
* @param url the URL of the website
* @param maxSeats maximum number of seats
* @param logoPath the relative path to the logo
* @param location its location {@link Location}
*/
public Establishment(
int id,
String name,
Type type,
Address address,
String phoneNumber,
String description,
URL url,
int maxSeats,
String logoPath,
Location location)
{
if (id < 0 || name == null || type == null || address == null || phoneNumber == null ||
description == null || url == null || maxSeats < 0 || logoPath == null ||
location == null)
{
throw new IllegalArgumentException();
}
mId = id;
mName = name;
mType = type;
mAddress = address;
mPhoneNumber = phoneNumber;
mDescription = description;
mUrl = url;
mMaxSeats = maxSeats;
mLogoPath = logoPath;
mLocation = location;
}
/**
* Getter for the id.
*
* @return
*/
public int getId() {
return mId;
}
/**
* Getter for the name.
*
* @return
*/
public String getName() {
return mName;
}
/**
* Getter for the logo path.
*
* @return
*/
public String getLogoPath() {
return mLogoPath;
}
/**
* Getter for the URL.
*
* @return
*/
public URL getUrl() {
return mUrl;
}
/**
* Getter for the description.
*
* @return
*/
public String getDescription() {
return mDescription;
}
/**
* Getter for the address.
*
* @return
*/
public Address getAddress() {
return mAddress;
}
/**
* Getter for the type {@link Type}
*
* @return
*/
public Type getType() {
return mType;
}
} |
package net.wurstclient.gui.options;
import java.util.Arrays;
import net.minecraft.client.gui.GuiButton;
import net.minecraft.client.gui.GuiScreen;
import net.wurstclient.WurstClient;
import net.wurstclient.compatibility.WMinecraft;
import net.wurstclient.files.ConfigFiles;
import net.wurstclient.gui.options.keybinds.GuiKeybindManager;
import net.wurstclient.gui.options.xray.GuiXRayBlocksManager;
import net.wurstclient.gui.options.zoom.GuiZoomManager;
import net.wurstclient.options.OptionsManager.GoogleAnalytics;
import net.wurstclient.utils.MiscUtils;
public class GuiWurstOptions extends GuiScreen
{
private GuiScreen prevScreen;
private String[] modListModes = {"Auto", "Count", "Hidden"};
private String[] toolTips = {"",
"Add/remove friends by clicking them with\n"
+ "the middle mouse button.",
"How the mod list under the Wurst logo\n" + "should be displayed.\n"
+ "lModes:r\n" + "nAutor: Renders the whole list if it fits\n"
+ "onto the screen.\n"
+ "nCountr: Only renders the number of active\n" + "mods.\n"
+ "nHiddenr: Renders nothing.",
"Automatically maximizes the Minecraft window.\n"
+ "Windows & Linux only!",
"Sends anonymous usage statistics that\n"
+ "help us improve the Wurst Client.",
"",
"Keybinds allow you to toggle any mod\n"
+ "or command by simply pressing a\n" + "button.",
"Manager for the blocks that X-Ray will\n" + "show.",
"The Zoom Manager allows you to\n" + "change the zoom key, how far it\n"
+ "will zoom in and more.",
"", "", "", "", "", "", ""};
private boolean autoMaximize =
WurstClient.INSTANCE.files.loadAutoMaximize();
public GuiWurstOptions(GuiScreen par1GuiScreen)
{
prevScreen = par1GuiScreen;
}
@Override
public void initGui()
{
buttonList.clear();
buttonList.add(new GuiButton(0, width / 2 - 100, height / 4 + 144 - 16,
200, 20, "Back"));
buttonList.add(
new GuiButton(1, width / 2 - 154, height / 4 + 24 - 16, 100, 20,
"Click Friends: "
+ (WurstClient.INSTANCE.options.middleClickFriends ? "ON"
: "OFF")));
buttonList.add(new GuiButton(2, width / 2 - 154, height / 4 + 48 - 16,
100, 20, "Mod List: "
+ modListModes[WurstClient.INSTANCE.options.modListMode]));
buttonList.add(new GuiButton(3, width / 2 - 154, height / 4 + 72 - 16,
100, 20, "AutoMaximize: " + (autoMaximize ? "ON" : "OFF")));
buttonList.add(
new GuiButton(4, width / 2 - 154, height / 4 + 96 - 16, 100, 20,
"Analytics: "
+ (WurstClient.INSTANCE.options.google_analytics.enabled
? "ON" : "OFF")));
// buttonList.add(new GuiButton(5, width / 2 - 154, height / 4 + 120 -
// 16, 100, 20, "???"));
buttonList.add(new GuiButton(6, width / 2 - 50, height / 4 + 24 - 16,
100, 20, "Keybinds"));
buttonList.add(new GuiButton(7, width / 2 - 50, height / 4 + 48 - 16,
100, 20, "X-Ray Blocks"));
buttonList.add(new GuiButton(8, width / 2 - 50, height / 4 + 72 - 16,
100, 20, "Zoom"));
// this.buttonList.add(new GuiButton(9, this.width / 2 - 50, this.height
// / 4 + 96 - 16, 100, 20, "???"));
// this.buttonList.add(new GuiButton(10, this.width / 2 - 50,
// this.height / 4 + 120 - 16, 100, 20, "???"));
buttonList.add(new GuiButton(11, width / 2 + 54, height / 4 + 24 - 16,
100, 20, "Official Website"));
buttonList.add(new GuiButton(12, width / 2 + 54, height / 4 + 48 - 16,
100, 20, "Twitter Page"));
buttonList.add(new GuiButton(13, width / 2 + 54, height / 4 + 72 - 16,
100, 20, "Discord Server"));
// buttonList.add(new GuiButton(14, width / 2 + 54, height / 4 + 96 -
// 16, 100, 20, "???"));
// buttonList.add(new GuiButton(15, width / 2 + 54, height / 4 + 120 -
// 16, 100, 20, "???"));
buttonList.get(3).enabled = !WMinecraft.isRunningOnMac();
}
@Override
protected void actionPerformed(GuiButton button)
{
if(!button.enabled)
return;
if(button.id == 0)
mc.displayGuiScreen(prevScreen);
else if(button.id == 1)
{
// Click Friends
WurstClient.INSTANCE.options.middleClickFriends =
!WurstClient.INSTANCE.options.middleClickFriends;
button.displayString = "Click Friends: "
+ (WurstClient.INSTANCE.options.middleClickFriends ? "ON"
: "OFF");
ConfigFiles.OPTIONS.save();
WurstClient.INSTANCE.analytics.trackEvent("options",
"click friends",
WurstClient.INSTANCE.options.middleClickFriends ? "ON" : "OFF");
}else if(button.id == 2)
{
// Mod List
WurstClient.INSTANCE.options.modListMode++;
if(WurstClient.INSTANCE.options.modListMode > 2)
WurstClient.INSTANCE.options.modListMode = 0;
button.displayString = "Mod List: "
+ modListModes[WurstClient.INSTANCE.options.modListMode];
ConfigFiles.OPTIONS.save();
WurstClient.INSTANCE.analytics.trackEvent("options", "mod list",
modListModes[WurstClient.INSTANCE.options.modListMode]);
}else if(button.id == 3)
{
// AutoMaximize
autoMaximize = !autoMaximize;
button.displayString =
"AutoMaximize: " + (autoMaximize ? "ON" : "OFF");
WurstClient.INSTANCE.files.saveAutoMaximize(autoMaximize);
WurstClient.INSTANCE.analytics.trackEvent("options", "automaximize",
autoMaximize ? "ON" : "OFF");
}else if(button.id == 4)
{
// Analytics
GoogleAnalytics analytics =
WurstClient.INSTANCE.options.google_analytics;
if(analytics.enabled)
WurstClient.INSTANCE.analytics.trackEvent("options",
"analytics", "disable");
analytics.enabled = !analytics.enabled;
if(analytics.enabled)
WurstClient.INSTANCE.analytics.trackEvent("options",
"analytics", "enable");
button.displayString =
"Analytics: " + (analytics.enabled ? "ON" : "OFF");
ConfigFiles.OPTIONS.save();
}else if(button.id == 5)
{
}else if(button.id == 6)
// Keybind Manager
mc.displayGuiScreen(new GuiKeybindManager(this));
else if(button.id == 7)
// X-Ray Block Manager
mc.displayGuiScreen(new GuiXRayBlocksManager(this));
else if(button.id == 8)
// Zoom Manager
mc.displayGuiScreen(new GuiZoomManager(this));
else if(button.id == 9)
{
}else if(button.id == 10)
{
}else if(button.id == 11)
MiscUtils.openLink("https:
else if(button.id == 12)
MiscUtils.openLink("https://twitter.com/Wurst_Imperium");
else if(button.id == 13)
MiscUtils.openLink("https://discord.gg/2K8cFmG");
else if(button.id == 14)
{
}else if(button.id == 15)
{
}
}
@Override
public void drawScreen(int par1, int par2, float par3)
{
drawDefaultBackground();
drawCenteredString(fontRendererObj, "Wurst Options", width / 2, 40,
0xffffff);
drawCenteredString(fontRendererObj, "Settings", width / 2 - 104,
height / 4 + 24 - 28, 0xcccccc);
drawCenteredString(fontRendererObj, "Managers", width / 2,
height / 4 + 24 - 28, 0xcccccc);
drawCenteredString(fontRendererObj, "Links", width / 2 + 104,
height / 4 + 24 - 28, 0xcccccc);
super.drawScreen(par1, par2, par3);
for(int i = 0; i < buttonList.size(); i++)
{
GuiButton button = buttonList.get(i);
if(button.isMouseOver() && !toolTips[button.id].isEmpty())
{
drawHoveringText(Arrays.asList(toolTips[button.id].split("\n")),
par1, par2);
break;
}
}
}
} |
package org.slc.sli.api.service;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import com.mongodb.CommandResult;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import org.bson.BasicBSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Primary;
import org.springframework.data.mongodb.core.index.IndexDefinition;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;
import org.slc.sli.common.constants.EntityNames;
import org.slc.sli.domain.Entity;
import org.slc.sli.domain.NeutralCriteria;
import org.slc.sli.domain.NeutralQuery;
import org.slc.sli.domain.Repository;
/**
* Mock implementation of the Repository<Entity> for unit testing.
*
*/
@Component
@Primary
public class MockRepo implements Repository<Entity> {
@Override
public boolean collectionExists(String collection) {
// TODO Auto-generated method stub
return false;
}
@Override
public void createCollection(String collection) {
// TODO Auto-generated method stub
}
@Override
public void ensureIndex(IndexDefinition index, String collection) {
// TODO Auto-generated method stub
}
private static final Logger LOG = LoggerFactory.getLogger(MockRepo.class);
private Map<String, Map<String, Entity>> repo = new HashMap<String, Map<String, Entity>>();
public MockRepo() {
setup();
}
private void setup() {
repo.put("course", new LinkedHashMap<String, Entity>());
repo.put("student", new LinkedHashMap<String, Entity>());
repo.put("school", new LinkedHashMap<String, Entity>());
repo.put("roles", new LinkedHashMap<String, Entity>());
repo.put("realm", new LinkedHashMap<String, Entity>());
repo.put("studentSchoolAssociation", new LinkedHashMap<String, Entity>());
repo.put("teacher", new LinkedHashMap<String, Entity>());
repo.put("section", new LinkedHashMap<String, Entity>());
repo.put("assessment", new LinkedHashMap<String, Entity>());
repo.put("studentAssessmentAssociation", new LinkedHashMap<String, Entity>());
repo.put("studentSectionAssociation", new LinkedHashMap<String, Entity>());
repo.put("teacherSchoolAssociation", new LinkedHashMap<String, Entity>());
repo.put("staff", new LinkedHashMap<String, Entity>());
repo.put("educationOrganization", new LinkedHashMap<String, Entity>());
repo.put("educationOrganizationSchoolAssociation", new LinkedHashMap<String, Entity>());
repo.put("staffEducationOrganizationAssociation", new LinkedHashMap<String, Entity>());
repo.put("sectionAssessmentAssociation", new LinkedHashMap<String, Entity>());
repo.put("sectionSchoolAssociation", new LinkedHashMap<String, Entity>());
repo.put("aggregation", new LinkedHashMap<String, Entity>());
repo.put("staffschoolassociation", new LinkedHashMap<String, Entity>());
repo.put("aggregationDefinition", new LinkedHashMap<String, Entity>());
repo.put("educationOrganizationAssociation", new LinkedHashMap<String, Entity>());
repo.put("session", new LinkedHashMap<String, Entity>());
repo.put("schoolSessionAssociation", new LinkedHashMap<String, Entity>());
repo.put("sessionCourseAssociation", new LinkedHashMap<String, Entity>());
repo.put("courseSectionAssociation", new LinkedHashMap<String, Entity>()); // known
// technical-debt.
repo.put("bellSchedule", new LinkedHashMap<String, Entity>());
repo.put("cohort", new LinkedHashMap<String, Entity>());
repo.put("disciplineIncident", new LinkedHashMap<String, Entity>());
repo.put("disciplineAction", new LinkedHashMap<String, Entity>());
repo.put("parent", new LinkedHashMap<String, Entity>());
repo.put("program", new LinkedHashMap<String, Entity>());
repo.put("gradebookEntry", new LinkedHashMap<String, Entity>());
repo.put("studentSectionGradebookEntry", new LinkedHashMap<String, Entity>());
repo.put("learningObjective", new LinkedHashMap<String, Entity>());
repo.put("studentDisciplineIncidentAssociation", new LinkedHashMap<String, Entity>());
repo.put("studentParentAssociation", new LinkedHashMap<String, Entity>());
repo.put("studentTranscriptAssociation", new LinkedHashMap<String, Entity>());
repo.put("teacherSectionAssociation", new LinkedHashMap<String, Entity>());
repo.put("studentProgramAssociation", new LinkedHashMap<String, Entity>());
repo.put("staffProgramAssociation", new LinkedHashMap<String, Entity>());
repo.put("authSession", new LinkedHashMap<String, Entity>());
repo.put("assessmentFamily", new LinkedHashMap<String, Entity>());
repo.put("application", new LinkedHashMap<String, Entity>());
repo.put("oauthSession", new LinkedHashMap<String, Entity>());
repo.put("oauth_access_token", new LinkedHashMap<String, Entity>());
repo.put(EntityNames.ATTENDANCE, new LinkedHashMap<String, Entity>());
repo.put(EntityNames.LEARNINGOBJECTIVE, new LinkedHashMap<String, Entity>());
repo.put(EntityNames.COHORT, new LinkedHashMap<String, Entity>());
repo.put(EntityNames.STAFF_COHORT_ASSOCIATION, new LinkedHashMap<String, Entity>());
repo.put(EntityNames.STUDENT_COHORT_ASSOCIATION, new LinkedHashMap<String, Entity>());
}
protected Map<String, Map<String, Entity>> getRepo() {
return repo;
}
protected void setRepo(Map<String, Map<String, Entity>> repo) {
this.repo = repo;
}
@Override
public Entity findById(String entityType, String id) {
return repo.get(entityType).get(id);
}
@SuppressWarnings("unchecked")
private Object getValue(Entity entity, String key, boolean prefixable) {
if (!"_id".equals(key) && prefixable) {
key = "body." + key;
}
String[] path = key.split("\\.");
Map<String, Object> container = null;
if (path.length > 0) {
if ("_id".equals(path[0])) {
return entity.getEntityId();
} else if ("body".equals(path[0])) {
container = entity.getBody();
} else if ("metaData".equals(path[0])) {
container = entity.getMetaData();
}
for (int i = 1; i < path.length - 1; i++) {
Object sub = container.get(path[i]);
if (sub != null && sub instanceof Map) {
container = (Map<String, Object>) sub;
} else {
return null;
}
}
}
if (container == null) {
return null;
}
return container.get(path[path.length - 1]);
}
@SuppressWarnings("unchecked")
@Override
public Iterable<Entity> findAll(String entityType, NeutralQuery neutralQuery) {
Map<String, Entity> results = repo.get(entityType);
if (results == null) {
results = new LinkedHashMap<String, Entity>();
}
for (NeutralCriteria criteria : neutralQuery.getCriteria()) {
Map<String, Entity> results2 = new LinkedHashMap<String, Entity>();
if (criteria.getOperator().equals("=")) {
for (Entry<String, Entity> idAndEntity : results.entrySet()) {
Object entityValue = this.getValue(idAndEntity.getValue(), criteria.getKey(),
criteria.canBePrefixed());
if (entityValue != null) {
if (entityValue.equals(criteria.getValue())) {
results2.put(idAndEntity.getKey(), idAndEntity.getValue());
}
}
}
results = results2;
} else if (criteria.getOperator().equals("in")) {
for (Entry<String, Entity> idAndEntity : results.entrySet()) {
String entityValue = String.valueOf(this.getValue(idAndEntity.getValue(), criteria.getKey(),
criteria.canBePrefixed()));
List<String> validValues = (List<String>) criteria.getValue();
if (validValues.contains(entityValue)) {
results2.put(idAndEntity.getKey(), idAndEntity.getValue());
}
}
results = results2;
} else if (criteria.getOperator().equals("!=")) {
for (Entry<String, Entity> idAndEntity : results.entrySet()) {
Object entityValue = this.getValue(idAndEntity.getValue(), criteria.getKey(),
criteria.canBePrefixed());
if (entityValue != null) {
if (!entityValue.equals(criteria.getValue())) {
results2.put(idAndEntity.getKey(), idAndEntity.getValue());
}
}
}
results = results2;
} else if (criteria.getOperator().equals(">")) {
for (Entry<String, Entity> idAndEntity : results.entrySet()) {
String entityValue = (String) this.getValue(idAndEntity.getValue(), criteria.getKey(),
criteria.canBePrefixed());
if (entityValue != null) {
if (entityValue.compareTo((String) criteria.getValue()) > 0) {
results2.put(idAndEntity.getKey(), idAndEntity.getValue());
}
}
}
results = results2;
} else if (criteria.getOperator().equals("<")) {
for (Entry<String, Entity> idAndEntity : results.entrySet()) {
String entityValue = this.getValue(idAndEntity.getValue(), criteria.getKey(),
criteria.canBePrefixed()).toString();
if (entityValue != null) {
if (entityValue.compareTo(criteria.getValue().toString()) < 0) {
results2.put(idAndEntity.getKey(), idAndEntity.getValue());
}
}
}
results = results2;
} else if (criteria.getOperator().equals(">=")) {
for (Entry<String, Entity> idAndEntity : results.entrySet()) {
String entityValue = (String) this.getValue(idAndEntity.getValue(), criteria.getKey(),
criteria.canBePrefixed());
if (entityValue != null) {
if (entityValue.compareTo((String) criteria.getValue()) >= 0) {
results2.put(idAndEntity.getKey(), idAndEntity.getValue());
}
}
}
results = results2;
} else if (criteria.getOperator().equals("<=")) {
for (Entry<String, Entity> idAndEntity : results.entrySet()) {
String entityValue = (String) this.getValue(idAndEntity.getValue(), criteria.getKey(),
criteria.canBePrefixed());
if (entityValue != null) {
if (entityValue.compareTo((String) criteria.getValue()) <= 0) {
results2.put(idAndEntity.getKey(), idAndEntity.getValue());
}
}
}
results = results2;
} else if (criteria.getOperator().equals("=~")) {
for (Entry<String, Entity> idAndEntity : results.entrySet()) {
Object entityValue = this.getValue(idAndEntity.getValue(), criteria.getKey(),
criteria.canBePrefixed());
if (entityValue != null) {
if (entityValue instanceof String && criteria.getValue() instanceof String) {
String entityValueString = (String) entityValue;
String criteriaValueString = (String) criteria.getValue();
if (!entityValueString.equals(entityValueString.replaceAll(criteriaValueString, ""))) {
results2.put(idAndEntity.getKey(), idAndEntity.getValue());
}
}
}
}
results = results2;
} else {
LOG.warn("Unsupported operator: {}", criteria.getOperator());
}
}
List<Entity> entitiesFound = new ArrayList<Entity>();
for (Entity entity : results.values()) {
entitiesFound.add(entity);
}
if (neutralQuery.getSortBy() != null) {
final NeutralQuery.SortOrder sortOrder = neutralQuery.getSortOrder();
Entity[] entities = entitiesFound.toArray(new Entity[] {});
final String[] keysToSortBy = neutralQuery.getSortBy().split(",");
Arrays.sort(entities, new Comparator<Entity>() {
@Override
public int compare(Entity entity1, Entity entity2) {
// loop for each key in the requested sort by
for (String sortKey : keysToSortBy) {
Object value1 = MockRepo.getValue(sortKey, entity1.getBody());
Object value2 = MockRepo.getValue(sortKey, entity2.getBody());
int compare = MockRepo.compareValues(value1, value2);
if (compare != 0) {
if (sortOrder == NeutralQuery.SortOrder.descending) {
return 0 - compare;
} else {
return compare;
}
}
}
return 0;
}
});
List<Entity> newEntitiesFound = new ArrayList<Entity>();
for (Entity entity : entities) {
newEntitiesFound.add(entity);
}
entitiesFound = newEntitiesFound;
}
int offset = (neutralQuery.getOffset() > 0) ? neutralQuery.getOffset() : 0;
for (int i = 0; i < offset; i++) {
entitiesFound.remove(0);
}
int limit = (neutralQuery.getLimit() > 0) ? neutralQuery.getLimit() : Integer.MAX_VALUE;
while (entitiesFound.size() > limit) {
entitiesFound.remove(entitiesFound.size() - 1);
}
return entitiesFound;
}
private static int compareValues(Object value1, Object value2) {
if (value1 == null || value2 == null) {
return 0;
}
if (value1 instanceof Integer && value2 instanceof Integer) {
return (Integer) value1 - (Integer) value2;
} else if (value1 instanceof String && value2 instanceof String) {
return ((String) value1).compareTo((String) value2);
} else if (value1 instanceof String && value2 instanceof Integer) {
return Integer.parseInt((String) value1) - ((Integer) value2);
} else if (value1 instanceof Integer && value2 instanceof String) {
return (Integer) value1 - Integer.parseInt((String) value2);
}
return 0;
}
@SuppressWarnings("unchecked")
private static Object getValue(String fullKey, Map<String, Object> map) {
Object value = null;
for (String subKey : fullKey.split("\\.")) {
if (subKey.equals("body")) {
continue;
} else if (map.get(subKey) instanceof Map) {
map = (Map<String, Object>) map.get(subKey);
} else {
value = map.get(subKey);
}
}
return value;
}
@Override
public Entity findOne(String entityType, NeutralQuery neutralQuery) {
if (entityType.equals("realm")) {
final Map<String, Object> body = new HashMap<String, Object>();
body.put("tenantId", "SLI");
return new Entity() {
@Override
public String getEntityId() {
return null;
}
@Override
public Map<String, Object> getMetaData() {
return new BasicBSONObject();
}
@Override
public Map<String, Object> getBody() {
return body;
}
@Override
public String getType() {
return "realm";
}
};
} else {
Iterator<Entity> iter = this.findAll(entityType, neutralQuery).iterator();
return iter.hasNext() ? iter.next() : null;
}
}
@Override
public boolean update(String type, Entity entity) {
if (repo.get(type) == null) {
repo.put(type, new LinkedHashMap<String, Entity>());
}
repo.get(type).put(entity.getEntityId(), entity);
return true;
}
@Override
public Entity create(String type, Map<String, Object> body) {
return create(type, body, type);
}
@Override
public Entity create(final String type, Map<String, Object> body, String collectionName) {
final HashMap<String, Object> clonedBody = new HashMap<String, Object>(body);
final String id = generateId();
Entity newEntity = new Entity() {
@Override
public String getEntityId() {
return id;
}
@Override
public Map<String, Object> getMetaData() {
return new BasicBSONObject();
}
@Override
public Map<String, Object> getBody() {
return clonedBody;
}
@Override
public String getType() {
return type;
}
};
update(collectionName, newEntity);
return newEntity;
}
@Override
public boolean delete(String entityType, String id) {
return repo.get(entityType).remove(id) != null;
}
@Override
public void deleteAll(String entityType) {
Map<String, Entity> repository = repo.get(entityType);
if (repository != null) {
repository.clear();
}
}
public void deleteAll() {
repo.clear();
setup();
}
@Override
public Iterable<Entity> findAll(String entityType) {
List<Entity> all = new ArrayList<Entity>(repo.get(entityType).values());
return all;
}
@Override
public long count(String collectionName, NeutralQuery neutralQuery) {
return ((List<?>) findAll(collectionName, neutralQuery)).size();
}
private String generateId() {
return UUID.randomUUID().toString();
}
@Override
public Iterable<Entity> findAllByPaths(String collectionName, Map<String, String> paths, NeutralQuery neutralQuery) {
// Not implemented
return null;
}
@Override
public Entity create(final String type, Map<String, Object> body, Map<String, Object> metaData,
String collectionName) {
final HashMap<String, Object> clonedBody = new HashMap<String, Object>(body);
final HashMap<String, Object> clonedMetadata = new HashMap<String, Object>(metaData);
final String id = generateId();
Entity newEntity = new Entity() {
@Override
public String getEntityId() {
return id;
}
@Override
public Map<String, Object> getMetaData() {
return clonedMetadata;
}
@Override
public Map<String, Object> getBody() {
return clonedBody;
}
@Override
public String getType() {
return type;
}
};
update(collectionName, newEntity);
return newEntity;
}
@Override
public Iterable<String> findAllIds(String collectionName, NeutralQuery neutralQuery) {
ArrayList<String> ids = new ArrayList<String>();
for (Entity e : this.findAll(collectionName, neutralQuery)) {
ids.add(e.getEntityId());
}
return ids;
}
@Override
public CommandResult execute(DBObject command) {
return null;
}
@Override
public DBCollection getCollection(String collectionName) {
return null;
}
@Override
public Iterable<Entity> findByPaths(String collectionName, Map<String, String> paths) {
// TODO Auto-generated method stub
return null;
}
@Override
public Iterable<Entity> findByQuery(String collectionName, Query query, int skip, int max) {
// TODO Auto-generated method stub
return null;
}
} |
package com.intellij.openapi.editor.impl;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.*;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.event.CaretEvent;
import com.intellij.openapi.editor.event.CaretListener;
import com.intellij.openapi.editor.event.DocumentEvent;
import com.intellij.openapi.editor.ex.EditorGutterComponentEx;
import com.intellij.openapi.editor.ex.PrioritizedDocumentListener;
import com.intellij.openapi.editor.ex.util.EditorUtil;
import com.intellij.openapi.editor.impl.event.DocumentEventImpl;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.util.text.CharArrayUtil;
import java.awt.*;
import java.util.concurrent.CopyOnWriteArrayList;
public class CaretModelImpl implements CaretModel, PrioritizedDocumentListener {
private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.CaretModelImpl");
private EditorImpl myEditor;
private CopyOnWriteArrayList<CaretListener> myCaretListeners = new CopyOnWriteArrayList<CaretListener>();
private LogicalPosition myLogicalCaret;
private VisualPosition myVisibleCaret;
private int myOffset;
private int myVisualLineStart;
private int myVisualLineEnd;
private TextAttributes myTextAttributes;
private boolean myIsInUpdate;
public CaretModelImpl(EditorImpl editor) {
myEditor = editor;
myLogicalCaret = new LogicalPosition(0, 0);
myVisibleCaret = new VisualPosition(0, 0);
myOffset = 0;
myVisualLineStart = 0;
Document doc = editor.getDocument();
if (doc.getLineCount() > 1) {
myVisualLineEnd = doc.getLineStartOffset(1);
}
else {
myVisualLineEnd = doc.getLineCount() == 0 ? 0 : doc.getLineEndOffset(0);
}
}
public void moveToVisualPosition(VisualPosition pos) {
validateCallContext();
int column = pos.column;
int line = pos.line;
if (column < 0) column = 0;
if (line < 0) line = 0;
int lastLine = myEditor.getVisibleLineCount() - 1;
if (lastLine <= 0) {
lastLine = 0;
}
if (line > lastLine) {
line = lastLine;
}
EditorSettings editorSettings = myEditor.getSettings();
if (!editorSettings.isVirtualSpace() && line <= lastLine) {
int lineEndColumn = EditorUtil.getLastVisualLineColumnNumber(myEditor, line);
if (column > lineEndColumn) {
column = lineEndColumn;
}
if (column < 0 && line > 0) {
line
column = EditorUtil.getLastVisualLineColumnNumber(myEditor, line);
}
}
int oldY = myEditor.visibleLineNumberToYPosition(myVisibleCaret.line);
myVisibleCaret = new VisualPosition(line, column);
LogicalPosition oldPosition = myLogicalCaret;
myLogicalCaret = myEditor.visualToLogicalPosition(myVisibleCaret);
myOffset = myEditor.logicalPositionToOffset(myLogicalCaret);
LOG.assertTrue(myOffset >= 0 && myOffset <= myEditor.getDocument().getTextLength());
myVisualLineStart =
myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line, 0)));
myVisualLineEnd =
myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line + 1, 0)));
((FoldingModelImpl)myEditor.getFoldingModel()).flushCaretPosition();
myEditor.setLastColumnNumber(myVisibleCaret.column);
myEditor.updateCaretCursor();
requestRepaint(oldY);
if (oldPosition.column != myLogicalCaret.column || oldPosition.line != myLogicalCaret.line) {
CaretEvent event = new CaretEvent(myEditor, oldPosition, myLogicalCaret);
for (CaretListener listener : myCaretListeners) {
listener.caretPositionChanged(event);
}
}
}
public void moveToOffset(int offset) {
validateCallContext();
moveToLogicalPosition(myEditor.offsetToLogicalPosition(offset));
if (myOffset != offset) {
LOG.error("caret moved to wrong offset. Requested:" + offset + " but actual:" + myOffset);
}
}
public void moveCaretRelatively(int columnShift,
int lineShift,
boolean withSelection,
boolean blockSelection,
boolean scrollToCaret) {
SelectionModel selectionModel = myEditor.getSelectionModel();
int selectionStart = selectionModel.getLeadSelectionOffset();
LogicalPosition blockSelectionStart = selectionModel.hasBlockSelection()
? selectionModel.getBlockStart()
: getLogicalPosition();
EditorSettings editorSettings = myEditor.getSettings();
VisualPosition visualCaret = getVisualPosition();
int newColumnNumber = visualCaret.column + columnShift;
int newLineNumber = visualCaret.line + lineShift;
if (!editorSettings.isVirtualSpace() && columnShift == 0) {
newColumnNumber = myEditor.getLastColumnNumber();
}
else if (!editorSettings.isVirtualSpace() && lineShift == 0 && columnShift == 1) {
int lastLine = myEditor.getDocument().getLineCount() - 1;
if (lastLine < 0) lastLine = 0;
if (EditorModificationUtil.calcAfterLineEnd(myEditor) >= 0 &&
newLineNumber < myEditor.logicalToVisualPosition(new LogicalPosition(lastLine, 0)).line) {
newColumnNumber = 0;
newLineNumber++;
}
}
else if (!editorSettings.isVirtualSpace() && lineShift == 0 && columnShift == -1) {
if (newColumnNumber < 0 && newLineNumber > 0) {
newLineNumber
newColumnNumber = EditorUtil.getLastVisualLineColumnNumber(myEditor, newLineNumber);
}
}
if (newColumnNumber < 0) newColumnNumber = 0;
if (newLineNumber < 0) newLineNumber = 0;
int lastColumnNumber = newColumnNumber;
if (!editorSettings.isCaretInsideTabs()) {
LogicalPosition log = myEditor.visualToLogicalPosition(new VisualPosition(newLineNumber, newColumnNumber));
int offset = myEditor.logicalPositionToOffset(log);
CharSequence text = myEditor.getDocument().getCharsSequence();
if (offset >= 0 && offset < myEditor.getDocument().getTextLength()) {
if (text.charAt(offset) == '\t') {
if (columnShift <= 0) {
newColumnNumber = myEditor.offsetToVisualPosition(offset).column;
}
else {
if (myEditor.offsetToVisualPosition(offset).column < newColumnNumber) {
newColumnNumber = myEditor.offsetToVisualPosition(offset + 1).column;
}
}
}
}
}
VisualPosition pos = new VisualPosition(newLineNumber, newColumnNumber);
moveToVisualPosition(pos);
if (!editorSettings.isVirtualSpace() && columnShift == 0) {
myEditor.setLastColumnNumber(lastColumnNumber);
}
if (withSelection) {
if (blockSelection) {
selectionModel.setBlockSelection(blockSelectionStart, getLogicalPosition());
}
else {
selectionModel.setSelection(selectionStart, getOffset());
}
}
else {
selectionModel.removeSelection();
}
if (scrollToCaret) {
myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
}
public void moveToLogicalPosition(LogicalPosition pos) {
validateCallContext();
int column = pos.column;
int line = pos.line;
Document doc = myEditor.getDocument();
if (column < 0) column = 0;
if (line < 0) line = 0;
int lineCount = doc.getLineCount();
if (lineCount == 0) {
line = 0;
}
else if (line > lineCount - 1) {
line = lineCount - 1;
}
EditorSettings editorSettings = myEditor.getSettings();
if (!editorSettings.isVirtualSpace() && line < lineCount) {
int lineEndOffset = doc.getLineEndOffset(line);
int lineEndColumnNumber = myEditor.offsetToLogicalPosition(lineEndOffset).column;
if (column > lineEndColumnNumber) {
column = lineEndColumnNumber;
}
}
((FoldingModelImpl)myEditor.getFoldingModel()).flushCaretPosition();
int oldY = myEditor.visibleLineNumberToYPosition(myVisibleCaret.line);
LogicalPosition oldCaretPosition = myLogicalCaret;
myLogicalCaret = new LogicalPosition(line, column);
final int offset = myEditor.logicalPositionToOffset(myLogicalCaret);
FoldRegion collapsedAt = myEditor.getFoldingModel().getCollapsedRegionAtOffset(offset);
if (collapsedAt != null && offset > collapsedAt.getStartOffset()) {
Runnable runnable = new Runnable() {
public void run() {
FoldRegion[] allCollapsedAt = ((FoldingModelImpl)myEditor.getFoldingModel()).fetchCollapsedAt(offset);
for (FoldRegion foldRange : allCollapsedAt) {
foldRange.setExpanded(true);
}
}
};
myEditor.getFoldingModel().runBatchFoldingOperation(runnable);
}
myEditor.setLastColumnNumber(myLogicalCaret.column);
myVisibleCaret = myEditor.logicalToVisualPosition(myLogicalCaret);
myOffset = myEditor.logicalPositionToOffset(myLogicalCaret);
LOG.assertTrue(myOffset >= 0 && myOffset <= myEditor.getDocument().getTextLength());
myVisualLineStart =
myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line, 0)));
myVisualLineEnd =
myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line + 1, 0)));
myEditor.updateCaretCursor();
requestRepaint(oldY);
if (oldCaretPosition.column != myLogicalCaret.column || oldCaretPosition.line != myLogicalCaret.line) {
CaretEvent event = new CaretEvent(myEditor, oldCaretPosition, myLogicalCaret);
for (CaretListener listener : myCaretListeners) {
listener.caretPositionChanged(event);
}
}
}
private void requestRepaint(int oldY) {
int newY = myEditor.visibleLineNumberToYPosition(myVisibleCaret.line);
int lineHeight = myEditor.getLineHeight();
Rectangle visibleRect = myEditor.getScrollingModel().getVisibleArea();
final EditorGutterComponentEx gutter = myEditor.getGutterComponentEx();
final EditorComponentImpl content = (EditorComponentImpl)myEditor.getContentComponent();
int updateWidth = myEditor.getScrollPane()
.getHorizontalScrollBar()
.getValue() + visibleRect.width;
if (Math.abs(newY - oldY) <= 2 * lineHeight) {
int minY = Math.min(oldY, newY);
int maxY = Math.max(oldY + lineHeight, newY + lineHeight);
content.repaintEditorComponent(0, minY, updateWidth, maxY - minY);
gutter.repaint(0, minY, gutter.getWidth(), maxY - minY);
}
else {
content.repaintEditorComponent(0, oldY, updateWidth, 2 * lineHeight);
gutter.repaint(0, oldY, updateWidth, 2 * lineHeight);
content.repaintEditorComponent(0, newY, updateWidth, 2 * lineHeight);
gutter.repaint(0, newY, updateWidth, 2 * lineHeight);
}
}
public LogicalPosition getLogicalPosition() {
validateCallContext();
return myLogicalCaret;
}
private void validateCallContext() {
ApplicationManager.getApplication().assertIsDispatchThread();
LOG.assertTrue(!myIsInUpdate, "Caret model is in its update process. All requests are illegal at this point.");
}
public VisualPosition getVisualPosition() {
validateCallContext();
return myVisibleCaret;
}
public int getOffset() {
validateCallContext();
return myOffset;
}
public int getVisualLineStart() {
return myVisualLineStart;
}
public int getVisualLineEnd() {
return myVisualLineEnd;
}
public void addCaretListener(CaretListener listener) {
myCaretListeners.add(listener);
}
public void removeCaretListener(CaretListener listener) {
boolean success = myCaretListeners.remove(listener);
LOG.assertTrue(success);
}
public TextAttributes getTextAttributes() {
if (myTextAttributes == null) {
myTextAttributes = new TextAttributes();
myTextAttributes.setBackgroundColor(myEditor.getColorsScheme().getColor(EditorColors.CARET_ROW_COLOR));
}
return myTextAttributes;
}
public void reinitSettings() {
myTextAttributes = null;
}
public void documentChanged(DocumentEvent e) {
myIsInUpdate = false;
DocumentEventImpl event = (DocumentEventImpl)e;
if (event.isWholeTextReplaced()) {
int newLength = myEditor.getDocument().getTextLength();
if (myOffset == newLength - e.getNewLength() + e.getOldLength()) {
moveToOffset(newLength);
}
else {
final int line = event.translateLineViaDiff(myLogicalCaret.line);
moveToLogicalPosition(new LogicalPosition(line, myLogicalCaret.column));
}
}
else {
int startOffset = e.getOffset();
int oldEndOffset = startOffset + e.getOldLength();
int newOffset = myOffset;
if (myOffset > oldEndOffset || myOffset == oldEndOffset && needToShiftWhitespaces(e)) {
newOffset += e.getNewLength() - e.getOldLength();
}
else if (myOffset >= startOffset && myOffset <= oldEndOffset) {
newOffset = Math.min(newOffset, startOffset + e.getNewLength());
}
newOffset = Math.min(newOffset, myEditor.getDocument().getTextLength());
//TODO:ask max about this code
// if (newOffset != myOffset) {
moveToOffset(newOffset);
//else {
// moveToVisualPosition(oldPosition);
}
myVisualLineStart =
myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line, 0)));
myVisualLineEnd =
myEditor.logicalPositionToOffset(myEditor.visualToLogicalPosition(new VisualPosition(myVisibleCaret.line + 1, 0)));
}
private boolean needToShiftWhitespaces(final DocumentEvent e) {
if(!CharArrayUtil.containsOnlyWhiteSpaces(e.getNewFragment()) || CharArrayUtil.containLineBreaks(e.getNewFragment()))
return e.getOldLength() > 0;
if(e.getOffset() == 0) return false;
final char charBefore = myEditor.getDocument().getCharsSequence().charAt(e.getOffset() - 1);
//final char charAfter = myEditor.getDocument().getCharsSequence().charAt(e.getOffset() + e.getNewLength());
return Character.isWhitespace(charBefore)/* || !Character.isWhitespace(charAfter)*/;
}
public void beforeDocumentChange(DocumentEvent e) {
myIsInUpdate = true;
}
public int getPriority() {
return 3;
}
} |
package com.intellij.openapi.vfs.encoding;
import com.intellij.openapi.actionSystem.*;
import com.intellij.openapi.actionSystem.impl.SimpleDataContext;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.util.IconUtil;
import com.intellij.util.Icons;
import com.intellij.util.containers.HashMap;
import com.intellij.util.ui.UIUtil;
import com.intellij.util.ui.treetable.TreeTable;
import com.intellij.util.ui.treetable.TreeTableCellRenderer;
import com.intellij.util.ui.treetable.TreeTableModel;
import gnu.trove.THashMap;
import org.jetbrains.annotations.NotNull;
import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableColumn;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeNode;
import java.awt.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.List;
public class FileTreeTable extends TreeTable {
private final MyModel myModel;
private final Project myProject;
public FileTreeTable(final Project project) {
super(new MyModel(project));
myProject = project;
myModel = (MyModel)getTableModel();
final TableColumn valueColumn = getColumnModel().getColumn(1);
valueColumn.setCellRenderer(new DefaultTableCellRenderer(){
public Component getTableCellRendererComponent(final JTable table, final Object value,
final boolean isSelected, final boolean hasFocus, final int row, final int column) {
super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column);
Charset t = (Charset)value;
if (t != null) {
setText(t.name());
}
else {
Object userObject = table.getModel().getValueAt(row, 0);
if (userObject instanceof VirtualFile) {
VirtualFile file = (VirtualFile)userObject;
Charset charset = ChooseFileEncodingAction.encodingFromContent(myProject, file);
if (charset != null) {
setText("Encoding: " + charset);
setEnabled(false);
return this;
}
}
}
setEnabled(true);
return this;
}
});
JComboBox valuesCombo = new JComboBox();
valuesCombo.setRenderer(new DefaultListCellRenderer(){
public Component getListCellRendererComponent(final JList list,
final Object value,
final int index, final boolean isSelected, final boolean cellHasFocus) {
Component component = super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
String text =((Charset)value).name();
setText(text);
return component;
}
});
valueColumn.setCellEditor(new DefaultCellEditor(new JComboBox()){
private VirtualFile myVirtualFile;
{
delegate = new EditorDelegate() {
public void setValue(Object value) {
myModel.setValueAt(value, new DefaultMutableTreeNode(myVirtualFile), -1);
//comboComponent.revalidate();
}
public Object getCellEditorValue() {
return myModel.getValueAt(new DefaultMutableTreeNode(myVirtualFile), 1);
}
};
}
public Component getTableCellEditorComponent(JTable table, final Object value, boolean isSelected, int row, int column) {
Object o = table.getModel().getValueAt(row, 0);
myVirtualFile = o instanceof Project ? null : (VirtualFile)o;
final ChooseFileEncodingAction changeAction = new ChooseFileEncodingAction(myVirtualFile, myProject){
protected void chosen(VirtualFile virtualFile, Charset charset) {
valueColumn.getCellEditor().stopCellEditing();
int ret = askWhetherClearSubdirectories(virtualFile);
if (ret != 2) {
myModel.setValueAt(charset, new DefaultMutableTreeNode(virtualFile), 1);
}
}
};
final JComponent comboComponent = changeAction.createCustomComponent(changeAction.getTemplatePresentation());
DataContext dataContext = SimpleDataContext.getSimpleContext(DataConstants.VIRTUAL_FILE, myVirtualFile, SimpleDataContext.getProjectContext(myProject));
AnActionEvent event = new AnActionEvent(null, dataContext, ActionPlaces.UNKNOWN, changeAction.getTemplatePresentation(), ActionManager.getInstance(), 0);
changeAction.update(event);
editorComponent = comboComponent;
Charset charset = (Charset)myModel.getValueAt(new DefaultMutableTreeNode(myVirtualFile), 1);
if (charset != null) {
changeAction.getTemplatePresentation().setText(charset.name());
}
comboComponent.revalidate();
return editorComponent;
}
});
getTree().setShowsRootHandles(true);
getTree().setLineStyleAngled();
getTree().setRootVisible(true);
getTree().setCellRenderer(new DefaultTreeCellRenderer(){
public Component getTreeCellRendererComponent(final JTree tree, final Object value, final boolean sel, final boolean expanded,
final boolean leaf, final int row, final boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, sel, expanded, leaf, row, hasFocus);
if (value instanceof ProjectRootNode) {
setText("Project");
return this;
}
VirtualFile file = ((FileNode)value).getObject();
setText(file.getName());
Icon icon;
if (file.isDirectory()) {
icon = expanded ? Icons.DIRECTORY_OPEN_ICON : Icons.DIRECTORY_CLOSED_ICON;
}
else {
icon = IconUtil.getIcon(file, 0, null);
}
setIcon(icon);
return this;
}
});
getTableHeader().setReorderingAllowed(false);
setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
setPreferredScrollableViewportSize(new Dimension(300, getRowHeight() * 10));
getColumnModel().getColumn(0).setPreferredWidth(280);
valueColumn.setPreferredWidth(60);
}
private int askWhetherClearSubdirectories(final VirtualFile parent) {
Map<VirtualFile, Charset> mappings = myModel.myCurrentMapping;
Map<VirtualFile, Charset> subdirectoryMappings = new THashMap<VirtualFile, Charset>();
for (VirtualFile file : mappings.keySet()) {
if (file != null && (parent == null || VfsUtil.isAncestor(parent, file, true))) {
subdirectoryMappings.put(file, mappings.get(file));
}
}
if (subdirectoryMappings.isEmpty()) {
return 0;
}
else {
int ret = Messages.showDialog(myProject, "There are encodings specified for the subdirectories. Override them?",
"Override Subdirectory Encoding", new String[]{"Override","Do Not Override","Cancel"}, 0, Messages.getWarningIcon());
if (ret == 0) {
for (VirtualFile file : subdirectoryMappings.keySet()) {
myModel.setValueAt(null, new DefaultMutableTreeNode(file), 1);
}
}
return ret;
}
}
public Map<VirtualFile, Charset> getValues() {
return myModel.getValues();
}
public TreeTableCellRenderer createTableRenderer(TreeTableModel treeTableModel) {
TreeTableCellRenderer tableRenderer = super.createTableRenderer(treeTableModel);
UIUtil.setLineStyleAngled(tableRenderer);
tableRenderer.setRootVisible(false);
tableRenderer.setShowsRootHandles(true);
return tableRenderer;
}
public void reset(final Map<VirtualFile, Charset> mappings) {
myModel.reset(mappings);
myModel.nodeChanged((TreeNode)myModel.getRoot());
getTree().setModel(null);
getTree().setModel(myModel);
}
private static class MyModel extends DefaultTreeModel implements TreeTableModel {
private final Map<VirtualFile, Charset> myCurrentMapping = new HashMap<VirtualFile, Charset>();
private final Project myProject;
private MyModel(Project project) {
super(new ProjectRootNode(project));
myProject = project;
myCurrentMapping.putAll(EncodingProjectManager.getInstance(project).getAllMappings());
}
private Map<VirtualFile, Charset> getValues() {
return new HashMap<VirtualFile, Charset>(myCurrentMapping);
}
public int getColumnCount() {
return 2;
}
public String getColumnName(final int column) {
switch(column) {
case 0: return "File/Directory";
case 1: return "Default Encoding";
default: throw new RuntimeException("invalid column " + column);
}
}
public Class getColumnClass(final int column) {
switch(column) {
case 0: return TreeTableModel.class;
case 1: return Charset.class;
default: throw new RuntimeException("invalid column " + column);
}
}
public Object getValueAt(final Object node, final int column) {
Object userObject = ((DefaultMutableTreeNode)node).getUserObject();
if (userObject instanceof Project) {
switch(column) {
case 0: return userObject;
case 1: return myCurrentMapping.get(null);
}
}
VirtualFile file = (VirtualFile)userObject;
switch(column) {
case 0: return file;
case 1: return myCurrentMapping.get(file);
default: throw new RuntimeException("invalid column " + column);
}
}
public boolean isCellEditable(final Object node, final int column) {
switch(column) {
case 0: return false;
case 1:
Object userObject = ((DefaultMutableTreeNode)node).getUserObject();
if (userObject instanceof VirtualFile) {
VirtualFile file = (VirtualFile)userObject;
Charset charset = ChooseFileEncodingAction.encodingFromContent(myProject, file);
return charset == null;
}
return true;
default: throw new RuntimeException("invalid column " + column);
}
}
public void setValueAt(final Object aValue, final Object node, final int column) {
DefaultMutableTreeNode treeNode = (DefaultMutableTreeNode)node;
Object userObject = treeNode.getUserObject();
if (userObject instanceof Project) return;
VirtualFile file = (VirtualFile)userObject;
Charset charset = (Charset)aValue;
if (charset == ChooseFileEncodingAction.NO_ENCODING) {
myCurrentMapping.remove(file);
}
else {
myCurrentMapping.put(file, charset);
}
fireTreeNodesChanged(this, new Object[]{getRoot()}, null, null);
}
public void reset(final Map<VirtualFile, Charset> mappings) {
myCurrentMapping.clear();
myCurrentMapping.putAll(mappings);
((ProjectRootNode)getRoot()).clearCachedChildren();
}
}
private static class ProjectRootNode extends ConvenientNode<Project> {
public ProjectRootNode(Project project) {
super(project);
}
protected void appendChildrenTo(final Collection<ConvenientNode> children) {
Project project = getObject();
VirtualFile[] roots = ProjectRootManager.getInstance(project).getContentRoots();
NextRoot:
for (VirtualFile root : roots) {
for (VirtualFile candidate : roots) {
if (VfsUtil.isAncestor(candidate, root, true)) continue NextRoot;
}
children.add(new FileNode(root, project));
}
}
}
private abstract static class ConvenientNode<T> extends DefaultMutableTreeNode {
private final T myObject;
private ConvenientNode(T object) {
myObject = object;
}
public T getObject() {
return myObject;
}
protected abstract void appendChildrenTo(final Collection<ConvenientNode> children);
public int getChildCount() {
init();
return super.getChildCount();
}
public TreeNode getChildAt(final int childIndex) {
init();
return super.getChildAt(childIndex);
}
public Enumeration children() {
init();
return super.children();
}
private void init() {
if (getUserObject() == null) {
setUserObject(myObject);
List<ConvenientNode> children = new ArrayList<ConvenientNode>();
appendChildrenTo(children);
Collections.sort(children, new Comparator<ConvenientNode>() {
public int compare(final ConvenientNode node1, final ConvenientNode node2) {
Object o1 = node1.getObject();
Object o2 = node2.getObject();
if (o1 == o2) return 0;
if (o1 instanceof Project) return -1;
if (o2 instanceof Project) return 1;
VirtualFile file1 = (VirtualFile)o1;
VirtualFile file2 = (VirtualFile)o2;
if (file1.isDirectory() != file2.isDirectory()) {
return file1.isDirectory() ? -1 : 1;
}
return file1.getName().compareTo(file2.getName());
}
});
int i=0;
for (ConvenientNode child : children) {
insert(child, i++);
}
}
}
public void clearCachedChildren() {
if (children != null) {
for (Object child : children) {
ConvenientNode<T> node = (ConvenientNode<T>)child;
node.clearCachedChildren();
}
}
removeAllChildren();
setUserObject(null);
}
}
private static class FileNode extends ConvenientNode<VirtualFile> {
private final Project myProject;
private FileNode(@NotNull VirtualFile file, final Project project) {
super(file);
myProject = project;
}
protected void appendChildrenTo(final Collection<ConvenientNode> children) {
VirtualFile[] childrenf = getObject().getChildren();
ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
for (VirtualFile child : childrenf) {
if (fileIndex.isInContent(child)) {
children.add(new FileNode(child, myProject));
}
}
}
}
} |
package com.intellij.psi.impl;
import com.intellij.openapi.application.Application;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.ex.DocumentEx;
import com.intellij.openapi.util.Pair;
import com.intellij.psi.*;
import com.intellij.psi.impl.smartPointers.SmartPointerManagerImpl;
import com.intellij.psi.impl.source.jsp.JspxFileImpl;
import com.intellij.psi.impl.source.tree.TreeUtil;
import com.intellij.psi.impl.source.tree.TreeElement;
import java.util.*;
public class PsiToDocumentSynchronizer extends PsiTreeChangeAdapter {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.PsiToDocumentSynchronizer");
private final SmartPointerManagerImpl mySmartPointerManager;
private PsiDocumentManagerImpl myPsiDocumentManager;
public PsiToDocumentSynchronizer(PsiDocumentManagerImpl psiDocumentManager, SmartPointerManagerImpl smartPointerManager) {
mySmartPointerManager = smartPointerManager;
myPsiDocumentManager = psiDocumentManager;
}
public DocumentChangeTransaction getTransaction(final Document document) {
final Pair<DocumentChangeTransaction, Integer> pair = myTransactionsMap.get(document);
return pair != null ? pair.getFirst() : null;
}
private static interface DocSyncAction {
void syncDocument(Document document, PsiTreeChangeEventImpl event);
}
private void doSync(PsiTreeChangeEvent event, DocSyncAction syncAction) {
if (!toProcessPsiEvent()) {
return;
}
PsiFile psiFile = event.getFile();
if (psiFile == null) return;
DocumentEx document = getCachedDocument(psiFile);
if (document == null) return;
TextBlock textBlock = getTextBlock(document);
if (!textBlock.isEmpty()) {
LOG.error("Attempt to modify PSI for non-commited Document!");
textBlock.clear();
}
final PsiElement scope = event.getParent();
if (scope != null && TreeUtil.getFileElement((TreeElement)scope.getNode()).getPsi() != scope.getContainingFile())
return;
myPsiDocumentManager.setProcessDocumentEvents(false);
try {
syncAction.syncDocument(document, (PsiTreeChangeEventImpl)event);
}
finally {
myPsiDocumentManager.setProcessDocumentEvents(true);
}
final boolean insideTransaction = myTransactionsMap.containsKey(document);
if(!insideTransaction){
document.setModificationStamp(psiFile.getModificationStamp());
mySmartPointerManager.synchronizePointers(psiFile);
if (LOG.isDebugEnabled()) {
PsiDocumentManagerImpl.checkConsistency(psiFile, document);
if (psiFile instanceof JspxFileImpl) {
((JspxFileImpl)psiFile).checkAllConsistent();
}
}
}
}
public void childAdded(final PsiTreeChangeEvent event) {
doSync(event, new DocSyncAction() {
public void syncDocument(Document document, PsiTreeChangeEventImpl event) {
insertString(document, event.getOffset(), event.getChild().getText());
}
});
}
public void childRemoved(final PsiTreeChangeEvent event) {
doSync(event, new DocSyncAction() {
public void syncDocument(Document document, PsiTreeChangeEventImpl event) {
deleteString(document, event.getOffset(), event.getOffset() + event.getOldLength());
}
});
}
public void childReplaced(final PsiTreeChangeEvent event) {
doSync(event, new DocSyncAction() {
public void syncDocument(Document document, PsiTreeChangeEventImpl event) {
replaceString(document, event.getOffset(), event.getOffset() + event.getOldLength(), event.getNewChild().getText());
}
});
}
public void childrenChanged(final PsiTreeChangeEvent event) {
doSync(event, new DocSyncAction() {
public void syncDocument(Document document, PsiTreeChangeEventImpl event) {
replaceString(document, event.getOffset(), event.getOffset() + event.getOldLength(), event.getParent().getText());
}
});
}
public void beforeChildReplacement(PsiTreeChangeEvent event) {
processBeforeEvent(event);
}
public void beforeChildAddition(PsiTreeChangeEvent event) {
processBeforeEvent(event);
}
public void beforeChildRemoval(PsiTreeChangeEvent event) {
processBeforeEvent(event);
}
public void beforeChildrenChange(PsiTreeChangeEvent event) {
processBeforeEvent(event);
}
private void processBeforeEvent(PsiTreeChangeEvent event) {
if (toProcessPsiEvent()) {
PsiFile psiFile = event.getParent().getContainingFile();
if (psiFile == null) return;
//TODO: get red of this?
mySmartPointerManager.fastenBelts(psiFile);
mySmartPointerManager.unfastenBelts(psiFile);
}
}
private static boolean toProcessPsiEvent() {
Application application = ApplicationManager.getApplication();
return application.getCurrentWriteAction(CommitToPsiFileAction.class) == null
&& application.getCurrentWriteAction(PsiExternalChangeAction.class) == null;
}
private Map<Document, Pair<DocumentChangeTransaction, Integer>> myTransactionsMap = new HashMap<Document, Pair<DocumentChangeTransaction, Integer>>();
public void replaceString(Document document, int startOffset, int endOffset, String s) {
final DocumentChangeTransaction documentChangeTransaction = getTransaction(document);
if(documentChangeTransaction != null) {
documentChangeTransaction.replace(startOffset, endOffset - startOffset, s);
}
else {
DocumentEx ex = (DocumentEx) document;
ex.suppressGuardedExceptions();
try {
boolean isReadOnly = !document.isWritable();
ex.setReadOnly(false);
ex.replaceString(startOffset, endOffset, s);
ex.setReadOnly(isReadOnly);
}
finally {
ex.unSuppressGuardedExceptions();
}
}
}
public void insertString(Document document, int offset, String s) {
final DocumentChangeTransaction documentChangeTransaction = getTransaction(document);
if(documentChangeTransaction != null){
documentChangeTransaction.replace(offset, 0, s);
}
else {
DocumentEx ex = (DocumentEx) document;
ex.suppressGuardedExceptions();
try {
boolean isReadOnly = !ex.isWritable();
ex.setReadOnly(false);
ex.insertString(offset, s);
ex.setReadOnly(isReadOnly);
}
finally {
ex.unSuppressGuardedExceptions();
}
}
}
public void deleteString(Document document, int startOffset, int endOffset){
final DocumentChangeTransaction documentChangeTransaction = getTransaction(document);
if(documentChangeTransaction != null){
documentChangeTransaction.replace(startOffset, endOffset - startOffset, "");
}
else {
DocumentEx ex = (DocumentEx) document;
ex.suppressGuardedExceptions();
try {
boolean isReadOnly = !ex.isWritable();
ex.setReadOnly(false);
ex.deleteString(startOffset, endOffset);
ex.setReadOnly(isReadOnly);
}
finally {
ex.unSuppressGuardedExceptions();
}
}
}
private DocumentEx getCachedDocument(PsiFile file) {
return (DocumentEx)myPsiDocumentManager.getCachedDocument(file);
}
private TextBlock getTextBlock(Document document) {
return myPsiDocumentManager.getTextBlock(document);
}
public void startTransaction(Document doc, PsiElement scope) {
Pair<DocumentChangeTransaction, Integer> pair = myTransactionsMap.get(doc);
if(pair == null)
pair = new Pair<DocumentChangeTransaction, Integer>(new DocumentChangeTransaction(doc, scope != null ? scope.getContainingFile() : null), new Integer(0));
else
pair = new Pair<DocumentChangeTransaction, Integer>(pair.getFirst(), new Integer(pair.getSecond().intValue() + 1));
myTransactionsMap.put(doc, pair);
}
public void commitTransaction(Document document){
final DocumentChangeTransaction documentChangeTransaction = removeTransaction(document);
if(documentChangeTransaction == null) return;
//if(documentChangeTransaction.getAffectedFragments().size() == 0) return; // Nothing to do
final PsiElement changeScope = documentChangeTransaction.getChangeScope();
final PsiTreeChangeEventImpl fakeEvent = new PsiTreeChangeEventImpl(changeScope.getManager());
fakeEvent.setParent(changeScope);
fakeEvent.setFile(changeScope.getContainingFile());
doSync(fakeEvent, new DocSyncAction() {
public void syncDocument(Document document, PsiTreeChangeEventImpl event) {
doCommitTransaction(document, documentChangeTransaction);
}
});
}
public void doCommitTransaction(final Document document){
doCommitTransaction(document, getTransaction(document));
}
private static void doCommitTransaction(final Document document, final DocumentChangeTransaction documentChangeTransaction) {
DocumentEx ex = (DocumentEx) document;
ex.suppressGuardedExceptions();
try {
boolean isReadOnly = !document.isWritable();
ex.setReadOnly(false);
final Set<Pair<MutableTextRange, StringBuffer>> affectedFragments = documentChangeTransaction.getAffectedFragments();
final Iterator<Pair<MutableTextRange, StringBuffer>> iterator = affectedFragments.iterator();
while (iterator.hasNext()) {
final Pair<MutableTextRange, StringBuffer> pair = iterator.next();
final StringBuffer replaceBuffer = pair.getSecond();
final MutableTextRange range = pair.getFirst();
if(replaceBuffer.length() == 0){
ex.deleteString(range.getStartOffset(), range.getEndOffset());
}
else if(range.getLength() == 0){
ex.insertString(range.getStartOffset(), replaceBuffer);
}
else{
ex.replaceString(range.getStartOffset(),
range.getEndOffset(),
replaceBuffer);
}
}
ex.setReadOnly(isReadOnly);
if(documentChangeTransaction.getChangeScope() != null) {
LOG.assertTrue(document.getText().equals(documentChangeTransaction.getChangeScope().getText()),
"Psi to document synchronization failed (send to IK)");
}
}
finally {
ex.unSuppressGuardedExceptions();
}
}
public DocumentChangeTransaction removeTransaction(Document doc) {
Pair<DocumentChangeTransaction, Integer> pair = myTransactionsMap.get(doc);
if(pair == null) return null;
if(pair.getSecond().intValue() > 0){
pair = new Pair<DocumentChangeTransaction, Integer>(pair.getFirst(), new Integer(pair.getSecond().intValue() - 1));
myTransactionsMap.put(doc, pair);
return null;
}
myTransactionsMap.remove(doc);
return pair.getFirst();
}
public static class DocumentChangeTransaction{
private final Set<Pair<MutableTextRange,StringBuffer>> myAffectedFragments = new TreeSet<Pair<MutableTextRange, StringBuffer>>(new Comparator<Pair<MutableTextRange, StringBuffer>>() {
public int compare(final Pair<MutableTextRange, StringBuffer> o1,
final Pair<MutableTextRange, StringBuffer> o2) {
return o1.getFirst().getStartOffset() - o2.getFirst().getStartOffset();
}
});
private final Document myDocument;
private final PsiFile myChangeScope;
public DocumentChangeTransaction(final Document doc, PsiFile scope) {
myDocument = doc;
myChangeScope = scope;
}
public Set<Pair<MutableTextRange, StringBuffer>> getAffectedFragments() {
return myAffectedFragments;
}
public PsiFile getChangeScope() {
return myChangeScope;
}
public void replace(int start, int length, String str){
final int startInFragment;
final StringBuffer fragmentReplaceText;
{ // calculating fragment
{ // minimize replace
final int oldStart = start;
int end = start + length;
final int newStringLength = str.length();
final String chars = getText(start, end);
if(chars.equals(str)) return;
int newStartInString = 0;
int newEndInString = newStringLength;
while (newStartInString < newStringLength &&
start < end &&
str.charAt(newStartInString) == chars.charAt(start - oldStart)) {
start++;
newStartInString++;
}
while (end > start &&
newEndInString > newStartInString &&
str.charAt(newEndInString - 1) == chars.charAt(end - oldStart - 1)) {
newEndInString
end
}
str = str.substring(newStartInString, newEndInString);
length = end - start;
}
final Pair<MutableTextRange, StringBuffer> fragment = getFragmentByRange(start, length);
fragmentReplaceText = fragment.getSecond();
startInFragment = start - fragment.getFirst().getStartOffset();
{ // text range adjustment
final int lengthDiff = str.length() - length;
final Iterator<Pair<MutableTextRange, StringBuffer>> iterator = myAffectedFragments.iterator();
boolean adjust = false;
while (iterator.hasNext()) {
final Pair<MutableTextRange, StringBuffer> pair = iterator.next();
if(adjust) pair.getFirst().shift(lengthDiff);
if(pair == fragment)
adjust = true;
}
}
}
fragmentReplaceText.replace(startInFragment, startInFragment + length, str);
}
private String getText(final int start, final int end) {
int currentOldDocumentOffset = 0;
int currentNewDocumentOffset = 0;
StringBuffer text = new StringBuffer();
Iterator<Pair<MutableTextRange, StringBuffer>> iterator = myAffectedFragments.iterator();
while (iterator.hasNext() && currentNewDocumentOffset < end) {
final Pair<MutableTextRange, StringBuffer> pair = iterator.next();
final MutableTextRange range = pair.getFirst();
final StringBuffer buffer = pair.getSecond();
final int fragmentEndInNewDocument = range.getStartOffset() + buffer.length();
if(range.getStartOffset() <= start && fragmentEndInNewDocument >= end){
return buffer.substring(start - range.getStartOffset(), end - range.getStartOffset());
}
if(range.getStartOffset() >= start){
final int effectiveStart = Math.max(currentNewDocumentOffset, start);
text.append(myDocument.getChars(),
effectiveStart - currentNewDocumentOffset + currentOldDocumentOffset,
Math.min(range.getStartOffset(), end) - effectiveStart);
if(end > range.getStartOffset()){
text.append(buffer.substring(0, Math.min(end - range.getStartOffset(), buffer.length())));
}
}
currentOldDocumentOffset += range.getEndOffset() - currentNewDocumentOffset;
currentNewDocumentOffset = fragmentEndInNewDocument;
}
if(currentNewDocumentOffset < end){
final int effectiveStart = Math.max(currentNewDocumentOffset, start);
text.append(myDocument.getChars(),
effectiveStart - currentNewDocumentOffset + currentOldDocumentOffset,
end - effectiveStart);
}
return text.toString();
}
private Pair<MutableTextRange, StringBuffer> getFragmentByRange(int start, final int length) {
final StringBuffer fragmentBuffer = new StringBuffer();
int end = start + length;
{
// restoring buffer and remove all subfragments from the list
int documentOffset = 0;
int effectiveOffset = 0;
Iterator<Pair<MutableTextRange, StringBuffer>> iterator = myAffectedFragments.iterator();
while (iterator.hasNext() && effectiveOffset <= end) {
final Pair<MutableTextRange, StringBuffer> pair = iterator.next();
final MutableTextRange range = pair.getFirst();
final StringBuffer buffer = pair.getSecond();
int effectiveFragmentEnd = range.getStartOffset() + buffer.length();
if(range.getStartOffset() <= start && effectiveFragmentEnd >= end) return pair;
if(effectiveFragmentEnd >= start){
final int effectiveStart = Math.max(effectiveOffset, start);
if(range.getStartOffset() > start){
fragmentBuffer.append(myDocument.getChars(),
effectiveStart - effectiveOffset + documentOffset,
Math.min(range.getStartOffset(), end) - effectiveStart);
}
if(end >= range.getStartOffset()){
fragmentBuffer.append(buffer);
end = end > effectiveFragmentEnd ? end - (buffer.length() - range.getLength()) : range.getEndOffset();
effectiveFragmentEnd = range.getEndOffset();
start = Math.min(start, range.getStartOffset());
iterator.remove();
}
}
documentOffset += range.getEndOffset() - effectiveOffset;
effectiveOffset = effectiveFragmentEnd;
}
if(effectiveOffset < end){
final int effectiveStart = Math.max(effectiveOffset, start);
fragmentBuffer.append(myDocument.getChars(),
effectiveStart - effectiveOffset + documentOffset,
end - effectiveStart);
}
}
final Pair<MutableTextRange, StringBuffer> pair = new Pair<MutableTextRange, StringBuffer>(new MutableTextRange(start, end), fragmentBuffer);
myAffectedFragments.add(pair);
return pair;
}
}
public static class MutableTextRange{
private int myLength;
private int myStartOffset;
public MutableTextRange(final int startOffset, final int endOffset) {
myStartOffset = startOffset;
myLength = endOffset - startOffset;
}
public int getStartOffset() {
return myStartOffset;
}
public int getEndOffset() {
return myStartOffset + myLength;
}
public int getLength() {
return myLength;
}
public String toString() {
return "[" + getStartOffset() + ", " + getEndOffset() + "]";
}
public void shift(final int lengthDiff) {
myStartOffset += lengthDiff;
}
}
} |
package com.intellij.psi.impl.file.impl;
import com.intellij.ide.highlighter.JavaClassFileType;
import com.intellij.lang.Language;
import com.intellij.lang.ParserDefinition;
import com.intellij.lang.StdLanguages;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileDocumentManagerAdapter;
import com.intellij.openapi.fileEditor.FileDocumentManagerListener;
import com.intellij.openapi.fileTypes.*;
import com.intellij.openapi.fileTypes.ex.FileTypeManagerEx;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ex.ProjectEx;
import com.intellij.openapi.roots.*;
import com.intellij.openapi.vfs.*;
import com.intellij.openapi.vfs.impl.local.VirtualFileImpl;
import com.intellij.openapi.util.Comparing;
import com.intellij.psi.*;
import com.intellij.psi.impl.*;
import com.intellij.psi.impl.cache.RepositoryIndex;
import com.intellij.psi.impl.cache.RepositoryManager;
import com.intellij.psi.impl.compiled.ClsFileImpl;
import com.intellij.psi.impl.file.PsiBinaryFileImpl;
import com.intellij.psi.impl.file.PsiDirectoryImpl;
import com.intellij.psi.impl.file.PsiPackageImpl;
import com.intellij.psi.impl.source.PsiFileImpl;
import com.intellij.psi.impl.source.PsiPlainTextFileImpl;
import com.intellij.psi.impl.source.resolve.ResolveUtil;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.xml.XmlFile;
import com.intellij.util.containers.WeakValueHashMap;
import com.intellij.util.containers.HashMap;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import java.io.IOException;
import java.io.Writer;
import java.util.*;
public class FileManagerImpl implements FileManager {
private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.file.impl.FileManagerImpl");
private static int MAX_INTELLISENSE_FILESIZE = maxIntellisenseFileSize();
private final PsiManagerImpl myManager;
private final FileTypeManager myFileTypeManager;
private final ProjectRootManager myProjectRootManager;
private ProjectFileIndex myProjectFileIndex = null;
private RootManager myRootManager = null;
private HashMap<VirtualFile, PsiDirectory> myVFileToPsiDirMap = new HashMap<VirtualFile, PsiDirectory>();
private WeakValueHashMap<FileCacheEntry,PsiFile> myVFileToPsiFileMap = new WeakValueHashMap<FileCacheEntry, PsiFile>(); // VirtualFile --> PsiFile
private VirtualFileListener myVirtualFileListener = null;
private FileDocumentManagerListener myFileDocumentManagerListener = null;
private ModuleRootListener myModuleRootListener = null;
private FileTypeListener myFileTypeListener = null;
private boolean myInitialized = false;
private boolean myDisposed = false;
private boolean myUseRepository = true;
private HashMap<GlobalSearchScope, PsiClass> myCachedObjectClassMap = null;
private Map<String,PsiClass> myNameToClassMap = new HashMap<String, PsiClass>(); // used only in mode without repository
private HashSet<String> myNontrivialPackagePrefixes = null;
private final VirtualFileManager myVirtualFileManager;
private final FileDocumentManager myFileDocumentManager;
private static final @NonNls String JAVA_EXTENSION = ".java";
private static final @NonNls String CLASS_EXTENSION = ".class";
@NonNls private static final String MAX_INTELLISENSE_SIZE_PROPERTY = "idea.max.intellisense.filesize";
public FileManagerImpl(PsiManagerImpl manager,
FileTypeManager fileTypeManager,
VirtualFileManager virtualFileManager,
FileDocumentManager fileDocumentManager,
ProjectRootManager projectRootManager) {
myFileTypeManager = fileTypeManager;
myManager = manager;
myVirtualFileManager = virtualFileManager;
myFileDocumentManager = fileDocumentManager;
myProjectRootManager = projectRootManager;
}
public void dispose() {
if (myInitialized) {
myVirtualFileManager.removeVirtualFileListener(myVirtualFileListener);
myFileDocumentManager.removeFileDocumentManagerListener(myFileDocumentManagerListener);
myProjectRootManager.removeModuleRootListener(myModuleRootListener);
myFileTypeManager.removeFileTypeListener(myFileTypeListener);
synchronized (PsiLock.LOCK) {
myCachedObjectClassMap = null;
}
}
myDisposed = true;
}
private static int maxIntellisenseFileSize() {
final String maxSizeS = System.getProperty(MAX_INTELLISENSE_SIZE_PROPERTY);
return maxSizeS != null ? Integer.parseInt(maxSizeS) * 1024 : -1;
}
public void cleanupForNextTest() {
myVFileToPsiFileMap.clear();
myVFileToPsiDirMap.clear();
}
public PsiFile findFile(VirtualFile file, Language aspect) {
final ProjectEx project = (ProjectEx)myManager.getProject();
if (project.isDummy() || project.isDefault()) return null;
ApplicationManager.getApplication().assertReadAccessAllowed();
if (file == null) {
LOG.assertTrue(false);
return null;
}
if (!file.isValid()) {
LOG.assertTrue(false, "Invalid file: " + file);
}
dispatchPendingEvents();
synchronized (PsiLock.LOCK) {
final FileCacheEntry key = new FileCacheEntry(file, aspect);
PsiFile psiFile = myVFileToPsiFileMap.get(key);
if (psiFile != null) return psiFile;
psiFile = createPsiFile(file, aspect);
if (psiFile == null) return null;
myVFileToPsiFileMap.put(key, psiFile);
return psiFile;
}
}
public void runStartupActivity() {
LOG.assertTrue(!myInitialized);
myDisposed = false;
myInitialized = true;
myRootManager = new RootManager(this, myProjectRootManager);
PsiManagerConfiguration configuration = PsiManagerConfiguration.getInstance();
myUseRepository = configuration.REPOSITORY_ENABLED;
myProjectFileIndex = myProjectRootManager.getFileIndex();
Runnable runnable = new Runnable() {
public void run() {
synchronized (PsiLock.LOCK) {
myCachedObjectClassMap = null;
}
}
};
myManager.registerRunnableToRunOnChange(runnable);
myVirtualFileListener = new MyVirtualFileListener();
myVirtualFileManager.addVirtualFileListener(myVirtualFileListener);
myFileDocumentManagerListener = new FileDocumentManagerAdapter() {
public void fileWithNoDocumentChanged(VirtualFile file) {
if (!myUseRepository) {
clearNonRepositoryMaps();
}
final PsiFile psiFile = getCachedPsiFileInner(file);
if (psiFile != null) {
ApplicationManager.getApplication().runWriteAction(
new PsiExternalChangeAction() {
public void run() {
reloadFromDisk(psiFile, true); // important to ignore document which might appear already!
}
}
);
}
}
};
myFileDocumentManager.addFileDocumentManagerListener(myFileDocumentManagerListener);
myModuleRootListener = new MyModuleRootListener();
myProjectRootManager.addModuleRootListener(myModuleRootListener);
myFileTypeListener = new FileTypeListener() {
public void beforeFileTypesChanged(FileTypeEvent event) {
}
public void fileTypesChanged(FileTypeEvent e) {
ApplicationManager.getApplication().runWriteAction(
new Runnable() {
public void run() {
PsiTreeChangeEventImpl event = new PsiTreeChangeEventImpl(myManager);
event.setPropertyName(PsiTreeChangeEvent.PROP_FILE_TYPES);
myManager.beforePropertyChange(event);
removeInvalidFilesAndDirs(true);
event = new PsiTreeChangeEventImpl(myManager);
event.setPropertyName(PsiTreeChangeEvent.PROP_FILE_TYPES);
myManager.propertyChanged(event);
}
}
);
}
};
myFileTypeManager.addFileTypeListener(myFileTypeListener);
}
private void dispatchPendingEvents() {
LOG.assertTrue(myInitialized);
//LOG.assertTrue(!myDisposed);
// [dsl]todo[max, dsl] this is a hack. MUST FIX
if (!ApplicationManager.getApplication().isDispatchThread()) return;
myVirtualFileManager.dispatchPendingEvent(myVirtualFileListener);
myFileDocumentManager.dispatchPendingEvents(myFileDocumentManagerListener);
myProjectRootManager.dispatchPendingEvent(myModuleRootListener);
((FileTypeManagerEx) myFileTypeManager).dispatchPendingEvents(myFileTypeListener);
//TODO: other listeners
}
// for tests
public void checkConsistency() {
Map<FileCacheEntry, PsiFile> fileToPsiFileMap = myVFileToPsiFileMap;
myVFileToPsiFileMap = new WeakValueHashMap<FileCacheEntry, PsiFile>();
for (FileCacheEntry fileCacheEntry : fileToPsiFileMap.keySet()) {
final VirtualFile vFile = fileCacheEntry.getFirst();
final PsiFile psiFile = fileToPsiFileMap.get(fileCacheEntry);
LOG.assertTrue(vFile.isValid());
PsiFile psiFile1 = findFile(vFile);
LOG.assertTrue(psiFile1 != null, vFile.toString());
if (psiFile != null) { // might get collected
LOG.assertTrue(psiFile1.getClass().equals(psiFile.getClass()));
}
VirtualFile parent = vFile.getParent();
LOG.assertTrue(myVFileToPsiDirMap.containsKey(parent));
}
HashMap<VirtualFile, PsiDirectory> fileToPsiDirMap = myVFileToPsiDirMap;
myVFileToPsiDirMap = new HashMap<VirtualFile, PsiDirectory>();
for (VirtualFile vFile : fileToPsiDirMap.keySet()) {
LOG.assertTrue(vFile.isValid());
PsiDirectory psiDir1 = findDirectory(vFile);
LOG.assertTrue(psiDir1 != null);
VirtualFile parent = vFile.getParent();
if (parent != null) {
LOG.assertTrue(myVFileToPsiDirMap.containsKey(parent));
}
}
}
public PsiFile findFile(VirtualFile vFile) {
final ProjectEx project = (ProjectEx)myManager.getProject();
if (project.isDummy() || project.isDefault()) return null;
ApplicationManager.getApplication().assertReadAccessAllowed();
if (vFile == null) {
LOG.assertTrue(false);
return null;
}
if (!vFile.isValid()) {
LOG.assertTrue(false, "Invalid file: " + vFile);
}
dispatchPendingEvents();
synchronized (PsiLock.LOCK) {
PsiFile psiFile = getCachedPsiFileInner(vFile);
if (psiFile != null) return psiFile;
psiFile = createPsiFile(vFile, vFile.getName());
if (psiFile == null) return null;
cachePsiFile(vFile, psiFile);
return psiFile;
}
}
public PsiFile getCachedPsiFile(VirtualFile vFile) {
ApplicationManager.getApplication().assertReadAccessAllowed();
LOG.assertTrue(vFile.isValid());
LOG.assertTrue(!myDisposed);
if (!myInitialized) return null;
dispatchPendingEvents();
synchronized (PsiLock.LOCK) {
return getCachedPsiFileInner(vFile);
}
}
public GlobalSearchScope getResolveScope(PsiElement element) {
VirtualFile vFile;
if (element instanceof PsiDirectory) {
vFile = ((PsiDirectory)element).getVirtualFile();
}
else {
final PsiFile contextFile = ResolveUtil.getContextFile(element);
if (contextFile == null || contextFile instanceof XmlFile) {
return GlobalSearchScope.allScope(myManager.getProject());
}
vFile = contextFile.getVirtualFile();
if (vFile == null) {
PsiFile originalFile = contextFile.getOriginalFile();
if (originalFile != null) {
vFile = originalFile.getVirtualFile();
}
}
}
if (vFile == null) {
return GlobalSearchScope.allScope(myManager.getProject());
}
ProjectFileIndex projectFileIndex = myProjectRootManager.getFileIndex();
Module module = projectFileIndex.getModuleForFile(vFile);
if (module != null) {
boolean includeTests = projectFileIndex.isInTestSourceContent(vFile) ||
!projectFileIndex.isContentJavaSourceFile(vFile);
return GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module, includeTests);
}
else {
// resolve references in libraries in context of all modules which contain it
GlobalSearchScope allInclusiveModuleScope = null;
OrderEntry[] orderEntries = projectFileIndex.getOrderEntriesForFile(vFile);
if (orderEntries.length > 0) {
for (OrderEntry entry : orderEntries) {
if (entry instanceof LibraryOrderEntry || entry instanceof JdkOrderEntry) {
Module ownerModule = entry.getOwnerModule();
final GlobalSearchScope moduleScope = GlobalSearchScope.moduleWithLibrariesScope(ownerModule);
if (allInclusiveModuleScope == null) {
allInclusiveModuleScope = moduleScope;
}
else {
allInclusiveModuleScope = allInclusiveModuleScope.uniteWith(moduleScope);
}
}
}
}
if (allInclusiveModuleScope == null) {
allInclusiveModuleScope = GlobalSearchScope.allScope(myManager.getProject());
}
return new LibrariesOnlyScope(allInclusiveModuleScope);
}
}
@NotNull
public GlobalSearchScope getUseScope(PsiElement element) {
VirtualFile vFile;
if (element instanceof PsiDirectory) {
vFile = ((PsiDirectory)element).getVirtualFile();
}
else {
final PsiFile containingFile = element.getContainingFile();
if (containingFile == null) return GlobalSearchScope.allScope(myManager.getProject());
final VirtualFile virtualFile = containingFile.getVirtualFile();
if (virtualFile == null) return GlobalSearchScope.allScope(myManager.getProject());
vFile = virtualFile.getParent();
}
if (vFile == null) return GlobalSearchScope.allScope(myManager.getProject());;
ProjectFileIndex projectFileIndex = myProjectRootManager.getFileIndex();
Module module = projectFileIndex.getModuleForFile(vFile);
if (module != null) {
boolean isTest = projectFileIndex.isInTestSourceContent(vFile);
return isTest
? GlobalSearchScope.moduleTestsWithDependentsScope(module)
: GlobalSearchScope.moduleWithDependentsScope(module);
}
else {
return GlobalSearchScope.allScope(myManager.getProject());
}
}
public Collection<String> getNonTrivialPackagePrefixes() {
if (myNontrivialPackagePrefixes == null) {
myNontrivialPackagePrefixes = new HashSet<String>();
final ProjectRootManager rootManager = myProjectRootManager;
final VirtualFile[] sourceRoots = rootManager.getContentSourceRoots();
final ProjectFileIndex fileIndex = rootManager.getFileIndex();
for (final VirtualFile sourceRoot : sourceRoots) {
final String packageName = fileIndex.getPackageNameByDirectory(sourceRoot);
if (packageName != null && packageName.length() > 0) {
myNontrivialPackagePrefixes.add(packageName);
}
}
}
return myNontrivialPackagePrefixes;
}
private PsiFile createPsiFile(VirtualFile vFile, Language lang) {
if (vFile.isDirectory()) return null;
VirtualFile parent = vFile.getParent();
if (parent == null) return null;
PsiDirectory psiDir = findDirectory(parent); // need to cache parent directory - used for firing events
if (psiDir == null) return null;
final Project project = myManager.getProject();
if (lang == StdLanguages.JAVA || !isTooLarge(vFile)) {
final ParserDefinition parserDefinition = lang.getParserDefinition();
if (parserDefinition != null) {
return parserDefinition.createFile(project, vFile);
}
}
return null;
}
private PsiFile createPsiFile(VirtualFile vFile, String name) {
try {
if (vFile.isDirectory()) return null;
if (myFileTypeManager.isFileIgnored(name)) return null; // cannot use ProjectFileIndex because of "name"!
VirtualFile parent = vFile.getParent();
if (parent == null) return null;
PsiDirectory psiDir = findDirectory(parent); // need to cache parent directory - used for firing events
if (psiDir == null) return null;
FileType fileType = myFileTypeManager.getFileTypeByFileName(name);
final Project project = myManager.getProject();
if (fileType instanceof LanguageFileType) {
final Language language = ((LanguageFileType)fileType).getLanguage();
if (language == StdLanguages.JAVA || !isTooLarge(vFile)) {
final ParserDefinition parserDefinition = language.getParserDefinition();
if (parserDefinition != null) {
return parserDefinition.createFile(project, vFile);
}
}
}
if (fileType instanceof JavaClassFileType) {
ProjectFileIndex fileIndex = ProjectRootManager.getInstance(project).getFileIndex();
if (fileIndex.isInLibraryClasses(vFile)) {
// skip inners & anonymous
int dotIndex = name.lastIndexOf('.');
if (dotIndex < 0) dotIndex = name.length();
int index = name.lastIndexOf('$', dotIndex);
if (index >= 0) return null;
return new ClsFileImpl((PsiManagerImpl)PsiManager.getInstance(project), vFile);
}
return null;
}
if (fileType.isBinary()) {
return new PsiBinaryFileImpl(myManager, vFile);
}
return new PsiPlainTextFileImpl(project, vFile);
}
catch (Throwable e) {
LOG.error(e);
return null;
}
}
private boolean isTooLarge(final VirtualFile vFile) {
if (MAX_INTELLISENSE_FILESIZE == -1) return false;
return getFileLength(vFile) > MAX_INTELLISENSE_FILESIZE;
}
private long getFileLength(final VirtualFile vFile) {
if (vFile instanceof VirtualFileImpl) {
return ((VirtualFileImpl)vFile).getPhysicalFileLength();
}
return vFile.getLength();
}
public PsiDirectory findDirectory(VirtualFile vFile) {
LOG.assertTrue(myInitialized, "Access to psi files should be performed only after startup activity");
LOG.assertTrue(!myDisposed);
ApplicationManager.getApplication().assertReadAccessAllowed();
LOG.assertTrue(vFile.isValid(), vFile.getName());
if (!vFile.isDirectory()) return null;
dispatchPendingEvents();
synchronized (PsiLock.LOCK) {
PsiDirectory psiDir = myVFileToPsiDirMap.get(vFile);
if (psiDir != null) return psiDir;
if (myProjectRootManager.getFileIndex().isIgnored(vFile)) return null;
VirtualFile parent = vFile.getParent();
if (parent != null) {
findDirectory(parent);// need to cache parent directory - used for firing events
}
psiDir = new PsiDirectoryImpl(myManager, vFile);
myVFileToPsiDirMap.put(vFile, psiDir);
return psiDir;
}
}
public PsiPackage findPackage(String packageName) {
VirtualFile[] dirs = myProjectRootManager.getFileIndex().getDirectoriesByPackageName(packageName, false);
if (dirs.length == 0) return null;
return new PsiPackageImpl(myManager, packageName);
}
public PsiDirectory[] getRootDirectories(int rootType) {
return myRootManager.getRootDirectories(rootType);
}
public PsiClass[] findClasses(String qName, GlobalSearchScope scope) {
RepositoryManager repositoryManager = myManager.getRepositoryManager();
long[] classIds = repositoryManager.getIndex().getClassesByQualifiedName(qName, null);
if (classIds.length == 0) return PsiClass.EMPTY_ARRAY;
ArrayList<PsiClass> result = new ArrayList<PsiClass>();
for (long classId : classIds) {
PsiClass aClass = (PsiClass)myManager.getRepositoryElementsManager().findOrCreatePsiElementById(classId);
VirtualFile vFile = aClass.getContainingFile().getVirtualFile();
if (scope.contains(vFile)) {
result.add(aClass);
}
}
return result.toArray(new PsiClass[result.size()]);
}
public PsiClass findClass(String qName, GlobalSearchScope scope) {
if (!myUseRepository) {
return findClassWithoutRepository(qName);
}
if (!myInitialized) {
LOG.error("Access to psi files should be performed only after startup activity");
return null;
}
LOG.assertTrue(!myDisposed);
if ("java.lang.Object".equals(qName)) { // optimization
synchronized (PsiLock.LOCK) {
if (myCachedObjectClassMap == null) {
myCachedObjectClassMap = new HashMap<GlobalSearchScope, PsiClass>();
Module[] modules = ModuleManager.getInstance(myManager.getProject()).getModules();
for (Module aModule : modules) {
GlobalSearchScope moduleScope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(aModule);
PsiClass objectClass = _findClass(qName, moduleScope);
myCachedObjectClassMap.put(moduleScope, objectClass);
}
GlobalSearchScope allScope = GlobalSearchScope.allScope(myManager.getProject());
PsiClass objectClass = _findClass(qName, allScope);
myCachedObjectClassMap.put(allScope, objectClass);
}
final PsiClass cachedClass = myCachedObjectClassMap.get(scope);
return cachedClass == null ? _findClass(qName, scope) : cachedClass;
}
}
return _findClass(qName, scope);
}
private PsiClass findClassWithoutRepository(String qName) {
synchronized (PsiLock.LOCK) {
if (myNameToClassMap.containsKey(qName)) return myNameToClassMap.get(qName);
PsiClass aClass = _findClassWithoutRepository(qName);
myNameToClassMap.put(qName, aClass);
return aClass;
}
}
private PsiClass _findClassWithoutRepository(String qName) {
PsiClass aClass = myNameToClassMap.get(qName);
if (aClass != null) return aClass;
VirtualFile[] sourcePath = myRootManager.getSourceRootsCopy();
VirtualFile[] classPath = myRootManager.getClassRootsCopy();
int index = 0;
while (index < qName.length()) {
int index1 = qName.indexOf('.', index);
if (index1 < 0) {
index1 = qName.length();
}
String name = qName.substring(index, index1);
final int sourceType = 0;
//final int compiledType = 1;
for (int type = 0; type < 2; type++) {
VirtualFile[] vDirs = type == sourceType ? sourcePath : classPath;
for (VirtualFile vDir : vDirs) {
if (vDir != null) {
VirtualFile vChild = type == sourceType
? vDir.findChild(name + JAVA_EXTENSION)
: vDir.findChild(name + CLASS_EXTENSION);
if (vChild != null) {
PsiFile file = findFile(vChild);
if (file instanceof PsiJavaFile) {
aClass = findClassByName((PsiJavaFile)file, name);
if (aClass != null) {
index = index1 + 1;
while (index < qName.length()) {
index1 = qName.indexOf('.', index);
if (index1 < 0) {
index1 = qName.length();
}
name = qName.substring(index, index1);
aClass = findClassByName(aClass, name);
if (aClass == null) return null;
index = index1 + 1;
}
return aClass;
}
}
}
}
}
}
boolean existsDir = false;
for (int type = 0; type < 2; type++) {
VirtualFile[] vDirs = type == sourceType ? sourcePath : classPath;
for (int i = 0; i < vDirs.length; i++) {
if (vDirs[i] != null) {
VirtualFile vDirChild = vDirs[i].findChild(name);
if (vDirChild != null) {
PsiDirectory dir = findDirectory(vDirChild);
if (dir != null) {
vDirs[i] = vDirChild;
existsDir = true;
continue;
}
}
vDirs[i] = null;
}
}
}
if (!existsDir) return null;
index = index1 + 1;
}
return null;
}
private static PsiClass findClassByName(PsiJavaFile scope, String name) {
PsiClass[] classes = scope.getClasses();
for (PsiClass aClass : classes) {
if (name.equals(aClass.getName())) {
return aClass;
}
}
return null;
}
private static PsiClass findClassByName(PsiClass scope, String name) {
PsiClass[] classes = scope.getInnerClasses();
for (PsiClass aClass : classes) {
if (name.equals(aClass.getName())) {
return aClass;
}
}
return null;
}
private PsiClass _findClass(String qName, GlobalSearchScope scope) {
RepositoryManager repositoryManager = myManager.getRepositoryManager();
RepositoryIndex index = repositoryManager.getIndex();
VirtualFileFilter rootFilter = null;//index.rootFilterBySearchScope(scope);
long[] classIds = index.getClassesByQualifiedName(qName, rootFilter);
if (classIds.length == 0) return null;
RepositoryElementsManager repositoryElementsManager = myManager.getRepositoryElementsManager();
VirtualFile bestFile = null;
PsiClass bestClass = null;
for (long classId : classIds) {
PsiClass aClass = (PsiClass)repositoryElementsManager.findOrCreatePsiElementById(classId);
LOG.assertTrue(aClass != null);
LOG.assertTrue(aClass.isValid());
PsiFile file = aClass.getContainingFile();
if (file == null) {
LOG.error("aClass=" + aClass);
continue;
}
VirtualFile vFile = file.getVirtualFile();
if (!scope.contains(vFile)) continue;
if (bestFile == null || scope.compare(vFile, bestFile) > 0) {
bestFile = vFile;
bestClass = aClass;
}
}
return bestClass;
}
public PsiFile getCachedPsiFileInner(VirtualFile file) {
return myVFileToPsiFileMap.get(new FileCacheEntry(file, Language.ANY));
}
private void cachePsiFile(VirtualFile vFile, PsiFile psiFile) {
final FileCacheEntry key = new FileCacheEntry(vFile, Language.ANY);
if(psiFile != null)
myVFileToPsiFileMap.put(key, psiFile);
else
myVFileToPsiFileMap.remove(key);
}
private void removeInvalidFilesAndDirs(boolean useFind) {
HashMap<VirtualFile, PsiDirectory> fileToPsiDirMap = myVFileToPsiDirMap;
if (useFind) {
myVFileToPsiDirMap = new HashMap<VirtualFile, PsiDirectory>();
}
for (Iterator<VirtualFile> iterator = fileToPsiDirMap.keySet().iterator(); iterator.hasNext();) {
VirtualFile vFile = iterator.next();
if (!vFile.isValid()) {
iterator.remove();
} else {
PsiDirectory psiDir = findDirectory(vFile);
if (psiDir == null) {
iterator.remove();
}
}
}
myVFileToPsiDirMap = fileToPsiDirMap;
// note: important to update directories map first - findFile uses findDirectory!
WeakValueHashMap<FileCacheEntry ,PsiFile> fileToPsiFileMap = myVFileToPsiFileMap;
if (useFind) {
myVFileToPsiFileMap = new WeakValueHashMap<FileCacheEntry, PsiFile>();
}
for (Iterator<FileCacheEntry> iterator = fileToPsiFileMap.keySet().iterator(); iterator.hasNext();) {
final FileCacheEntry fileCacheEntry = iterator.next();
VirtualFile vFile = fileCacheEntry.getFirst();
if (!vFile.isValid()) {
iterator.remove();
continue;
}
if (useFind) {
PsiFile psiFile = fileToPsiFileMap.get(fileCacheEntry);
if (psiFile == null) { // soft ref. collected
iterator.remove();
continue;
}
PsiFile psiFile1 = findFile(vFile);
if (psiFile1 == null) {
iterator.remove();
continue;
}
if (!psiFile1.getClass().equals(psiFile.getClass()))
iterator.remove();
}
}
myVFileToPsiFileMap = fileToPsiFileMap;
}
public void reloadFromDisk(PsiFile file) {
reloadFromDisk(file, false);
}
private void reloadFromDisk(PsiFile file, boolean ignoreDocument) {
VirtualFile vFile = file.getVirtualFile();
assert vFile != null;
if (file instanceof PsiBinaryFile) {
file.setModificationStamp(vFile.getModificationStamp());
}
else {
FileDocumentManager fileDocumentManager = myFileDocumentManager;
Document document = fileDocumentManager.getCachedDocument(vFile);
if (document != null && !ignoreDocument){
fileDocumentManager.reloadFromDisk(document);
}
else{
PsiTreeChangeEventImpl event = new PsiTreeChangeEventImpl(myManager);
event.setParent(file);
event.setFile(file);
if (file instanceof PsiFileImpl && ((PsiFileImpl)file).isContentsLoaded()) {
event.setOffset(0);
event.setOldLength(file.getTextLength());
}
myManager.beforeChildrenChange(event);
if (file instanceof PsiFileImpl) {
PsiFileImpl fileImpl = (PsiFileImpl)file;
fileImpl.subtreeChanged(); // important! otherwise cached information is not released
if (fileImpl.isContentsLoaded()) {
((PsiFileImpl)file).unloadContent();
}
}
else if (file instanceof ClsFileImpl) {
if (((ClsFileImpl)file).isContentsLoaded()) {
((ClsFileImpl)file).unloadContent();
}
}
file.setModificationStamp(vFile.getModificationStamp());
myManager.childrenChanged(event);
}
}
}
private void clearNonRepositoryMaps() {
myNameToClassMap.clear();
}
private class MyVirtualFileListener extends VirtualFileAdapter {
public void contentsChanged(final VirtualFileEvent event) {
// handled by FileDocumentManagerListener
}
public void fileCreated(VirtualFileEvent event) {
if (!myUseRepository) {
clearNonRepositoryMaps();
}
final VirtualFile vFile = event.getFile();
ApplicationManager.getApplication().runWriteAction(
new PsiExternalChangeAction() {
public void run() {
PsiDirectory parentDir = myVFileToPsiDirMap.get(vFile.getParent());
if (parentDir == null) return; // do not notifyListeners event if parent directory was never accessed via PSI
if (!vFile.isDirectory()) {
PsiFile psiFile = findFile(vFile);
if (psiFile != null) {
PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
treeEvent.setParent(parentDir);
myManager.beforeChildAddition(treeEvent);
treeEvent.setChild(psiFile);
myManager.childAdded(treeEvent);
}
}
else {
PsiDirectory psiDir = findDirectory(vFile);
if (psiDir != null) {
PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
treeEvent.setParent(parentDir);
myManager.beforeChildAddition(treeEvent);
treeEvent.setChild(psiDir);
myManager.childAdded(treeEvent);
}
}
}
}
);
}
public void beforeFileDeletion(VirtualFileEvent event) {
if (!myUseRepository) {
clearNonRepositoryMaps();
}
final VirtualFile vFile = event.getFile();
final PsiDirectory parentDir = myVFileToPsiDirMap.get(vFile.getParent());
if (parentDir == null) return; // do not notify listeners if parent directory was never accessed via PSI
ApplicationManager.getApplication().runWriteAction(
new PsiExternalChangeAction() {
public void run() {
if (!vFile.isDirectory()) {
PsiFile psiFile = findFile(vFile);
if (psiFile != null) {
PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
treeEvent.setParent(parentDir);
treeEvent.setChild(psiFile);
myManager.beforeChildRemoval(treeEvent);
}
}
else {
PsiDirectory psiDir = findDirectory(vFile);
if (psiDir != null) {
PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
treeEvent.setParent(parentDir);
treeEvent.setChild(psiDir);
myManager.beforeChildRemoval(treeEvent);
}
}
}
}
);
}
public void fileDeleted(final VirtualFileEvent event) {
if (!myUseRepository) {
clearNonRepositoryMaps();
}
final VirtualFile vFile = event.getFile();
final PsiDirectory parentDir = myVFileToPsiDirMap.get(event.getParent());
if (!event.isDirectory()) {
final PsiFile psiFile = getCachedPsiFileInner(vFile);
if (psiFile != null) {
cachePsiFile(vFile, null);
if (parentDir != null) {
ApplicationManager.getApplication().runWriteAction(
new PsiExternalChangeAction() {
public void run() {
PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
treeEvent.setParent(parentDir);
treeEvent.setChild(psiFile);
myManager.childRemoved(treeEvent);
}
}
);
}
}
}
else {
final PsiDirectory psiDir = myVFileToPsiDirMap.get(vFile);
if (psiDir != null) {
removeInvalidFilesAndDirs(false);
if (parentDir != null) {
ApplicationManager.getApplication().runWriteAction(
new PsiExternalChangeAction() {
public void run() {
PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
treeEvent.setParent(parentDir);
treeEvent.setChild(psiDir);
myManager.childRemoved(treeEvent);
}
}
);
}
}
}
}
public void beforePropertyChange(final VirtualFilePropertyEvent event) {
if (!myUseRepository) {
clearNonRepositoryMaps();
}
final VirtualFile vFile = event.getFile();
final String propertyName = event.getPropertyName();
final PsiDirectory parentDir = myVFileToPsiDirMap.get(vFile.getParent());
if (parentDir == null) return; // do not notifyListeners event if parent directory was never accessed via PSI
ApplicationManager.getApplication().runWriteAction(
new PsiExternalChangeAction() {
public void run() {
PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
treeEvent.setParent(parentDir);
if (VirtualFile.PROP_NAME.equals(propertyName)) {
final String newName = (String)event.getNewValue();
if (vFile.isDirectory()) {
PsiDirectory psiDir = findDirectory(vFile);
if (psiDir != null) {
if (!myFileTypeManager.isFileIgnored(newName)) {
treeEvent.setChild(psiDir);
treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_DIRECTORY_NAME);
treeEvent.setOldValue(vFile.getName());
treeEvent.setNewValue(newName);
myManager.beforePropertyChange(treeEvent);
}
else {
treeEvent.setChild(psiDir);
myManager.beforeChildRemoval(treeEvent);
}
}
else {
if (!isExcludeRoot(vFile) && !myFileTypeManager.isFileIgnored(newName)) {
myManager.beforeChildAddition(treeEvent);
}
}
}
else {
PsiFile psiFile = findFile(vFile);
PsiFile psiFile1 = createPsiFile(vFile, newName);
if (psiFile != null) {
if (psiFile1 == null) {
treeEvent.setChild(psiFile);
myManager.beforeChildRemoval(treeEvent);
}
else if (!psiFile1.getClass().equals(psiFile.getClass())) {
treeEvent.setOldChild(psiFile);
myManager.beforeChildReplacement(treeEvent);
}
else {
treeEvent.setChild(psiFile);
treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_FILE_NAME);
treeEvent.setOldValue(vFile.getName());
treeEvent.setNewValue(newName);
myManager.beforePropertyChange(treeEvent);
}
}
else {
if (psiFile1 != null) {
myManager.beforeChildAddition(treeEvent);
}
}
}
}
else if (VirtualFile.PROP_WRITABLE.equals(propertyName)) {
PsiFile psiFile = getCachedPsiFileInner(vFile);
if (psiFile == null) return;
treeEvent.setElement(psiFile);
treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_WRITABLE);
treeEvent.setOldValue(event.getOldValue());
treeEvent.setNewValue(event.getNewValue());
myManager.beforePropertyChange(treeEvent);
}
}
}
);
}
private boolean isExcludeRoot(VirtualFile file) {
VirtualFile parent = file.getParent();
Module module = myProjectRootManager.getFileIndex().getModuleForFile(parent);
if (module == null) return false;
VirtualFile[] excludeRoots = ModuleRootManager.getInstance(module).getExcludeRoots();
for (VirtualFile root : excludeRoots) {
if (root.equals(file)) return true;
}
return false;
}
public void propertyChanged(final VirtualFilePropertyEvent event) {
if (!myUseRepository) {
clearNonRepositoryMaps();
}
final String propertyName = event.getPropertyName();
final VirtualFile vFile = event.getFile();
final PsiDirectory parentDir = myVFileToPsiDirMap.get(vFile.getParent());
if (parentDir == null) {
boolean fire = VirtualFile.PROP_NAME.equals(propertyName) &&
vFile.isDirectory();
if (fire) {
PsiDirectory psiDir = myVFileToPsiDirMap.get(vFile);
fire = psiDir != null;
}
if (!fire) return; // do not fire event if parent directory was never accessed via PSI
}
ApplicationManager.getApplication().runWriteAction(
new PsiExternalChangeAction() {
public void run() {
PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
treeEvent.setParent(parentDir);
if (VirtualFile.PROP_NAME.equals(propertyName)) {
if (vFile.isDirectory()) {
PsiDirectory psiDir = myVFileToPsiDirMap.get(vFile);
if (psiDir != null) {
if (myFileTypeManager.isFileIgnored(vFile.getName())) {
removeFilesAndDirsRecursively(vFile);
treeEvent.setChild(psiDir);
myManager.childRemoved(treeEvent);
}
else {
treeEvent.setElement(psiDir);
treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_DIRECTORY_NAME);
treeEvent.setOldValue(event.getOldValue());
treeEvent.setNewValue(event.getNewValue());
myManager.propertyChanged(treeEvent);
}
}
else {
PsiDirectory psiDir1 = findDirectory(vFile);
if (psiDir1 != null) {
treeEvent.setChild(psiDir1);
myManager.childAdded(treeEvent);
}
}
}
else {
PsiFile psiFile = getCachedPsiFileInner(vFile);
if (psiFile != null) {
PsiFile psiFile1 = createPsiFile(vFile, vFile.getName());
if (psiFile1 == null) {
cachePsiFile(vFile, null);
treeEvent.setChild(psiFile);
myManager.childRemoved(treeEvent);
}
else if (!psiFile1.getClass().equals(psiFile.getClass()) ||
psiFile1.getFileType() != myFileTypeManager.getFileTypeByFileName((String)event.getOldValue())
) {
cachePsiFile(vFile, null);
treeEvent.setOldChild(psiFile);
treeEvent.setNewChild(psiFile1);
myManager.childReplaced(treeEvent);
}
else {
treeEvent.setElement(psiFile);
treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_FILE_NAME);
treeEvent.setOldValue(event.getOldValue());
treeEvent.setNewValue(event.getNewValue());
myManager.propertyChanged(treeEvent);
}
}
else {
PsiFile psiFile1 = findFile(vFile);
if (psiFile1 != null) {
treeEvent.setChild(psiFile1);
myManager.childAdded(treeEvent);
}
}
}
}
else if (VirtualFile.PROP_WRITABLE.equals(propertyName)) {
PsiFile psiFile = getCachedPsiFileInner(vFile);
if (psiFile == null) return;
treeEvent.setElement(psiFile);
treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_WRITABLE);
treeEvent.setOldValue(event.getOldValue());
treeEvent.setNewValue(event.getNewValue());
myManager.propertyChanged(treeEvent);
}
}
}
);
}
public void beforeFileMovement(VirtualFileMoveEvent event) {
final VirtualFile vFile = event.getFile();
final PsiDirectory oldParentDir = findDirectory(event.getOldParent());
final PsiDirectory newParentDir = findDirectory(event.getNewParent());
if (oldParentDir == null && newParentDir == null) return;
if (myFileTypeManager.isFileIgnored(vFile.getName())) return;
ApplicationManager.getApplication().runWriteAction(
new PsiExternalChangeAction() {
public void run() {
PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
boolean isExcluded = vFile.isDirectory() && myProjectFileIndex.isIgnored(vFile);
if (oldParentDir != null && !isExcluded) {
if (newParentDir != null) {
treeEvent.setOldParent(oldParentDir);
treeEvent.setNewParent(newParentDir);
if (vFile.isDirectory()) {
PsiDirectory psiDir = findDirectory(vFile);
treeEvent.setChild(psiDir);
}
else {
PsiFile psiFile = findFile(vFile);
treeEvent.setChild(psiFile);
}
myManager.beforeChildMovement(treeEvent);
}
else {
treeEvent.setParent(oldParentDir);
if (vFile.isDirectory()) {
PsiDirectory psiDir = findDirectory(vFile);
treeEvent.setChild(psiDir);
}
else {
PsiFile psiFile = findFile(vFile);
treeEvent.setChild(psiFile);
}
myManager.beforeChildRemoval(treeEvent);
}
}
else {
LOG.assertTrue(newParentDir != null); // checked above
treeEvent.setParent(newParentDir);
myManager.beforeChildAddition(treeEvent);
}
}
}
);
}
public void fileMoved(VirtualFileMoveEvent event) {
if (!myUseRepository) {
clearNonRepositoryMaps();
}
final VirtualFile vFile = event.getFile();
final PsiDirectory oldParentDir = findDirectory(event.getOldParent());
final PsiDirectory newParentDir = findDirectory(event.getNewParent());
if (oldParentDir == null && newParentDir == null) return;
final PsiElement oldElement = vFile.isDirectory() ? myVFileToPsiDirMap.get(vFile) : getCachedPsiFileInner(vFile);
removeInvalidFilesAndDirs(true);
final PsiElement newElement = vFile.isDirectory() ? findDirectory(vFile) : findFile(vFile);
if (oldElement == null && newElement == null) return;
if (oldElement != null && newElement != null) {
if (oldElement != newElement) {
// [dsl] fix for 24136: if one cuts file from non-source-dir, and pastes it into source dir
// the above holds
ApplicationManager.getApplication().runWriteAction(new PsiExternalChangeAction() {
public void run() {
PsiTreeChangeEventImpl treeRemoveEvent = new PsiTreeChangeEventImpl(myManager);
treeRemoveEvent.setParent(oldParentDir);
treeRemoveEvent.setChild(oldElement);
myManager.childRemoved(treeRemoveEvent);
PsiTreeChangeEventImpl treeAddEvent = new PsiTreeChangeEventImpl(myManager);
treeAddEvent.setParent(newParentDir);
treeAddEvent.setChild(newElement);
myManager.childAdded(treeAddEvent);
}
});
return;
}
}
ApplicationManager.getApplication().runWriteAction(
new PsiExternalChangeAction() {
public void run() {
PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
if (oldElement != null) {
if (newElement != null) {
treeEvent.setOldParent(oldParentDir);
treeEvent.setNewParent(newParentDir);
treeEvent.setChild(newElement);
myManager.childMoved(treeEvent);
}
else {
treeEvent.setParent(oldParentDir);
treeEvent.setChild(oldElement);
myManager.childRemoved(treeEvent);
}
}
else {
LOG.assertTrue(newElement != null); // checked above
treeEvent.setParent(newParentDir);
treeEvent.setChild(newElement);
myManager.childAdded(treeEvent);
}
}
}
);
}
private void removeFilesAndDirsRecursively(VirtualFile vFile) {
if (vFile.isDirectory()) {
myVFileToPsiDirMap.remove(vFile);
VirtualFile[] children = vFile.getChildren();
for (VirtualFile child : children) {
removeFilesAndDirsRecursively(child);
}
}
else {
cachePsiFile(vFile, null);
}
}
}
private class MyModuleRootListener implements ModuleRootListener {
private VirtualFile[] myOldContentRoots = null;
public void beforeRootsChange(final ModuleRootEvent event) {
if (!myInitialized) return;
if (event.isCausedByFileTypesChange()) return;
ApplicationManager.getApplication().runWriteAction(
new PsiExternalChangeAction() {
public void run() {
PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_ROOTS);
final VirtualFile[] contentRoots = myProjectRootManager.getContentRoots();
LOG.assertTrue(myOldContentRoots == null);
myOldContentRoots = contentRoots;
treeEvent.setOldValue(contentRoots);
myManager.beforePropertyChange(treeEvent);
}
}
);
}
public void rootsChanged(final ModuleRootEvent event) {
dispatchPendingEvents();
myNontrivialPackagePrefixes = null;
if (!myInitialized) return;
if (!myUseRepository) {
clearNonRepositoryMaps();
}
if (event.isCausedByFileTypesChange()) return;
ApplicationManager.getApplication().runWriteAction(
new PsiExternalChangeAction() {
public void run() {
RepositoryManager repositoryManager = myManager.getRepositoryManager();
removeInvalidFilesAndDirs(true);
if (repositoryManager != null) {
repositoryManager.updateByRootsChange();
}
PsiTreeChangeEventImpl treeEvent = new PsiTreeChangeEventImpl(myManager);
treeEvent.setPropertyName(PsiTreeChangeEvent.PROP_ROOTS);
final VirtualFile[] contentRoots = myProjectRootManager.getContentRoots();
treeEvent.setNewValue(contentRoots);
LOG.assertTrue(myOldContentRoots != null);
treeEvent.setOldValue(myOldContentRoots);
myOldContentRoots = null;
myManager.propertyChanged(treeEvent);
}
}
);
}
}
@SuppressWarnings({"HardCodedStringLiteral"})
public void dumpFilesWithContentLoaded(Writer out) throws IOException {
out.write("Files with content loaded cached in FileManagerImpl:\n");
Set<FileCacheEntry> vFiles = myVFileToPsiFileMap.keySet();
for (FileCacheEntry fileCacheEntry : vFiles) {
final PsiFile psiFile = myVFileToPsiFileMap.get(fileCacheEntry);
if (psiFile instanceof PsiFileImpl && ((PsiFileImpl)psiFile).isContentsLoaded()) {
out.write(fileCacheEntry.getFirst().getPresentableUrl());
out.write("\n");
}
}
}
private static class LibrariesOnlyScope extends GlobalSearchScope {
private final GlobalSearchScope myOriginal;
public LibrariesOnlyScope(final GlobalSearchScope original) {
myOriginal = original;
}
public boolean contains(VirtualFile file) {
return myOriginal.contains(file);
}
public int compare(VirtualFile file1, VirtualFile file2) {
return myOriginal.compare(file1, file2);
}
public boolean isSearchInModuleContent(Module aModule) {
return false;
}
public boolean isSearchInLibraries() {
return true;
}
}
public static class FileCacheEntry {
public final VirtualFile first;
public final Language second;
public FileCacheEntry(VirtualFile first, Language second) {
this.first = first;
this.second = second;
}
public VirtualFile getFirst() {
return first;
}
public Language getSecond() {
return second;
}
public boolean equals(Object o){
return o instanceof FileCacheEntry && Comparing.equal(first, ((FileCacheEntry)o).first)
&& (Comparing.equal(second, ((FileCacheEntry)o).second) || second == Language.ANY || ((FileCacheEntry)o).second == Language.ANY);
}
public int hashCode(){
return first.hashCode();
}
public String toString() {
return "<" + first + "," + second + ">";
}
}
} |
package com.example.jeson.textviewdemo3;
import android.graphics.drawable.Drawable;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView pt_tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pt_tv = (TextView) findViewById(R.id.pt_tv);
Drawable[] drawable = pt_tv.getCompoundDrawables();
drawable[1].setBounds(100, 0, 200, 200);
pt_tv.setCompoundDrawables(drawable[0], drawable[1], drawable[2],
drawable[3]);
}
} |
package edu.wustl.cab2b.common.util;
import static edu.wustl.cab2b.common.util.Constants.CONNECTOR;
import static edu.wustl.cab2b.common.util.Constants.PROJECT_VERSION;
import static edu.wustl.cab2b.common.util.Constants.TYPE_CATEGORY;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import edu.common.dynamicextensions.domain.BooleanAttributeTypeInformation;
import edu.common.dynamicextensions.domain.DateAttributeTypeInformation;
import edu.common.dynamicextensions.domain.DoubleAttributeTypeInformation;
import edu.common.dynamicextensions.domain.FloatAttributeTypeInformation;
import edu.common.dynamicextensions.domain.IntegerAttributeTypeInformation;
import edu.common.dynamicextensions.domain.LongAttributeTypeInformation;
import edu.common.dynamicextensions.domain.StringAttributeTypeInformation;
import edu.common.dynamicextensions.domaininterface.AbstractAttributeInterface;
import edu.common.dynamicextensions.domaininterface.AbstractMetadataInterface;
import edu.common.dynamicextensions.domaininterface.AssociationInterface;
import edu.common.dynamicextensions.domaininterface.AttributeInterface;
import edu.common.dynamicextensions.domaininterface.AttributeTypeInformationInterface;
import edu.common.dynamicextensions.domaininterface.EntityGroupInterface;
import edu.common.dynamicextensions.domaininterface.EntityInterface;
import edu.common.dynamicextensions.domaininterface.PermissibleValueInterface;
import edu.common.dynamicextensions.domaininterface.TaggedValueInterface;
import edu.common.dynamicextensions.domaininterface.UserDefinedDEInterface;
import edu.wustl.cab2b.common.errorcodes.ErrorCodeConstants;
import edu.wustl.cab2b.common.exception.RuntimeException;
import edu.wustl.cab2b.common.queryengine.result.IQueryResult;
import edu.wustl.cab2b.common.queryengine.result.IRecord;
import edu.wustl.common.querysuite.metadata.associations.IAssociation;
import edu.wustl.common.querysuite.metadata.path.IPath;
import edu.wustl.common.querysuite.queryobject.DataType;
import edu.wustl.common.util.logger.Logger;
/**
* Utility Class contain general methods used through out the application.
*
* @author Chandrakant Talele
* @author Gautam Shetty
*/
public class Utility {
/**
* Checks whether passed attribute/association is inheriated.
*
* @param abstractAttribute Attribute/Association to check.
* @return TRUE if it is inherited else returns FALSE
*/
public static boolean isInherited(AbstractAttributeInterface abstractAttribute) {
for (TaggedValueInterface tag : abstractAttribute.getTaggedValueCollection()) {
if (tag.getKey().equals(Constants.TYPE_DERIVED)) {
return true;
}
}
return false;
}
/**
* @param association Association
* @return Unique string to represent given association
*/
public static String generateUniqueId(AssociationInterface association) {
return concatStrings(association.getEntity().getName(), association.getSourceRole().getName(),
association.getTargetRole().getName(), association.getTargetEntity().getName());
}
/**
* @param s1 String
* @param s2 String
* @param s3 String
* @param s4 String
* @return Concatenated string made after connecting s1, s2, s3, s4 by
* {@link Constants#CONNECTOR}
*/
public static String concatStrings(String s1, String s2, String s3, String s4) {
StringBuffer buff = new StringBuffer();
buff.append(s1);
buff.append(CONNECTOR);
buff.append(s2);
buff.append(CONNECTOR);
buff.append(s3);
buff.append(CONNECTOR);
buff.append(s4);
return buff.toString();
}
/**
* Compares whether given searchPattern is present in passed searchString
*
* @param searchPattern search Pattern to look for
* @param searchString String which is to be searched
* @return Returns TRUE if given searchPattern is present in searchString ,
* else return returns false.
*/
public static boolean compareRegEx(String searchPattern, String searchString) {
searchPattern = searchPattern.replace("*", ".*");
Pattern pat = Pattern.compile(searchPattern, Pattern.CASE_INSENSITIVE);
Matcher mat = pat.matcher(searchString);
return mat.matches();
}
/**
* Returns all the URLs of the deployed services which are exposing given
* entity
*
* @param entity Entity to check
* @return Returns the List of URLs
*/
public static String[] getServiceURLS(EntityInterface entity) {
EntityGroupInterface eg = getEntityGroup(entity);
String shortName = eg.getShortName();
return PropertyLoader.getServiceUrls(shortName);
}
/**
* Returns the entity group of given entity
*
* @param entity Entity to check
* @return Returns parent Entity Group
*/
public static EntityGroupInterface getEntityGroup(EntityInterface entity) {
for (EntityGroupInterface entityGroup : entity.getEntityGroupCollection()) {
Collection<TaggedValueInterface> taggedValues = entityGroup.getTaggedValueCollection();
if (getTaggedValue(taggedValues, Constants.CAB2B_ENTITY_GROUP) != null) {
return entityGroup;
}
}
throw new RuntimeException("This entity does not have DE entity group", new java.lang.RuntimeException(),
ErrorCodeConstants.DE_0003);
}
/**
* @param taggedValues collection of TaggedValueInterface
* @param key string
* @return The tagged value for given key in given tagged value collection.
*/
public static TaggedValueInterface getTaggedValue(Collection<TaggedValueInterface> taggedValues, String key) {
for (TaggedValueInterface taggedValue : taggedValues) {
if (taggedValue.getKey().equals(key)) {
return taggedValue;
}
}
return null;
}
/**
* @param taggable taggable object
* @param key string
* @return The tagged value for given key.
*/
public static TaggedValueInterface getTaggedValue(AbstractMetadataInterface taggable, String key) {
return getTaggedValue(taggable.getTaggedValueCollection(), key);
}
/**
* Checks whether passed Entity is a category or not.
*
* @param entity Entity to check
* @return Returns TRUE if given entity is Category, else returns false.
*/
public static boolean isCategory(EntityInterface entity) {
TaggedValueInterface tag = getTaggedValue(entity.getTaggedValueCollection(), TYPE_CATEGORY);
return tag != null;
}
/**
* Converts DE datatype to queryObject dataType.
*
* @param type the DE attribute type.
* @return the DataType.
*/
public static DataType getDataType(AttributeTypeInformationInterface type) {
if (type instanceof StringAttributeTypeInformation) {
return DataType.String;
} else if (type instanceof DoubleAttributeTypeInformation) {
return DataType.Double;
} else if (type instanceof IntegerAttributeTypeInformation) {
return DataType.Integer;
} else if (type instanceof DateAttributeTypeInformation) {
return DataType.Date;
} else if (type instanceof FloatAttributeTypeInformation) {
return DataType.Float;
} else if (type instanceof BooleanAttributeTypeInformation) {
return DataType.Boolean;
} else if (type instanceof LongAttributeTypeInformation) {
return DataType.Long;
} else {
throw new RuntimeException("Unknown Attribute type");
}
}
/**
* @param attribute Check will be done for this Attribute.
* @return TRUE if there are any permissible values associated with this
* attribute, otherwise returns false.
*/
public static boolean isEnumerated(AttributeInterface attribute) {
if (attribute.getAttributeTypeInformation().getDataElement() instanceof UserDefinedDEInterface) {
UserDefinedDEInterface de = (UserDefinedDEInterface) attribute.getAttributeTypeInformation().getDataElement();
return de.getPermissibleValueCollection().size() != 0;
}
return false;
}
/**
* @param attribute Attribute to process.
* @return Returns all the permissible values associated with this
* attribute.
*/
public static Collection<PermissibleValueInterface> getPermissibleValues(AttributeInterface attribute) {
if (isEnumerated(attribute)) {
UserDefinedDEInterface de = (UserDefinedDEInterface) attribute.getAttributeTypeInformation().getDataElement();
return de.getPermissibleValueCollection();
}
return new ArrayList<PermissibleValueInterface>(0);
}
/**
* Returns the display name if present as tagged value. Else returns the
* actual name of the entity
*
* @param entity The entity to process
* @return The display name.
*/
public static String getDisplayName(EntityInterface entity) {
String name = entity.getName();
if (isCategory(entity)) {
return name;
}
EntityGroupInterface eg = getEntityGroup(entity);
String version = "";
for (TaggedValueInterface tag : eg.getTaggedValueCollection()) {
if (tag.getKey().equals(PROJECT_VERSION)) {
version = tag.getValue();
break;
}
}
// As per Bug# 4577 <class name> (app_name v<version name) e.g.
// Participant (caTissue Core v1.1)
String projectName = eg.getLongName();
if (projectName.equals("caFE Server 1.1")) {
projectName = "caFE Server";
}
StringBuffer buff = new StringBuffer();
buff.append(name.substring(name.lastIndexOf(".") + 1, name.length()));
buff.append(" (");
buff.append(projectName);
buff.append(" v");
buff.append(version);
buff.append(")");
;
return buff.toString();
}
/**
* @param path A IPath object
* @return Display string for given path
*/
public static String getPathDisplayString(IPath path) {
String text = "<HTML><B>Path</B>:";
// text=text.concat("<HTML><B>Path</B>:");
List<IAssociation> pathList = path.getIntermediateAssociations();
text = text.concat(Utility.getDisplayName(path.getSourceEntity()));
for (int i = 0; i < pathList.size(); i++) {
text = text.concat("<B>
text = text.concat(Utility.getDisplayName(pathList.get(i).getTargetEntity()));
}
text = text.concat("</HTML>");
Logger.out.debug(text);
StringBuffer sb = new StringBuffer();
int textLength = text.length();
Logger.out.debug(textLength);
int currentStart = 0;
String currentString = null;
int offset = 100;
int strLen = 0;
int len = 0;
while (currentStart < textLength && textLength > offset) {
currentString = text.substring(currentStart, (currentStart + offset));
strLen = strLen + currentString.length() + len;
sb.append(currentString);
int index = text.indexOf("<B>----></B>", (currentStart + offset));
if (index != -1) {
len = index - strLen;
currentString = text.substring((currentStart + offset), (currentStart + offset + len));
sb.append(currentString);
sb.append("<P>");
} else {
sb.append(text.substring(currentStart));
return sb.toString();
}
currentStart = currentStart + offset + len;
if ((currentStart + offset + len) > textLength)
break;
}
sb.append(text.substring(currentStart));
return sb.toString();
}
/**
* @param entity Entity to check
* @return Attribute whose name is "identifier" OR "id"
*/
public static AttributeInterface getIdAttribute(EntityInterface entity) {
for (AttributeInterface attribute : entity.getAttributeCollection()) {
if (isIdentifierAttribute(attribute)) {
return attribute;
}
}
return null;
}
// /**
// * Returns true if an application returns associatied objects information in
// * result of CQLs.
// *
// * @param entity Entity to check
// * @return true/false
// */
// public static boolean isOutGoingAssociationSupported(EntityInterface entity) {
// EntityGroupInterface eg = getEntityGroup(entity);
// String shortName = eg.getShortName();
// boolean isOutGoingAssociationSupported = false;
// String supportOutGoingAssociation = props.getProperty(shortName + ".supportOutGoingAssociation");
// if (supportOutGoingAssociation != null && supportOutGoingAssociation.equalsIgnoreCase("true")) {
// isOutGoingAssociationSupported = true;
// return isOutGoingAssociationSupported;
/**
* @param entity Entity to check
* @return Name of the application to which given entity belongs
*/
public static String getApplicationName(EntityInterface entity) {
return getEntityGroup(entity).getName();
}
/**
* @param attribute Attribute to check
* @return TRUE if attribute name is "identifier" OR "id"
*/
public static boolean isIdentifierAttribute(AttributeInterface attribute) {
String attribName = attribute.getName();
return attribName.equalsIgnoreCase("id") || attribName.equalsIgnoreCase("identifier");
}
/**
* Converts attribute set into a alphabatically sorted list.
*
* @param inputAttributeSet Attribute set to sort
* @return Sorted list of attributes
*/
public static List<AttributeInterface> getAttributeList(Set<AttributeInterface> inputAttributeSet) {
List<AttributeInterface> attributes = new ArrayList<AttributeInterface>(inputAttributeSet);
Collections.sort(attributes, new AttributeInterfaceComparator());
return attributes;
}
/**
* @param queryResult Query result to process.
* @return Total no of records present in query set (i.e for all services)
*/
public static int getNoOfRecords(IQueryResult queryResult) {
int size = 0;
Map<String, List<IRecord>> allRecords = queryResult.getRecords();
for (List<IRecord> valueList : allRecords.values()) {
size += valueList.size();
}
return size;
}
/**
* @param queryResult Query result to process.
* @return List of attributes from query result
*/
public static List<AttributeInterface> getAttributeList(IQueryResult queryResult) {
Map<String, List<IRecord>> allRecords = queryResult.getRecords();
List<AttributeInterface> attributeList = new ArrayList<AttributeInterface>();
if (!allRecords.isEmpty()) {
List<IRecord> recordList = allRecords.values().iterator().next();
if (!recordList.isEmpty()) {
IRecord record = recordList.get(0);
attributeList = getAttributeList(record.getAttributes());
}
}
return attributeList;
}
/**
* This method converts stack trace to the string representation
* @param aThrowable throwable object
* @return String representation of the stack trace
*/
public static String getStackTrace(Throwable throwable)
{
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
throwable.printStackTrace(printWriter);
return result.toString();
}
} |
package com.aayaffe.sailingracecoursemanager.communication;
import java.io.Serializable;
public enum ObjectTypes {
WorkerBoat,
FlagBuoy,
TomatoBuoy,
TriangleBuoy,
StartLine,
FinishLine,
StartFinishLine,
RaceManager, //from here, the relevant ObjectTypes:
Buoy,
Gate,
Satellite,
ReferencePoint,
Other
} |
package com.ambergleam.android.photogallery.controller;
import android.app.SearchManager;
import android.app.SearchableInfo;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.ActivityOptionsCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.SearchView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import com.ambergleam.android.photogallery.R;
import com.ambergleam.android.photogallery.base.BaseFragment;
import com.ambergleam.android.photogallery.model.Photo;
import com.ambergleam.android.photogallery.util.PreferenceUtils;
import com.ambergleam.android.photogallery.web.FlickrFetchr;
import com.facebook.appevents.AppEventsLogger;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
import butterknife.ButterKnife;
import butterknife.InjectView;
import timber.log.Timber;
public class GalleryFragment extends BaseFragment {
private ArrayList<Photo> mPhotos;
@InjectView(R.id.fragment_gallery_refresh) SwipeRefreshLayout mSwipeRefreshLayout;
@InjectView(R.id.fragment_gallery_grid) GridView mGridView;
public static GalleryFragment newInstance() {
return new GalleryFragment();
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
search();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
ButterKnife.inject(this, view);
setupAdapter();
setupListeners();
return view;
}
@Override
public void onResume() {
super.onResume();
AppEventsLogger.activateApp(getActivity());
}
@Override
public void onPause() {
super.onPause();
AppEventsLogger.deactivateApp(getActivity());
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
inflater.inflate(R.menu.fragment_gallery, menu);
MenuItem menuItem = menu.findItem(R.id.menu_item_gallery_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setOnCloseListener(() -> {
PreferenceUtils.setSearchQuery(getActivity(), null);
return false;
});
SearchManager searchManager = (SearchManager) getActivity().getSystemService(Context.SEARCH_SERVICE);
ComponentName name = getActivity().getComponentName();
SearchableInfo searchInfo = searchManager.getSearchableInfo(name);
searchView.setSearchableInfo(searchInfo);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_gallery_history:
Intent intentHistory = new Intent(getActivity(), HistoryActivity.class);
startActivity(intentHistory);
return true;
case R.id.menu_item_gallery_settings:
Intent intentSettings = new Intent(getActivity(), SettingsActivity.class);
startActivity(intentSettings);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void setupAdapter() {
if (getActivity() == null || mGridView == null) {
return;
}
if (mPhotos != null) {
mGridView.setAdapter(new PhotoGridViewAdapter(mPhotos));
} else {
mGridView.setAdapter(null);
}
}
private void setupListeners() {
mGridView.setOnItemClickListener((gridView, gridItem, position, id) -> {
Intent intent = new Intent(getActivity(), PhotoActivity.class);
intent.putExtra(PhotoFragment.ARGS_PHOTO, mPhotos.get(position));
ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(
getActivity(),
gridItem,
getString(R.string.transition_photo)
);
ActivityCompat.startActivity(getActivity(), intent, options.toBundle());
});
mSwipeRefreshLayout.setOnRefreshListener(() -> search());
mSwipeRefreshLayout.setColorSchemeResources(R.color.primary, R.color.accent);
}
public void search() {
new SearchAsyncTask().execute();
}
private class SearchAsyncTask extends AsyncTask<Void, Void, ArrayList<Photo>> {
@Override
protected ArrayList<Photo> doInBackground(Void... params) {
if (getActivity() == null) {
return new ArrayList<>();
}
String query = PreferenceUtils.getSearchQuery(getActivity());
Timber.i("Search Query: " + query);
if (query != null) {
return new FlickrFetchr().getPhotos(query);
} else {
return new FlickrFetchr().getPhotos();
}
}
@Override
protected void onPostExecute(ArrayList<Photo> items) {
mPhotos = items;
if (items.size() > 0) {
String resultId = items.get(0).getId();
PreferenceUtils.setLastResultId(getActivity(), resultId);
}
setupAdapter();
mSwipeRefreshLayout.setRefreshing(false);
}
}
private class PhotoGridViewAdapter extends ArrayAdapter<Photo> {
public PhotoGridViewAdapter(ArrayList<Photo> items) {
super(getActivity(), 0, items);
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = getActivity().getLayoutInflater().inflate(R.layout.grid_item_gallery, parent, false);
}
Photo item = getItem(position);
ImageView imageView = (ImageView) convertView.findViewById(R.id.grid_item_gallery_image);
Picasso.with(getActivity())
.load(item.getUrl())
.into(imageView);
return convertView;
}
}
} |
package com.birdbraintechnologies.birdblocks.bluetooth;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Helper class for basic bluetooth connectivity
*
* @author Terence Sun (tsun1215)
*/
public class BluetoothHelper {
private static final String TAG = "BluetoothHelper";
private static final int SCAN_DURATION = 900; /* Length of time to perform a scan */
private BluetoothAdapter btAdapter;
private Handler handler;
private boolean btScanning;
private Context context;
private HashMap<String, BluetoothDevice> deviceList;
/* Callback for populating the device list */
private ScanCallback populateDevices = new ScanCallback() {
@Override
public void onScanResult(int callbackType, ScanResult result) {
synchronized (deviceList) {
deviceList.put(result.getDevice().getAddress(), result.getDevice());
}
}
};
/**
* Initializes a Bluetooth helper
*
* @param context Context that bluetooth is being used by
*/
public BluetoothHelper(Context context) {
this.context = context;
this.btScanning = false;
this.handler = new Handler();
this.deviceList = new HashMap<>();
// Acquire Bluetooth service
final BluetoothManager btManager =
(BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE);
this.btAdapter = btManager.getAdapter();
// Ask to enable Bluetooth if disabled
if (!btAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
enableBtIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(enableBtIntent);
}
}
/**
* Scans for Bluetooth devices that matches the filter.
*
* @param scanFilters List of bluetooth.le.ScanFilter to filter by
* @return List of devices that matches the filters
*/
synchronized public List<BluetoothDevice> scanDevices(List<ScanFilter> scanFilters) {
final BluetoothLeScanner scanner = btAdapter.getBluetoothLeScanner();
// Schedule thread to stop scanning after SCAN_DURATION
handler.postDelayed(new Runnable() {
@Override
public void run() {
btScanning = false;
scanner.stopScan(populateDevices);
}
}, SCAN_DURATION);
// Start scanning for devices
btScanning = true;
// Build scan settings (scan as fast as possible)
ScanSettings scanSettings = (new ScanSettings.Builder())
.setScanMode(ScanSettings.SCAN_MODE_LOW_LATENCY)
.build();
scanner.startScan(scanFilters, scanSettings, populateDevices);
// Wait until scanning is complete
try {
while (btScanning) {
Thread.sleep(SCAN_DURATION);
}
} catch (InterruptedException e) {
Log.e(TAG, e.toString());
}
return new ArrayList<>(deviceList.values());
}
/**
* Connects to a device and returns the resulting connection
*
* @param addr MAC Address of the device to connect to
* @param settings Settings to define the UART connection's TX and RX lines
* @return Result connection, null if the given MAC Address doesn't match any scanned device
*/
synchronized public UARTConnection connectToDeviceUART(String addr, UARTSettings settings) {
BluetoothDevice device = deviceList.get(addr);
if (device == null) {
Log.e(TAG, "Unable to connect to device: " + addr);
return null;
}
UARTConnection conn = new UARTConnection(context, device, settings);
return conn;
}
} |
package de.fau.cs.mad.kwikshop.android.viewmodel;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.inject.Inject;
import de.fau.cs.mad.kwikshop.android.R;
import de.fau.cs.mad.kwikshop.android.model.*;
import de.fau.cs.mad.kwikshop.android.model.interfaces.ListManager;
import de.fau.cs.mad.kwikshop.android.model.interfaces.SimpleStorage;
import de.fau.cs.mad.kwikshop.android.model.messages.*;
import de.fau.cs.mad.kwikshop.android.util.ItemComparator;
import de.fau.cs.mad.kwikshop.android.view.DisplayHelper;
import de.fau.cs.mad.kwikshop.android.view.ItemSortType;
import de.fau.cs.mad.kwikshop.android.viewmodel.common.*;
import de.fau.cs.mad.kwikshop.common.Group;
import de.fau.cs.mad.kwikshop.common.Item;
import de.fau.cs.mad.kwikshop.common.LastLocation;
import de.fau.cs.mad.kwikshop.common.ShoppingList;
import de.fau.cs.mad.kwikshop.common.Unit;
import se.walkercrou.places.GooglePlaces;
import se.walkercrou.places.Param;
import se.walkercrou.places.Place;
public class ShoppingListViewModel extends ListViewModel<ShoppingList> {
private final ResourceProvider resourceProvider;
private final ObservableArrayList<Item, Integer> boughtItems = new ObservableArrayList<>(new ItemIdExtractor());
private ItemSortType itemSortType = ItemSortType.MANUAL;
private final Command<Integer> toggleIsBoughtCommand = new Command<Integer>() {
@Override
public void execute(Integer parameter) { toggleIsBoughtCommandExecute(parameter); }
};
private final Command<Integer> deleteItemCommand = new Command<Integer>() {
@Override
public void execute(Integer parameter) { deleteItemCommandExecute(parameter);}
};
@Inject
public ShoppingListViewModel(ViewLauncher viewLauncher,
ListManager<ShoppingList> shoppingListManager,
SimpleStorage<Unit> unitStorage,
SimpleStorage<Group> groupStorage,
ItemParser itemParser,
DisplayHelper displayHelper,
AutoCompletionHelper autoCompletionHelper,
LocationFinderHelper locationFinderHelper,
ResourceProvider resourceProvider) {
super(viewLauncher, shoppingListManager, unitStorage, groupStorage, itemParser, displayHelper,
autoCompletionHelper, locationFinderHelper);
if (resourceProvider == null) {
throw new IllegalArgumentException("'resourceProvider' must not be null");
}
this.resourceProvider = resourceProvider;
}
/**
* Gets the shopping list items that have already been bought
*/
/*public ObservableArrayList<Item, Integer> getBoughtItems() {
return boughtItems;
}*/
/**
* Gets how items are supposed to be sorted for the current shopping list
*/
public ItemSortType getItemSortType() {
return this.itemSortType;
}
/**
* Sets how items are supposed to be sorted for the current shopping list
*/
public void setItemSortType(ItemSortType value) {
this.itemSortType = value;
}
public void sortItems() {
Collections.sort(getItems(), new ItemComparator(displayHelper, getItemSortType()));
moveBoughtItemsToEnd();
//updateOrderOfItems();
listener.onItemSortTypeChanged();
}
/**
* Gets the command to be executed when a item in the view is swiped
*/
public Command<Integer> getToggleIsBoughtCommand() {
return toggleIsBoughtCommand;
}
/**
* Gets the command to be executed when an item's delete-button is pressed
*/
public Command<Integer> getDeleteItemCommand() {
return deleteItemCommand;
}
@Override
public void itemsSwapped(int position1, int position2) {
Item item1 = items.get(position1);
Item item2 = items.get(position2);
item1.setOrder(position1);
item2.setOrder(position2);
listManager.saveListItem(listId, item1);
listManager.saveListItem(listId, item2);
}
public void setLocationOnItemBought(final int id, final String googleBrowserApiKey){
AsyncTask<Void, Void, Void> locationAsyncTask = new AsyncTask<Void, Void, Void>() {
Item item;
LastLocation location;
List<Place> places;
@Override
protected void onPreExecute() {
super.onPreExecute();
item = items.getById(id);
if(item == null) {
item = boughtItems.getById(id);
}
}
@Override
protected Void doInBackground(Void... params) {
// get location
location = locationFinderHelper.getLastLocation();
// try to get information about a location
try {
GooglePlaces client = new GooglePlaces(googleBrowserApiKey);
places = client.getNearbyPlaces(location.getLatitude(), location.getLongitude(), 200, 1, Param.name("types").value("grocery_or_supermarket"));
} catch (Exception e) {
// e.printStackTrace();
}
// place was found
if (places != null) {
location.setName(places.get(0).getName());
}
return null;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
item.setLocation(location);
listManager.saveListItem(listId, item);
}
};
if(listManager.getListItem(listId, id).getLocation() == null) {
locationAsyncTask.execute();
}
}
@SuppressWarnings("unused")
public void onEventMainThread(ShoppingListChangedEvent event) {
if(event.getListId() == this.listId) {
if(event.getChangeType() == ListChangeType.Deleted) {
finish();
} else if(event.getChangeType() == ListChangeType.PropertiesModified) {
loadList();
}
}
}
@SuppressWarnings("unused")
public void onEventMainThread(ItemChangedEvent event) {
if(event.getListId() == this.listId) {
switch (event.getChangeType()) {
case Added: // TODO: New Items are moved to the top of the list, maybe we want to change this
Item item = listManager.getListItem(listId, event.getItemId());
updateItem(item);
sortItems();
//updateOrderOfItems();
break;
case PropertiesModified:
Item item1 = listManager.getListItem(listId, event.getItemId());
updateItem(item1);
//updateOrderOfItems();
break;
case Deleted:
items.removeById(event.getItemId());
break;
}
}
}
@SuppressWarnings("unused")
public void onEventBackgroundThread(MoveAllItemsEvent event) {
boolean isBoughtNew = event.isMoveAllToBought();
ShoppingList list = listManager.getList(listId);
List<Item> changedItems = new LinkedList<>();
for(Item item : list.getItems()) {
if(item.isBought() != isBoughtNew) {
item.setBought(isBoughtNew);
changedItems.add(item);
}
}
for(Item item : changedItems) {
listManager.saveListItem(listId, item);
}
}
@SuppressWarnings("unused")
public void onEventMainThread(ItemSortType sortType) {
setItemSortType(sortType);
sortItems();
}
@Override
protected void addItemCommandExecute() {
ensureIsInitialized();
getItems().enableEvents();
viewLauncher.showItemDetailsView(this.listId);
}
@Override
protected void selectItemCommandExecute(int itemId) {
ensureIsInitialized();
viewLauncher.showItemDetailsView(this.listId, itemId);
}
@Override
protected void loadList() {
ShoppingList shoppingList = listManager.getList(this.listId);
for(Item item : shoppingList.getItems()) {
updateItem(item);
}
int sortTypeInt = shoppingList.getSortTypeInt();
switch (sortTypeInt) {
case 1:
setItemSortType(ItemSortType.GROUP);
break;
case 2:
setItemSortType(ItemSortType.ALPHABETICALLY);
break;
default:
setItemSortType(ItemSortType.MANUAL);
break;
}
sortItems();
//moveBoughtItemsToEnd();
this.setName(shoppingList.getName());
}
private void toggleIsBoughtCommandExecute(final int id) {
Item item = items.getById(id);
if(item != null) {
item.setBought(!item.isBought());
if (item.isBought()) {
if (item.isRegularlyRepeatItem() && item.isRemindFromNextPurchaseOn() && item.getLastBought() == null) {
Calendar now = Calendar.getInstance();
item.setLastBought(now.getTime());
RegularlyRepeatHelper repeatHelper = RegularlyRepeatHelper.getInstance();
//save location
Calendar remindDate = Calendar.getInstance();
switch (item.getPeriodType()) {
case DAYS:
remindDate.add(Calendar.DAY_OF_MONTH, item.getSelectedRepeatTime());
break;
case WEEKS:
remindDate.add(Calendar.DAY_OF_MONTH, item.getSelectedRepeatTime() * 7);
break;
case MONTHS:
remindDate.add(Calendar.MONTH, item.getSelectedRepeatTime());
break;
}
item.setRemindAtDate(remindDate.getTime());
repeatHelper.offerRepeatData(item);
DateFormat dateFormat = SimpleDateFormat.getDateTimeInstance(SimpleDateFormat.DEFAULT, SimpleDateFormat.DEFAULT, resourceProvider.getLocale());
String message = resourceProvider.getString(R.string.reminder_set_msg) + " " + dateFormat.format(remindDate.getTime());
viewLauncher.showToast(message, Toast.LENGTH_LONG);
}
}
listManager.saveListItem(listId, item);
}
}
private void deleteItemCommandExecute(final int id) {
listManager.deleteItem(listId, id);
}
public int getBoughtItemsCount() {
ListIterator li = items.listIterator(items.size());
int i = 0;
while(li.hasPrevious()) {
Item item = (Item)li.previous();
if(item.isBought())
i++;
else
break;
}
return i;
}
public void moveBoughtItemsToEnd() {
Collections.sort(getItems(), new ItemComparator(displayHelper, ItemSortType.BOUGHTITEMS));
}
private void updateItem(Item item) {
if(item.isBought()) { // Add bought items at the end of the list
if (items.size() - 1 >= 0) {
items.setOrAddById(items.size() - 1, item);
} else {
items.setOrAddById(item);
}
} else {
items.setOrAddById(item);
}
items.notifyItemModified(item);
}
} |
package com.chikeandroid.debtmanager20.data.source;
import com.chikeandroid.debtmanager20.data.Debt;
import com.chikeandroid.debtmanager20.data.Person;
import com.chikeandroid.debtmanager20.data.PersonDebt;
import com.chikeandroid.debtmanager20.util.TestUtil;
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.util.List;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNull;
import static junit.framework.Assert.assertTrue;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.verify;
import static org.powermock.api.mockito.PowerMockito.when;
public class DebtsRepositoryTest {
private PersonDebtsRepository mDebtsRepository;
@Mock
private PersonDebtsDataSource mDebtsLocalDataSource;
@Before
public void setUp() {
// Mockito has a very convenient way to inject mocks by using the @Mock annotation. To
// inject the mocks in the test the initMocks method needs to be called.
MockitoAnnotations.initMocks(this);
// Get a reference to the class under test
mDebtsRepository = new PersonDebtsRepository(mDebtsLocalDataSource);
}
@Test
public void shouldBeAbleToSaveOwedDebtToLocalDataSource() {
// save debt owed
Person person1 = TestUtil.getPerson();
Debt debt1 = TestUtil.createAndGetOwedDebt(person1.getId());
mDebtsRepository.savePersonDebt(debt1, person1);
verify(mDebtsLocalDataSource).savePersonDebt(eq(debt1), eq(person1));
assertThat(mDebtsRepository.getCacheOwed().size(), is(1));
}
@Test
public void shouldBeAbleToSaveIOweDebtToLocalDataSource() {
// save i owe debt
Person person2 = TestUtil.createPerson("Nkeiru Ineh", "070414741");
Debt debt2 = TestUtil.createDebt(person2.getId(), 60000000, Debt.DEBT_TYPE_IOWE,
Debt.DEBT_STATUS_ACTIVE, "");
mDebtsRepository.savePersonDebt(debt2, person2);
verify(mDebtsLocalDataSource).savePersonDebt(eq(debt2), eq(person2));
assertThat(mDebtsRepository.getCacheIOwe().size(), is(1));
}
@Test
public void shouldBeAbleGetAllDebsFromLocalDatabaseByType() {
mDebtsRepository.getAllPersonDebtsByType(Debt.DEBT_TYPE_IOWE);
verify(mDebtsLocalDataSource).getAllPersonDebtsByType(eq(Debt.DEBT_TYPE_IOWE));
mDebtsRepository.getAllPersonDebtsByType(Debt.DEBT_TYPE_OWED);
verify(mDebtsLocalDataSource).getAllPersonDebtsByType(eq(Debt.DEBT_TYPE_OWED));
}
@Test
public void shouldBeAbleToReturnNullWhenLocalDataSourceUnavailable() {
setOweMeDebtsNotAvailable(mDebtsLocalDataSource);
List<PersonDebt> returnedDebts = mDebtsRepository.getAllPersonDebts();
assertNull(returnedDebts);
}
private void setOweMeDebtsNotAvailable(PersonDebtsDataSource dataSource) {
// owe me debts
when(dataSource.getAllPersonDebts()).thenReturn(null);
}
@Test
public void shouldBeAbleToDeleteAllOwedDebts() {
Person person1 = TestUtil.getPerson();
Debt debt1 = TestUtil.createAndGetOwedDebt(person1.getId());
mDebtsRepository.savePersonDebt(debt1, person1);
verify(mDebtsLocalDataSource).savePersonDebt(eq(debt1), eq(person1));
Person person2 = TestUtil.createPerson("Emeka Onu", "07045124589");
Debt debt2 = TestUtil.createDebt(person2.getId(), 400, Debt.DEBT_TYPE_OWED,
Debt.DEBT_STATUS_ACTIVE, "note 4345");
mDebtsRepository.savePersonDebt(debt2, person2);
verify(mDebtsLocalDataSource).savePersonDebt(eq(debt2), eq(person2));
mDebtsRepository.deleteAllPersonDebtsByType(Debt.DEBT_TYPE_OWED);
verify(mDebtsLocalDataSource).deleteAllPersonDebtsByType(eq(Debt.DEBT_TYPE_OWED));
assertTrue(mDebtsRepository.mCacheOwed.size() == 0);
}
@Test
public void shouldBeAbleToGetDebtFromLocalDataSource() {
String id = "1234";
mDebtsRepository.getPersonDebt(id, Debt.DEBT_TYPE_OWED);
verify(mDebtsLocalDataSource).getPersonDebt(eq(id), eq(Debt.DEBT_TYPE_OWED));
}
@Test
public void shouldBeAbleToDeleteAPersonDebtFromLocalDataSource() {
Person person1 = TestUtil.getPerson();
Debt debt1 = TestUtil.createAndGetOwedDebt(person1.getId());
mDebtsRepository.savePersonDebt(debt1, person1);
verify(mDebtsLocalDataSource).savePersonDebt(eq(debt1), eq(person1));
PersonDebt personDebt = new PersonDebt(person1, debt1);
mDebtsRepository.deletePersonDebt(personDebt);
verify(mDebtsLocalDataSource).deletePersonDebt(eq(personDebt));
assertTrue(mDebtsRepository.mCacheOwed.size() == 0);
}
@Test
public void shouldBeAbleToGetAllDebtsByTypeFromLocalDataSource() {
mDebtsRepository.getAllPersonDebtsByType(Debt.DEBT_TYPE_IOWE);
verify(mDebtsLocalDataSource).getAllPersonDebtsByType(eq(Debt.DEBT_TYPE_IOWE));
mDebtsRepository.getAllPersonDebtsByType(Debt.DEBT_TYPE_OWED);
verify(mDebtsLocalDataSource).getAllPersonDebtsByType(eq(Debt.DEBT_TYPE_OWED));
}
@Test
public void shouldBeAbleToDeleteDebtsByTypeFromLocalDataSource() {
// Owed debt
Person person1 = TestUtil.getPerson();
Debt debt1 = TestUtil.createAndGetOwedDebt(person1.getId());
mDebtsRepository.savePersonDebt(debt1, person1);
Person person2 = TestUtil.createPerson("Ijeoma James", "0501245784");
Debt debt2 = TestUtil.createDebt(person2.getId(), 600000, Debt.DEBT_TYPE_OWED,
Debt.DEBT_STATUS_ACTIVE, "note 7774");
mDebtsRepository.savePersonDebt(debt2, person2);
mDebtsRepository.deleteAllPersonDebtsByType(Debt.DEBT_TYPE_OWED);
verify(mDebtsLocalDataSource).deleteAllPersonDebtsByType(eq(Debt.DEBT_TYPE_OWED));
assertTrue(mDebtsRepository.getAllPersonDebtsByType(Debt.DEBT_TYPE_OWED).size() == 0);
}
@Test
public void shouldBeAbleToUpdateDebtFromLocalDataSource() {
Person person1 = TestUtil.getPerson();
Debt debt1 = TestUtil.createAndGetOwedDebt(person1.getId());
mDebtsRepository.savePersonDebt(debt1, person1);
PersonDebt personDebt = mDebtsRepository.getPersonDebt(debt1.getId(), Debt.DEBT_TYPE_OWED);
personDebt.getPerson().setFullname("Emeka Onu");
personDebt.getDebt().setAmount(300);
mDebtsRepository.updatePersonDebt(personDebt);
verify(mDebtsLocalDataSource).updatePersonDebt(eq(personDebt));
PersonDebt personDebt1 = mDebtsRepository.getPersonDebt(debt1.getId(), Debt.DEBT_TYPE_OWED);
assertEquals(personDebt1, personDebt);
}
} |
package com.axelor.apps.hr.web.leave;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import com.axelor.apps.base.db.Company;
import com.axelor.apps.base.db.Wizard;
import com.axelor.apps.base.service.PeriodService;
import com.axelor.apps.base.service.message.MessageServiceBaseImpl;
import com.axelor.apps.hr.db.Employee;
import com.axelor.apps.hr.db.ExtraHours;
import com.axelor.apps.hr.db.LeaveLine;
import com.axelor.apps.hr.db.LeaveReason;
import com.axelor.apps.hr.db.LeaveRequest;
import com.axelor.apps.hr.db.repo.EmployeeRepository;
import com.axelor.apps.hr.db.repo.LeaveReasonRepository;
import com.axelor.apps.hr.db.repo.LeaveRequestRepository;
import com.axelor.apps.hr.exception.IExceptionMessage;
import com.axelor.apps.hr.service.HRMenuTagService;
import com.axelor.apps.hr.service.HRMenuValidateService;
import com.axelor.apps.hr.service.config.HRConfigService;
import com.axelor.apps.hr.service.leave.LeaveService;
import com.axelor.apps.message.db.Message;
import com.axelor.apps.message.db.repo.MessageRepository;
import com.axelor.auth.AuthUtils;
import com.axelor.auth.db.User;
import com.axelor.db.Query;
import com.axelor.exception.AxelorException;
import com.axelor.exception.service.TraceBackService;
import com.axelor.i18n.I18n;
import com.axelor.inject.Beans;
import com.axelor.meta.schema.actions.ActionView;
import com.axelor.meta.schema.actions.ActionView.ActionViewBuilder;
import com.axelor.rpc.ActionRequest;
import com.axelor.rpc.ActionResponse;
import com.google.inject.Inject;
import com.google.inject.Provider;
import com.google.inject.persist.Transactional;
public class LeaveController {
@Inject
private Provider<HRMenuTagService> hrMenuTagServiceProvider;
@Inject
private Provider<LeaveService> leaveServiceProvider;
@Inject
private Provider<LeaveRequestRepository> leaveRequestRepositoryProvider;
@Inject
private HRConfigService hrConfigService;
public void editLeave(ActionRequest request, ActionResponse response) {
User user = AuthUtils.getUser();
List<LeaveRequest> leaveList = Beans.get(LeaveRequestRepository.class).all().filter("self.user = ?1 AND self.company = ?2 AND self.statusSelect = 1",
user, user.getActiveCompany()).fetch();
if(leaveList.isEmpty()){
response.setView(ActionView
.define(I18n.get("LeaveRequest"))
.model(LeaveRequest.class.getName())
.add("form", "leave-request-form")
.map());
}
else if(leaveList.size() == 1){
response.setView(ActionView
.define(I18n.get("LeaveRequest"))
.model(LeaveRequest.class.getName())
.add("form", "leave-request-form")
.param("forceEdit", "true")
.context("_showRecord", String.valueOf(leaveList.get(0).getId())).map());
}
else{
response.setView(ActionView
.define(I18n.get("LeaveRequest"))
.model(Wizard.class.getName())
.add("form", "popup-leave-request-form")
.param("forceEdit", "true")
.param("popup", "true")
.param("show-toolbar", "false")
.param("show-confirm", "false")
.param("forceEdit", "true")
.param("popup-save", "false")
.map());
}
}
@SuppressWarnings("unchecked")
public void editLeaveSelected(ActionRequest request, ActionResponse response){
Map<String, Object> leaveMap = (Map<String, Object>) request.getContext().get("leaveSelect");
Long leaveId = new Long((Integer) leaveMap.get("id"));
response.setView(ActionView
.define(I18n.get("LeaveRequest"))
.model(LeaveRequest.class.getName())
.add("form", "leave-request-form")
.param("forceEdit", "true")
.domain("self.id = " + leaveId)
.context("_showRecord", leaveId).map());
}
public void validateLeave(ActionRequest request, ActionResponse response) throws AxelorException{
User user = AuthUtils.getUser();
Employee employee = user.getEmployee();
ActionViewBuilder actionView = ActionView.define(I18n.get("Leave Requests to Validate"))
.model(LeaveRequest.class.getName())
.add("grid","leave-request-validate-grid")
.add("form","leave-request-form");
Beans.get(HRMenuValidateService.class).createValidateDomain(user, employee, actionView);
response.setView(actionView.map());
}
public void historicLeave(ActionRequest request, ActionResponse response){
User user = AuthUtils.getUser();
Employee employee = user.getEmployee();
ActionViewBuilder actionView = ActionView.define(I18n.get("Colleague Leave Requests"))
.model(LeaveRequest.class.getName())
.add("grid","leave-request-grid")
.add("form","leave-request-form");
actionView.domain("self.statusSelect = 3 OR self.statusSelect = 4");
if(employee == null || !employee.getHrManager()) {
actionView.domain(actionView.get().getDomain() + " AND self.user.employee.manager = :_user")
.context("_user", user);
}
response.setView(actionView.map());
}
public void showSubordinateLeaves(ActionRequest request, ActionResponse response){
User user = AuthUtils.getUser();
Company activeCompany = user.getActiveCompany();
ActionViewBuilder actionView = ActionView.define(I18n.get("Leaves to be Validated by your subordinates"))
.model(LeaveRequest.class.getName())
.add("grid","leave-request-grid")
.add("form","leave-request-form");
String domain = "self.user.employee.manager.employee.manager = :_user AND self.statusSelect = 2";
long nbLeaveRequests = Query.of(ExtraHours.class).filter(domain).bind("_user", user).bind("_activeCompany", activeCompany).count();
if(nbLeaveRequests == 0) {
response.setNotify(I18n.get("No Leave Request to be validated by your subordinates"));
}
else {
response.setView(actionView.domain(domain).context("_user", user).context("_activeCompany", activeCompany).map());
}
}
public void testDuration(ActionRequest request, ActionResponse response){
LeaveRequest leave = request.getContext().asType(LeaveRequest.class);
Double duration = leave.getDuration().doubleValue();
if(duration % 0.5 != 0){
response.setError(I18n.get("Invalid duration (must be a 0.5's multiple)"));
}
}
public void computeDuration(ActionRequest request, ActionResponse response) throws AxelorException{
LeaveRequest leave = request.getContext().asType(LeaveRequest.class);
response.setValue("duration", leaveServiceProvider.get().computeDuration(leave));
}
//sending leave request and an email to the manager
public void send(ActionRequest request, ActionResponse response) throws AxelorException{
try{
LeaveService leaveService = leaveServiceProvider.get();
LeaveRequest leaveRequest = request.getContext().asType(LeaveRequest.class);
leaveRequest = leaveRequestRepositoryProvider.get().find(leaveRequest.getId());
if(leaveRequest.getUser().getEmployee().getWeeklyPlanning() == null) {
response.setAlert(String.format(I18n.get(IExceptionMessage.EMPLOYEE_PLANNING), leaveRequest.getUser().getEmployee().getName()));
return;
}
if(leaveRequest.getLeaveLine().getQuantity().subtract(leaveRequest.getDuration()).compareTo(BigDecimal.ZERO ) < 0 ){
if(!leaveRequest.getLeaveLine().getLeaveReason().getAllowNegativeValue() && !leaveService.willHaveEnoughDays(leaveRequest)){
String instruction = leaveRequest.getLeaveLine().getLeaveReason().getInstruction();
if (instruction == null) { instruction = ""; }
response.setAlert( String.format(
I18n.get(IExceptionMessage.LEAVE_ALLOW_NEGATIVE_VALUE_REASON),
leaveRequest.getLeaveLine().getLeaveReason().getLeaveReason()
) + " " + instruction );
return;
}else{
response.setNotify( String.format(I18n.get(IExceptionMessage.LEAVE_ALLOW_NEGATIVE_ALERT), leaveRequest.getLeaveLine().getLeaveReason().getLeaveReason()) );
}
}
leaveService.confirm(leaveRequest);
Message message = leaveService.sendConfirmationEmail(leaveRequest);
if(message != null && message.getStatusSelect() == MessageRepository.STATUS_SENT) {
response.setFlash(String.format(I18n.get("Email sent to %s"), Beans.get(MessageServiceBaseImpl.class).getToRecipients(message)));
}
} catch(Exception e) {
TraceBackService.trace(response, e);
}
finally {
response.setReload(true);
}
}
/**
* validating leave request and sending an email to the applicant
* @param request
* @param response
* @throws AxelorException
*/
public void validate(ActionRequest request, ActionResponse response) throws AxelorException{
try{
LeaveService leaveService = leaveServiceProvider.get();
LeaveRequest leaveRequest = request.getContext().asType(LeaveRequest.class);
leaveRequest = leaveRequestRepositoryProvider.get().find(leaveRequest.getId());
leaveService.validate(leaveRequest);
Message message = leaveService.sendValidationEmail(leaveRequest);
if(message != null && message.getStatusSelect() == MessageRepository.STATUS_SENT) {
response.setFlash(String.format(I18n.get("Email sent to %s"), Beans.get(MessageServiceBaseImpl.class).getToRecipients(message)));
}
Beans.get(PeriodService.class).checkPeriod(leaveRequest.getCompany(), leaveRequest.getToDate(), leaveRequest.getFromDate());
} catch(Exception e) {
TraceBackService.trace(response, e);
}
finally {
response.setReload(true);
}
}
//refusing leave request and sending an email to the applicant
public void refuse(ActionRequest request, ActionResponse response) throws AxelorException{
try{
LeaveService leaveService = leaveServiceProvider.get();
LeaveRequest leaveRequest = request.getContext().asType(LeaveRequest.class);
leaveRequest = leaveRequestRepositoryProvider.get().find(leaveRequest.getId());
leaveService.refuse(leaveRequest);
Message message = leaveService.sendRefusalEmail(leaveRequest);
if(message != null && message.getStatusSelect() == MessageRepository.STATUS_SENT) {
response.setFlash(String.format(I18n.get("Email sent to %s"), Beans.get(MessageServiceBaseImpl.class).getToRecipients(message)));
}
} catch(Exception e) {
TraceBackService.trace(response, e);
}
finally {
response.setReload(true);
}
}
public void cancel(ActionRequest request, ActionResponse response) throws AxelorException {
try {
LeaveRequest leave = request.getContext().asType(LeaveRequest.class);
leave = leaveRequestRepositoryProvider.get().find(leave.getId());
LeaveService leaveService = leaveServiceProvider.get();
leaveService.cancel(leave);
Message message = leaveService.sendCancellationEmail(leave);
if (message != null && message.getStatusSelect() == MessageRepository.STATUS_SENT) {
response.setFlash(String.format(I18n.get("Email sent to %s"), Beans.get(MessageServiceBaseImpl.class).getToRecipients(message)));
}
} catch(Exception e) {
TraceBackService.trace(response, e);
} finally {
response.setReload(true);
}
}
/* Count Tags displayed on the menu items */
@Transactional
public void leaveReasonToJustify(ActionRequest request, ActionResponse response) throws AxelorException {
LeaveRequest leave = request.getContext().asType(LeaveRequest.class);
Boolean leaveToJustify = leave.getToJustifyLeaveReason();
LeaveLine leaveLine = null;
if (!leaveToJustify) {
return;
}
Company company = leave.getCompany();
if (leave.getUser() == null) {
return;
}
if (company == null) {
company = leave.getUser().getActiveCompany();
}
if (company == null) {
return;
}
hrConfigService.getLeaveReason(company.getHrConfig());
Employee employee = leave.getUser().getEmployee();
LeaveReason leaveReason = Beans.get(LeaveReasonRepository.class).find(company.getHrConfig().getToJustifyLeaveReason().getId());
if (employee != null) {
employee = Beans.get(EmployeeRepository.class).find(leave.getUser().getEmployee().getId());
leaveLine = leaveServiceProvider.get().addLeaveReasonOrCreateIt(employee, leaveReason);
response.setValue("leaveLine", leaveLine);
}
}
public String leaveValidateMenuTag() {
return hrMenuTagServiceProvider.get().countRecordsTag(LeaveRequest.class, LeaveRequestRepository.STATUS_AWAITING_VALIDATION);
}
} |
package at.fhj.swd14.pse.person;
import static org.mockito.Mockito.times;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.naming.NamingException;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.runners.MockitoJUnitRunner;
import at.fhj.swd14.pse.converter.PersonConverter;
import at.fhj.swd14.pse.converter.UserConverter;
import at.fhj.swd14.pse.general.ContextMocker;
import at.fhj.swd14.pse.repository.PersonRepository;
import at.fhj.swd14.pse.user.User;
import at.fhj.swd14.pse.user.UserService;
@RunWith(MockitoJUnitRunner.class)
public class PersonServiceImplTest {
@InjectMocks
private PersonServiceImpl service;
@Mock
private PersonRepository personRepo;
@Mock
private UserService userService;
@Mock
private PersonVerifier verifier;
private User user;
private Person person;
private List<Person> persons;
@Before
public void setup() throws NamingException
{
person = PersonTestTools.getDummyPerson();
user = person.getUser();
persons = new ArrayList<Person>();
persons.add(person);
}
@Test
public void testFind()
{
Mockito.when(personRepo.find(1L)).thenReturn(person);
PersonDto foundPerson = service.find(person.getId());
PersonDtoTester.assertEquals(PersonConverter.convert(person), foundPerson);
}
@Test
public void testFindByUser()
{
Mockito.when(personRepo.findByUserId(1L)).thenReturn(person);
PersonDto foundPerson = service.findByUser(UserConverter.convert(user));
PersonDtoTester.assertEquals(PersonConverter.convert(person), foundPerson);
}
@Test
public void testGetLoggedInPerson()
{
FacesContext context = ContextMocker.mockFacesContext();
ExternalContext extContext = Mockito.mock(ExternalContext.class);
Mockito.when(context.getExternalContext()).thenReturn(extContext);
Principal principal = Mockito.mock(Principal.class);
Mockito.when(extContext.getUserPrincipal()).thenReturn(principal);
//TODO: Mockito.when(principal.getId()).thenReturn(1L);
Mockito.when(userService.find(1L)).thenReturn(UserConverter.convert(user));
Mockito.when(personRepo.findByUserId(1L)).thenReturn(person);
PersonDto foundPerson = service.getLoggedInPerson();
PersonDtoTester.assertEquals(PersonConverter.convert(person), foundPerson);
}
@Test
public void testFindAllUser()
{
Mockito.when(personRepo.findAll()).thenReturn(persons);
Collection<PersonDto> persons = service.findAllUser();
for(PersonDto person : persons)
{
PersonDtoTester.assertEquals(person, person);
}
}
@Test(expected=IllegalArgumentException.class)
public void testSaveNull()
{
service.saveLoggedInPerson(null);
}
@Test
public void testSave()
{
service.saveLoggedInPerson(PersonConverter.convert(person));
Mockito.verify(personRepo, times(1)).save(Mockito.any(Person.class));
}
} |
package org.ovirt.engine.core.bll;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.EnumSet;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.context.CommandContext;
import org.ovirt.engine.core.bll.job.ExecutionContext;
import org.ovirt.engine.core.bll.job.ExecutionHandler;
import org.ovirt.engine.core.bll.job.JobRepositoryFactory;
import org.ovirt.engine.core.bll.network.cluster.NetworkHelper;
import org.ovirt.engine.core.bll.provider.ProviderProxyFactory;
import org.ovirt.engine.core.bll.provider.network.NetworkProviderProxy;
import org.ovirt.engine.core.bll.quota.QuotaConsumptionParameter;
import org.ovirt.engine.core.bll.quota.QuotaVdsDependent;
import org.ovirt.engine.core.bll.quota.QuotaVdsGroupConsumptionParameter;
import org.ovirt.engine.core.bll.scheduling.SchedulingManager;
import org.ovirt.engine.core.bll.scheduling.VdsFreeMemoryChecker;
import org.ovirt.engine.core.bll.utils.PermissionSubject;
import org.ovirt.engine.core.bll.utils.VmDeviceUtils;
import org.ovirt.engine.core.bll.validator.RunVmValidator;
import org.ovirt.engine.core.common.AuditLogType;
import org.ovirt.engine.core.common.FeatureSupported;
import org.ovirt.engine.core.common.VdcObjectType;
import org.ovirt.engine.core.common.action.CreateAllSnapshotsFromVmParameters;
import org.ovirt.engine.core.common.action.IdParameters;
import org.ovirt.engine.core.common.action.LockProperties;
import org.ovirt.engine.core.common.action.LockProperties.Scope;
import org.ovirt.engine.core.common.action.RunVmParams;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.action.VdcReturnValueBase;
import org.ovirt.engine.core.common.asynctasks.EntityInfo;
import org.ovirt.engine.core.common.businessentities.ActionGroup;
import org.ovirt.engine.core.common.businessentities.BootSequence;
import org.ovirt.engine.core.common.businessentities.Disk;
import org.ovirt.engine.core.common.businessentities.Entities;
import org.ovirt.engine.core.common.businessentities.ImageFileType;
import org.ovirt.engine.core.common.businessentities.InitializationType;
import org.ovirt.engine.core.common.businessentities.Provider;
import org.ovirt.engine.core.common.businessentities.RepoImage;
import org.ovirt.engine.core.common.businessentities.Snapshot.SnapshotType;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType;
import org.ovirt.engine.core.common.businessentities.VmDeviceId;
import org.ovirt.engine.core.common.businessentities.VmPayload;
import org.ovirt.engine.core.common.businessentities.VmPool;
import org.ovirt.engine.core.common.businessentities.VmPoolType;
import org.ovirt.engine.core.common.businessentities.VmRngDevice;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.businessentities.network.VmNic;
import org.ovirt.engine.core.common.businessentities.network.VnicProfile;
import org.ovirt.engine.core.common.errors.VdcBLLException;
import org.ovirt.engine.core.common.errors.VdcBllErrors;
import org.ovirt.engine.core.common.errors.VdcBllMessages;
import org.ovirt.engine.core.common.job.Job;
import org.ovirt.engine.core.common.job.Step;
import org.ovirt.engine.core.common.job.StepEnum;
import org.ovirt.engine.core.common.utils.VmDeviceType;
import org.ovirt.engine.core.common.validation.group.StartEntity;
import org.ovirt.engine.core.common.vdscommands.CreateVmVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.IrsBaseVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.ResumeVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.Version;
import org.ovirt.engine.core.dal.dbbroker.auditloghandling.AuditLogDirector;
import org.ovirt.engine.core.dal.job.ExecutionMessageDirector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@NonTransactiveCommandAttribute
public class RunVmCommand<T extends RunVmParams> extends RunVmCommandBase<T>
implements QuotaVdsDependent {
enum RunVmFlow {
/** regular flow */
RUN,
/** run VM which is paused */
RESUME_PAUSE,
/** run VM which is suspended */
RESUME_HIBERNATE,
/** create the stateless images in order to run the VM as stateless */
CREATE_STATELESS_IMAGES,
/** remove stateless images that remained from last time the VM ran as stateless */
REMOVE_STATELESS_IMAGES,
/** wrap things up after the VM reach UP state */
RUNNING_SUCCEEDED
}
/** Cache the current flow the command is in. use {@link #getFlow()} to retrieve the flow */
private RunVmFlow cachedFlow;
/** Note: this field should not be used directly, use {@link #isStatelessSnapshotExistsForVm()} instead */
private Boolean cachedStatelessSnapshotExistsForVm;
/** Indicates whether there is a possibility that the active snapshot's memory was already restored */
private boolean memoryFromSnapshotUsed;
private Guid cachedActiveIsoDomainId;
public static final String ISO_PREFIX = "iso:
public static final String STATELESS_SNAPSHOT_DESCRIPTION = "stateless snapshot";
private static final Logger log = LoggerFactory.getLogger(RunVmCommand.class);
protected RunVmCommand(Guid commandId) {
super(commandId);
}
public RunVmCommand(T runVmParams) {
this(runVmParams, null);
}
public RunVmCommand(T runVmParams, CommandContext commandContext) {
super(runVmParams, commandContext);
getParameters().setEntityInfo(new EntityInfo(VdcObjectType.VM, runVmParams.getVmId()));
setStoragePoolId(getVm() != null ? getVm().getStoragePoolId() : null);
// Load payload from Database (only if none was sent via the parameters)
loadPayloadDevice();
}
@Override
protected LockProperties applyLockProperties(LockProperties lockProperties) {
return lockProperties.withScope(Scope.Execution);
}
protected Guid getPredefinedVdsIdToRunOn() {
return getVm().getDedicatedVmForVds();
}
private String getMemoryFromActiveSnapshot() {
// If the memory from the snapshot could have been restored already, the disks might be
// non coherent with the memory, thus we don't want to try to restore the memory again
if (memoryFromSnapshotUsed) {
return StringUtils.EMPTY;
}
if (getFlow() == RunVmFlow.RESUME_HIBERNATE) {
return getActiveSnapshot().getMemoryVolume();
}
if (!FeatureSupported.isMemorySnapshotSupportedByArchitecture(
getVm().getClusterArch(),
getVm().getVdsGroupCompatibilityVersion())) {
return StringUtils.EMPTY;
}
if (!FeatureSupported.memorySnapshot(getVm().getVdsGroupCompatibilityVersion())) {
return StringUtils.EMPTY;
}
return getActiveSnapshot().getMemoryVolume();
}
/**
* Sets up the command specific boot parameters. This method is not expected to be
* extended, however it can be overridden (e.g. the children will not call the super)
*/
protected void refreshBootParameters(RunVmParams runVmParameters) {
getVm().setBootSequence(getVm().getDefaultBootSequence());
getVm().setRunOnce(false);
}
/**
* Returns the full path file name of Iso file. If the Iso file has prefix of Iso://, then we set the prefix to the
* path of the domain on the Iso Domain server<BR/>
* otherwise, returns the original name.<BR/>
* Note: The prefix is not case sensitive.
*
* @param url
* - String of the file url. ("iso://initrd.ini" or "/init/initrd.ini".
* @return String of the full file path.
*/
protected String getIsoPrefixFilePath(String url) {
// The initial Url.
String fullPathFileName = url;
// If file name got prefix of iso:// then set the path to the Iso domain.
int prefixLength = ISO_PREFIX.length();
if (url.length() >= prefixLength && (url.substring(0, prefixLength)).equalsIgnoreCase(ISO_PREFIX)) {
fullPathFileName = cdPathWindowsToLinux(url.substring(prefixLength));
}
return fullPathFileName;
}
protected String cdPathWindowsToLinux(String url) {
return ImagesHandler.cdPathWindowsToLinux(url, getVm().getStoragePoolId(), getVdsId());
}
private void resumeVm() {
setVdsId(getVm().getRunOnVds());
if (getVds() != null) {
try {
VDSReturnValue result = getBackend().getResourceManager()
.RunAsyncVdsCommand(
VDSCommandType.Resume,
new ResumeVDSCommandParameters(getVdsId(), getVm().getId()),
this);
setActionReturnValue(result.getReturnValue());
setSucceeded(result.getSucceeded());
ExecutionHandler.setAsyncJob(getExecutionContext(), true);
} finally {
freeLock();
}
} else {
setActionReturnValue(getVm().getStatus());
}
}
protected void runVm() {
setActionReturnValue(VMStatus.Down);
if (getVdsToRunOn()) {
VMStatus status = null;
try {
if (connectLunDisks(getVdsId())) {
status = createVm();
ExecutionHandler.setAsyncJob(getExecutionContext(), true);
}
} catch(VdcBLLException e) {
// if the returned exception is such that shoudn't trigger the re-run process,
// re-throw it. otherwise, continue (the vm will be down and a re-run will be triggered)
switch (e.getErrorCode()) {
case Done: // should never get here with errorCode = 'Done' though
case exist:
reportCompleted();
throw e;
case VDS_NETWORK_ERROR: // probably wrong xml format sent.
case PROVIDER_FAILURE:
runningFailed();
throw e;
default:
log.warn("Failed to run VM '{}': {}", getVmName(), e.getMessage());
}
} finally {
freeLock();
}
setActionReturnValue(status);
if (status != null && (status.isRunning() || status == VMStatus.RestoringState)) {
setSucceeded(true);
} else {
// Try to rerun Vm on different vds no need to log the command because it is
// being logged inside the rerun
log.info("Trying to rerun VM '{}'", getVm().getName());
setCommandShouldBeLogged(false);
setSucceeded(true);
rerun();
}
}
else {
runningFailed();
}
}
@Override
protected void executeVmCommand() {
setActionReturnValue(VMStatus.Down);
initVm();
perform();
}
@Override
public void rerun() {
setFlow(null);
super.rerun();
}
private RunVmFlow setFlow(RunVmFlow flow) {
return cachedFlow = flow;
}
/**
* Determine the flow in which the command should be operating or
* return the cached flow if it was already computed
*
* @return the flow in which the command is operating
*/
protected RunVmFlow getFlow() {
if (cachedFlow != null) {
return cachedFlow;
}
switch(getVm().getStatus()) {
case Paused:
return setFlow(RunVmFlow.RESUME_PAUSE);
case Suspended:
return setFlow(RunVmFlow.RESUME_HIBERNATE);
default:
}
if (isRunAsStateless()) {
fetchVmDisksFromDb();
if (getVm().getDiskList().isEmpty()) {
// If there are no snappable disks, there is no meaning for
// running as stateless, log a warning and run normally
warnIfNotAllDisksPermitSnapshots();
return setFlow(RunVmFlow.RUN);
}
return setFlow(RunVmFlow.CREATE_STATELESS_IMAGES);
}
if (!isInternalExecution()
&& isStatelessSnapshotExistsForVm()
&& !isVmPartOfManualPool()) {
return setFlow(RunVmFlow.REMOVE_STATELESS_IMAGES);
}
return setFlow(RunVmFlow.RUN);
}
protected void perform() {
switch(getFlow()) {
case RESUME_PAUSE:
resumeVm();
break;
case REMOVE_STATELESS_IMAGES:
removeVmStatlessImages();
break;
case CREATE_STATELESS_IMAGES:
statelessVmTreatment();
break;
case RESUME_HIBERNATE:
case RUN:
default:
runVm();
}
}
/**
* @return true if a stateless snapshot exists for the VM, false otherwise
*/
protected boolean isStatelessSnapshotExistsForVm() {
if (cachedStatelessSnapshotExistsForVm == null) {
cachedStatelessSnapshotExistsForVm = getSnapshotDAO().exists(getVm().getId(), SnapshotType.STATELESS);
}
return cachedStatelessSnapshotExistsForVm;
}
/**
* Returns the CD path in the following order (from high to low):
* (1) The path given in the parameters
* (2) The ISO path stored in the database if the boot sequence contains CD ROM
* (3) Guest agent tools iso
* (4) The ISO path stored in the database
*
* Note that in (2) we assume that the CD is bootable
*/
private String chooseCd() {
if (getParameters().getDiskPath() != null) {
return getParameters().getDiskPath();
}
if (getVm().getBootSequence() != null && getVm().getBootSequence().containsSubsequence(BootSequence.D)) {
return getVm().getIsoPath();
}
String guestToolPath = guestToolsVersionTreatment();
if (guestToolPath != null) {
return guestToolPath;
}
return getVm().getIsoPath();
}
protected IsoDomainListSyncronizer getIsoDomainListSyncronizer() {
return IsoDomainListSyncronizer.getInstance();
}
private void statelessVmTreatment() {
warnIfNotAllDisksPermitSnapshots();
if (isStatelessSnapshotExistsForVm()) {
log.error(
"VM '{}' ({}) already contains stateless snapshot, removing it",
getVm().getName(), getVm().getId());
removeVmStatlessImages();
} else {
log.info("Creating stateless snapshot for VM '{}' ({})",
getVm().getName(), getVm().getId());
CreateAllSnapshotsFromVmParameters createAllSnapshotsFromVmParameters = buildCreateSnapshotParameters();
VdcReturnValueBase vdcReturnValue = runInternalAction(VdcActionType.CreateAllSnapshotsFromVm,
createAllSnapshotsFromVmParameters,
createContextForStatelessSnapshotCreation());
// setting lock to null in order not to release lock twice
setLock(null);
setSucceeded(vdcReturnValue.getSucceeded());
if (vdcReturnValue.getSucceeded()) {
getReturnValue().getVdsmTaskIdList().addAll(vdcReturnValue.getInternalVdsmTaskIdList());
} else {
if (areDisksLocked(vdcReturnValue)) {
throw new VdcBLLException(VdcBllErrors.IRS_IMAGE_STATUS_ILLEGAL);
}
getReturnValue().setFault(vdcReturnValue.getFault());
log.error("Failed to create stateless snapshot for VM '{}' ({})",
getVm().getName(), getVm().getId());
}
}
}
private CommandContext createContextForStatelessSnapshotCreation() {
Map<String, String> values = getVmValuesForMsgResolving();
// Creating snapshots as sub step of run stateless
Step createSnapshotsStep = addSubStep(StepEnum.EXECUTING,
StepEnum.CREATING_SNAPSHOTS, values);
// Add the step as the first step of the new context
ExecutionContext createSnapshotsCtx = new ExecutionContext();
createSnapshotsCtx.setMonitored(true);
createSnapshotsCtx.setStep(createSnapshotsStep);
return cloneContext().withExecutionContext(createSnapshotsCtx);
}
private CreateAllSnapshotsFromVmParameters buildCreateSnapshotParametersForEndAction() {
CreateAllSnapshotsFromVmParameters parameters = buildCreateSnapshotParameters();
parameters.setImagesParameters(getParameters().getImagesParameters());
return parameters;
}
private CreateAllSnapshotsFromVmParameters buildCreateSnapshotParameters() {
CreateAllSnapshotsFromVmParameters parameters =
new CreateAllSnapshotsFromVmParameters(getVm().getId(), STATELESS_SNAPSHOT_DESCRIPTION);
parameters.setShouldBeLogged(false);
parameters.setParentCommand(getActionType());
parameters.setParentParameters(getParameters());
parameters.setEntityInfo(getParameters().getEntityInfo());
parameters.setSnapshotType(SnapshotType.STATELESS);
return parameters;
}
private boolean areDisksLocked(VdcReturnValueBase vdcReturnValue) {
return vdcReturnValue.getCanDoActionMessages().contains(
VdcBllMessages.ACTION_TYPE_FAILED_DISKS_LOCKED.name());
}
private void warnIfNotAllDisksPermitSnapshots() {
for (Disk disk : getVm().getDiskMap().values()) {
if (!disk.isAllowSnapshot()) {
AuditLogDirector.log(this,
AuditLogType.USER_RUN_VM_AS_STATELESS_WITH_DISKS_NOT_ALLOWING_SNAPSHOT);
break;
}
}
}
protected Map<String, String> getVmValuesForMsgResolving() {
return Collections.singletonMap(VdcObjectType.VM.name().toLowerCase(), getVmName());
}
private void removeVmStatlessImages() {
runInternalAction(VdcActionType.ProcessDownVm,
new IdParameters(getVm().getId()),
ExecutionHandler.createDefaultContextForTasks(getContext(), getLock()));
// setting lock to null in order not to release lock twice
setLock(null);
setSucceeded(true);
}
protected VMStatus createVm() {
final String cdPath = chooseCd();
if (StringUtils.isNotEmpty(cdPath)) {
log.info("Running VM with attached cd '{}'", cdPath);
}
updateCurrentCd(cdPath);
getVm().setCdPath(cdPathWindowsToLinux(cdPath));
if (!StringUtils.isEmpty(getParameters().getFloppyPath())) {
getVm().setFloppyPath(cdPathWindowsToLinux(getParameters().getFloppyPath()));
}
// Set path for initrd and kernel image.
if (!StringUtils.isEmpty(getVm().getInitrdUrl())) {
getVm().setInitrdUrl(getIsoPrefixFilePath(getVm().getInitrdUrl()));
}
if (!StringUtils.isEmpty(getVm().getKernelUrl())) {
getVm().setKernelUrl(getIsoPrefixFilePath(getVm().getKernelUrl()));
}
initParametersForExternalNetworks();
VMStatus vmStatus = (VMStatus) getBackend()
.getResourceManager()
.RunAsyncVdsCommand(VDSCommandType.CreateVm, buildCreateVmParameters(), this).getReturnValue();
// Don't use the memory from the active snapshot anymore if there's a chance that disks were changed
memoryFromSnapshotUsed = vmStatus.isRunning() || vmStatus == VMStatus.RestoringState;
// After VM was create (or not), we can remove the quota vds group memory.
return vmStatus;
}
protected void updateCurrentCd(String cdPath) {
VmHandler.updateCurrentCd(getVdsId(), getVm(), cdPath);
}
/**
* Initialize the parameters for the VDSM command of VM creation
*
* @return the VDS create VM parameters
*/
protected CreateVmVDSCommandParameters buildCreateVmParameters() {
CreateVmVDSCommandParameters parameters = new CreateVmVDSCommandParameters(getVdsId(), getVm());
return parameters;
}
protected void initParametersForExternalNetworks() {
if (getVm().getInterfaces().isEmpty()) {
return;
}
Map<VmDeviceId, VmDevice> nicDevices =
Entities.businessEntitiesById(getDbFacade().getVmDeviceDao().getVmDeviceByVmIdAndType(getVmId(),
VmDeviceGeneralType.INTERFACE));
for (VmNic iface : getVm().getInterfaces()) {
VnicProfile vnicProfile = getDbFacade().getVnicProfileDao().get(iface.getVnicProfileId());
Network network = NetworkHelper.getNetworkByVnicProfile(vnicProfile);
VmDevice vmDevice = nicDevices.get(new VmDeviceId(iface.getId(), getVmId()));
if (network != null && network.isExternal() && vmDevice.getIsPlugged()) {
Provider<?> provider = getDbFacade().getProviderDao().get(network.getProvidedBy().getProviderId());
NetworkProviderProxy providerProxy = ProviderProxyFactory.getInstance().create(provider);
Map<String, String> deviceProperties = providerProxy.allocate(network, vnicProfile, iface, getVds());
getVm().getRuntimeDeviceCustomProperties().put(vmDevice.getId(), deviceProperties);
}
}
}
@Override
public AuditLogType getAuditLogTypeValue() {
switch (getActionState()) {
case EXECUTE:
if (getFlow() == RunVmFlow.REMOVE_STATELESS_IMAGES) {
return AuditLogType.USER_RUN_VM_FAILURE_STATELESS_SNAPSHOT_LEFT;
}
if (getFlow() == RunVmFlow.RESUME_PAUSE) {
return getSucceeded() ? AuditLogType.USER_RESUME_VM : AuditLogType.USER_FAILED_RESUME_VM;
} else if (isInternalExecution()) {
if (getSucceeded()) {
boolean isStateless = isStatelessSnapshotExistsForVm();
if (isStateless) {
return AuditLogType.VDS_INITIATED_RUN_VM_AS_STATELESS;
} else if (getFlow() == RunVmFlow.CREATE_STATELESS_IMAGES) {
return AuditLogType.VDS_INITIATED_RUN_AS_STATELESS_VM_NOT_YET_RUNNING;
} else {
return AuditLogType.VDS_INITIATED_RUN_VM;
}
}
return AuditLogType.VDS_INITIATED_RUN_VM_FAILED;
} else {
return getSucceeded() ?
(VMStatus) getActionReturnValue() == VMStatus.Up ?
isVmRunningOnNonDefaultVds() ?
AuditLogType.USER_RUN_VM_ON_NON_DEFAULT_VDS
: (isStatelessSnapshotExistsForVm() ?
AuditLogType.USER_RUN_VM_AS_STATELESS
: AuditLogType.USER_RUN_VM)
: _isRerun ?
AuditLogType.VDS_INITIATED_RUN_VM
: getTaskIdList().size() > 0 ?
AuditLogType.USER_INITIATED_RUN_VM
: getVm().isRunAndPause() ? AuditLogType.USER_INITIATED_RUN_VM_AND_PAUSE
: AuditLogType.USER_STARTED_VM
: _isRerun ? AuditLogType.USER_INITIATED_RUN_VM_FAILED : AuditLogType.USER_FAILED_RUN_VM;
}
case END_SUCCESS:
// if not running as stateless, or if succeeded running as
// stateless,
// command should be with 'CommandShouldBeLogged = false':
return isStatelessSnapshotExistsForVm() && !getSucceeded() ?
AuditLogType.USER_RUN_VM_AS_STATELESS_FINISHED_FAILURE : AuditLogType.UNASSIGNED;
case END_FAILURE:
// if not running as stateless, command should
// be with 'CommandShouldBeLogged = false':
return isStatelessSnapshotExistsForVm() ?
AuditLogType.USER_RUN_VM_AS_STATELESS_FINISHED_FAILURE : AuditLogType.UNASSIGNED;
default:
// all other cases should be with 'CommandShouldBeLogged =
// false':
return AuditLogType.UNASSIGNED;
}
}
protected boolean isVmRunningOnNonDefaultVds() {
return getVm().getDedicatedVmForVds() != null
&& !getVm().getRunOnVds().equals(getVm().getDedicatedVmForVds());
}
/**
* @return true if we need to create the VM object, false otherwise
*/
private boolean isInitVmRequired() {
return EnumSet.of(RunVmFlow.RUN, RunVmFlow.RESUME_HIBERNATE).contains(getFlow());
}
protected void initVm() {
if (!isInitVmRequired()) {
return;
}
fetchVmDisksFromDb();
// reevaluate boot parameters if VM was executed with 'run once'
refreshBootParameters(getParameters());
// Before running the VM we update its devices, as they may
// need to be changed due to configuration option change
VmDeviceUtils.updateVmDevices(getVm().getStaticData());
getVm().setKvmEnable(getParameters().getKvmEnable());
getVm().setRunAndPause(getParameters().getRunAndPause() == null ? getVm().isRunAndPause() : getParameters().getRunAndPause());
getVm().setAcpiEnable(getParameters().getAcpiEnable());
if (getParameters().getBootMenuEnabled() != null) {
getVm().setBootMenuEnabled(getParameters().getBootMenuEnabled());
}
if (getParameters().getSpiceFileTransferEnabled() != null) {
getVm().setSpiceFileTransferEnabled(getParameters().getSpiceFileTransferEnabled());
}
if (getParameters().getSpiceCopyPasteEnabled() != null) {
getVm().setSpiceCopyPasteEnabled(getParameters().getSpiceCopyPasteEnabled());
}
// Clear the first user:
getVm().setConsoleUserId(null);
if (getParameters().getInitializationType() == null) {
// if vm not initialized, use sysprep/cloud-init
if (!getVm().isInitialized()) {
VmHandler.updateVmInitFromDB(getVm().getStaticData(), false);
getVm().setInitializationType(InitializationType.None);
if (osRepository.isWindows(getVm().getVmOsId())) {
if (!isPayloadExists(VmDeviceType.FLOPPY)) {
getVm().setInitializationType(InitializationType.Sysprep);
}
}
else if (getVm().getVmInit() != null) {
if (!isPayloadExists(VmDeviceType.CDROM)) {
getVm().setInitializationType(InitializationType.CloudInit);
}
}
}
} else {
getVm().setInitializationType(getParameters().getInitializationType());
// If the user asked for sysprep/cloud-init via run-once we eliminate
// the payload since we can only have one media (Floppy/CDROM) per payload.
if (getParameters().getInitializationType() == InitializationType.Sysprep &&
isPayloadExists(VmDeviceType.FLOPPY)) {
getVm().setVmPayload(null);
} else if (getParameters().getInitializationType() == InitializationType.CloudInit &&
isPayloadExists(VmDeviceType.CDROM)) {
getVm().setVmPayload(null);
}
}
// if we asked for floppy from Iso Domain we cannot
// have floppy payload since we are limited to only one floppy device
if (!StringUtils.isEmpty(getParameters().getFloppyPath()) && isPayloadExists(VmDeviceType.FLOPPY)) {
getVm().setVmPayload(null);
}
VmHandler.updateVmGuestAgentVersion(getVm());
// update dynamic cluster-parameters
if (getVm().getCpuName() == null) { // no run-once data -> use static field or inherit from cluster
if (getVm().getCustomCpuName() != null) {
getVm().setCpuName(getVm().getCustomCpuName());
} else {
// get what cpu flags should be passed to vdsm according to the cluster
getVm().setCpuName(CpuFlagsManagerHandler.getCpuId(getVm().getVdsGroupCpuName(), getVm()
.getVdsGroupCompatibilityVersion()));
}
}
if (getVm().getEmulatedMachine() == null) {
getVm().setEmulatedMachine((getVm().getCustomEmulatedMachine() != null ?
getVm().getCustomEmulatedMachine() :
getVdsGroup().getEmulatedMachine()));
}
getVm().setHibernationVolHandle(getMemoryFromActiveSnapshot());
}
protected boolean isPayloadExists(VmDeviceType deviceType) {
if (getVm().getVmPayload() != null && getVm().getVmPayload().getDeviceType().equals(deviceType)) {
return true;
}
return false;
}
protected void loadPayloadDevice() {
if (getParameters().getVmPayload() == null) {
VmPayload payload = getVmPayloadByDeviceType(VmDeviceType.CDROM);
if (payload != null) {
getVm().setVmPayload(payload);
} else {
getVm().setVmPayload(getVmPayloadByDeviceType(VmDeviceType.FLOPPY));
}
}
}
protected VmPayload getVmPayloadByDeviceType(VmDeviceType deviceType) {
List<VmDevice> vmDevices = getVmDeviceDao()
.getVmDeviceByVmIdTypeAndDevice(getVm().getId(),
VmDeviceGeneralType.DISK,
deviceType.getName());
for (VmDevice vmDevice : vmDevices) {
if (vmDevice.getIsManaged() && VmPayload.isPayload(vmDevice.getSpecParams())) {
return new VmPayload(vmDevice);
}
}
return null;
}
protected void fetchVmDisksFromDb() {
if (getVm().getDiskMap().isEmpty()) {
VmHandler.updateDisksFromDb(getVm());
}
}
protected boolean getVdsToRunOn() {
Guid vdsToRunOn =
SchedulingManager.getInstance().schedule(getVdsGroup(),
getVm(),
getRunVdssList(),
getVdsWhiteList(),
getPredefinedVdsIdToRunOn(),
new ArrayList<String>(),
new VdsFreeMemoryChecker(this),
getCorrelationId());
setVdsId(vdsToRunOn);
if (vdsToRunOn != null && !Guid.Empty.equals(vdsToRunOn)) {
getRunVdssList().add(vdsToRunOn);
}
setVds(null);
setVdsName(null);
if (getVdsId().equals(Guid.Empty)) {
log.error("Can't find VDS to run the VM '{}' on, so this VM will not be run.", getVmId());
return false;
}
if (getVds() == null) {
VdcBLLException outEx = new VdcBLLException(VdcBllErrors.RESOURCE_MANAGER_VDS_NOT_FOUND);
log.error("VmHandler::{}: {}", getClass().getName(), outEx.getMessage());
return false;
}
return true;
}
/**
* If vds version greater then vm's and vm not running with cd and there is appropriate RhevAgentTools image -
* add it to vm as cd.
*/
private String guestToolsVersionTreatment() {
boolean attachCd = false;
String selectedToolsVersion = "";
String selectedToolsClusterVersion = "";
Guid isoDomainId = getActiveIsoDomainId();
if (osRepository.isWindows(getVm().getVmOsId()) && null != isoDomainId) {
// get cluster version of the vm tools
Version vmToolsClusterVersion = null;
if (getVm().getHasAgent()) {
Version clusterVer = getVm().getPartialVersion();
if (new Version("4.4").equals(clusterVer)) {
vmToolsClusterVersion = new Version("2.1");
} else {
vmToolsClusterVersion = clusterVer;
}
}
// Fetch cached Iso files from active Iso domain.
List<RepoImage> repoFilesMap =
getIsoDomainListSyncronizer().getCachedIsoListByDomainId(isoDomainId, ImageFileType.ISO);
Version bestClusterVer = null;
int bestToolVer = 0;
for (RepoImage map : repoFilesMap) {
String fileName = StringUtils.defaultString(map.getRepoImageId(), "");
Matcher matchToolPattern =
Pattern.compile(IsoDomainListSyncronizer.REGEX_TOOL_PATTERN).matcher(fileName);
if (matchToolPattern.find()) {
// Get cluster version and tool version of Iso tool.
Version clusterVer = new Version(matchToolPattern.group(IsoDomainListSyncronizer.TOOL_CLUSTER_LEVEL));
int toolVersion = Integer.parseInt(matchToolPattern.group(IsoDomainListSyncronizer.TOOL_VERSION));
if (clusterVer.compareTo(getVm().getVdsGroupCompatibilityVersion()) <= 0) {
if ((bestClusterVer == null)
|| (clusterVer.compareTo(bestClusterVer) > 0)) {
bestToolVer = toolVersion;
bestClusterVer = clusterVer;
} else if (clusterVer.equals(bestClusterVer) && toolVersion > bestToolVer) {
bestToolVer = toolVersion;
bestClusterVer = clusterVer;
}
}
}
}
if (bestClusterVer != null
&& (vmToolsClusterVersion == null
|| vmToolsClusterVersion.compareTo(bestClusterVer) < 0 || (vmToolsClusterVersion.equals(bestClusterVer)
&& getVm().getHasAgent() &&
getVm().getGuestAgentVersion().getBuild() < bestToolVer))) {
// Vm has no tools or there are new tools
selectedToolsVersion = (Integer.toString(bestToolVer));
selectedToolsClusterVersion = bestClusterVer.toString();
attachCd = true;
}
}
if (attachCd) {
String rhevToolsPath =
String.format("%1$s%2$s_%3$s.iso", IsoDomainListSyncronizer.getGuestToolsSetupIsoPrefix(),
selectedToolsClusterVersion, selectedToolsVersion);
String isoDir = (String) runVdsCommand(VDSCommandType.IsoDirectory,
new IrsBaseVDSCommandParameters(getVm().getStoragePoolId())).getReturnValue();
rhevToolsPath = isoDir + File.separator + rhevToolsPath;
return rhevToolsPath;
}
return null;
}
@Override
protected boolean canDoAction() {
VM vm = getVm();
if (vm == null) {
return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_VM_NOT_FOUND);
}
if (!validateObject(vm.getStaticData())) {
return false;
}
if (!canRunActionOnNonManagedVm()) {
return false;
}
RunVmValidator runVmValidator = getRunVmValidator();
if (!runVmValidator.canRunVm(
getReturnValue().getCanDoActionMessages(),
getStoragePool(),
getRunVdssList(),
getVdsWhiteList(),
getPredefinedVdsIdToRunOn(),
getVdsGroup())) {
return false;
}
if (!validate(runVmValidator.validateNetworkInterfaces())) {
return false;
}
// check for Vm Payload
if (getParameters().getVmPayload() != null) {
if (checkPayload(getParameters().getVmPayload(), getParameters().getDiskPath()) &&
!StringUtils.isEmpty(getParameters().getFloppyPath()) &&
getParameters().getVmPayload().getDeviceType() == VmDeviceType.FLOPPY) {
return failCanDoAction(VdcBllMessages.VMPAYLOAD_FLOPPY_EXCEEDED);
}
getVm().setVmPayload(getParameters().getVmPayload());
}
if (!checkRngDeviceClusterCompatibility()) {
return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_RNG_SOURCE_NOT_SUPPORTED);
}
// Note: that we are setting the payload from database in the ctor.
// Checking if the user sent Payload and Sysprep/Cloud-init at the same media -
// Currently we cannot use two payloads in the same media (cdrom/floppy)
if (getParameters().getInitializationType() != null) {
if (getParameters().getInitializationType() == InitializationType.Sysprep && getParameters().getVmPayload() != null &&
getParameters().getVmPayload().getDeviceType() == VmDeviceType.FLOPPY) {
return failCanDoAction(VdcBllMessages.VMPAYLOAD_FLOPPY_WITH_SYSPREP);
} else if (getParameters().getInitializationType() == InitializationType.CloudInit && getParameters().getVmPayload() != null &&
getParameters().getVmPayload().getDeviceType() == VmDeviceType.CDROM) {
return failCanDoAction(VdcBllMessages.VMPAYLOAD_CDROM_WITH_CLOUD_INIT);
}
}
return true;
}
/**
* Checks whether rng device of vm is required by cluster, which is requirement for running vm.
*
* @return true if the source of vm rng device is required by cluster (and therefore supported by hosts in cluster)
*/
boolean checkRngDeviceClusterCompatibility() {
List<VmDevice> rngDevs =
getVmDeviceDao().getVmDeviceByVmIdTypeAndDevice(getVmId(), VmDeviceGeneralType.RNG, VmDeviceType.VIRTIO.getName());
if (!rngDevs.isEmpty()) {
VmRngDevice rngDev = new VmRngDevice(rngDevs.get(0));
if (!getVdsGroup().getRequiredRngSources().contains(rngDev.getSource())) {
return false;
}
}
return true;
}
@Override
protected List<Class<?>> getValidationGroups() {
addValidationGroup(StartEntity.class);
return super.getValidationGroups();
}
protected RunVmValidator getRunVmValidator() {
return new RunVmValidator(getVm(), getParameters(), isInternalExecution(), getActiveIsoDomainId());
}
protected Guid getActiveIsoDomainId() {
if (cachedActiveIsoDomainId == null) {
cachedActiveIsoDomainId = getIsoDomainListSyncronizer()
.findActiveISODomain(getVm().getStoragePoolId());
}
return cachedActiveIsoDomainId;
}
@Override
protected void setActionMessageParameters() {
addCanDoActionMessage(VdcBllMessages.VAR__ACTION__RUN);
addCanDoActionMessage(VdcBllMessages.VAR__TYPE__VM);
}
@Override
protected void endSuccessfully() {
if (isStatelessSnapshotExistsForVm()) {
getBackend().endAction(VdcActionType.CreateAllSnapshotsFromVm,
buildCreateSnapshotParametersForEndAction(),
getContext().clone().withoutCompensationContext().withoutExecutionContext().withoutLock());
getParameters().setShouldBeLogged(false);
getParameters().setRunAsStateless(false);
setSucceeded(getBackend().runInternalAction(
getActionType(), getParameters(), createContextForRunStatelessVm()).getSucceeded());
if (!getSucceeded()) {
getParameters().setShouldBeLogged(true);
log.error("Could not run VM '{}' ({}) in stateless mode",
getVm().getName(), getVm().getId());
// could not run the vm don't try to run the end action again
getReturnValue().setEndActionTryAgain(false);
}
}
// Hibernation (VMStatus.Suspended) treatment:
else {
super.endSuccessfully();
}
}
private CommandContext createContextForRunStatelessVm() {
Step step = getExecutionContext().getStep();
// Retrieve the job object and its steps as this the endSuccessfully stage of command execution -
// at this is a new instance of the command is used
// (comparing with the execution state) so all information on the job and steps should be retrieved.
Job job = JobRepositoryFactory.getJobRepository().getJobWithSteps(step.getJobId());
Step executingStep = job.getDirectStep(StepEnum.EXECUTING);
// We would like to to set the run stateless step as substep of executing step
setInternalExecution(true);
ExecutionContext runStatelessVmCtx = new ExecutionContext();
// The internal command should be monitored for tasks
runStatelessVmCtx.setMonitored(true);
Step runStatelessStep =
ExecutionHandler.addSubStep(getExecutionContext(),
executingStep,
StepEnum.RUN_STATELESS_VM,
ExecutionMessageDirector.resolveStepMessage(StepEnum.RUN_STATELESS_VM,
getVmValuesForMsgResolving()));
// This is needed in order to end the job upon execution of the steps of the child command
runStatelessVmCtx.setShouldEndJob(true);
runStatelessVmCtx.setJob(job);
// Since run stateless step involves invocation of command, we should set the run stateless vm step as
// the "beginning step" of the child command.
runStatelessVmCtx.setStep(runStatelessStep);
return cloneContextAndDetachFromParent().withExecutionContext(runStatelessVmCtx);
}
@Override
protected void endWithFailure() {
if (isStatelessSnapshotExistsForVm()) {
VdcReturnValueBase vdcReturnValue = getBackend().endAction(VdcActionType.CreateAllSnapshotsFromVm,
buildCreateSnapshotParametersForEndAction(), cloneContext().withoutExecutionContext().withoutLock());
setSucceeded(vdcReturnValue.getSucceeded());
// we are not running the VM, of course,
// since we couldn't create a snapshot.
}
else {
super.endWithFailure();
}
}
@Override
public void runningSucceded() {
setFlow(RunVmFlow.RUNNING_SUCCEEDED);
removeMemoryFromActiveSnapshot();
super.runningSucceded();
}
@Override
protected void runningFailed() {
if (memoryFromSnapshotUsed) {
removeMemoryFromActiveSnapshot();
}
super.runningFailed();
}
private void removeMemoryFromActiveSnapshot() {
String memory = getActiveSnapshot().getMemoryVolume();
if (StringUtils.isEmpty(memory)) {
return;
}
getSnapshotDAO().removeMemoryFromActiveSnapshot(getVmId());
// If the memory volumes are not used by any other snapshot, we can remove them
if (getSnapshotDAO().getNumOfSnapshotsByMemory(memory) == 0) {
removeMemoryVolumes(memory, getActionType(), true);
}
}
/**
* @return true if the VM should run as stateless
*/
protected boolean isRunAsStateless() {
return getParameters().getRunAsStateless() != null ?
getParameters().getRunAsStateless()
: getVm().isStateless();
}
@Override
public List<PermissionSubject> getPermissionCheckSubjects() {
final List<PermissionSubject> permissionList = super.getPermissionCheckSubjects();
if (!StringUtils.isEmpty(getParameters().getCustomProperties())) {
permissionList.add(new PermissionSubject(getParameters().getVmId(),
VdcObjectType.VM,
ActionGroup.CHANGE_VM_CUSTOM_PROPERTIES));
}
return permissionList;
}
@Override
public void addQuotaPermissionSubject(List<PermissionSubject> quotaPermissionList) {
}
@Override
public List<QuotaConsumptionParameter> getQuotaVdsConsumptionParameters() {
List<QuotaConsumptionParameter> list = new ArrayList<QuotaConsumptionParameter>();
list.add(new QuotaVdsGroupConsumptionParameter(getVm().getQuotaId(),
null,
QuotaConsumptionParameter.QuotaAction.CONSUME,
getVm().getVdsGroupId(),
getVm().getCpuPerSocket() * getVm().getNumOfSockets(),
getVm().getMemSizeMb()));
return list;
}
protected boolean isVmPartOfManualPool() {
if (getVm().getVmPoolId() == null) {
return false;
}
final VmPool vmPool = getDbFacade().getVmPoolDao().get(getVm().getVmPoolId());
return vmPool.getVmPoolType().equals(VmPoolType.Manual);
}
@Override
protected void endExecutionMonitoring() {
if (getVm().isRunAndPause() && getVmDynamicDao().get(getVmId()).getStatus() == VMStatus.Paused) {
final ExecutionContext executionContext = getExecutionContext();
executionContext.setShouldEndJob(true);
ExecutionHandler.endJob(executionContext, true);
} else {
super.endExecutionMonitoring();
}
}
// initial white list (null == all hosts)
protected List<Guid> getVdsWhiteList() {
return null;
}
/**
* Since this callback is called by the VdsUpdateRunTimeInfo thread, we don't want it
* to fetch the VM using {@link #getVm()}, as the thread that invokes {@link #rerun()},
* which runs in parallel, is doing setVm(null) to refresh the VM, and because of this
* race we might end up with null VM. so we fetch the static part of the VM from the DB.
*/
@Override
public void onPowerringUp() {
decreasePendingVm(getVmStaticDAO().get(getVmId()));
}
} |
package org.ovirt.engine.core.bll;
import static org.ovirt.engine.core.common.config.ConfigValues.UknownTaskPrePollingLapse;
import org.ovirt.engine.core.common.asynctasks.AsyncTaskParameters;
import org.ovirt.engine.core.common.businessentities.AsyncTaskStatus;
import org.ovirt.engine.core.common.businessentities.AsyncTaskStatusEnum;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.errors.VdcBllErrors;
import org.ovirt.engine.core.common.vdscommands.SPMTaskGuidBaseVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.compat.LogCompat;
import org.ovirt.engine.core.compat.LogFactoryCompat;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
public class SPMAsyncTask {
public SPMAsyncTask(AsyncTaskParameters parameters) {
setParameters(parameters);
setState(AsyncTaskState.Initializing);
AddOrUpdateTaskInDB();
}
private AsyncTaskParameters privateParameters;
public AsyncTaskParameters getParameters() {
return privateParameters;
}
public void setParameters(AsyncTaskParameters value) {
privateParameters = value;
}
public Guid getTaskID() {
return getParameters().getTaskID();
}
public Guid getStoragePoolID() {
return getParameters().getStoragePoolID();
}
private AsyncTaskState privateState = AsyncTaskState.forValue(0);
public AsyncTaskState getState() {
return privateState;
}
public void setState(AsyncTaskState value) {
privateState = value;
}
public boolean getShouldPoll() {
AsyncTaskState state = getState();
return (state == AsyncTaskState.Polling || state == AsyncTaskState.Ended || state == AsyncTaskState.ClearFailed)
&& getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.unknown
&& (getParameters().getEntityId() == null ? isTaskOverPrePollingLapse() : true);
}
private AsyncTaskStatus _lastTaskStatus = new AsyncTaskStatus(AsyncTaskStatusEnum.init);
public AsyncTaskStatus getLastTaskStatus() {
return _lastTaskStatus;
}
/**
* Set the _lastTaskStatus with taskStatus.
*
* @param taskStatus
* - task status to set.
*/
protected void setLastTaskStatus(AsyncTaskStatus taskStatus) {
_lastTaskStatus = taskStatus;
}
/**
* Update task last access date ,only for not active task.
*/
public void setLastStatusAccessTime() {
// Change access date to now , when task is not active.
if (getState() == AsyncTaskState.Ended
|| getState() == AsyncTaskState.AttemptingEndAction
|| getState() == AsyncTaskState.ClearFailed
|| getState() == AsyncTaskState.Cleared) {
_lastAccessToStatusSinceEnd = System.currentTimeMillis();
}
}
// Indicates time in milliseconds when task status recently changed.
protected long _lastAccessToStatusSinceEnd = System.currentTimeMillis();
public long getLastAccessToStatusSinceEnd() {
return _lastAccessToStatusSinceEnd;
}
public Object getContainerId() {
return getParameters().getEntityId();
}
private void AddOrUpdateTaskInDB() {
try {
if (getParameters().getDbAsyncTask() != null) {
if (DbFacade.getInstance().getAsyncTaskDAO().get(getTaskID()) == null) {
log.infoFormat("BaseAsyncTask::AddOrUpdateTaskInDB: Adding task {0} to DataBase", getTaskID());
DbFacade.getInstance().getAsyncTaskDAO().save(getParameters().getDbAsyncTask());
} else {
DbFacade.getInstance().getAsyncTaskDAO().update(getParameters().getDbAsyncTask());
}
}
} catch (RuntimeException e) {
log.error(String.format(
"BaseAsyncTask::AddOrUpdateTaskInDB: Adding/Updating task %1$s to DataBase threw an exception.",
getTaskID()), e);
}
}
public void UpdateAsyncTask() {
AddOrUpdateTaskInDB();
}
public void StartPollingTask() {
AsyncTaskState state = getState();
if (state != AsyncTaskState.AttemptingEndAction
&& state != AsyncTaskState.Cleared
&& state != AsyncTaskState.ClearFailed) {
log.infoFormat("BaseAsyncTask::StartPollingTask: Starting to poll task '{0}'.", getTaskID());
ConcreteStartPollingTask();
}
}
/**
* Use this to hold unknown tasks from polling, to overcome bz673695 without a complete re-haul to the
* AsyncTaskManager and CommandBase.
* @TODO remove this and re-factor {@link AsyncTaskManager}
* @return true when the time passed after creating the task is bigger than
* <code>ConfigValues.UknownTaskPrePollingLapse</code>
* @see AsyncTaskManager
* @see CommandBase
* @since 3.0
*/
boolean isTaskOverPrePollingLapse() {
AsyncTaskParameters parameters = getParameters();
long taskStartTime = parameters.getDbAsyncTask().getaction_parameters().getTaskStartTime();
Integer prePollingPeriod = Config.<Integer> GetValue(UknownTaskPrePollingLapse);
boolean idlePeriodPassed =
System.currentTimeMillis() - taskStartTime > prePollingPeriod;
log.infoFormat("task id {0} {1}. Pre-polling period is {2} millis. ",
parameters.getTaskID(),
idlePeriodPassed ? "has passed pre-polling period time and should be polled"
: "is in pre-polling period and should not be polled", prePollingPeriod);
return idlePeriodPassed;
}
protected void ConcreteStartPollingTask() {
setState(AsyncTaskState.Polling);
}
/**
* For each task set its updated status retrieved from VDSM.
*
* @param returnTaskStatus
* - Task status returned from VDSM.
*/
public void UpdateTask(AsyncTaskStatus returnTaskStatus) {
try {
switch (getState()) {
case Polling:
// Get the returned task
returnTaskStatus = CheckTaskExist(returnTaskStatus);
if (returnTaskStatus.getStatus() != getLastTaskStatus().getStatus()) {
AddLogStatusTask(returnTaskStatus);
}
setLastTaskStatus(returnTaskStatus);
if (!getLastTaskStatus().getTaskIsRunning()) {
HandleEndedTask();
}
break;
case Ended:
HandleEndedTask();
break;
// Try to clear task which failed to be cleared before SPM and DB
case ClearFailed:
ClearAsyncTask();
break;
}
}
catch (RuntimeException e) {
log.error(
String.format(
"BaseAsyncTask::PollAndUpdateTask: Handling task '%1$s' (State: %2$s, Parent Command: %3$s, Parameters Type: %4$s) threw an exception",
getTaskID(),
getState(),
(getParameters().getDbAsyncTask()
.getaction_type()),
getParameters()
.getClass().getName()),
e);
}
}
/**
* Handle ended task operation. Change task state to Ended ,Cleared or
* Cleared Failed , and log appropriate message.
*/
private void HandleEndedTask() {
// If task state is different from Ended chnage it to Ended and set the
// last access time to now.
if (getState() != AsyncTaskState.Ended) {
setState(AsyncTaskState.Ended);
setLastStatusAccessTime();
}
if (HasTaskEndedSuccessfully()) {
OnTaskEndSuccess();
}
else if (HasTaskEndedInFailure()) {
OnTaskEndFailure();
}
else if (!DoesTaskExist()) {
OnTaskDoesNotExist();
}
}
protected void RemoveTaskFromDB() {
try {
if (DbFacade.getInstance().getAsyncTaskDAO().get(getTaskID()) != null) {
log.infoFormat("BaseAsyncTask::RemoveTaskFromDB: Removing task {0} from DataBase", getTaskID());
DbFacade.getInstance().getAsyncTaskDAO().remove(getTaskID());
}
}
catch (RuntimeException e) {
log.error(String.format(
"BaseAsyncTask::RemoveTaskFromDB: Removing task %1$s from DataBase threw an exception.",
getTaskID()), e);
}
}
private boolean HasTaskEndedSuccessfully() {
return getLastTaskStatus().getTaskEndedSuccessfully();
}
private boolean HasTaskEndedInFailure() {
return !getLastTaskStatus().getTaskIsRunning() && !getLastTaskStatus().getTaskEndedSuccessfully();
}
private boolean DoesTaskExist() {
return getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.unknown;
}
protected void OnTaskEndSuccess() {
LogEndTaskSuccess();
ClearAsyncTask();
}
protected void LogEndTaskSuccess() {
log.infoFormat(
"BaseAsyncTask::OnTaskEndSuccess: Task '{0}' (Parent Command {1}, Parameters Type {2}) ended successfully.",
getTaskID(),
(getParameters().getDbAsyncTask().getaction_type()),
getParameters()
.getClass().getName());
}
protected void OnTaskEndFailure() {
LogEndTaskFailure();
ClearAsyncTask();
}
protected void LogEndTaskFailure() {
log.errorFormat(
"BaseAsyncTask::LogEndTaskFailure: Task '{0}' (Parent Command {1}, Parameters Type {2}) ended with failure:"
+ "\r\n" + "-- Result: '{3}'" + "\r\n" + "-- Message: '{4}'," + "\r\n" + "-- Exception: '{5}'",
getTaskID(),
(getParameters().getDbAsyncTask().getaction_type()),
getParameters()
.getClass().getName(),
getLastTaskStatus().getResult(),
(getLastTaskStatus().getMessage() == null ? "[null]" : getLastTaskStatus().getMessage()),
(getLastTaskStatus()
.getException() == null ? "[null]" : getLastTaskStatus().getException().getMessage()));
}
protected void OnTaskDoesNotExist() {
LogTaskDoesntExist();
ClearAsyncTask();
}
protected void LogTaskDoesntExist() {
log.errorFormat(
"BaseAsyncTask::LogTaskDoesntExist: Task '{0}' (Parent Command {1}, Parameters Type {2}) does not exist.",
getTaskID(),
(getParameters().getDbAsyncTask().getaction_type()),
getParameters()
.getClass().getName());
}
/**
* Print log message, Checks if the cachedStatusTask is null, (indicating the task was not found in the SPM).
* If so returns {@link AsyncTaskStatusEnum#running} status, otherwise returns the status as given.<br>
* <br>
* <b>Note:</b> The task is returned as running since we need to support a case where there is a change of SPM,
* or the SPM is just recovering from crash, and the SPM might return that it doesn't know that this task exists,
* but in actuality it exists. If in this case {@link AsyncTaskStatusEnum#unknown} is returned then the task
* will become a permanent zombie task since it won't be polled, so take notice if you ever want to change this
* behavior.
*
* @param cachedStatusTask The status from the SPM, or <code>null</code> is the task wasn't found in the SPM.
* @return - Updated status task
*/
protected AsyncTaskStatus CheckTaskExist(AsyncTaskStatus cachedStatusTask) {
AsyncTaskStatus returnedStatusTask = null;
// If the cachedStatusTask is null ,that means the task has not been found in the SPM.
if (cachedStatusTask == null) {
// Set to running in order to continue polling the task in case SPM hasn't loaded the tasks yet..
returnedStatusTask = new AsyncTaskStatus(AsyncTaskStatusEnum.running);
if (getLastTaskStatus().getStatus() != returnedStatusTask.getStatus()) {
log.errorFormat("SPMAsyncTask::PollTask: Task '{0}' (Parent Command {1}, Parameters Type {2}) " +
"was not found in VDSM, will change its status to running.",
getTaskID(), (getParameters().getDbAsyncTask().getaction_type()),
getParameters().getClass().getName());
}
} else {
returnedStatusTask = cachedStatusTask;
}
return returnedStatusTask;
}
/**
* Prints a log message of the task status,
*
* @param cachedStatusTask
* - Status got from VDSM
*/
protected void AddLogStatusTask(AsyncTaskStatus cachedStatusTask) {
String formatString = "SPMAsyncTask::PollTask: Polling task '{0}' (Parent Command {1}, Parameters Type {2}) "
+ "returned status '{3}'{4}.";
// If task doesn't exist (unknown) or has ended with failure (aborting)
// , log warn.
if (cachedStatusTask.getTaskIsInUnusualState()) {
log.warnFormat(
formatString,
getTaskID(),
(getParameters().getDbAsyncTask()
.getaction_type()),
getParameters().getClass().getName(),
cachedStatusTask.getStatus(),
((cachedStatusTask.getStatus() == AsyncTaskStatusEnum.finished) ? (String
.format(", result '%1$s'",
cachedStatusTask.getResult())) : ("")));
}
else {
log.infoFormat(
formatString,
getTaskID(),
(getParameters().getDbAsyncTask()
.getaction_type()),
getParameters().getClass().getName(),
cachedStatusTask.getStatus(),
((cachedStatusTask.getStatus() == AsyncTaskStatusEnum.finished) ? (String
.format(", result '%1$s'",
cachedStatusTask.getResult())) : ("")));
}
}
protected AsyncTaskStatus PollTask() {
AsyncTaskStatus returnValue = null;
try {
Object tempVar = Backend
.getInstance()
.getResourceManager()
.RunVdsCommand(VDSCommandType.SPMGetTaskStatus,
new SPMTaskGuidBaseVDSCommandParameters(getStoragePoolID(), getTaskID())).getReturnValue();
returnValue = (AsyncTaskStatus) ((tempVar instanceof AsyncTaskStatus) ? tempVar : null);
}
catch (RuntimeException e) {
log.error(
String.format(
"SPMAsyncTask::PollTask: Polling task '%1$s' (Parent Command %2$s, Parameters Type %3$s) threw an exception, task is still considered running.",
getTaskID(),
(getParameters().getDbAsyncTask().getaction_type()),
getParameters().getClass().getName()),
e);
}
if (returnValue == null) {
log.errorFormat(
"SPMAsyncTask::PollTask: Polling task '{0}' (Parent Command {1}, Parameters Type {2}) failed, task is still considered running.",
getTaskID(),
(getParameters().getDbAsyncTask().getaction_type()),
getParameters()
.getClass().getName());
AsyncTaskStatus tempVar2 = new AsyncTaskStatus();
tempVar2.setStatus(AsyncTaskStatusEnum.running);
returnValue = tempVar2;
}
String formatString =
"SPMAsyncTask::PollTask: Polling task '{0}' (Parent Command {1}, Parameters Type {2}) returned status '{3}'{4}.";
if (returnValue.getTaskIsInUnusualState()) {
log.warnFormat(
formatString,
getTaskID(),
(getParameters().getDbAsyncTask().getaction_type()),
getParameters().getClass().getName(),
returnValue.getStatus(),
((returnValue.getStatus() == AsyncTaskStatusEnum.finished) ? (String.format(", result '%1$s'",
returnValue.getResult())) : ("")));
}
else {
log.infoFormat(
formatString,
getTaskID(),
(getParameters().getDbAsyncTask().getaction_type()),
getParameters().getClass().getName(),
returnValue.getStatus(),
((returnValue.getStatus() == AsyncTaskStatusEnum.finished) ? (String.format(", result '%1$s'",
returnValue.getResult())) : ("")));
}
return returnValue;
}
public void StopTask() {
if (getState() != AsyncTaskState.AttemptingEndAction && getState() != AsyncTaskState.Cleared
&& getState() != AsyncTaskState.ClearFailed) {
try {
log.infoFormat(
"SPMAsyncTask::StopTask: Attempting to stop task '{0}' (Parent Command {1}, Parameters Type {2}).",
getTaskID(),
(getParameters().getDbAsyncTask().getaction_type()),
getParameters().getClass().getName());
Backend.getInstance()
.getResourceManager()
.RunVdsCommand(VDSCommandType.SPMStopTask,
new SPMTaskGuidBaseVDSCommandParameters(getStoragePoolID(), getTaskID()));
} catch (RuntimeException e) {
log.error(
String.format("SPMAsyncTask::StopTask: Stopping task '%1$s' threw an exception.", getTaskID()),
e);
} finally {
setState(AsyncTaskState.Polling);
}
}
}
public void ClearAsyncTask() {
VDSReturnValue vdsReturnValue = null;
try {
log.infoFormat("SPMAsyncTask::ClearAsyncTask: Attempting to clear task '{0}'", getTaskID());
vdsReturnValue = Backend
.getInstance()
.getResourceManager()
.RunVdsCommand(VDSCommandType.SPMClearTask,
new SPMTaskGuidBaseVDSCommandParameters(getStoragePoolID(), getTaskID()));
}
catch (RuntimeException e) {
log.error(String.format("SPMAsyncTask::ClearAsyncTask: Clearing task '%1$s' threw an exception.",
getTaskID()), e);
}
if (!isTaskStateError(vdsReturnValue)) {
if (vdsReturnValue == null || !vdsReturnValue.getSucceeded()) {
setState(AsyncTaskState.ClearFailed);
OnTaskCleanFailure();
} else {
setState(AsyncTaskState.Cleared);
RemoveTaskFromDB();
}
}
}
/**
* Function return true if we got error 410 - which is SPM initializing and
* we did not clear the task
*
* @param vdsReturnValue
* @return
*/
private boolean isTaskStateError(VDSReturnValue vdsReturnValue) {
if (vdsReturnValue != null && vdsReturnValue.getVdsError() != null
&& vdsReturnValue.getVdsError().getCode() == VdcBllErrors.TaskStateError) {
log.infoFormat(
"SPMAsyncTask::ClearAsyncTask: At time of attemp to clear task '{0}' the response code was {2} and message was {3}. Task will not be cleaned",
getTaskID(),
vdsReturnValue.getVdsError().getCode(),
vdsReturnValue.getVdsError().getMessage());
return true;
}
return false;
}
protected void OnTaskCleanFailure() {
LogTaskCleanFailure();
}
protected void LogTaskCleanFailure() {
log.errorFormat("SPMAsyncTask::ClearAsyncTask: Clearing task '{0}' failed.", getTaskID());
}
private static LogCompat log = LogFactoryCompat.getLog(SPMAsyncTask.class);
} |
package com.rbmhtechnology.vind.solr.backend;
import com.google.common.io.Resources;
import com.rbmhtechnology.vind.SearchServerException;
import com.rbmhtechnology.vind.annotations.AnnotationUtil;
import com.rbmhtechnology.vind.api.Document;
import com.rbmhtechnology.vind.api.SearchServer;
import com.rbmhtechnology.vind.api.ServiceProvider;
import com.rbmhtechnology.vind.api.query.*;
import com.rbmhtechnology.vind.api.query.delete.Delete;
import com.rbmhtechnology.vind.api.query.division.Page;
import com.rbmhtechnology.vind.api.query.division.Slice;
import com.rbmhtechnology.vind.api.query.facet.Facet;
import com.rbmhtechnology.vind.api.query.facet.Interval;
import com.rbmhtechnology.vind.api.query.get.RealTimeGet;
import com.rbmhtechnology.vind.api.query.suggestion.DescriptorSuggestionSearch;
import com.rbmhtechnology.vind.api.query.suggestion.ExecutableSuggestionSearch;
import com.rbmhtechnology.vind.api.query.suggestion.StringSuggestionSearch;
import com.rbmhtechnology.vind.api.query.update.Update;
import com.rbmhtechnology.vind.api.query.update.Update.UpdateOperations;
import com.rbmhtechnology.vind.api.query.update.UpdateOperation;
import com.rbmhtechnology.vind.api.result.*;
import com.rbmhtechnology.vind.configure.SearchConfiguration;
import com.rbmhtechnology.vind.model.DocumentFactory;
import com.rbmhtechnology.vind.model.FieldDescriptor;
import com.rbmhtechnology.vind.model.value.LatLng;
import com.rbmhtechnology.vind.utils.FileSystemUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.util.Asserts;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.schema.SchemaRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.SolrPingResponse;
import org.apache.solr.client.solrj.response.schema.SchemaResponse;
import org.apache.solr.client.solrj.util.ClientUtils;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.*;
import org.apache.solr.common.util.DateUtil;
import org.apache.solr.common.util.NamedList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.file.Path;
import java.text.NumberFormat;
import java.text.ParseException;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static com.rbmhtechnology.vind.api.query.update.Update.UpdateOperations.set;
import static com.rbmhtechnology.vind.solr.backend.SolrUtils.Fieldname.*;
/**
* @author Thomas Kurz (tkurz@apache.org)
* @since 21.06.16.
*/
public class SolrSearchServer extends SearchServer {
private static final Logger log = LoggerFactory.getLogger(SolrSearchServer.class);
private static final Logger solrClientLogger = LoggerFactory.getLogger(log.getName() + "#solrClient");
public static final String SOLR_WILDCARD = "*";
public static final String SUGGESTION_DF_FIELD = "suggestions";
private ServiceProvider serviceProviderClass;
private final SolrClient solrClient;
public SolrSearchServer() {
// this is mainly used with the ServiceLoader infrastructure
this(getSolrServerProvider() != null ? getSolrServerProvider().getInstance() : null);
serviceProviderClass = getSolrServerProvider();
}
public SolrSearchServer(SolrClient client) {
this(client, true);
}
/**
* Creates an instance of SolrSearch server allowing to avoid the schema validity check.
* @param client SolrClient to connect to.
* @param check true to perform local schema validity check against remote schema, false otherwise.
*/
protected SolrSearchServer(SolrClient client, boolean check) {
solrClient = client;
//In order to perform unit tests with mocked solrClient, we do not need to do the schema check.
if(check && client != null) {
try {
final SolrPingResponse ping = solrClient.ping();
if (ping.getStatus() == 0) {
log.debug("Pinged Solr in {}", ping.getQTime());
}
} catch (SolrServerException | IOException e) {
log.error("Cannot connect to solr server", e);
throw new RuntimeException();
}
log.info("Connection to solr server successful");
checkVersionAndSchema();
} else {
log.warn("Solr ping and schema validity check has been deactivated.");
}
}
private void checkVersionAndSchema() {
//check schema
try {
final SchemaResponse response = new SchemaRequest().process(solrClient);
final Path localSchema = FileSystemUtils.toPath(Resources.getResource("solrhome/core/conf/schema.xml"));
SolrSchemaChecker.checkSchema(localSchema, response);
} catch (SolrServerException e) {
log.error("Cannot get schema for solr client", e);
throw new RuntimeException(e);
} catch (URISyntaxException | IOException e) {
log.error("Cannot read schema", e);
throw new RuntimeException(e);
} catch (SchemaValidationException e) {
log.error("Schema is not valid for library", e);
throw new RuntimeException(e);
}
}
@Override
public Object getBackend() {
return solrClient;
}
@Override
public void index(Document ... docs) {
Asserts.notNull(docs,"Document to index should not be null.");
Asserts.check(docs.length > 0, "Should be at least one document to index.");
for(Document doc: docs) {
indexSingleDocument(doc);
}
}
@Override
public void index(List<Document> docs) {
Asserts.notNull(docs,"Document to index should not be null.");
Asserts.check(docs.size() > 0, "Should be at least one document to index.");
indexMultipleDocuments(docs);
}
private void indexSingleDocument(Document doc) {
final SolrInputDocument document = createInputDocument(doc);
try {
if (solrClientLogger.isTraceEnabled()) {
solrClientLogger.debug(">>> add({}): {}", doc.getId(), ClientUtils.toXML(document));
} else {
solrClientLogger.debug(">>> add({})", doc.getId());
}
this.solrClient.add(document);
} catch (SolrServerException | IOException e) {
log.error("Cannot index document {}", document.getField(ID) , e);
throw new SearchServerException("Cannot index document", e);
}
}
private void indexMultipleDocuments(List<Document> docs) {
final List<SolrInputDocument> solrDocs = docs.parallelStream()
.map(doc -> createInputDocument(doc))
.collect(Collectors.toList());
try {
if (solrClientLogger.isTraceEnabled()) {
solrClientLogger.debug(">>> add({})", solrDocs);
} else {
solrClientLogger.debug(">>> add({})", solrDocs);
}
this.solrClient.add(solrDocs);
} catch (SolrServerException | IOException e) {
log.error("Cannot index documents {}", solrDocs, e);
throw new SearchServerException("Cannot index documents", e);
}
}
private SolrInputDocument createInputDocument(Document doc) {
final SolrInputDocument document = new SolrInputDocument();
//add fields
doc.listFieldDescriptors()
.values()
.stream()
.filter(doc::hasValue)
//TODO: move again to an approach where we do not go through all the use cases but based on which flags the descriptor has set to true
.forEach(descriptor ->
doc.getFieldContexts(descriptor).stream().forEach(context ->
Stream.of(UseCase.values())
.forEach(useCase -> {
final String fieldname = getFieldname(descriptor, useCase, context);
if (Objects.nonNull(fieldname)) {
final Object value = doc.getContextualizedValue(descriptor, context);
final Object caseValue = SolrUtils.FieldValue.getFieldCaseValue(value, descriptor, useCase);
if(Objects.nonNull(caseValue)) {
document.addField(
fieldname,
toSolrJType(caseValue)
//,descriptor.getBoost() TODO should we have index time boost?
);
}
}
}
)));
//add subdocuments
if (doc.hasChildren()) {
doc.getChildren().forEach(childDocument ->
document.addChildDocument(createInputDocument(childDocument))
);
}
document.addField(ID, doc.getId());
document.addField(TYPE, doc.getType());
return document;
}
private Object toSolrJType(Object value) {
if(value!=null) {
if(Object[].class.isAssignableFrom(value.getClass())){
return toSolrJType(Arrays.asList((Object[])value));
}
if(Collection.class.isAssignableFrom(value.getClass())){
return((Collection)value).stream()
.map(o -> toSolrJType(o))
.collect(Collectors.toList());
}
if(value instanceof ZonedDateTime) {
return Date.from(((ZonedDateTime) value).toInstant());
}
if(value instanceof LatLng) {
return value.toString();
}
if(value instanceof Date) {
//noinspection RedundantCast
return ((Date) value);
}
}
return value;
}
@Override
public void commit(boolean optimize) {
try {
solrClientLogger.debug(">>> commit()");
this.solrClient.commit();
if(optimize) {
solrClientLogger.debug(">>> optimize()");
this.solrClient.optimize();
}
} catch (SolrServerException | IOException e) {
log.error("Cannot commit", e);
throw new SearchServerException("Cannot commit", e);
}
}
@Override
public <T> BeanSearchResult<T> execute(FulltextSearch search, Class<T> c) {
final DocumentFactory factory = AnnotationUtil.createDocumentFactory(c);
final SearchResult docResult = this.execute(search, factory);
return docResult.toPojoResult(docResult, c);
}
@Override
public void delete(Document doc) {
try {
solrClientLogger.debug(">>> delete({})", doc.getId());
solrClient.deleteById(doc.getId());
//Deleting nested documents
solrClient.deleteByQuery("_root_:" + doc.getId());
} catch (SolrServerException | IOException e) {
log.error("Cannot delete document {}", doc.getId() , e);
throw new SearchServerException("Cannot delete document", e);
}
}
@Override
public SearchResult execute(FulltextSearch search, DocumentFactory factory) {
final SolrQuery query = buildSolrQuery(search, factory);
//query
try {
solrClientLogger.debug(">>> query({})", query.toString());
final QueryResponse response = solrClient.query(query, SolrRequest.METHOD.POST);
if(response!=null){
final Map<String,Integer> childCounts = SolrUtils.getChildCounts(response);
final List<Document> documents = SolrUtils.Result.buildResultList(response.getResults(), childCounts, factory, search.getSearchContext());
final FacetResults facetResults = SolrUtils.Result.buildFacetResult(response, factory, search.getChildrenFactory(), search.getFacets(),search.getSearchContext());
switch(search.getResultSet().getType()) {
case page:{
return new PageResult(response.getResults().getNumFound(), documents, search, facetResults, this, factory);
}
case slice: {
return new SliceResult(response.getResults().getNumFound(), documents, search, facetResults, this, factory);
}
default:
return new PageResult(response.getResults().getNumFound(), documents, search, facetResults, this, factory);
}
}else {
throw new SolrServerException("Null result from SolrClient");
}
} catch (SolrServerException | IOException e) {
throw new SearchServerException("Cannot issue query", e);
}
}
protected SolrQuery buildSolrQuery(FulltextSearch search, DocumentFactory factory) {
//build query
final SolrQuery query = new SolrQuery();
final String searchContext = search.getSearchContext();
if(search.getTimeZone() != null) {
query.set(CommonParams.TZ,search.getTimeZone());
}
// fulltext search
query.set(CommonParams.Q, search.getSearchString());
if(SearchConfiguration.get(SearchConfiguration.SEARCH_RESULT_SHOW_SCORE, true)) {
query.set(CommonParams.FL, "*,score");
} else {
query.set(CommonParams.FL, "*");
}
if(search.getGeoDistance() != null) {
final FieldDescriptor descriptor = factory.getField(search.getGeoDistance().getFieldName());
if (Objects.nonNull(descriptor)) {
query.setParam(CommonParams.FL, query.get(CommonParams.FL) + "," + DISTANCE + ":geodist()");
query.setParam("pt", search.getGeoDistance().getLocation().toString());
query.setParam("sfield", getFieldname(descriptor, UseCase.Facet, searchContext));
}
}
Collection<FieldDescriptor<?>> fulltext = factory.listFields().stream().filter(FieldDescriptor::isFullText).collect(Collectors.toList());
if(!fulltext.isEmpty()) {
query.setParam(DisMaxParams.QF, SolrUtils.Query.buildQueryFieldString(fulltext, searchContext));
query.setParam("defType","edismax");
} else {
query.setParam(CommonParams.DF, TEXT);
}
//filters
query.add(CommonParams.FQ,"_type_:"+factory.getType());
if(search.hasFilter()) {
SolrUtils.Query.buildFilterString(search.getFilter(), factory,search.getChildrenFactory(),query, searchContext, search.getStrict());
}
// fulltext search deep search
if(search.isChildrenSearchEnabled()) {
//append childCount facet
search.facet(new Facet.SubdocumentFacet(factory));
//TODO: move to SolrUtils
final String parentSearchQuery = "(" + query.get(CommonParams.Q) + " AND " + TYPE + ":" + factory.getType() + ")";
final String childrenSearchQuery = "_query_:\"{!parent which="+ TYPE+":"+factory.getType()+"}(" + TYPE+":"+search.getChildrenFactory().getType()+" AND ("+search.getChildrenSearchString().getEscapedSearchString()+"))\"";
query.set(CommonParams.Q, String.join(" ",parentSearchQuery, search.getChildrenSearchOperator().name(), childrenSearchQuery));
if(search.getChildrenSearchString().hasFilter()){
//TODO clean up!
final String parentFilterQuery = "(" + String.join(" AND ", query.getFilterQueries()) + ")";
final String childrenFilterQuery = search.getChildrenSearchString()
.getFilter().accept(new SolrChildrenSerializerVisitor(factory,search.getChildrenFactory(),searchContext, search.getStrict()));
query.set(CommonParams.FQ, String.join(" ", parentFilterQuery, search.getChildrenSearchOperator().name(), "("+childrenFilterQuery+")"));
}
}
if(search.hasFacet()) {
query.setFacet(true);
query.setFacetMinCount(search.getFacetMinCount());
query.setFacetLimit(search.getFacetLimit());
//Query facets
search.getFacets().values().stream()
.filter(facet -> Facet.QueryFacet.class.isAssignableFrom(facet.getClass()))
.map(genericFacet -> (Facet.QueryFacet)genericFacet)
.forEach(queryFacet ->
query.addFacetQuery(StringUtils.join(SolrUtils.Query.buildSolrFacetCustomName(SolrUtils.Query.buildFilterString(queryFacet.getFilter(), factory, search.getChildrenFactory(), searchContext,search.getStrict()), queryFacet)))
);
//Numeric Range facet
search.getFacets().values().stream()
.filter(facet -> Facet.NumericRangeFacet.class.isAssignableFrom(facet.getClass()))
.map(genericFacet -> (Facet.NumericRangeFacet) genericFacet)
.forEach(numericRangeFacet -> {
String fieldName = getFieldname(numericRangeFacet.getFieldDescriptor(), UseCase.Facet, searchContext);
query.add(FacetParams.FACET_RANGE,SolrUtils.Query.buildSolrFacetCustomName(fieldName, numericRangeFacet));
query.add(String.format(Locale.ROOT, "f.%s.%s", fieldName,
FacetParams.FACET_RANGE_START),
numericRangeFacet.getStart().toString());
query.add(String.format(Locale.ROOT, "f.%s.%s", fieldName,
FacetParams.FACET_RANGE_END),
numericRangeFacet.getEnd().toString());
query.add(String.format(Locale.ROOT, "f.%s.%s", fieldName,
FacetParams.FACET_RANGE_GAP),
numericRangeFacet.getGap().toString());
/*query.addNumericRangeFacet(
SolrUtils.Query.buildSolrFacetCustomName(fieldName, numericRangeFacet.getName()),
numericRangeFacet.getStart(),
numericRangeFacet.getEnd(),
numericRangeFacet.getGap());*/});
//Interval Range facet
search.getFacets().values().stream()
.filter(facet -> Facet.IntervalFacet.class.isAssignableFrom(facet.getClass()))
.map(genericFacet -> (Facet.IntervalFacet) genericFacet)
.forEach(intervalFacet -> {
String fieldName = getFieldname(intervalFacet.getFieldDescriptor(), UseCase.Facet, searchContext);
query.add(FacetParams.FACET_INTERVAL, SolrUtils.Query.buildSolrFacetKey(intervalFacet.getName()) + fieldName);
for(Object o : intervalFacet.getIntervals()) {
Interval i = (Interval) o; //TODO why is this necessary?
query.add(String.format("f.%s.%s", fieldName, FacetParams.FACET_INTERVAL_SET),
String.format("%s%s%s,%s%s",
SolrUtils.Query.buildSolrFacetKey(i.getName()),
i.includesStart() ? "[" : "(",
i.getStart() == null? SOLR_WILDCARD : SolrUtils.Query.buildSolrQueryValue(i.getStart()),
i.getEnd() == null? SOLR_WILDCARD : SolrUtils.Query.buildSolrQueryValue(i.getEnd()),
i.includesEnd() ? "]" : ")")
);
}
});
//Date Range facet
search.getFacets().values().stream()
.filter(facet -> Facet.DateRangeFacet.class.isAssignableFrom(facet.getClass()))
.map(genericFacet -> (Facet.DateRangeFacet)genericFacet)
.forEach(dateRangeFacet ->
generateDateRangeQuery(dateRangeFacet, query, searchContext)
);
//stats
search.getFacets().values().stream()
.filter(facet -> Facet.StatsFacet.class.isAssignableFrom(facet.getClass()))
.map(genericFacet -> (Facet.StatsFacet)genericFacet)
.forEach(statsFacet -> {
String fieldName = getFieldname(statsFacet.getField(), UseCase.Facet, searchContext);
query.add(StatsParams.STATS, "true");
query.add(StatsParams.STATS_FIELD, SolrUtils.Query.buildSolrStatsQuery(fieldName, statsFacet));
});
//pivot facet
search.getFacets().values().stream()
.filter(facet -> Facet.PivotFacet.class.isAssignableFrom(facet.getClass()))
.map(genericFacet -> (Facet.PivotFacet)genericFacet)
.forEach(pivotFacet -> {
String[] fieldNames=
pivotFacet.getFieldDescriptors().stream()
.map(fieldDescriptor -> getFieldname(fieldDescriptor, UseCase.Facet, searchContext))
.toArray(String[]::new);
query.add(FacetParams.FACET_PIVOT,SolrUtils.Query.buildSolrPivotSubFacetName(pivotFacet.getName(),fieldNames));
});
//facet fields
final HashMap<String, Object> strings = SolrUtils.Query.buildJsonTermFacet(search.getFacets(), factory, search.getChildrenFactory(), searchContext);
query.add("json.facet", strings.toString().replaceAll("=",":"));
//facet Subdocument count
final String subdocumentFacetString = SolrUtils.Query.buildSubdocumentFacet(search, factory, searchContext);
if(Objects.nonNull(subdocumentFacetString)) {
query.add("json.facet", subdocumentFacetString);
}
}
// sorting
if(search.hasSorting()) {
final String sortString = SolrUtils.Query.buildSortString(search, search.getSorting(), factory);
query.set(CommonParams.SORT, sortString);
}
//boost functions
//TODO this is a mess
if(search.hasSorting()) {
query.set(DisMaxParams.BF, SolrUtils.Query.buildBoostFunction(search.getSorting(), searchContext));
}
// paging
switch(search.getResultSet().getType()) {
case page:{
final Page resultSet = (Page) search.getResultSet();
query.setStart(resultSet.getOffset());
query.setRows(resultSet.getPagesize());
break;
}
case slice: {
final Slice resultSet = (Slice) search.getResultSet();
query.setStart(resultSet.getOffset());
query.setRows(resultSet.getSliceSize());
break;
}
}
return query;
}
private void generateDateRangeQuery(Facet.DateRangeFacet dateRangeFacet, SolrQuery query, String searchContext) {
final String fieldName = getFieldname(dateRangeFacet.getFieldDescriptor(), UseCase.Facet, searchContext);
query.add(FacetParams.FACET_RANGE,SolrUtils.Query.buildSolrFacetCustomName(fieldName, dateRangeFacet));
final Object startDate = dateRangeFacet.getStart();
final Object endDate = dateRangeFacet.getEnd();
String startString;
String endString;
if (dateRangeFacet instanceof Facet.DateRangeFacet.UtilDateRangeFacet){
final Instant startInstant = ((Date) startDate).toInstant();
startString = DateUtil.getThreadLocalDateFormat().format(Date.from(startInstant));
final Instant endInstant = ((Date) endDate).toInstant();
endString = DateUtil.getThreadLocalDateFormat().format(Date.from(endInstant));
} else if (dateRangeFacet instanceof Facet.DateRangeFacet.ZoneDateRangeFacet){
final Instant startInstant = ((ZonedDateTime) startDate).toInstant();
startString = DateUtil.getThreadLocalDateFormat().format(Date.from(startInstant));
final Instant endInstant = ((ZonedDateTime) endDate).toInstant();
endString = DateUtil.getThreadLocalDateFormat().format(Date.from(endInstant));
} else {
startString = dateRangeFacet.getStart().toString();
endString = dateRangeFacet.getEnd().toString();
}
query.add(String.format(Locale.ROOT, "f.%s.%s", fieldName,
FacetParams.FACET_RANGE_START),
startString);
query.add(String.format(Locale.ROOT, "f.%s.%s", fieldName,
FacetParams.FACET_RANGE_END),
endString);
query.add(String.format(Locale.ROOT, "f.%s.%s", fieldName,
FacetParams.FACET_RANGE_GAP),
SolrUtils.Query.buildSolrTimeGap(dateRangeFacet.getGap()));
}
@Override
public boolean execute(Update update,DocumentFactory factory) {
//Check if document is updatable and all its fields are stored.
final boolean isUpdatable = factory.isUpdatable() && factory.getFields().values().stream()
.allMatch( descriptor -> descriptor.isUpdate());
if (isUpdatable) {
final SolrInputDocument sdoc = new SolrInputDocument();
sdoc.addField(ID, update.getId());
sdoc.addField(TYPE, factory.getType());
HashMap<FieldDescriptor<?>, HashMap<String, SortedSet<UpdateOperation>>> updateOptions = update.getOptions();
updateOptions.keySet()
.forEach(fieldDescriptor ->
Stream.of(UseCase.values()).forEach(useCase ->
updateOptions.get(fieldDescriptor).keySet()
.stream().forEach(context -> {
//NOTE: Backwards compatibility
final String updateContext = Objects.isNull(context)? update.getUpdateContext() : context;
final String fieldName = getFieldname(fieldDescriptor, useCase, updateContext);
if (fieldName != null) {
final Map<String, Object> fieldModifiers = new HashMap<>();
updateOptions.get(fieldDescriptor).get(context).stream().forEach(entry -> {
UpdateOperations opType = entry.getType();
if(fieldName.startsWith("dynamic_single_") && useCase.equals(UseCase.Sort) && opType.equals(UpdateOperations.add)) {
opType = set;
}
fieldModifiers.put(opType.name(),
toSolrJType(SolrUtils.FieldValue.getFieldCaseValue(entry.getValue(), fieldDescriptor, useCase)));
});
sdoc.addField(fieldName, fieldModifiers);
}
})
)
);
try {
if (solrClientLogger.isTraceEnabled()) {
solrClientLogger.debug(">>> add({}): {}", update.getId(), sdoc);
} else {
solrClientLogger.debug(">>> add({})", update.getId());
}
SolrInputDocument finalDoc = sdoc;
//Get the original document
final SolrDocument updatedDoc = solrClient.getById(update.getId());
//Setting the document version for optimistic concurrency
final Object version = updatedDoc.getFieldValue("_version_");
if (Objects.nonNull(version)) {
finalDoc.setField("_version_", version);
} else {
log.warn("Error updating document '{}': " +
"Atomic updates in nested documents are not supported by Solr", updatedDoc.get(ID));
return false;
}
//Get the nested docs of the document if existing
final NamedList<Object> paramList = new NamedList<>();
paramList.add(CommonParams.Q, "!( _id_:"+ update.getId()+")&(_root_:"+ update.getId()+")");
final QueryResponse query = solrClient.query(SolrParams.toSolrParams(paramList), SolrRequest.METHOD.POST);
//if the document has nested docs solr does not support atomic updates
if (CollectionUtils.isNotEmpty(query.getResults())) {
finalDoc = this.getUpdatedSolrDocument(sdoc, updatedDoc, query);
}
try {
solrClient.add(finalDoc);
return true;
} catch (HttpSolrClient.RemoteSolrException e) {
log.warn("Error updating document {}: {}", finalDoc.getFieldValue(ID),e.getMessage(), e);
return false;
}
} catch (SolrServerException | IOException e) {
log.error("Unable to perform solr partial update on document with id [{}]", update.getId(), e);
throw new SearchServerException("Can not execute solr partial update.", e);
}
} else {
Exception e = new SearchServerException("It is not safe to execute solr partial update: Document contains non stored fields");
log.error("Unable to perform solr partial update on document with id [{}]", update.getId(), e);
throw new RuntimeException("Can not execute solr partial update.", e);
}
}
private SolrInputDocument getUpdatedSolrDocument(SolrInputDocument sdoc, SolrDocument updatedDoc, QueryResponse query) {
//TODO:find a better way - non deprecated way
//Create an input document from the original doc to be updated
final SolrInputDocument inputDoc = ClientUtils.toSolrInputDocument(updatedDoc);
//Get the list of nested documents
final List<SolrInputDocument> childDocs = query.getResults().stream()
.map(nestedDoc -> ClientUtils.toSolrInputDocument(nestedDoc))
.collect(Collectors.toList());
//Add nested documents to the doc
inputDoc.addChildDocuments(childDocs);
//TODO: think about a cleaner solution
//Update the original document
sdoc.getFieldNames().stream()
.filter(fn -> !fn.equals(ID) && !fn.equals(TYPE) && !fn.equals("_version_") )//TODO: Add all the special fields or do the oposite check, whether it fits a dynamic Vind field
.forEach( fn -> {
final ArrayList fieldOp = (ArrayList) sdoc.getFieldValues(fn);
fieldOp.stream()
.forEach( op -> {
final Set<String> keys = ((HashMap<String, String>) op).keySet();
keys.stream()
.forEach(k -> {
switch (UpdateOperations.valueOf(k)) {
case set:
inputDoc.setField(fn, ((HashMap<String, String>) op).get(k) );
break;
case add:
inputDoc.addField(fn, ((HashMap<String, String>) op).get(k) );
break;
case inc:
final Number fieldValue;
try {
fieldValue = NumberFormat.getInstance().parse((String)inputDoc.getFieldValue(fn));
} catch (ParseException e) {
throw new RuntimeException();
}
inputDoc.setField(fn,String.valueOf(fieldValue.floatValue()+1));
break;
case remove:
inputDoc.removeField(fn);
break;
case removeregex:
final String fieldStringValue = (String)inputDoc.getFieldValue(fn);
final String regex = ((HashMap<String, String>) op).get(k);
if (regex.matches(fieldStringValue)) {
inputDoc.removeField(fn);
}
break;
}
});
}
);
}
);
return inputDoc;
}
@Override
public void execute(Delete delete, DocumentFactory factory) {
String query = SolrUtils.Query.buildFilterString(delete.getQuery(), factory, delete.getUpdateContext(),true);
try {
solrClientLogger.debug(">>> delete query({})", query);
//Finding the ID of the documents to delete
final SolrQuery solrQuery = new SolrQuery();
solrQuery.setParam(CommonParams.Q, "*:*");
solrQuery.setParam(CommonParams.FQ,query.trim().replaceAll("^\\+","").split("\\+"));
final QueryResponse response = solrClient.query(solrQuery, SolrRequest.METHOD.POST);
if(Objects.nonNull(response) && CollectionUtils.isNotEmpty(response.getResults())){
final List<String> idList = response.getResults().stream().map(doc -> (String) doc.get(ID)).collect(Collectors.toList());
solrClient.deleteById(idList);
//Deleting nested documents
solrClient.deleteByQuery("_root_:("+StringUtils.join(idList, " OR ")+")");
}
} catch (SolrServerException | IOException e) {
log.error("Cannot delete with query {}", query, e);
throw new SearchServerException("Cannot delete with query", e);
}
}
@Override
public <T> SuggestionResult execute(ExecutableSuggestionSearch search, Class<T> c) {
DocumentFactory documentFactory = AnnotationUtil.createDocumentFactory(c);
return this.execute(search, documentFactory);
}
@Override
public SuggestionResult execute(ExecutableSuggestionSearch search, DocumentFactory assets) {
return execute(search,assets,null);
}
@Override
public SuggestionResult execute(ExecutableSuggestionSearch search, DocumentFactory assets,DocumentFactory childFactory) {
SolrQuery query = buildSolrQuery(search, assets, childFactory);
try {
log.debug(">>> query({})", query.toString());
QueryResponse response = solrClient.query(query, SolrRequest.METHOD.POST);
if(response!=null){
return SolrUtils.Result.buildSuggestionResult(response, assets, childFactory, search.getSearchContext());
}else {
log.error("Null result from SolrClient");
throw new SolrServerException("Null result from SolrClient");
}
} catch (SolrServerException | IOException e) {
log.error("Cannot execute suggestion query");
throw new SearchServerException("Cannot execute suggestion query", e);
}
}
protected SolrQuery buildSolrQuery(ExecutableSuggestionSearch search, DocumentFactory assets, DocumentFactory childFactory) {
final String searchContext = search.getSearchContext();
final SolrQuery query = new SolrQuery();
query.setRequestHandler("/suggester");
if(search.isStringSuggestion()) {
StringSuggestionSearch s = (StringSuggestionSearch) search;
query.setParam("suggestion.field", s.getSuggestionFields()
.stream()
.map(name -> {
if(Objects.nonNull(childFactory)) {
final FieldDescriptor<?> field = Objects.nonNull(assets.getField(name))?
assets.getField(name):
childFactory.getField(name);
if(Objects.isNull(field)) {
log.warn("No field descriptor found for field name {} in factories: {}, {}", name,assets.getType(), childFactory.getType());
}
return getFieldname(field, UseCase.Suggest, searchContext);
} else {
if(Objects.isNull(assets.getField(name))) {
log.warn("No field descriptor found for field name {} in factory: {}", name,assets.getType());
}
return getFieldname(assets.getField(name), UseCase.Suggest, searchContext);
}
})
.filter(Objects::nonNull)
.toArray(String[]::new));
} else {
DescriptorSuggestionSearch s = (DescriptorSuggestionSearch) search;
query.setParam("suggestion.field", s.getSuggestionFields()
.stream()
.map(descriptor -> getFieldname(descriptor, UseCase.Suggest, searchContext))
.filter(Objects::nonNull)
.toArray(String[]::new));
}
query.setParam("q", search.getInput());
query.setParam("suggestion.df", SUGGESTION_DF_FIELD);//TODO: somehow this is still needed here, it should by configuration
query.setParam("suggestion.limit", String.valueOf(search.getLimit()));
String parentTypeFilter = "_type_:" + assets.getType();
if(Objects.nonNull(childFactory)) {
parentTypeFilter ="("+parentTypeFilter+" OR _type_:" + childFactory.getType() + ")";
}
query.add(CommonParams.FQ, parentTypeFilter);
//filters
if(search.hasFilter()) {
SolrUtils.Query.buildFilterString(search.getFilter(), assets,childFactory,query, searchContext, false);
new SolrChildrenSerializerVisitor(assets,childFactory,searchContext,false);
}
// suggestion deep search
if(Objects.nonNull(childFactory)) {
if(search.hasFilter()){
//TODO clean up!
final String parentFilterQuery = "(" + String.join(" AND ", query.getFilterQueries()) + ")";
final String childrenFilterQuery = search.getFilter()
.accept(new SolrChildrenSerializerVisitor(assets,childFactory,searchContext, false));
final String childrenBJQ = "{!child of=\"_type_:"+assets.getType()+"\" v='"+childrenFilterQuery+"'}";
query.set(CommonParams.FQ, String.join(" ", parentFilterQuery, "OR", childrenBJQ));
}
}
return query;
}
@Override
public <T> GetResult execute(RealTimeGet search, Class<T> c) {
DocumentFactory documentFactory = AnnotationUtil.createDocumentFactory(c);
return this.execute(search,documentFactory);
}
@Override
public GetResult execute(RealTimeGet search, DocumentFactory assets) {
SolrQuery query = buildSolrQuery(search, assets);
try {
log.debug(">>> query({})", query.toString());
QueryResponse response = solrClient.query(query, SolrRequest.METHOD.POST);
if(response!=null){
return SolrUtils.Result.buildRealTimeGetResult(response, search, assets);
}else {
log.error("Null result from SolrClient");
throw new SolrServerException("Null result from SolrClient");
}
} catch (SolrServerException | IOException e) {
log.error("Cannot execute realTime get query");
throw new SearchServerException("Cannot execute realTime get query", e);
}
}
@Override
public void clearIndex() {
try {
solrClientLogger.debug(">>> clear complete index");
solrClient.deleteByQuery("*:*");
} catch (SolrServerException | IOException e) {
log.error("Cannot clear index", e);
throw new SearchServerException("Cannot clear index", e);
}
}
protected SolrQuery buildSolrQuery(RealTimeGet search, DocumentFactory assets) {
SolrQuery query = new SolrQuery();
query.setRequestHandler("/get");
search.getValues().forEach(v -> query.add("id" , v.toString()));
return query;
}
@Override
public void close() {
if (solrClient != null) try {
solrClient.close();
} catch (IOException e) {
log.error("Cannot close search server", e);
throw new SearchServerException("Cannot close search server", e);
}
}
protected static SolrServerProvider getSolrServerProvider() {
String providerClassName = SearchConfiguration.get(SearchConfiguration.SERVER_PROVIDER, null);
//Backwards compatibility needed
final String solrProviderClassName = SearchConfiguration.get(SearchConfiguration.SERVER_SOLR_PROVIDER, null);
if (providerClassName == null && solrProviderClassName != null) {
providerClassName = solrProviderClassName;
}
final ServiceLoader<SolrServerProvider> loader = ServiceLoader.load(SolrServerProvider.class);
final Iterator<SolrServerProvider> it = loader.iterator();
SolrServerProvider serverProvider = null;
if(providerClassName == null) {
if (!it.hasNext()) {
log.error("No SolrServerProvider in classpath");
throw new RuntimeException("No SolrServerProvider in classpath");
} else {
serverProvider = it.next();
}
if (it.hasNext()) {
log.warn("Multiple bindings for SolrServerProvider found: {}", loader.iterator());
}
} else {
try {
final Class<?> providerClass = Class.forName(providerClassName);
while(it.hasNext()) {
final SolrServerProvider p = it.next();
if(providerClass.isAssignableFrom(p.getClass())) {
serverProvider = p;
break;
}
}
} catch (ClassNotFoundException e) {
log.warn("Specified class {} is not in classpath",providerClassName, e);
//throw new RuntimeException("Specified class " + providerClassName + " is not in classpath");
}
log.info("No server provider of type class {} found in classpath for server {}", providerClassName, SolrSearchServer.class.getCanonicalName());
//if(serverProvider == null) throw new RuntimeException("No server provider found for class " + providerClassName);
}
return serverProvider;
}
@Override
public Class getServiceProviderClass() {
return serviceProviderClass!=null? serviceProviderClass.getClass() : null;
}
} |
package ai.verta.modeldb.experimentRun.subtypes;
import ai.verta.common.KeyValue;
import ai.verta.modeldb.Observation;
import ai.verta.modeldb.common.CommonUtils;
import ai.verta.modeldb.common.exceptions.ModelDBException;
import ai.verta.modeldb.common.futures.FutureJdbi;
import ai.verta.modeldb.common.futures.InternalFuture;
import ai.verta.modeldb.exceptions.InvalidArgumentException;
import ai.verta.modeldb.utils.ModelDBUtils;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.protobuf.Value;
import java.util.List;
import java.util.Optional;
import java.util.concurrent.Executor;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class ObservationHandler {
private static Logger LOGGER = LogManager.getLogger(KeyValueHandler.class);
private final Executor executor;
private final FutureJdbi jdbi;
public ObservationHandler(Executor executor, FutureJdbi jdbi) {
this.executor = executor;
this.jdbi = jdbi;
}
public InternalFuture<List<Observation>> getObservations(String runId, String key) {
// TODO: support artifacts?
// Validate input
var currentFuture =
InternalFuture.runAsync(
() -> {
if (key.isEmpty()) {
throw new InvalidArgumentException("Empty observation key");
}
},
executor);
// Query
return currentFuture.thenCompose(
unused ->
jdbi.withHandle(
handle ->
handle
.createQuery(
"select k.kv_value value, k.value_type type, o.epoch_number epoch from "
+ "(select keyvaluemapping_id, epoch_number from observation "
+ "where experiment_run_id =:run_id and entity_name = :entity_name:) o, "
+ "(select id, kv_value, value_type from keyvalue where kv_key =:name and entity_name IS NULL) k "
+ "where o.keyvaluemapping_id = k.id")
.bind("run_id", runId)
.bind("entity_name", "\"ExperimentRunEntity\"")
.bind("name", key)
.map(
(rs, ctx) -> {
try {
return Observation.newBuilder()
.setEpochNumber(
Value.newBuilder().setNumberValue(rs.getLong("epoch")))
.setAttribute(
KeyValue.newBuilder()
.setKey(key)
.setValue(
(Value.Builder)
CommonUtils.getProtoObjectFromString(
rs.getString("value"), Value.newBuilder()))
.setValueTypeValue(rs.getInt("type")))
.build();
} catch (InvalidProtocolBufferException e) {
LOGGER.error(
"Error generating builder for {}", rs.getString("value"));
throw new ModelDBException(e);
}
})
.list()),
executor);
}
public InternalFuture<Void> logObservations(
String runId, List<Observation> observations, long now) {
// TODO: support artifacts?
// Validate input
var currentFuture =
InternalFuture.runAsync(
() -> {
for (final var observation : observations) {
if (observation.getAttribute().getKey().isEmpty()) {
throw new InvalidArgumentException("Empty observation key");
}
}
},
executor);
// Log observations
for (final var observation : observations) {
final var attribute = observation.getAttribute();
currentFuture =
currentFuture
.thenCompose(
unused -> {
// If the epoch is specified, save it directly
if (observation.hasEpochNumber()) {
if (observation.getEpochNumber().getKindCase()
!= Value.KindCase.NUMBER_VALUE) {
String invalidEpochMessage =
"Observations can only have numeric epoch_number, condition not met in "
+ observation;
throw new InvalidArgumentException(invalidEpochMessage);
}
return InternalFuture.completedInternalFuture(
(long) observation.getEpochNumber().getNumberValue());
} else {
// Otherwise, infer at runtime. We can't do this in the same SQL command as
// we'll be updating these tables and some SQL implementations don't support
// select together with updates
final var sql =
"select max(o.epoch_number) from "
+ "(select keyvaluemapping_id, epoch_number from observation "
+ "where experiment_run_id =:run_id and entity_name = :entity_name) o, "
+ "(select id from keyvalue where kv_key =:name and entity_name IS NULL) k "
+ "where o.keyvaluemapping_id = k.id";
return jdbi.withHandle(
handle ->
handle
.createQuery(sql)
.bind("run_id", runId)
.bind("entity_name", "\"ExperimentRunEntity\"")
.bind("name", attribute.getKey())
.mapTo(Long.class)
.findOne()
.map(x -> x + 1)
.orElse(0L));
}
},
executor)
.thenCompose(
epoch ->
// Insert into KV table
jdbi.useHandle(
handle -> {
final var kvId =
handle
.createUpdate(
"insert into keyvalue (field_type, kv_key, kv_value, value_type) "
+ "values (:field_type, :key, :value, :type)")
.bind("field_type", "\"attributes\"")
.bind("key", attribute.getKey())
.bind(
"value",
ModelDBUtils.getStringFromProtoObject(attribute.getValue()))
.bind("type", attribute.getValueTypeValue())
.executeAndReturnGeneratedKeys()
.mapTo(Long.class)
.one();
// Insert to observation table
// We don't need transaction here since it's fine to add to the kv table
// and fail to insert into the observation table, as the value will be
// just ignored
handle
.createUpdate(
"insert into observation (entity_name, field_type, timestamp, experiment_run_id, keyvaluemapping_id, epoch_number) "
+ "values (:entity_name, :field_type, :timestamp, :run_id, :kvid, :epoch)")
.bind(
"timestamp",
observation.getTimestamp() == 0
? now
: observation.getTimestamp())
.bind("entity_name", "\"ExperimentRunEntity\"")
.bind("field_type", "\"observations\"")
.bind("run_id", runId)
.bind("kvid", kvId)
.bind("epoch", epoch)
.executeAndReturnGeneratedKeys()
.mapTo(Long.class)
.one();
}),
executor);
}
return currentFuture;
}
public InternalFuture<Void> deleteObservations(String runId, Optional<List<String>> maybeKeys) {
return jdbi.useHandle(
handle -> {
// Delete from keyvalue
var sql =
"delete from keyvalue where id in "
+ "(select keyvaluemapping_id from observation where entity_name=:entity_name and field_type=:field_type and experiment_run_id=:run_id)";
if (maybeKeys.isPresent()) {
sql += " and kv_key in (<keys>)";
}
var query =
handle
.createUpdate(sql)
.bind("entity_name", "\"ExperimentRunEntity\"")
.bind("field_type", "\"observations\"")
.bind("run_id", runId);
if (maybeKeys.isPresent()) {
query = query.bindList("keys", maybeKeys.get());
}
query.execute();
// Delete from observations by finding missing keyvalue matches
sql =
"delete from observation where id in "
+ "(select o.id from observation o left join keyvalue k on o.keyvaluemapping_id=k.id where o.experiment_run_id=:run_id and o.keyvaluemapping_id is null)";
query = handle.createUpdate(sql).bind("run_id", runId);
query.execute();
});
}
} |
package com.github.kubatatami.judonetworking.exceptions;
public class HttpException extends ConnectionException {
private int code;
private String body;
public HttpException(String message, String body, int code) {
super(message);
this.code = code;
this.body = body;
}
public int getCode() {
return code;
}
public String getBody() {
return body;
}
@Override
public String toString() {
String msg = getLocalizedMessage();
String name = getClass().getName();
String body = getBody();
if (msg == null && body == null) {
return name;
} else if (body == null) {
return name + ": " + msg;
} else if (msg == null) {
return name + ": " + body;
}
return name + ": " + msg + " " + body;
}
} |
package org.opendaylight.protocol.bgp.rib.impl;
import static java.util.Objects.requireNonNull;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.MoreObjects;
import com.google.common.base.MoreObjects.ToStringHelper;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.ScheduledFuture;
import java.io.IOException;
import java.nio.channels.NonWritableChannelException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import org.checkerframework.checker.lock.qual.GuardedBy;
import org.opendaylight.protocol.bgp.parser.AsNumberUtil;
import org.opendaylight.protocol.bgp.parser.BGPDocumentedException;
import org.opendaylight.protocol.bgp.parser.BGPError;
import org.opendaylight.protocol.bgp.parser.BgpExtendedMessageUtil;
import org.opendaylight.protocol.bgp.parser.BgpTableTypeImpl;
import org.opendaylight.protocol.bgp.parser.GracefulRestartUtil;
import org.opendaylight.protocol.bgp.parser.spi.MultiPathSupport;
import org.opendaylight.protocol.bgp.parser.spi.PeerConstraint;
import org.opendaylight.protocol.bgp.parser.spi.pojo.MultiPathSupportImpl;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPMessagesListener;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPPeerRegistry;
import org.opendaylight.protocol.bgp.rib.impl.spi.BGPSessionPreferences;
import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateImpl;
import org.opendaylight.protocol.bgp.rib.impl.state.BGPSessionStateProvider;
import org.opendaylight.protocol.bgp.rib.spi.BGPSession;
import org.opendaylight.protocol.bgp.rib.spi.BGPSessionListener;
import org.opendaylight.protocol.bgp.rib.spi.BGPTerminationReason;
import org.opendaylight.protocol.bgp.rib.spi.State;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPSessionState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPTimersState;
import org.opendaylight.protocol.bgp.rib.spi.state.BGPTransportState;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.AsNumber;
import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Ipv4Address;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Keepalive;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.KeepaliveBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Notify;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.NotifyBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Open;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.Update;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.BgpParameters;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.bgp.parameters.OptionalCapabilities;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.message.rev180329.open.message.bgp.parameters.optional.capabilities.CParameters;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.BgpTableType;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.CParameters1;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.MpCapabilities;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.RouteRefresh;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.AddPathCapability;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.GracefulRestartCapability;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.LlGracefulRestartCapability;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.MultiprotocolCapability;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.multiprotocol.rev180329.mp.capabilities.add.path.capability.AddressFamilies;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.bgp.rib.rev180329.rib.TablesKey;
import org.opendaylight.yangtools.yang.binding.ChildOf;
import org.opendaylight.yangtools.yang.binding.Notification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@VisibleForTesting
public class BGPSessionImpl extends SimpleChannelInboundHandler<Notification> implements BGPSession,
BGPSessionStateProvider, AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(BGPSessionImpl.class);
private static final Notification KEEP_ALIVE = new KeepaliveBuilder().build();
private static final int KA_TO_DEADTIMER_RATIO = 3;
private static final String EXTENDED_MSG_DECODER = "EXTENDED_MSG_DECODER";
static final String END_OF_INPUT = "End of input detected. Close the session.";
/**
* System.nanoTime value about when was sent the last message.
*/
@VisibleForTesting
private long lastMessageSentAt;
/**
* System.nanoTime value about when was received the last message.
*/
private long lastMessageReceivedAt;
private final BGPSessionListener listener;
private final BGPSynchronization sync;
private int kaCounter = 0;
private final Channel channel;
@GuardedBy("this")
private State state = State.OPEN_CONFIRM;
private final Set<BgpTableType> tableTypes;
private final List<AddressFamilies> addPathTypes;
private final long holdTimerNanos;
private final long keepAliveNanos;
private final AsNumber asNumber;
private final Ipv4Address bgpId;
private final BGPPeerRegistry peerRegistry;
private final ChannelOutputLimiter limiter;
private final BGPSessionStateImpl sessionState;
private final GracefulRestartCapability gracefulCapability;
private final LlGracefulRestartCapability llGracefulCapability;
private boolean terminationReasonNotified;
public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen,
final BGPSessionPreferences localPreferences, final BGPPeerRegistry peerRegistry) {
this(listener, channel, remoteOpen, localPreferences.getHoldTime(), peerRegistry);
}
public BGPSessionImpl(final BGPSessionListener listener, final Channel channel, final Open remoteOpen,
final int localHoldTimer, final BGPPeerRegistry peerRegistry) {
this.listener = requireNonNull(listener);
this.channel = requireNonNull(channel);
this.limiter = new ChannelOutputLimiter(this);
this.channel.pipeline().addLast(this.limiter);
final int holdTimerValue = remoteOpen.getHoldTimer() < localHoldTimer ? remoteOpen.getHoldTimer()
: localHoldTimer;
LOG.info("BGP HoldTimer new value: {}", holdTimerValue);
this.holdTimerNanos = TimeUnit.SECONDS.toNanos(holdTimerValue);
this.keepAliveNanos = TimeUnit.SECONDS.toNanos(holdTimerValue / KA_TO_DEADTIMER_RATIO);
this.asNumber = AsNumberUtil.advertizedAsNumber(remoteOpen);
this.peerRegistry = peerRegistry;
this.sessionState = new BGPSessionStateImpl();
final Set<TablesKey> tts = new HashSet<>();
final Set<BgpTableType> tats = new HashSet<>();
final List<AddressFamilies> addPathCapabilitiesList = new ArrayList<>();
final List<BgpParameters> bgpParameters = remoteOpen.getBgpParameters();
if (bgpParameters != null) {
for (final BgpParameters param : bgpParameters) {
for (final OptionalCapabilities optCapa : param.getOptionalCapabilities()) {
final CParameters cParam = optCapa.getCParameters();
final CParameters1 cParam1 = cParam.augmentation(CParameters1.class);
if (cParam1 != null) {
final MultiprotocolCapability multi = cParam1.getMultiprotocolCapability();
if (multi != null) {
final TablesKey tt = new TablesKey(multi.getAfi(), multi.getSafi());
LOG.trace("Added table type to sync {}", tt);
tts.add(tt);
tats.add(new BgpTableTypeImpl(tt.getAfi(), tt.getSafi()));
} else {
final AddPathCapability addPathCap = cParam1.getAddPathCapability();
if (addPathCap != null) {
addPathCapabilitiesList.addAll(addPathCap.getAddressFamilies());
}
}
}
}
}
this.gracefulCapability = findSingleCapability(bgpParameters, "Graceful Restart",
CParameters1::getGracefulRestartCapability).orElse(GracefulRestartUtil.EMPTY_GR_CAPABILITY);
this.llGracefulCapability = findSingleCapability(bgpParameters, "Long-lived Graceful Restart",
CParameters1::getLlGracefulRestartCapability).orElse(GracefulRestartUtil.EMPTY_LLGR_CAPABILITY);
} else {
this.gracefulCapability = GracefulRestartUtil.EMPTY_GR_CAPABILITY;
this.llGracefulCapability = GracefulRestartUtil.EMPTY_LLGR_CAPABILITY;
}
this.sync = new BGPSynchronization(this.listener, tts);
this.tableTypes = tats;
this.addPathTypes = addPathCapabilitiesList;
if (!this.addPathTypes.isEmpty()) {
addDecoderConstraint(MultiPathSupport.class,
MultiPathSupportImpl.createParserMultiPathSupport(this.addPathTypes));
}
if (holdTimerValue != 0) {
channel.eventLoop().schedule(this::handleHoldTimer, this.holdTimerNanos, TimeUnit.NANOSECONDS);
channel.eventLoop().schedule(this::handleKeepaliveTimer, this.keepAliveNanos, TimeUnit.NANOSECONDS);
}
this.bgpId = remoteOpen.getBgpIdentifier();
this.sessionState.advertizeCapabilities(holdTimerValue, channel.remoteAddress(), channel.localAddress(),
this.tableTypes, bgpParameters);
}
private static <T extends ChildOf<MpCapabilities>> Optional<T> findSingleCapability(
final List<BgpParameters> bgpParameters, final String name, final Function<CParameters1, T> extractor) {
final List<T> found = new ArrayList<>(1);
for (BgpParameters bgpParams : bgpParameters) {
for (OptionalCapabilities optCapability : bgpParams.nonnullOptionalCapabilities()) {
final CParameters cparam = optCapability.getCParameters();
if (cparam != null) {
final CParameters1 augment = cparam.augmentation(CParameters1.class);
if (augment != null) {
final T capa = extractor.apply(augment);
if (capa != null) {
found.add(capa);
}
}
}
}
}
final Set<T> set = ImmutableSet.copyOf(found);
switch (set.size()) {
case 0:
LOG.debug("{} capability not advertised.", name);
return Optional.empty();
case 1:
return Optional.of(found.get(0));
default:
LOG.warn("Multiple instances of {} capability advertised: {}, ignoring.", name, set);
return Optional.empty();
}
}
/**
* Set the extend message coder for current channel.
* The reason for separating this part from constructor is, in #channel.pipeline().replace(..), the
* invokeChannelRead() will be invoked after the original message coder handler got removed. And there
* is chance that before the session instance is fully initiated (constructor returns), a KeepAlive
* message arrived already in the channel buffer. Thus #AbstractBGPSessionNegotiator.handleMessage(..)
* gets invoked again and a deadlock is caused. A BGP final state machine error will happen as BGP
* negotiator is still in OPEN_SENT state as the session constructor hasn't returned yet.
*/
public synchronized void setChannelExtMsgCoder(final Open remoteOpen) {
final boolean enableExMess = BgpExtendedMessageUtil.advertizedBgpExtendedMessageCapability(remoteOpen);
if (enableExMess) {
this.channel.pipeline().replace(BGPMessageHeaderDecoder.class, EXTENDED_MSG_DECODER,
BGPMessageHeaderDecoder.getExtendedBGPMessageHeaderDecoder());
}
}
@Override
public synchronized void close() {
if (this.state != State.IDLE) {
if (!this.terminationReasonNotified) {
this.writeAndFlush(new NotifyBuilder().setErrorCode(BGPError.CEASE.getCode())
.setErrorSubcode(BGPError.CEASE.getSubcode()).build());
}
this.closeWithoutMessage();
}
}
/**
* Handles incoming message based on their type.
*
* @param msg incoming message
*/
synchronized void handleMessage(final Notification msg) {
if (this.state == State.IDLE) {
return;
}
try {
// Update last reception time
this.lastMessageReceivedAt = System.nanoTime();
if (msg instanceof Open) {
// Open messages should not be present here
this.terminate(new BGPDocumentedException(null, BGPError.FSM_ERROR));
} else if (msg instanceof Notify) {
final Notify notify = (Notify) msg;
// Notifications are handled internally
LOG.info("Session closed because Notification message received: {} / {}, data={}",
notify.getErrorCode(),
notify.getErrorSubcode(),
notify.getData() != null ? ByteBufUtil.hexDump(notify.getData()) : null);
notifyTerminationReasonAndCloseWithoutMessage(notify.getErrorCode(), notify.getErrorSubcode());
} else if (msg instanceof Keepalive) {
// Keepalives are handled internally
LOG.trace("Received KeepAlive message.");
this.kaCounter++;
if (this.kaCounter >= 2) {
this.sync.kaReceived();
}
} else if (msg instanceof RouteRefresh) {
this.listener.onMessage(this, msg);
} else if (msg instanceof Update) {
this.listener.onMessage(this, msg);
this.sync.updReceived((Update) msg);
} else {
LOG.warn("Ignoring unhandled message: {}.", msg.getClass());
}
this.sessionState.messageReceived(msg);
} catch (final BGPDocumentedException e) {
this.terminate(e);
}
}
private synchronized void notifyTerminationReasonAndCloseWithoutMessage(
final Short errorCode,
final Short errorSubcode) {
this.terminationReasonNotified = true;
this.closeWithoutMessage();
this.listener.onSessionTerminated(this, new BGPTerminationReason(
BGPError.forValue(errorCode, errorSubcode)));
}
synchronized void endOfInput() {
if (this.state == State.UP) {
LOG.info(END_OF_INPUT);
this.listener.onSessionDown(this, new IOException(END_OF_INPUT));
}
}
@GuardedBy("this")
private ChannelFuture writeEpilogue(final ChannelFuture future, final Notification msg) {
future.addListener((ChannelFutureListener) f -> {
if (!f.isSuccess()) {
LOG.warn("Failed to send message {} to socket {}", msg, BGPSessionImpl.this.channel, f.cause());
} else {
LOG.trace("Message {} sent to socket {}", msg, BGPSessionImpl.this.channel);
}
});
this.lastMessageSentAt = System.nanoTime();
this.sessionState.messageSent(msg);
return future;
}
void flush() {
this.channel.flush();
}
@SuppressWarnings("checkstyle:illegalCatch")
synchronized void write(final Notification msg) {
try {
writeEpilogue(this.channel.write(msg), msg);
} catch (final Exception e) {
LOG.warn("Message {} was not sent.", msg, e);
}
}
synchronized ChannelFuture writeAndFlush(final Notification msg) {
if (this.channel.isWritable()) {
return writeEpilogue(this.channel.writeAndFlush(msg), msg);
}
return this.channel.newFailedFuture(new NonWritableChannelException());
}
@Override
public synchronized void closeWithoutMessage() {
if (this.state == State.IDLE) {
return;
}
LOG.info("Closing session: {}", this);
this.channel.close().addListener((ChannelFutureListener) future
-> Preconditions.checkArgument(future.isSuccess(), "Channel failed to close: %s", future.cause()));
this.state = State.IDLE;
removePeerSession();
this.sessionState.setSessionState(this.state);
}
/**
* Closes BGP session from the parent with given reason. A message needs to be sent, but parent doesn't have to be
* modified, because he initiated the closing. (To prevent concurrent modification exception).
*
* @param cause BGPDocumentedException
*/
@VisibleForTesting
synchronized void terminate(final BGPDocumentedException cause) {
final BGPError error = cause.getError();
final byte[] data = cause.getData();
final NotifyBuilder builder = new NotifyBuilder().setErrorCode(error.getCode())
.setErrorSubcode(error.getSubcode());
if (data != null && data.length != 0) {
builder.setData(data);
}
this.writeAndFlush(builder.build());
notifyTerminationReasonAndCloseWithoutMessage(error.getCode(), error.getSubcode());
}
private void removePeerSession() {
if (this.peerRegistry != null) {
this.peerRegistry.removePeerSession(StrictBGPPeerRegistry.getIpAddress(this.channel.remoteAddress()));
}
}
/**
* If HoldTimer expires, the session ends. If a message (whichever) was received during this period, the HoldTimer
* will be rescheduled by HOLD_TIMER_VALUE + the time that has passed from the start of the HoldTimer to the time at
* which the message was received. If the session was closed by the time this method starts to execute (the session
* state will become IDLE), then rescheduling won't occur.
*/
private synchronized void handleHoldTimer() {
if (this.state == State.IDLE) {
return;
}
final long ct = System.nanoTime();
final long nextHold = this.lastMessageReceivedAt + holdTimerNanos;
if (ct >= nextHold) {
LOG.debug("HoldTimer expired. {}", new Date());
this.terminate(new BGPDocumentedException(BGPError.HOLD_TIMER_EXPIRED));
} else {
this.channel.eventLoop().schedule(this::handleHoldTimer, nextHold - ct, TimeUnit.NANOSECONDS);
}
}
/**
* If KeepAlive Timer expires, sends KeepAlive message. If a message (whichever) was send during this period, the
* KeepAlive Timer will be rescheduled by KEEP_ALIVE_TIMER_VALUE + the time that has passed from the start of the
* KeepAlive timer to the time at which the message was sent. If the session was closed by the time this method
* starts to execute (the session state will become IDLE), that rescheduling won't occur.
*/
private synchronized void handleKeepaliveTimer() {
if (this.state == State.IDLE) {
LOG.debug("Skipping keepalive on session idle {}", this);
return;
}
final long ct = System.nanoTime();
final long nextKeepalive = this.lastMessageSentAt + keepAliveNanos;
long nextNanos = nextKeepalive - ct;
if (nextNanos <= 0) {
final ChannelFuture future = this.writeAndFlush(KEEP_ALIVE);
LOG.debug("Enqueued session {} keepalive as {}", this, future);
nextNanos = keepAliveNanos;
if (LOG.isDebugEnabled()) {
future.addListener(compl -> LOG.debug("Session {} keepalive completed as {}", this, compl));
}
} else {
LOG.debug("Skipping keepalive on session {}", this);
}
LOG.debug("Scheduling next keepalive on {} in {} nanos", this, nextNanos);
this.channel.eventLoop().schedule(this::handleKeepaliveTimer, nextNanos, TimeUnit.NANOSECONDS);
}
@Override
public final String toString() {
return addToStringAttributes(MoreObjects.toStringHelper(this)).toString();
}
protected ToStringHelper addToStringAttributes(final ToStringHelper toStringHelper) {
toStringHelper.add("channel", this.channel);
toStringHelper.add("state", this.getState());
return toStringHelper;
}
@Override
public Set<BgpTableType> getAdvertisedTableTypes() {
return this.tableTypes;
}
@Override
public List<AddressFamilies> getAdvertisedAddPathTableTypes() {
return this.addPathTypes;
}
@Override
public GracefulRestartCapability getAdvertisedGracefulRestartCapability() {
return this.gracefulCapability;
}
@Override
public LlGracefulRestartCapability getAdvertisedLlGracefulRestartCapability() {
return this.llGracefulCapability;
}
@VisibleForTesting
@SuppressWarnings("checkstyle:illegalCatch")
synchronized void sessionUp() {
this.state = State.UP;
try {
this.sessionState.setSessionState(this.state);
this.listener.onSessionUp(this);
} catch (final Exception e) {
handleException(e);
throw e;
}
}
public synchronized State getState() {
return this.state;
}
@Override
public final Ipv4Address getBgpId() {
return this.bgpId;
}
@Override
public final AsNumber getAsNumber() {
return this.asNumber;
}
public ChannelOutputLimiter getLimiter() {
return this.limiter;
}
@Override
@SuppressWarnings("checkstyle:illegalCatch")
public final void channelInactive(final ChannelHandlerContext ctx) {
LOG.debug("Channel {} inactive.", ctx.channel());
this.endOfInput();
try {
super.channelInactive(ctx);
} catch (final Exception e) {
throw new IllegalStateException("Failed to delegate channel inactive event on channel " + ctx.channel(), e);
}
}
@Override
protected final void channelRead0(final ChannelHandlerContext ctx, final Notification msg) {
LOG.debug("Message was received: {}", msg);
this.handleMessage(msg);
}
@Override
public final void handlerAdded(final ChannelHandlerContext ctx) {
this.sessionUp();
}
@Override
public synchronized void exceptionCaught(final ChannelHandlerContext ctx, final Throwable cause) {
handleException(cause);
}
/**
* Handle exception occurred in the BGP session. The session in error state should be closed
* properly so that it can be restored later.
*/
@VisibleForTesting
void handleException(final Throwable cause) {
LOG.warn("BGP session encountered error", cause);
final Throwable docCause = cause.getCause();
if (docCause instanceof BGPDocumentedException) {
this.terminate((BGPDocumentedException) docCause);
} else {
this.terminate(new BGPDocumentedException(BGPError.CEASE));
}
}
@Override
public BGPSessionState getBGPSessionState() {
return this.sessionState;
}
@Override
public BGPTimersState getBGPTimersState() {
return this.sessionState;
}
@Override
public BGPTransportState getBGPTransportState() {
return this.sessionState;
}
@Override
public void registerMessagesCounter(final BGPMessagesListener bgpMessagesListener) {
this.sessionState.registerMessagesCounter(bgpMessagesListener);
}
@Override
public <T extends PeerConstraint> void addDecoderConstraint(final Class<T> constraintClass, final T constraint) {
this.channel.pipeline().get(BGPByteToMessageDecoder.class).addDecoderConstraint(constraintClass, constraint);
}
@Override
public ScheduledFuture<?> schedule(final Runnable command, final long delay, final TimeUnit unit) {
return this.channel.eventLoop().schedule(command, delay, unit);
}
} |
package com.specmate.auth.internal;
import java.util.HashMap;
import java.util.Map;
import org.osgi.service.component.annotations.Activate;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import com.specmate.auth.api.IAuthentificationService;
import com.specmate.auth.config.AuthentificationServiceConfig;
import com.specmate.common.SpecmateException;
import com.specmate.common.SpecmateValidationException;
@Component(configurationPid = AuthentificationServiceConfig.PID, configurationPolicy = ConfigurationPolicy.REQUIRE,
service = IAuthentificationService.class)
public class AuthentificationServiceImpl implements IAuthentificationService {
private RandomString randomString = new RandomString();
private Map<String, UserSession> userSessions = new HashMap<>();
private int maxIdleMinutes;
@Activate
public void activate(Map<String, Object> properties) throws SpecmateValidationException {
readConfig(properties);
}
@Override
public String authenticate(String username, String password, String projectname) throws SpecmateException {
/*
* TODO retrieve the access rights for this user and set in the user session.
*/
String token = randomString.nextString();
userSessions.put(token, new UserSession(AccessRights.AUTHENTICATE_ALL, maxIdleMinutes, projectname));
return token;
}
@Override
public void deauthenticate(String token) throws SpecmateException {
checkSessionExists(token);
userSessions.remove(token);
}
@Override
public void validateToken(String token, String path) throws SpecmateException {
checkSessionExists(token);
UserSession session = userSessions.get(token);
if (session.isExpired()) {
userSessions.remove(token);
throw new SpecmateException("Session " + token + " is expired.");
}
if (!session.isAuthorized(path)) {
throw new SpecmateException("Session " + token + " not authorized for " + path + ".");
}
session.refresh();
}
private void checkSessionExists(String token) throws SpecmateException {
if (!userSessions.containsKey(token)) {
throw new SpecmateException("Session " + token + " does not exist.");
}
}
private void readConfig(Map<String, Object> properties) throws SpecmateValidationException {
String errMsg = "Missing config for %s";
if (!properties.containsKey(AuthentificationServiceConfig.SESSION_MAX_IDLE_MINUTES)) {
throw new SpecmateValidationException(String.format(errMsg, AuthentificationServiceConfig.SESSION_MAX_IDLE_MINUTES));
} else {
this.maxIdleMinutes = (int) properties.get(AuthentificationServiceConfig.SESSION_MAX_IDLE_MINUTES);
}
}
} |
package gov.nih.nci.cagrid.metadata;
import gov.nih.nci.cagrid.metadata.exceptions.InternalRuntimeException;
import gov.nih.nci.cagrid.metadata.exceptions.InvalidResourcePropertyException;
import gov.nih.nci.cagrid.metadata.exceptions.QueryInvalidException;
import gov.nih.nci.cagrid.metadata.exceptions.RemoteResourcePropertyRetrievalException;
import gov.nih.nci.cagrid.metadata.exceptions.ResourcePropertyRetrievalException;
import java.io.InputStream;
import java.rmi.RemoteException;
import javax.xml.namespace.QName;
import javax.xml.rpc.ServiceException;
import org.apache.axis.EngineConfiguration;
import org.apache.axis.client.AxisClient;
import org.apache.axis.client.Stub;
import org.apache.axis.configuration.FileProvider;
import org.apache.axis.message.MessageElement;
import org.apache.axis.message.addressing.EndpointReferenceType;
import org.apache.axis.types.URI.MalformedURIException;
import org.globus.axis.gsi.GSIConstants;
import org.globus.axis.util.Util;
import org.globus.wsrf.WSRFConstants;
import org.globus.wsrf.impl.security.authorization.Authorization;
import org.globus.wsrf.impl.security.authorization.NoAuthorization;
import org.globus.wsrf.utils.AnyHelper;
import org.oasis.wsrf.properties.GetMultipleResourcePropertiesResponse;
import org.oasis.wsrf.properties.GetMultipleResourceProperties_Element;
import org.oasis.wsrf.properties.GetMultipleResourceProperties_PortType;
import org.oasis.wsrf.properties.GetResourceProperty;
import org.oasis.wsrf.properties.GetResourcePropertyResponse;
import org.oasis.wsrf.properties.InvalidQueryExpressionFaultType;
import org.oasis.wsrf.properties.InvalidResourcePropertyQNameFaultType;
import org.oasis.wsrf.properties.QueryEvaluationErrorFaultType;
import org.oasis.wsrf.properties.QueryExpressionType;
import org.oasis.wsrf.properties.QueryResourcePropertiesResponse;
import org.oasis.wsrf.properties.QueryResourceProperties_Element;
import org.oasis.wsrf.properties.QueryResourceProperties_PortType;
import org.oasis.wsrf.properties.UnknownQueryExpressionDialectFaultType;
import org.oasis.wsrf.properties.WSResourcePropertiesServiceAddressingLocator;
import org.w3c.dom.Element;
public class ResourcePropertyHelper {
static {
Util.registerTransport();
}
public static MessageElement[] queryResourceProperties(EndpointReferenceType endpoint, String queryExpression)
throws RemoteResourcePropertyRetrievalException, QueryInvalidException {
return queryResourceProperties(endpoint, queryExpression, null);
}
public static MessageElement[] queryResourceProperties(EndpointReferenceType endpoint, String queryExpression,
InputStream wsdd) throws RemoteResourcePropertyRetrievalException, QueryInvalidException {
return queryResourceProperties(endpoint, queryExpression, null, null);
}
public static MessageElement[] queryResourceProperties(EndpointReferenceType endpoint, String queryExpression,
InputStream wsdd, Authorization authz) throws RemoteResourcePropertyRetrievalException, QueryInvalidException {
WSResourcePropertiesServiceAddressingLocator locator = new WSResourcePropertiesServiceAddressingLocator();
if (wsdd != null) {
// we found it, so tell axis to configure an engine to use it
EngineConfiguration engineConfig = new FileProvider(wsdd);
// set the engine of the locator
locator.setEngine(new AxisClient(engineConfig));
}
QueryExpressionType query = new QueryExpressionType();
try {
query.setDialect(WSRFConstants.XPATH_1_DIALECT);
} catch (MalformedURIException e) {
// this should never happen, and the user can't fix it if it does
throw new InternalRuntimeException(e);
}
query.setValue(queryExpression);
QueryResourceProperties_PortType port;
try {
port = locator.getQueryResourcePropertiesPort(endpoint);
} catch (ServiceException e) {
throw new RemoteResourcePropertyRetrievalException(e);
}
setAnonymous((Stub) port, authz);
QueryResourceProperties_Element request = new QueryResourceProperties_Element();
request.setQueryExpression(query);
QueryResourcePropertiesResponse response = null;
response = issueRPQuery(port, request);
return response.get_any();
}
public static Element getResourceProperties(EndpointReferenceType endpoint)
throws ResourcePropertyRetrievalException, RemoteResourcePropertyRetrievalException, QueryInvalidException {
return getResourceProperties(endpoint, (InputStream) null);
}
public static Element getResourceProperties(EndpointReferenceType endpoint, InputStream wsdd)
throws ResourcePropertyRetrievalException, RemoteResourcePropertyRetrievalException, QueryInvalidException {
return getResourceProperties(endpoint, (InputStream) null, null);
}
public static Element getResourceProperties(EndpointReferenceType endpoint, InputStream wsdd, Authorization authz)
throws ResourcePropertyRetrievalException, RemoteResourcePropertyRetrievalException, QueryInvalidException {
String dialect = WSRFConstants.XPATH_1_DIALECT;
String queryExpression = "/";
WSResourcePropertiesServiceAddressingLocator locator = new WSResourcePropertiesServiceAddressingLocator();
if (wsdd != null) {
// we found it, so tell axis to configure an engine to use it
EngineConfiguration engineConfig = new FileProvider(wsdd);
// set the engine of the locator
locator.setEngine(new AxisClient(engineConfig));
}
QueryExpressionType query = new QueryExpressionType();
try {
query.setDialect(dialect);
} catch (MalformedURIException e) {
// this should never happen, and the user can't fix it if it does
throw new InternalRuntimeException(e);
}
query.setValue(queryExpression);
QueryResourceProperties_PortType port;
try {
port = locator.getQueryResourcePropertiesPort(endpoint);
} catch (ServiceException e) {
throw new RemoteResourcePropertyRetrievalException(e);
}
setAnonymous((Stub) port, authz);
QueryResourceProperties_Element request = new QueryResourceProperties_Element();
request.setQueryExpression(query);
QueryResourcePropertiesResponse response = issueRPQuery(port, request);
MessageElement messageElements[] = response.get_any();
if (messageElements == null) {
return (null);
}
if (messageElements.length > 1) {
throw new ResourcePropertyRetrievalException("Resource property query returned "
+ Integer.toString(messageElements.length) + " elements; I only know how to deal with one");
}
Element element;
try {
element = messageElements[0].getAsDOM();
} catch (Exception e) {
throw new ResourcePropertyRetrievalException("Error parsing message element(" + messageElements[0] + ")", e);
}
return element;
}
public static Element getResourceProperty(EndpointReferenceType endpoint, QName rpName)
throws ResourcePropertyRetrievalException, RemoteResourcePropertyRetrievalException,
InvalidResourcePropertyException {
return getResourceProperty(endpoint, rpName, null);
}
public static Element getResourceProperty(EndpointReferenceType endpoint, QName rpName, InputStream wsdd)
throws ResourcePropertyRetrievalException, RemoteResourcePropertyRetrievalException,
InvalidResourcePropertyException {
return getResourceProperty(endpoint, rpName, null, null);
}
public static Element getResourceProperty(EndpointReferenceType endpoint, QName rpName, InputStream wsdd,
Authorization authz) throws ResourcePropertyRetrievalException, RemoteResourcePropertyRetrievalException,
InvalidResourcePropertyException {
GetResourceProperty port;
WSResourcePropertiesServiceAddressingLocator locator = new WSResourcePropertiesServiceAddressingLocator();
if (wsdd != null) {
// we found it, so tell axis to configure an engine to use it
EngineConfiguration engineConfig = new FileProvider(wsdd);
// set the engine of the locator
locator.setEngine(new AxisClient(engineConfig));
}
try {
port = locator.getGetResourcePropertyPort(endpoint);
} catch (ServiceException e) {
throw new RemoteResourcePropertyRetrievalException(e);
}
setAnonymous((Stub) port, authz);
GetResourcePropertyResponse response = null;
try {
response = port.getResourceProperty(rpName);
} catch (InvalidResourcePropertyQNameFaultType e) {
throw new InvalidResourcePropertyException(e);
} catch (RemoteException e) {
throw new RemoteResourcePropertyRetrievalException("Error getting resource property; " + "endpoint was '"
+ endpoint + "', name was '" + rpName.toString(), e);
}
MessageElement[] messageElements = response.get_any();
if (messageElements == null) {
return (null);
}
if (messageElements.length > 1) {
throw new ResourcePropertyRetrievalException("Get resource property returned "
+ Integer.toString(messageElements.length) + " elements; I only know how to deal with one");
}
Element element;
try {
element = messageElements[0].getAsDOM();
} catch (Exception e) {
throw new ResourcePropertyRetrievalException("Error parsing message element(" + messageElements[0] + ")", e);
}
return element;
}
public static Element[] getResourceProperties(EndpointReferenceType endpoint, QName[] rpNames)
throws ResourcePropertyRetrievalException {
return getResourceProperties(endpoint, rpNames, null);
}
public static Element[] getResourceProperties(EndpointReferenceType endpoint, QName[] rpNames, InputStream wsdd)
throws ResourcePropertyRetrievalException {
return getResourceProperties(endpoint, rpNames, null, null);
}
public static Element[] getResourceProperties(EndpointReferenceType endpoint, QName[] rpNames, InputStream wsdd,
Authorization authz) throws ResourcePropertyRetrievalException {
WSResourcePropertiesServiceAddressingLocator locator = new WSResourcePropertiesServiceAddressingLocator();
if (wsdd != null) {
// we found it, so tell axis to configure an engine to use it
EngineConfiguration engineConfig = new FileProvider(wsdd);
// set the engine of the locator
locator.setEngine(new AxisClient(engineConfig));
}
GetMultipleResourceProperties_PortType port;
try {
port = locator.getGetMultipleResourcePropertiesPort(endpoint);
} catch (ServiceException e) {
throw new RemoteResourcePropertyRetrievalException(e);
}
setAnonymous((Stub) port, authz);
GetMultipleResourceProperties_Element request = new GetMultipleResourceProperties_Element();
request.setResourceProperty(rpNames);
GetMultipleResourcePropertiesResponse response;
try {
response = port.getMultipleResourceProperties(request);
} catch (InvalidResourcePropertyQNameFaultType e) {
throw new InvalidResourcePropertyException(e);
} catch (RemoteException e) {
throw new RemoteResourcePropertyRetrievalException(e);
}
Element result[];
try {
result = AnyHelper.toElement(response.get_any());
} catch (Exception e) {
throw new ResourcePropertyRetrievalException("Error converting resource properties to elements: "
+ e.getMessage(), e);
}
return result;
}
private static void setAnonymous(Stub stub, Authorization authz) {
stub._setProperty(org.globus.wsrf.security.Constants.GSI_ANONYMOUS, Boolean.TRUE);
if (authz == null) {
stub._setProperty(org.globus.wsrf.security.Constants.AUTHORIZATION, NoAuthorization.getInstance());
stub._setProperty(GSIConstants.GSI_AUTHORIZATION, org.globus.gsi.gssapi.auth.NoAuthorization.getInstance());
} else {
stub._setProperty(org.globus.wsrf.security.Constants.AUTHORIZATION, authz);
}
}
private static QueryResourcePropertiesResponse issueRPQuery(QueryResourceProperties_PortType port,
QueryResourceProperties_Element request) throws QueryInvalidException, RemoteResourcePropertyRetrievalException {
QueryResourcePropertiesResponse response = null;
try {
response = port.queryResourceProperties(request);
} catch (InvalidQueryExpressionFaultType e) {
throw new QueryInvalidException(e);
} catch (QueryEvaluationErrorFaultType e) {
throw new QueryInvalidException(e);
} catch (UnknownQueryExpressionDialectFaultType e) {
// shouldn't happen and user can't handle this
throw new InternalRuntimeException(e);
} catch (RemoteException e) {
throw new RemoteResourcePropertyRetrievalException(e);
}
return response;
}
} |
package timely.collectd.plugin;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.collectd.api.Collectd;
import org.collectd.api.DataSource;
import org.collectd.api.OConfigItem;
import org.collectd.api.ValueList;
public abstract class CollectDPluginParent {
private static final String PUT = "put {0} {1} {2}{3}\n";
private static final Pattern HADOOP_STATSD_PATTERN = Pattern
.compile("([\\w-_]+)\\.([\\w-_]+)\\.([\\w-_]+)\\.([\\w-_]+)");
private static final String INSTANCE = " instance=";
private static final String NAME = " name=";
private static final String SAMPLE = " sample=";
private static final String CODE = " code=";
private static final String PERIOD = ".";
private static final String SAMPLE_TYPE = " sampleType=";
private static final String COUNTER = "COUNTER";
private static final String GAUGE = "GAUGE";
private static final String DERIVE = "DERIVE";
private static final String ABSOLUTE = "ABSOLUTE";
private static final Pattern NSQ_PATTERN1 = Pattern.compile("([\\w-_]+)\\.([\\w-_]+)\\.([\\w-_]+)");
private static final Pattern NSQ_PATTERN2 = Pattern.compile("([\\w-_]+)\\.([\\w-_]+)\\.([\\w-_]+)\\.([\\w-_]+)");
private static final Pattern NSQ_PATTERN3 = Pattern
.compile("([\\w-_]+)\\.([\\w-_]+)\\.([\\w-_]+)\\.([\\w-_]+)\\.([\\w-_
private static final Pattern ETHSTAT_PATTERN = Pattern.compile("([\\w-_]+)_queue_([\\w-_]+)_([\\w-_]+)");
private static final String STATSD_PREFIX = "statsd";
private static final String NSQ_PREFIX = STATSD_PREFIX + ".nsq.";
private static final Pattern HAPROXY_PATTERN = Pattern.compile("\\[([\\w-_=]+),([\\w-_=]+)\\]");
private final SMARTCodeMapping smart = new SMARTCodeMapping();
protected Set<String> addlTags = new HashSet<>();
public int config(OConfigItem config) {
for (OConfigItem child : config.getChildren()) {
switch (child.getKey()) {
case "Tags":
case "tags":
String[] additionalTags = child.getValues().get(0).getString().split(",");
for (String t : additionalTags) {
addlTags.add(" " + t.trim());
}
default:
}
}
return 0;
}
public abstract void write(String metric);
public void process(ValueList vl) {
debugValueList(vl);
StringBuilder metric = new StringBuilder();
Long timestamp = vl.getTime();
StringBuilder tags = new StringBuilder();
String host = vl.getHost();
int idx = host.indexOf(PERIOD);
if (-1 != idx) {
tags.append(" host=").append(host.substring(0, idx));
} else {
tags.append(" host=").append(host);
}
int nIdx = host.indexOf('n');
if (-1 != nIdx) {
tags.append(" rack=").append(host.substring(0, nIdx));
}
for (String tag : addlTags) {
tags.append(tag);
}
if (vl.getPlugin().equals(STATSD_PREFIX)) {
Matcher m = HADOOP_STATSD_PATTERN.matcher(vl.getTypeInstance());
Matcher n1 = NSQ_PATTERN1.matcher(vl.getTypeInstance());
Matcher n2 = NSQ_PATTERN2.matcher(vl.getTypeInstance());
Matcher n3 = NSQ_PATTERN3.matcher(vl.getTypeInstance());
String instance = null;
if (m.matches() && !vl.getTypeInstance().startsWith("nsq")) {
// Here we are processing the statsd metrics coming from the
// Hadoop Metrics2 StatsDSink without the host name.
// The format of metric is:
// serviceName.contextName.recordName.metricName. The recordName
// is typically duplicative and is dropped here. The serviceName
// is used as the instance.
metric.append(STATSD_PREFIX).append(PERIOD).append(m.group(2)).append(PERIOD).append(m.group(4));
instance = m.group(1);
} else if (n1.matches() && vl.getTypeInstance().startsWith("nsq")) {
metric.append(NSQ_PREFIX).append(n1.group(2)).append(PERIOD).append(n1.group(3));
} else if (n2.matches() && vl.getTypeInstance().startsWith("nsq")) {
metric.append(NSQ_PREFIX).append(n2.group(2)).append(PERIOD).append(n2.group(4));
instance = n2.group(3);
} else if (n3.matches() && vl.getTypeInstance().startsWith("nsq")) {
metric.append(NSQ_PREFIX).append(n3.group(4)).append(PERIOD).append(n3.group(6));
instance = n3.group(5);
} else {
// Handle StatsD metrics of unknown formats. If there is a
// period in the metric name, use everything up to that as
// the instance.
int period = vl.getTypeInstance().indexOf('.');
if (-1 == period) {
metric.append(STATSD_PREFIX).append(PERIOD).append(vl.getTypeInstance());
} else {
instance = vl.getTypeInstance().substring(0, period);
metric.append(STATSD_PREFIX).append(PERIOD).append(vl.getTypeInstance().substring(period + 1));
}
}
timestamp = vl.getTime();
if (null != instance) {
tags.append(INSTANCE).append(instance);
}
} else if (vl.getPlugin().equals("ethstat")) {
metric.append("sys.ethstat.");
if (vl.getTypeInstance().contains("queue")) {
Matcher m = ETHSTAT_PATTERN.matcher(vl.getTypeInstance());
if (m.matches()) {
metric.append(m.group(1)).append("_").append(m.group(3));
tags.append(" queue=").append(m.group(2));
} else {
metric.append(vl.getTypeInstance());
}
} else {
metric.append(vl.getTypeInstance());
}
tags.append(INSTANCE).append(vl.getPluginInstance());
} else if (vl.getPlugin().equals("hddtemp")) {
metric.append("sys.hddtemp.").append(vl.getType());
tags.append(INSTANCE).append(vl.getTypeInstance());
} else if (vl.getPlugin().equals("smart")) {
int code = -1;
String name = null;
if (vl.getTypeInstance().startsWith("attribute-")) {
int hyphen = vl.getTypeInstance().indexOf('-');
code = Integer.parseInt(vl.getTypeInstance().substring(hyphen + 1));
name = smart.get(code);
}
if (code == -1) {
if (notEmpty(vl.getTypeInstance())) {
metric.append("sys.smart.").append(vl.getTypeInstance());
} else {
metric.append("sys.smart.").append(vl.getType());
}
} else {
metric.append("sys.smart.").append(name);
tags.append(CODE).append(code);
}
tags.append(INSTANCE).append(vl.getPluginInstance());
} else if (vl.getPlugin().equals("sensors")) {
String instance = "";
if (vl.getTypeInstance().startsWith("temp")) {
instance = vl.getTypeInstance().substring(4);
}
metric.append("sys.sensors.").append(vl.getType()).append(PERIOD).append(vl.getPluginInstance());
tags.append(INSTANCE).append(instance);
} else if (vl.getPlugin().equals("haproxy")) {
metric.append("sys.haproxy.").append(vl.getTypeInstance());
Matcher m = HAPROXY_PATTERN.matcher(vl.getPluginInstance());
if (m.matches()) {
tags.append(" ").append(m.group(1));
tags.append(" ").append(m.group(2));
}
} else if (vl.getPlugin().equals("ipmi")) {
metric.append("sys.ipmi.").append(vl.getType());
tags.append(INSTANCE).append(vl.getTypeInstance().replaceAll(" ", "_"));
} else if (vl.getPlugin().equals("snmp")) {
metric.append("sys.snmp.").append(vl.getType());
tags.append(INSTANCE).append(vl.getTypeInstance().replaceAll(" ", "_"));
} else if (vl.getPlugin().equals("GenericJMX")) {
metric.append("sys.").append(vl.getPlugin()).append(PERIOD).append(vl.getType()).append(PERIOD)
.append(vl.getTypeInstance());
String[] pluginInstanceSplit = vl.getPluginInstance().split("-");
if (pluginInstanceSplit.length > 0) {
tags.append(INSTANCE).append(pluginInstanceSplit[0].replaceAll(" ", "_"));
}
if (pluginInstanceSplit.length > 1) {
tags.append(NAME).append(pluginInstanceSplit[1].replaceAll(" ", "_"));
}
} else if (notEmpty(vl.getTypeInstance()) && notEmpty(vl.getType()) && notEmpty(vl.getPluginInstance())
&& notEmpty(vl.getPlugin())) {
metric.append("sys.").append(vl.getPlugin()).append(PERIOD).append(vl.getType()).append(PERIOD)
.append(vl.getTypeInstance());
tags.append(INSTANCE).append(vl.getPluginInstance().replaceAll(" ", "_"));
} else if (notEmpty(vl.getTypeInstance()) && notEmpty(vl.getType()) && notEmpty(vl.getPlugin())) {
metric.append("sys.").append(vl.getPlugin()).append(PERIOD).append(vl.getType()).append(PERIOD)
.append(vl.getTypeInstance());
} else if (notEmpty(vl.getType()) && notEmpty(vl.getPluginInstance()) && notEmpty(vl.getPlugin())) {
metric.append("sys.").append(vl.getPlugin()).append(PERIOD).append(vl.getType());
tags.append(INSTANCE).append(vl.getPluginInstance().replaceAll(" ", "_"));
} else if (notEmpty(vl.getType()) && notEmpty(vl.getPlugin())) {
metric.append("sys.").append(vl.getPlugin()).append(PERIOD).append(vl.getType());
} else {
Collectd.logWarning("Unhandled metric: " + vl.toString());
return;
}
final String metricName = metric.toString().replaceAll(" ", "_");
for (int i = 0; i < vl.getValues().size(); i++) {
StringBuilder tagsWithSample = new StringBuilder(tags.toString());
String sampleName = vl.getDataSet().getDataSources().get(i).getName();
int type = vl.getDataSet().getDataSources().get(i).getType();
String sampleType = convertType(type);
if (null != sampleName) {
tagsWithSample.append(SAMPLE).append(sampleName);
}
if (null != sampleType) {
tagsWithSample.append(SAMPLE_TYPE).append(sampleType);
}
Double value = vl.getValues().get(i).doubleValue();
String datapoint = MessageFormat.format(PUT, metricName, timestamp.toString(), value.toString(),
tagsWithSample.toString());
Collectd.logDebug("Writing: " + datapoint);
write(datapoint);
}
}
private void debugValueList(ValueList vl) {
Collectd.logDebug("Input: " + vl.toString());
Collectd.logDebug("Plugin: " + vl.getPlugin());
Collectd.logDebug("PluginInstance: " + vl.getPluginInstance());
Collectd.logDebug("Type: " + vl.getType());
Collectd.logDebug("TypeInstance: " + vl.getTypeInstance());
for (int i = 0; i < vl.getValues().size(); i++) {
Number value = vl.getValues().get(i);
DataSource ds = vl.getDataSet().getDataSources().get(i);
Collectd.logDebug(convertType(ds.getType()) + " " + ds.getName() + " = " + value);
}
}
private String convertType(int type) {
String result = null;
switch (type) {
case 0:
result = COUNTER;
break;
case 1:
result = GAUGE;
break;
case 2:
result = DERIVE;
break;
case 3:
result = ABSOLUTE;
break;
default:
result = GAUGE;
break;
}
return result;
}
private boolean notEmpty(String arg) {
return (null != arg) && !(arg.equals(""));
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.