gt stringclasses 1 value | context stringlengths 2.05k 161k |
|---|---|
package com.chenjishi.u148;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.TypedValue;
import android.view.*;
import android.widget.*;
import com.chenjishi.u148.utils.Constants;
import com.chenjishi.u148.utils.Utils;
import com.chenjishi.u148.widget.LoadingView;
import com.flurry.android.FlurryAgent;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
/**
* Created by jishichen on 2017/4/14.
*/
public class BaseActivity extends AppCompatActivity {
protected boolean mHideTitle;
protected int mTitleResId = -1;
protected LayoutInflater mInflater;
protected FrameLayout mRootView;
protected int mTheme;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mRootView = (FrameLayout) findViewById(android.R.id.content);
mRootView.setBackgroundColor(getResources().getColor(Constants.MODE_NIGHT == Config.getThemeMode(this)
? R.color.background_night : R.color.background));
mInflater = LayoutInflater.from(this);
setStatusViewColor(Config.getThemeMode(this) ==
Constants.MODE_DAY ? 0xFFE5E5E5 : 0xFF1C1C1C);
}
@Override
protected void onResume() {
super.onResume();
mTheme = Config.getThemeMode(this);
applyTheme();
}
@Override
protected void onStart() {
super.onStart();
FlurryAgent.onStartSession(this);
}
@Override
public void setContentView(int layoutResID) {
super.setContentView(R.layout.base_layout);
if (!mHideTitle) {
int resId = mTitleResId == -1 ? R.layout.title_base : mTitleResId;
mInflater.inflate(resId, mRootView);
}
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(MATCH_PARENT,
MATCH_PARENT, Gravity.BOTTOM);
lp.topMargin = mHideTitle ? 0 : dp2px(48);
mRootView.addView(mInflater.inflate(layoutResID, null), lp);
}
protected void setContentView(int layoutResID, int titleResId) {
mTitleResId = titleResId;
setContentView(layoutResID);
}
protected void setContentView(int layoutResID, boolean hideTitle) {
mHideTitle = hideTitle;
setContentView(layoutResID);
}
protected void onRightIconClicked() {
}
public void onBackClicked(View v) {
finish();
}
@Override
public void setTitle(CharSequence title) {
TextView textView = (TextView) findViewById(R.id.tv_title);
textView.setText(title);
textView.setVisibility(View.VISIBLE);
}
@Override
public void setTitle(int titleId) {
setTitle(getString(titleId));
}
protected void setRightButtonIcon(int resId) {
RelativeLayout layout = (RelativeLayout) findViewById(R.id.right_view);
layout.removeAllViews();
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(dp2px(48), MATCH_PARENT);
ImageButton button = getImageButton(resId);
button.setBackgroundResource(R.drawable.home_button_bkg);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
onRightIconClicked();
}
});
layout.addView(button, lp);
}
protected ImageButton getImageButton(int resId) {
ImageButton button = new ImageButton(this);
button.setBackgroundResource(R.drawable.home_up_bg);
button.setImageResource(resId);
return button;
}
private LoadingView mLoadingView;
protected void showLoadingView() {
if (null == mLoadingView) {
mLoadingView = new LoadingView(this);
mLoadingView.setBackgroundColor(getResources().getColor(Constants.MODE_NIGHT == Config.getThemeMode(this)
? R.color.background_night : R.color.background));
}
FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(MATCH_PARENT, MATCH_PARENT);
lp.topMargin = dp2px(48);
lp.gravity = Gravity.BOTTOM;
ViewParent viewParent = mLoadingView.getParent();
if (null != viewParent) {
((ViewGroup) viewParent).removeView(mLoadingView);
}
mRootView.addView(mLoadingView, lp);
}
protected void hideLoadingView() {
if (null != mLoadingView) {
ViewParent viewParent = mLoadingView.getParent();
if (null != viewParent) {
((ViewGroup) viewParent).removeView(mLoadingView);
}
mLoadingView = null;
}
}
protected void setError(String tips) {
if (null != mLoadingView) {
mLoadingView.setError(tips);
}
}
protected void setError() {
if (null != mLoadingView) {
int resId = R.string.network_invalid;
if (Utils.isNetworkConnected(this)) {
resId = R.string.server_error;
}
mLoadingView.setError(getString(resId));
}
}
protected void applyTheme() {
if (!mHideTitle) {
final RelativeLayout titleView = (RelativeLayout) findViewById(R.id.title_bar);
final TextView titleText = (TextView) findViewById(R.id.tv_title);
final View divider = findViewById(R.id.split_h);
final ImageView backBtn = (ImageView) findViewById(R.id.ic_arrow);
if (Constants.MODE_NIGHT == mTheme) {
titleView.setBackgroundColor(0xFF1C1C1C);
titleText.setTextColor(0xFF999999);
divider.setBackgroundColor(0xFF303030);
backBtn.setImageResource(R.drawable.ic_back_night);
} else {
titleView.setBackgroundColor(0xFFE5E5E5);
titleText.setTextColor(0xFF666666);
divider.setBackgroundColor(0xFFCACACA);
backBtn.setImageResource(R.drawable.back_arrow);
}
}
}
protected int dp2px(int dp) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
}
@Override
protected void onStop() {
super.onStop();
FlurryAgent.onEndSession(this);
}
protected void setStatusViewColor(@ColorInt int color) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) return;
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
getWindow().setStatusBarColor(color);
}
}
| |
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.ui;
import com.intellij.ide.ui.UISettings;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonShortcuts;
import com.intellij.openapi.actionSystem.ShortcutSet;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.util.ui.UIUtil;
import org.intellij.lang.annotations.JdkConstants;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
public class ListScrollingUtil {
private static final Logger LOG = Logger.getInstance("#com.intellij.ui.ListScrollingUtil");
@NonNls
protected static final String SCROLLUP_ACTION_ID = "scrollUp";
@NonNls
protected static final String SCROLLDOWN_ACTION_ID = "scrollDown";
@NonNls
protected static final String SELECT_PREVIOUS_ROW_ACTION_ID = "selectPreviousRow";
@NonNls
protected static final String SELECT_NEXT_ROW_ACTION_ID = "selectNextRow";
@NonNls
protected static final String SELECT_LAST_ROW_ACTION_ID = "selectLastRow";
@NonNls
protected static final String SELECT_FIRST_ROW_ACTION_ID = "selectFirstRow";
@NonNls
protected static final String MOVE_HOME_ID = "MOVE_HOME";
@NonNls
protected static final String MOVE_END_ID = "MOVE_END";
public static final int ROW_PADDING = 2;
public static void selectItem(JList list, int index) {
LOG.assertTrue(index >= 0);
LOG.assertTrue(index < list.getModel().getSize());
ensureIndexIsVisible(list, index, 0);
list.setSelectedIndex(index);
}
public static void ensureSelectionExists(JList list) {
int size = list.getModel().getSize();
if (size == 0) {
list.clearSelection();
return;
}
int selectedIndex = list.getSelectedIndex();
if (selectedIndex < 0 || selectedIndex >= size) { // fit index to [0, size-1] range
selectedIndex = 0;
}
selectItem(list, selectedIndex);
}
public static boolean selectItem(JList list, @NotNull Object item) {
ListModel model = list.getModel();
for (int i = 0; i < model.getSize(); i++) {
Object anItem = model.getElementAt(i);
if (item.equals(anItem)) {
selectItem(list, i);
return true;
}
}
return false;
}
public static void movePageUp(JList list) {
int visible = getVisibleRowCount(list);
ListSelectionModel selectionModel = list.getSelectionModel();
if (visible <= 0) {
moveHome(list);
return;
}
int size = list.getModel().getSize();
int decrement = visible - 1;
int index = Math.max(list.getSelectedIndex() - decrement, 0);
int top = list.getFirstVisibleIndex() - decrement;
if (top < 0) {
top = 0;
}
int bottom = top + visible - 1;
if (bottom >= size) {
bottom = size - 1;
}
//list.clearSelection();
Rectangle cellBounds = list.getCellBounds(top, bottom);
if (cellBounds == null) {
moveHome(list);
return;
}
list.scrollRectToVisible(cellBounds);
selectionModel.setSelectionInterval(index,index);
list.ensureIndexIsVisible(index);
}
public static void movePageDown(JList list) {
int visible = getVisibleRowCount(list);
if (visible <= 0) {
moveEnd(list);
return;
}
int size = list.getModel().getSize();
int increment = visible - 1;
int index = Math.min(list.getSelectedIndex() + increment, size - 1);
int top = list.getFirstVisibleIndex() + increment;
int bottom = top + visible - 1;
if (bottom >= size) {
bottom = size - 1;
}
//list.clearSelection();
Rectangle cellBounds = list.getCellBounds(top, bottom);
if (cellBounds == null) {
moveEnd(list);
return;
}
list.scrollRectToVisible(cellBounds);
list.setSelectedIndex(index);
list.ensureIndexIsVisible(index);
}
public static void moveHome(JList list) {
list.setSelectedIndex(0);
list.ensureIndexIsVisible(0);
}
public static void moveEnd(JList list) {
int index = list.getModel().getSize() - 1;
list.setSelectedIndex(index);
list.ensureIndexIsVisible(index);
}
public static void ensureIndexIsVisible(JList list, int index, int moveDirection) {
int visible = getVisibleRowCount(list);
int top;
int bottom;
if (moveDirection == 0) {
top = index - (visible - 1) / ROW_PADDING;
bottom = top + visible - 1;
}
else if (moveDirection < 0) {
top = index - ROW_PADDING;
bottom = index;
}
else {
top = index;
bottom = index + ROW_PADDING;
}
ensureRangeIsVisible(list, top, bottom);
}
public static void ensureRangeIsVisible(JList list, int top, int bottom) {
int size = list.getModel().getSize();
if (top < 0) {
top = 0;
}
if (bottom >= size) {
bottom = size - 1;
}
Rectangle cellBounds = list.getCellBounds(top, bottom);
if (cellBounds != null) {
cellBounds.x = 0;
list.scrollRectToVisible(cellBounds);
}
}
public static boolean isIndexFullyVisible(JList list, int index) {
int first = list.getFirstVisibleIndex();
int last = list.getLastVisibleIndex();
if (index < 0 || first < 0 || last < 0 || index < first || index > last) {
return false;
}
if (index > first && index < last) {
return true;
}
return list.getVisibleRect().contains(list.getCellBounds(index, index));
}
private static int getVisibleRowCount(JList list) {
return list.getLastVisibleIndex() - list.getFirstVisibleIndex() + 1;
}
public static void moveDown(JList list, @JdkConstants.InputEventMask final int modifiers) {
int size = list.getModel().getSize();
if (size == 0) {
return;
}
final ListSelectionModel selectionModel = list.getSelectionModel();
int index = selectionModel.getLeadSelectionIndex();
boolean cycleScrolling = UISettings.getInstance().CYCLE_SCROLLING;
final int indexToSelect;
if (index < size - 1) {
indexToSelect = index + 1;
}
else if (cycleScrolling && index == size - 1) {
indexToSelect = 0;
}
else {
return;
}
ensureIndexIsVisible(list, indexToSelect, +1);
if (selectionModel.getSelectionMode() == ListSelectionModel.SINGLE_SELECTION) {
selectionModel.setSelectionInterval(indexToSelect,indexToSelect);
}
else {
if ((modifiers & InputEvent.SHIFT_DOWN_MASK) == 0) {
selectionModel.removeSelectionInterval(selectionModel.getMinSelectionIndex(), selectionModel.getMaxSelectionIndex());
}
selectionModel.addSelectionInterval(indexToSelect, indexToSelect);
}
}
public static void moveUp(JList list, @JdkConstants.InputEventMask int modifiers) {
int size = list.getModel().getSize();
final ListSelectionModel selectionModel = list.getSelectionModel();
int index = selectionModel.getMinSelectionIndex();
boolean cycleScrolling = UISettings.getInstance().CYCLE_SCROLLING;
int indexToSelect;
if (index > 0) {
indexToSelect = index - 1;
}
else if (cycleScrolling && index == 0) {
indexToSelect = size - 1;
}
else {
return;
}
ensureIndexIsVisible(list, indexToSelect, -1);
if (selectionModel.getSelectionMode() == ListSelectionModel.SINGLE_SELECTION) {
selectionModel.setSelectionInterval(indexToSelect, indexToSelect);
}
else {
if ((modifiers & InputEvent.SHIFT_DOWN_MASK) == 0) {
selectionModel.removeSelectionInterval(selectionModel.getMinSelectionIndex(), selectionModel.getMaxSelectionIndex());
}
selectionModel.addSelectionInterval(indexToSelect, indexToSelect);
}
}
public static void installActions(final JList list) {
installActions(list, null);
}
public static void installActions(final JList list, @Nullable JComponent focusParent) {
ActionMap actionMap = list.getActionMap();
actionMap.put(SCROLLUP_ACTION_ID, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
movePageUp(list);
}
});
actionMap.put(SCROLLDOWN_ACTION_ID, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
movePageDown(list);
}
});
actionMap.put(SELECT_PREVIOUS_ROW_ACTION_ID, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
moveUp(list, e.getModifiers());
}
});
actionMap.put(SELECT_NEXT_ROW_ACTION_ID, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
moveDown(list, e.getModifiers());
}
});
actionMap.put(SELECT_LAST_ROW_ACTION_ID, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
moveEnd(list);
}
});
actionMap.put(SELECT_FIRST_ROW_ACTION_ID, new AbstractAction() {
public void actionPerformed(ActionEvent e) {
moveHome(list);
}
});
actionMap.put(MOVE_HOME_ID, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
moveHome(list);
}
});
actionMap.put(MOVE_END_ID, new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
moveEnd(list);
}
});
maybeInstallDefaultShortcuts(list);
installMoveUpAction(list, focusParent);
installMoveDownAction(list, focusParent);
installMovePageUpAction(list, focusParent);
installMovePageDownAction(list, focusParent);
installMoveHomeAction(list, focusParent);
installMoveEndAction(list, focusParent);
}
public static void installMoveEndAction(final JList list, @Nullable JComponent focusParent) {
new ListScrollAction(CommonShortcuts.getMoveEnd(), focusParent == null ? list : focusParent){
@Override
public void actionPerformed(AnActionEvent e) {
moveEnd(list);
}
};
}
public static void installMoveHomeAction(final JList list, @Nullable JComponent focusParent) {
new ListScrollAction(CommonShortcuts.getMoveHome(), focusParent == null ? list : focusParent){
@Override
public void actionPerformed(AnActionEvent e) {
moveHome(list);
}
};
}
public static void installMovePageDownAction(final JList list, @Nullable JComponent focusParent) {
new ListScrollAction(CommonShortcuts.getMovePageDown(), focusParent == null ? list : focusParent){
@Override
public void actionPerformed(AnActionEvent e) {
movePageDown(list);
}
};
}
public static void installMovePageUpAction(final JList list, @Nullable JComponent focusParent) {
new ListScrollAction(CommonShortcuts.getMovePageUp(), focusParent == null ? list : focusParent){
@Override
public void actionPerformed(AnActionEvent e) {
movePageUp(list);
}
};
}
public static void installMoveDownAction(final JList list, @Nullable JComponent focusParent) {
new ListScrollAction(CommonShortcuts.getMoveDown(), focusParent == null ? list : focusParent){
@Override
public void actionPerformed(AnActionEvent e) {
moveDown(list, 0);
}
};
}
public static void installMoveUpAction(final JList list, @Nullable JComponent focusParent) {
new ListScrollAction(CommonShortcuts.getMoveUp(), focusParent == null ? list : focusParent) {
@Override
public void actionPerformed(AnActionEvent e) {
moveUp(list, 0);
}
};
}
static void maybeInstallDefaultShortcuts(JComponent component) {
InputMap map = component.getInputMap(JComponent.WHEN_FOCUSED);
UIUtil.maybeInstall(map, SCROLLUP_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0));
UIUtil.maybeInstall(map, SCROLLDOWN_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0));
UIUtil.maybeInstall(map, SELECT_PREVIOUS_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0));
UIUtil.maybeInstall(map, SELECT_NEXT_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0));
UIUtil.maybeInstall(map, SELECT_FIRST_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0));
UIUtil.maybeInstall(map, SELECT_LAST_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_END, 0));
UIUtil.maybeInstall(map, MOVE_HOME_ID, KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0));
UIUtil.maybeInstall(map, MOVE_END_ID, KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));
}
public static abstract class ListScrollAction extends AnAction {
protected ListScrollAction(final ShortcutSet shortcutSet, final JComponent component) {
registerCustomShortcutSet(shortcutSet, component);
}
}
}
| |
/*
* Copyright (c) 2008 Harold Cooper. All rights reserved.
* Licensed under the MIT License.
* See LICENSE file in the project root for full license information.
*/
package org.pcollections.tests;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;
import java.util.Random;
import junit.framework.TestCase;
import org.pcollections.ConsPStack;
import org.pcollections.PStack;
public class ConsPStackTest extends TestCase {
/** Compares the behavior of java.util.LinkedList to the behavior of ConsPStack. */
public void testRandomlyAgainstJavaList() {
PStack<Integer> pstack = ConsPStack.empty();
List<Integer> list = new LinkedList<Integer>();
Random r = new Random();
for (int i = 0; i < 1000; i++) {
if (pstack.size() == 0 || r.nextBoolean()) { // add
if (r.nextBoolean()) { // append
Integer v = r.nextInt();
assertEquals(list.contains(v), pstack.contains(v));
list.add(0, v);
pstack = pstack.plus(v);
} else { // insert
int k = r.nextInt(pstack.size() + 1);
Integer v = r.nextInt();
assertEquals(list.contains(v), pstack.contains(v));
if (k < pstack.size()) assertEquals(list.get(k), pstack.get(k));
list.add(k, v);
pstack = pstack.plus(k, v);
}
} else if (r.nextBoolean()) { // replace
int k = r.nextInt(pstack.size());
Integer v = r.nextInt();
list.set(k, v);
pstack = pstack.with(k, v);
} else { // remove a random element
int j = r.nextInt(pstack.size()), k = 0;
for (Integer e : pstack) {
assertTrue(list.contains(e));
assertTrue(pstack.contains(e));
assertEquals(e, pstack.get(k));
assertEquals(list.get(k), pstack.get(k));
UtilityTest.assertEqualsAndHash(pstack, pstack.minus(k).plus(k, pstack.get(k)));
UtilityTest.assertEqualsAndHash(pstack, pstack.plus(k, 10).minus(k));
if (k == j) {
list.remove(k);
pstack = pstack.minus(k);
k--; // indices are now smaller
j = -1; // don't remove again
}
k++;
}
}
// also try to remove a _totally_ random value:
Integer v = r.nextInt();
assertEquals(list.contains(v), pstack.contains(v));
list.remove(v);
pstack = pstack.minus(v);
// and try out a non-Integer:
String s = Integer.toString(v);
assertFalse(pstack.contains(v));
pstack = pstack.minus(s);
assertEquals(list.size(), pstack.size());
UtilityTest.assertEqualsAndHash(list, pstack);
UtilityTest.assertEqualsAndHash(pstack, ConsPStack.from(pstack));
UtilityTest.assertEqualsAndHash(ConsPStack.empty(), pstack.minusAll(pstack));
UtilityTest.assertEqualsAndHash(
pstack, ConsPStack.empty().plusAll(UtilityTest.reverse(pstack)));
UtilityTest.assertEqualsAndHash(
pstack, ConsPStack.singleton(10).plusAll(1, UtilityTest.reverse(pstack)).minus(0));
int end = r.nextInt(pstack.size() + 1), start = r.nextInt(end + 1);
UtilityTest.assertEqualsAndHash(pstack.subList(start, end), list.subList(start, end));
if (!pstack.isEmpty()) {
final Integer x = pstack.get(r.nextInt(pstack.size()));
assertEquals(pstack.indexOf(x), list.indexOf(x));
}
}
}
/** Make sure the right element is removed */
public void testMinusInt() {
// First, let's try a list with distinct elements
PStack<String> pstack = ConsPStack.<String>empty().plus("C").plus("B").plus("A");
assertEquals(Arrays.asList("A", "B", "C"), pstack);
assertEquals(Arrays.asList("B", "C"), pstack.minus(0));
assertEquals(Arrays.asList("A", "B"), pstack.minus(2));
// Now, let's try duplicates
pstack = pstack.plus("B");
assertEquals(Arrays.asList("B", "A", "B", "C"), pstack);
assertEquals(Arrays.asList("A", "B", "C"), pstack.minus(0));
assertEquals(Arrays.asList("B", "A", "C"), pstack.minus(2));
}
public void testListIterator() {
PStack<Integer> s = ConsPStack.empty();
for (int i = 0; i < 1000; i++) {
s = s.plus(i);
}
int i = 0;
ListIterator<Integer> it = s.listIterator();
for (final Integer x : s) {
final int j = it.nextIndex();
final Integer y = it.next();
assertEquals(x, y);
assertEquals(i, j);
assertEquals(i, it.previousIndex());
i++;
}
}
public void testSubListStackOverflowRegression() {
PStack<Integer> s = ConsPStack.empty();
for (int i = 0; i < 20000; i++) {
s = s.plus(i);
}
PStack<Integer> head = s.subList(0, 10000);
assertEquals(head.size(), 10000 - 0);
PStack<Integer> tail = s.subList(10000, 20000);
assertEquals(tail.size(), 20000 - 10000);
PStack<Integer> t = s.subList(9000, 11000);
assertEquals(t.size(), 11000 - 9000);
}
public void testPlusStackOverflowRegression() {
PStack<Integer> s = ConsPStack.empty();
for (int i = 0; i < 20000; i++) {
s = s.plus(i);
}
PStack<Integer> t = s.plus(10000, 1234);
assertEquals(t.size(), s.size() + 1);
}
public void testPlusAllStackOverflowRegression() {
PStack<Integer> s = ConsPStack.empty();
for (int i = 0; i < 20000; i++) {
s = s.plus(i);
}
PStack<Integer> t = s.plusAll(10000, s);
assertEquals(t.size(), 2 * s.size());
}
public void testMinusStackOverflowRegression() {
PStack<String> s = ConsPStack.empty();
for (int i = 0; i < 20000; i++) {
s = s.plus(Integer.toString(i));
}
PStack<String> t = s.minus("10000");
assertEquals(t.size(), s.size() - 1);
}
public void testMinusIndexStackOverflowRegression() {
PStack<String> s = ConsPStack.empty();
for (int i = 0; i < 20000; i++) {
s = s.plus(Integer.toString(i));
}
// unlike the other tests, this one wasn't failing at 10,000, no idea why...
PStack<String> t = s.minus(19000);
assertEquals(t.size(), s.size() - 1);
}
public void testMinusAllStackOverflowRegression() {
PStack<Integer> s = ConsPStack.empty();
for (int i = 0; i < 20000; i++) {
s = s.plus(i);
}
PStack<Integer> t = s.minusAll(s);
assertTrue(t.isEmpty());
}
public void testWithStackOverflowRegression() {
PStack<Integer> s = ConsPStack.empty();
for (int i = 0; i < 20000; i++) {
s = s.plus(i);
}
PStack<Integer> t = s.with(10000, 1234);
assertEquals(t.size(), s.size());
}
}
| |
/**
* Copyright 2010 Richard Johnson & Orin Eman
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* ---
*
* This file is part of java-libpst.
*
* java-libpst is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* java-libpst is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with java-libpst. If not, see <http://www.gnu.org/licenses/>.
*
*/
package com.pff.objects;
import java.io.IOException;
import java.util.*;
import com.pff.PSTUtils;
import com.pff.exceptions.PSTException;
import com.pff.objects.sub.PSTTimeZone;
import com.pff.parsing.DescriptorIndexNode;
import com.pff.parsing.PSTDescriptorItem;
import com.pff.parsing.PSTNodeInputStream;
import com.pff.parsing.tables.PSTTableBC;
import com.pff.parsing.tables.PSTTableBCItem;
import com.pff.source.PSTSource;
/**
* PST Object is the root class of all PST Items.
* It also provides a number of static utility functions. The most important of which is the
* detectAndLoadPSTObject call which allows extraction of a PST Item from the file.
* @author Richard Johnson
*/
public class PSTObject {
public static final int NID_TYPE_HID = 0x00; // Heap node
public static final int NID_TYPE_INTERNAL = 0x01; // Internal node (section 2.4.1)
public static final int NID_TYPE_NORMAL_FOLDER = 0x02; // Normal Folder object (PC)
public static final int NID_TYPE_SEARCH_FOLDER = 0x03; // Search Folder object (PC)
public static final int NID_TYPE_NORMAL_MESSAGE = 0x04; // Normal Message object (PC)
public static final int NID_TYPE_ATTACHMENT = 0x05; // Attachment object (PC)
public static final int NID_TYPE_SEARCH_UPDATE_QUEUE = 0x06; // Queue of changed objects for search Folder objects
public static final int NID_TYPE_SEARCH_CRITERIA_OBJECT = 0x07; // Defines the search criteria for a search Folder object
public static final int NID_TYPE_ASSOC_MESSAGE = 0x08; // Folder associated information (FAI) Message object (PC)
public static final int NID_TYPE_CONTENTS_TABLE_INDEX = 0x0A; // Internal, persisted view-related
public static final int NID_TYPE_RECEIVE_FOLDER_TABLE = 0X0B; // Receive Folder object (Inbox)
public static final int NID_TYPE_OUTGOING_QUEUE_TABLE = 0x0C; // Outbound queue (Outbox)
public static final int NID_TYPE_HIERARCHY_TABLE = 0x0D; // Hierarchy table (TC)
public static final int NID_TYPE_CONTENTS_TABLE = 0x0E; // Contents table (TC)
public static final int NID_TYPE_ASSOC_CONTENTS_TABLE = 0x0F; // FAI contents table (TC)
public static final int NID_TYPE_SEARCH_CONTENTS_TABLE = 0x10; // Contents table (TC) of a search Folder object
public static final int NID_TYPE_ATTACHMENT_TABLE = 0x11; // Attachment table (TC)
public static final int NID_TYPE_RECIPIENT_TABLE = 0x12; // Recipient table (TC)
public static final int NID_TYPE_SEARCH_TABLE_INDEX = 0x13; // Internal, persisted view-related
public static final int NID_TYPE_LTP = 0x1F; // LTP
public String getItemsString() {
return items.toString();
}
protected PSTSource pstFile;
protected byte[] data;
protected DescriptorIndexNode descriptorIndexNode;
protected HashMap<Integer, PSTTableBCItem> items;
protected HashMap<Integer, PSTDescriptorItem> localDescriptorItems = null;
protected LinkedHashMap<String, HashMap<DescriptorIndexNode, PSTObject>> children;
protected PSTObject(PSTSource theFile, DescriptorIndexNode descriptorIndexNode)
throws PSTException, IOException
{
this.pstFile = theFile;
this.descriptorIndexNode = descriptorIndexNode;
//descriptorIndexNode.readData(theFile);
//PSTTableBC table = new PSTTableBC(descriptorIndexNode.dataBlock.data, descriptorIndexNode.dataBlock.blockOffsets);
PSTTableBC table = new PSTTableBC(new PSTNodeInputStream(pstFile, pstFile.getOffsetIndexNode(descriptorIndexNode.dataOffsetIndexIdentifier)));
//System.out.println(table);
this.items = table.getItems();
if (descriptorIndexNode.localDescriptorsOffsetIndexIdentifier != 0) {
//PSTDescriptor descriptor = new PSTDescriptor(theFile, descriptorIndexNode.localDescriptorsOffsetIndexIdentifier);
//localDescriptorItems = descriptor.getChildren();
this.localDescriptorItems = theFile.getPSTDescriptorItems(descriptorIndexNode.localDescriptorsOffsetIndexIdentifier);
}
}
/**
* for pre-population
* @param theFile
* @param folderIndexNode
* @param table
*/
protected PSTObject(PSTSource theFile, DescriptorIndexNode folderIndexNode, PSTTableBC table, HashMap<Integer, PSTDescriptorItem> localDescriptorItems) {
this.pstFile = theFile;
this.descriptorIndexNode = folderIndexNode;
this.items = table.getItems();
this.table = table;
this.localDescriptorItems = localDescriptorItems;
}
protected PSTTableBC table;
/**
* get the descriptor node for this item
* this identifies the location of the node in the BTree and associated info
* @return item's descriptor node
*/
public DescriptorIndexNode getDescriptorNode() {
return this.descriptorIndexNode;
}
/**
* get the descriptor identifier for this item
* can be used for loading objects through detectAndLoadPSTObject(PSTFile theFile, long descriptorIndex)
* @return item's descriptor node identifier
*/
public long getDescriptorNodeId() {
//return this.descriptorIndexNode.descriptorIdentifier;
if (this.descriptorIndexNode != null) { // Prevent null pointer exceptions for embedded messages
return this.descriptorIndexNode.descriptorIdentifier;
}
return 0;
}
public int getNodeType() {
return PSTObject.getNodeType(this.descriptorIndexNode.descriptorIdentifier);
}
public static int getNodeType(int descriptorIdentifier) {
return descriptorIdentifier & 0x1F;
}
protected int getIntItem(int identifier) {
return getIntItem(identifier, 0);
}
protected int getIntItem(int identifier, int defaultValue) {
if (this.items.containsKey(identifier)) {
PSTTableBCItem item = this.items.get(identifier);
return item.entryValueReference;
}
return defaultValue;
}
protected boolean getBooleanItem(int identifier) {
return getBooleanItem(identifier, false);
}
protected boolean getBooleanItem(int identifier, boolean defaultValue) {
if (this.items.containsKey(identifier)) {
PSTTableBCItem item = this.items.get(identifier);
return item.entryValueReference != 0;
}
return defaultValue;
}
protected double getDoubleItem(int identifier) {
return getDoubleItem(identifier, 0);
}
protected double getDoubleItem(int identifier, double defaultValue) {
if (this.items.containsKey(identifier)) {
PSTTableBCItem item = this.items.get(identifier);
long longVersion = PSTUtils.convertLittleEndianBytesToLong(item.data);
return Double.longBitsToDouble(longVersion);
}
return defaultValue;
}
protected long getLongItem(int identifier) {
return getLongItem(identifier, 0);
}
protected long getLongItem(int identifier, long defaultValue) {
if (this.items.containsKey(identifier)) {
PSTTableBCItem item = this.items.get(identifier);
if (item.entryValueType == 0x0003) {
// we are really just an int
return item.entryValueReference;
} else if ( item.entryValueType == 0x0014 ){
// we are a long
if ( item.data != null && item.data.length == 8 ) {
return PSTUtils.convertLittleEndianBytesToLong(item.data, 0, 8);
} else {
System.err.printf("Invalid data length for long id 0x%04X\n", identifier);
// Return the default value for now...
}
}
}
return defaultValue;
}
protected String getStringItem(int identifier) {
return getStringItem(identifier, 0);
}
protected String getStringItem(int identifier, int stringType) {
return getStringItem(identifier, stringType, null);
}
protected String getStringItem(int identifier, int stringType, String codepage) {
PSTTableBCItem item = this.items.get(identifier);
if ( item != null ) {
if (codepage == null) {
codepage = this.getStringCodepage();
}
// get the string type from the item if not explicitly set
if ( stringType == 0 ) {
stringType = item.entryValueType;
}
// see if there is a descriptor entry
if ( !item.isExternalValueReference ) {
//System.out.println("here: "+new String(item.data)+this.descriptorIndexNode.descriptorIdentifier);
return PSTObject.createJavaString(item.data, stringType, codepage);
}
if (this.localDescriptorItems != null &&
this.localDescriptorItems.containsKey(item.entryValueReference))
{
// we have a hit!
PSTDescriptorItem descItem = this.localDescriptorItems.get(item.entryValueReference);
try {
byte[] data = descItem.getData();
if ( data == null ) {
return "";
}
return PSTObject.createJavaString(data, stringType, codepage);
} catch (Exception e) {
System.err.printf("Exception %s decoding string %s: %s\n",
e.toString(),
PSTSource.getPropertyDescription(identifier, stringType), data != null ? data.toString() : "null");
return "";
}
//System.out.printf("PSTObject.getStringItem - item isn't a string: 0x%08X\n", identifier);
//return "";
}
return PSTObject.createJavaString(data, stringType, codepage);
}
return "";
}
static String createJavaString(byte[] data, int stringType, String codepage)
{
try {
if ( stringType == 0x1F ) {
return new String(data, "UTF-16LE");
}
if (codepage == null) {
return new String(data);
} else {
codepage = codepage.toUpperCase();
return new String(data, codepage);
}
/*
if (codepage == null || codepage.toUpperCase().equals("UTF-8") || codepage.toUpperCase().equals("UTF-7")) {
// PST UTF-8 strings are not... really UTF-8
// it seems that they just don't use multibyte chars at all.
// indeed, with some crylic chars in there, the difficult chars are just converted to %3F(?)
// I suspect that outlook actually uses RTF to store these problematic strings.
StringBuffer sbOut = new StringBuffer();
for (int x = 0; x < data.length; x++) {
sbOut.append((char)(data[x] & 0xFF)); // just blindly accept the byte as a UTF char, seems right half the time
}
return new String(sbOut);
} else {
codepage = codepage.toUpperCase();
return new String(data, codepage);
}
*/
} catch (Exception err) {
System.err.println("Unable to decode string");
err.printStackTrace();
return "";
}
}
private String getStringCodepage() {
// try and get the codepage
PSTTableBCItem cpItem = this.items.get(0x3FFD); // PidTagMessageCodepage
if (cpItem == null) {
cpItem = this.items.get(0x3FDE); // PidTagInternetCodepage
}
if (cpItem != null) {
return PSTSource.getInternetCodePageCharset(cpItem.entryValueReference);
}
return null;
}
public Date getDateItem(int identifier) {
if ( this.items.containsKey(identifier) ) {
PSTTableBCItem item = this.items.get(identifier);
if (item.data.length == 0 ) {
return new Date(0);
}
int high = (int)PSTUtils.convertLittleEndianBytesToLong(item.data, 4, 8);
int low = (int)PSTUtils.convertLittleEndianBytesToLong(item.data, 0, 4);
return PSTUtils.filetimeToDate(high, low);
}
return null;
}
protected byte[] getBinaryItem(int identifier) {
if (this.items.containsKey(identifier)) {
PSTTableBCItem item = this.items.get(identifier);
if ( item.entryValueType == 0x0102 ) {
if ( !item.isExternalValueReference ) {
return item.data;
}
if ( this.localDescriptorItems != null &&
this.localDescriptorItems.containsKey(item.entryValueReference))
{
// we have a hit!
PSTDescriptorItem descItem = this.localDescriptorItems.get(item.entryValueReference);
try {
return descItem.getData();
} catch (Exception e) {
System.err.printf("Exception reading binary item: reference 0x%08X\n", item.entryValueReference);
return null;
}
}
//System.out.println("External reference!!!\n");
}
}
return null;
}
protected PSTTimeZone getTimeZoneItem(int identifier) {
byte[] tzData = getBinaryItem(identifier);
if ( tzData != null && tzData.length != 0 ) {
return new PSTTimeZone(tzData);
}
return null;
}
public String getMessageClass() {
return this.getStringItem(0x001a);
}
public String toString() {
return this.localDescriptorItems + "\n" +
(this.items);
}
/**
* These are the common properties, some don't really appear to be common across folders and emails, but hey
*/
/**
* get the display name
*/
public String getDisplayName() {
return this.getStringItem(0x3001);
}
/**
* Address type
* Known values are SMTP, EX (Exchange) and UNKNOWN
*/
public String getAddrType() {
return this.getStringItem(0x3002);
}
/**
* E-mail address
*/
public String getEmailAddress() {
return this.getStringItem(0x3003);
}
/**
* Comment
*/
public String getComment() {
return this.getStringItem(0x3004);
}
/**
* Creation time
*/
public Date getCreationTime() {
return this.getDateItem(0x3007);
}
/**
* Modification time
*/
public Date getLastModificationTime() {
return this.getDateItem(0x3008);
}
/**
* Detect and load a PST Object from a file with the specified descriptor index
* @param theFile
* @param descriptorIndex
* @return PSTObject with that index
* @throws IOException
* @throws PSTException
*/
public static PSTObject detectAndLoadPSTObject(PSTSource theFile, long descriptorIndex)
throws IOException, PSTException
{
return detectAndLoadPSTObject(theFile, theFile.getDescriptorIndexNode(descriptorIndex));
}
/**
* Detect and load a PST Object from a file with the specified descriptor index
* @param theFile
* @param folderIndexNode
* @return PSTObject with that index
* @throws IOException
* @throws PSTException
*/
public static PSTObject detectAndLoadPSTObject(PSTSource theFile, DescriptorIndexNode folderIndexNode)
throws IOException, PSTException
{
int nidType = (folderIndexNode.descriptorIdentifier & 0x1F);
if ( nidType == 0x02 || nidType == 0x03 || nidType == 0x04 ) {
PSTTableBC table = new PSTTableBC(new PSTNodeInputStream(theFile, theFile.getOffsetIndexNode(folderIndexNode.dataOffsetIndexIdentifier)));
HashMap<Integer, PSTDescriptorItem> localDescriptorItems = null;
if (folderIndexNode.localDescriptorsOffsetIndexIdentifier != 0) {
localDescriptorItems = theFile.getPSTDescriptorItems(folderIndexNode.localDescriptorsOffsetIndexIdentifier);
}
if ( nidType == 0x02 || nidType == 0x03 ) {
return new PSTFolder(theFile, folderIndexNode, table, localDescriptorItems);
} else {
return createAppropriatePSTMessageObject(theFile, folderIndexNode, table, localDescriptorItems);
}
}
else
{
throw new PSTException("Unknown child type with offset id: "+folderIndexNode.localDescriptorsOffsetIndexIdentifier);
}
}
static PSTMessage createAppropriatePSTMessageObject(PSTSource theFile, DescriptorIndexNode folderIndexNode, PSTTableBC table, HashMap<Integer, PSTDescriptorItem> localDescriptorItems)
{
PSTTableBCItem item = table.getItems().get(0x001a);
String messageClass = "";
if ( item != null )
{
messageClass = item.getStringValue();
}
if (messageClass.equals("IPM.Note")) {
return new PSTMessage(theFile, folderIndexNode, table, localDescriptorItems);
} else if (messageClass.equals("IPM.Appointment") ||
messageClass.equals("IPM.OLE.CLASS.{00061055-0000-0000-C000-000000000046}") ||
messageClass.startsWith("IPM.Schedule.Meeting")) {
return new PSTAppointment(theFile, folderIndexNode, table, localDescriptorItems);
} else if (messageClass.equals("IPM.Contact")) {
return new PSTContact(theFile, folderIndexNode, table, localDescriptorItems);
} else if (messageClass.equals("IPM.Task")) {
return new PSTTask(theFile, folderIndexNode, table, localDescriptorItems);
} else if (messageClass.equals("IPM.Activity")) {
return new PSTActivity(theFile, folderIndexNode, table, localDescriptorItems);
} else if (messageClass.equals("IPM.Post.Rss")) {
return new PSTRss(theFile, folderIndexNode, table, localDescriptorItems);
} else {
System.err.println("Unknown message type: "+messageClass);
}
return new PSTMessage(theFile, folderIndexNode, table, localDescriptorItems);
}
public static String guessPSTObjectType(PSTSource theFile, DescriptorIndexNode folderIndexNode)
throws IOException, PSTException
{
PSTTableBC table = new PSTTableBC(new PSTNodeInputStream(theFile, theFile.getOffsetIndexNode(folderIndexNode.dataOffsetIndexIdentifier)));
// get the table items and look at the types we are dealing with
Set<Integer> keySet = table.getItems().keySet();
Iterator<Integer> iterator = keySet.iterator();
while (iterator.hasNext()) {
Integer key = iterator.next();
if (key.intValue() >= 0x0001 &&
key.intValue() <= 0x0bff)
{
return "Message envelope";
}
else if (key.intValue() >= 0x1000 &&
key.intValue() <= 0x2fff)
{
return "Message content";
}
else if (key.intValue() >= 0x3400 &&
key.intValue() <= 0x35ff)
{
return "Message store";
}
else if (key.intValue() >= 0x3600 &&
key.intValue() <= 0x36ff)
{
return "Folder and address book";
}
else if (key.intValue() >= 0x3700 &&
key.intValue() <= 0x38ff)
{
return "Attachment";
}
else if (key.intValue() >= 0x3900 &&
key.intValue() <= 0x39ff)
{
return "Address book";
}
else if (key.intValue() >= 0x3a00 &&
key.intValue() <= 0x3bff)
{
return "Messaging user";
}
else if (key.intValue() >= 0x3c00 &&
key.intValue() <= 0x3cff)
{
return "Distribution list";
}
}
return "Unknown";
}
}
| |
/*
* ConnectBot: simple, powerful, open-source SSH client for Android
* Copyright 2007 Kenny Root, Jeffrey Sharkey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.schoentoon.connectbot.transport;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Context;
import android.net.Uri;
import android.util.Log;
import com.schoentoon.connectbot.R;
import com.schoentoon.connectbot.bean.HostBean;
import com.schoentoon.connectbot.service.TerminalBridge;
import com.schoentoon.connectbot.service.TerminalManager;
import com.schoentoon.connectbot.util.HostDatabase;
import de.mud.telnet.TelnetProtocolHandler;
/**
* Telnet transport implementation.<br/>
* Original idea from the JTA telnet package (de.mud.telnet)
*
* @author Kenny Root
*
*/
public class Telnet extends AbsTransport {
private static final String TAG = "ConnectBot.Telnet";
private static final String PROTOCOL = "telnet";
private static final int DEFAULT_PORT = 23;
private TelnetProtocolHandler handler;
private Socket socket;
private InputStream is;
private OutputStream os;
private int width;
private int height;
private boolean connected = false;
static final Pattern hostmask;
static {
hostmask = Pattern.compile("^([0-9a-z.-]+)(:(\\d+))?$", Pattern.CASE_INSENSITIVE);
}
public Telnet() {
handler = new TelnetProtocolHandler() {
/** get the current terminal type */
@Override
public String getTerminalType() {
return getEmulation();
}
/** get the current window size */
@Override
public int[] getWindowSize() {
return new int[] { width, height };
}
/** notify about local echo */
@Override
public void setLocalEcho(boolean echo) {
/* EMPTY */
}
/** write data to our back end */
@Override
public void write(byte[] b) throws IOException {
if (os != null)
os.write(b);
}
/** sent on IAC EOR (prompt terminator for remote access systems). */
@Override
public void notifyEndOfRecord() {
}
@Override
protected String getCharsetName() {
Charset charset = bridge.getCharset();
if (charset != null)
return charset.name();
else
return "";
}
};
}
/**
* @param host
* @param bridge
* @param manager
*/
public Telnet(HostBean host, TerminalBridge bridge, TerminalManager manager) {
super(host, bridge, manager);
}
public static String getProtocolName() {
return PROTOCOL;
}
@Override
public void connect() {
try {
socket = new Socket(host.getHostname(), host.getPort());
connected = true;
is = socket.getInputStream();
os = socket.getOutputStream();
bridge.onConnected();
} catch (UnknownHostException e) {
Log.d(TAG, "IO Exception connecting to host", e);
} catch (IOException e) {
Log.d(TAG, "IO Exception connecting to host", e);
}
}
@Override
public void close() {
connected = false;
if (socket != null)
try {
socket.close();
socket = null;
} catch (IOException e) {
Log.d(TAG, "Error closing telnet socket.", e);
}
}
@Override
public void flush() throws IOException {
os.flush();
}
@Override
public int getDefaultPort() {
return DEFAULT_PORT;
}
@Override
public boolean isConnected() {
return connected;
}
@Override
public boolean isSessionOpen() {
return connected;
}
@Override
public int read(byte[] buffer, int start, int len) throws IOException {
/* process all already read bytes */
int n = 0;
do {
n = handler.negotiate(buffer, start);
if (n > 0)
return n;
} while (n == 0);
while (n <= 0) {
do {
n = handler.negotiate(buffer, start);
if (n > 0)
return n;
} while (n == 0);
n = is.read(buffer, start, len);
if (n < 0) {
bridge.dispatchDisconnect(false);
throw new IOException("Remote end closed connection.");
}
handler.inputfeed(buffer, start, n);
n = handler.negotiate(buffer, start);
}
return n;
}
@Override
public void write(byte[] buffer) throws IOException {
try {
if (os != null)
os.write(buffer);
} catch (SocketException e) {
bridge.dispatchDisconnect(false);
}
}
@Override
public void write(int c) throws IOException {
try {
if (os != null)
os.write(c);
} catch (SocketException e) {
bridge.dispatchDisconnect(false);
}
}
@Override
public void setDimensions(int columns, int rows, int width, int height) {
try {
handler.setWindowSize(columns, rows);
} catch (IOException e) {
Log.e(TAG, "Couldn't resize remote terminal", e);
}
}
@Override
public String getDefaultNickname(String username, String hostname, int port) {
if (port == DEFAULT_PORT) {
return String.format("%s", hostname);
} else {
return String.format("%s:%d", hostname, port);
}
}
public static Uri getUri(String input) {
Matcher matcher = hostmask.matcher(input);
if (!matcher.matches())
return null;
StringBuilder sb = new StringBuilder();
sb.append(PROTOCOL)
.append("://")
.append(matcher.group(1));
String portString = matcher.group(3);
int port = DEFAULT_PORT;
if (portString != null) {
try {
port = Integer.parseInt(portString);
if (port < 1 || port > 65535) {
port = DEFAULT_PORT;
}
} catch (NumberFormatException nfe) {
// Keep the default port
}
}
if (port != DEFAULT_PORT) {
sb.append(':');
sb.append(port);
}
sb.append("/#")
.append(Uri.encode(input));
Uri uri = Uri.parse(sb.toString());
return uri;
}
@Override
public HostBean createHost(Uri uri) {
HostBean host = new HostBean();
host.setProtocol(PROTOCOL);
host.setHostname(uri.getHost());
int port = uri.getPort();
if (port < 0)
port = DEFAULT_PORT;
host.setPort(port);
String nickname = uri.getFragment();
if (nickname == null || nickname.length() == 0) {
host.setNickname(getDefaultNickname(host.getUsername(),
host.getHostname(), host.getPort()));
} else {
host.setNickname(uri.getFragment());
}
return host;
}
@Override
public void getSelectionArgs(Uri uri, Map<String, String> selection) {
selection.put(HostDatabase.FIELD_HOST_PROTOCOL, PROTOCOL);
selection.put(HostDatabase.FIELD_HOST_NICKNAME, uri.getFragment());
selection.put(HostDatabase.FIELD_HOST_HOSTNAME, uri.getHost());
int port = uri.getPort();
if (port < 0)
port = DEFAULT_PORT;
selection.put(HostDatabase.FIELD_HOST_PORT, Integer.toString(port));
}
public static String getFormatHint(Context context) {
return String.format("%s:%s",
context.getString(R.string.format_hostname),
context.getString(R.string.format_port));
}
/* (non-Javadoc)
* @see org.connectbot.transport.AbsTransport#usesNetwork()
*/
@Override
public boolean usesNetwork() {
return true;
}
}
| |
/*
* #%L
* omakase
* %%
* Copyright (C) 2015 Project Omakase LLC
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package org.projectomakase.omakase.job.task;
import com.google.common.collect.ImmutableMap;
import org.projectomakase.omakase.exceptions.NotFoundException;
import org.projectomakase.omakase.job.task.jcr.TaskGroupNode;
import org.projectomakase.omakase.job.task.jcr.TaskNode;
import org.projectomakase.omakase.task.api.Task;
import org.projectomakase.omakase.task.api.TaskInstanceLoader;
import org.projectomakase.omakase.task.api.TaskStatus;
import org.projectomakase.omakase.task.api.TaskStatusUpdate;
import org.projectomakase.omakase.task.spi.TaskConfiguration;
import org.projectomakase.omakase.task.spi.TaskOutput;
import org.apache.deltaspike.core.api.config.ConfigProperty;
import javax.enterprise.context.ApplicationScoped;
import javax.inject.Inject;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import java.io.StringReader;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Comparator;
import java.util.Date;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
/**
* Utility methods for working with the task API.
*
* @author Richard Lucas
*/
@ApplicationScoped
public class Tasks {
private static final Map<TaskStatus, Integer> taskStatusWeight =
ImmutableMap.of(TaskStatus.QUEUED, 2, TaskStatus.EXECUTING, 1, TaskStatus.COMPLETED, 5, TaskStatus.FAILED_DIRTY, 3, TaskStatus.FAILED_CLEAN, 4);
@Inject
TaskManager taskManager;
@Inject
@ConfigProperty(name = "omakase.max.task.retries")
int maxTaskRetries;
/**
* Maps a {@link TaskNode} to a {@link Task}.
*
* @param taskNode
* the {@link TaskNode}
* @return the {@link Task}.
*/
public Task fromTaskNode(TaskNode taskNode) {
TaskConfiguration taskConfiguration = TaskInstanceLoader.loadTaskConfigurationInstance(taskNode.getType());
taskConfiguration.fromJson(taskNode.getConfiguration());
Optional<TaskOutput> taskOutput = Optional.ofNullable(taskNode.getOutput()).map(out -> TaskInstanceLoader.loadTaskOutputInstance(taskNode.getType()));
taskOutput.ifPresent(out -> out.fromJson(taskNode.getOutput()));
return new Task(taskNode.getId(), taskNode.getType(), taskNode.getDescription(), taskNode.getStatus(), fromDate(taskNode.getStatusTimestamp()), taskNode.getPriority(), taskConfiguration,
taskOutput.orElse(null), fromDate(taskNode.getCreated()));
}
/**
* Maps a {@link Task} to a {@link TaskNode}.
*
* @param task
* the {@link Task}
* @return the {@link TaskNode}.
*/
public TaskNode fromTask(Task task) {
String output = task.getOutput().map(TaskOutput::toJson).orElse(null);
return new TaskNode(task.getId(), task.getType(), task.getDescription(), task.getStatus(), Date.from(task.getStatusTimestamp().toInstant()), task.getPriority(),
task.getConfiguration().toJson(), output);
}
/**
* Maps a {@link TaskGroupNode} to a {@link TaskGroup}.
*
* @param taskGroupNode
* the {@link TaskGroupNode}
* @return the {@link TaskGroup}.
*/
public TaskGroup fromTaskGroupNode(TaskGroupNode taskGroupNode) {
return new TaskGroup(taskGroupNode.getId(), taskGroupNode.getStatus(), fromDate(taskGroupNode.getStatusTimestamp()), taskGroupNode.getJobId(), taskGroupNode.getPipelineId(),
taskGroupNode.getCallbackListenerId(), fromDate(taskGroupNode.getCreated()));
}
/**
* Maps a {@link TaskGroup} to a {@link TaskGroupNode}.
*
* @param taskGroup
* the {@link TaskGroup}
* @return the {@link TaskGroupNode}.
*/
public TaskGroupNode fromTaskGroup(TaskGroup taskGroup) {
return new TaskGroupNode(taskGroup.getId(), taskGroup.getStatus(), Date.from(taskGroup.getStatusTimestamp().toInstant()), taskGroup.getJobId(), taskGroup.getPipelineId(),
taskGroup.getCallbackListenerId());
}
/**
* Creates a {@link TaskStatusUpdate} from a json string.
*
* @param taskId
* the task id the update is related to.
* @param json
* a json string representation of the update
* @return a {@link TaskStatusUpdate}.
*/
public TaskStatusUpdate taskStatusUpdateFromJson(String taskId, String json) {
Task task = taskManager.getTask(taskId).orElseThrow(() -> new NotFoundException("task " + taskId + " does not exist"));
try (StringReader stringReader = new StringReader(json); JsonReader jsonReader = Json.createReader(stringReader)) {
JsonObject jsonObject = jsonReader.readObject();
return new TaskStatusUpdate(getTaskStatus(jsonObject), getMessage(jsonObject), getPercentComplete(jsonObject), getTaskOutput(jsonObject, TaskInstanceLoader.loadTaskOutputInstance(task.getType())));
}
}
/**
* Returns the task group status based on a list of task statuses.
*
* @param tasks
* a list of tasks
* @return the task group status.
*/
public TaskStatus getTaskGroupStatusFromTasks(Set<Task> tasks) {
return tasks.stream().map(Task::getStatus).sorted(Comparator.comparing(taskStatusWeight::get)).findFirst().get();
}
/**
* Returns the task group status based on a list of task statuses.
*
* @param taskStatuses
* a list of task statuses
* @return the task group status
*/
public TaskStatus getTaskGroupStatusFromTaskStatuses(Set<TaskStatus> taskStatuses) {
return taskStatuses.stream().sorted(Comparator.comparing(taskStatusWeight::get)).findFirst().get();
}
/**
* Returns true if the task status is a failure statue otherwise true.
*
* @param taskStatus
* the task status
* @return true if the task status is a failure statue otherwise true.
*/
public boolean isFailedTaskStatus(TaskStatus taskStatus) {
return TaskStatus.FAILED_CLEAN.equals(taskStatus) || TaskStatus.FAILED_DIRTY.equals(taskStatus);
}
/**
* Returns the maximum number of times a task should be retired before marking as failed.
*
* @return the maximum number of times a task should be retired before marking as failed.
*/
public int getMaxTaskRetries() {
if (maxTaskRetries > 10) {
return 10;
} else if (maxTaskRetries < 0) {
return 0;
} else {
return maxTaskRetries;
}
}
/**
* Returns true if the task should be retried otherwise false.
*
* @param taskStatus
* the task status
* @param currentRetryAttempts
* the current number of retry attempts
* @param maxRetryAttempts
* the maximum number of retry attempts
* @return true if the task should be retried otherwise false.
*/
public boolean shouldRetryTask(TaskStatus taskStatus, int currentRetryAttempts, int maxRetryAttempts) {
return isFailedTaskStatus(taskStatus) && maxRetryAttempts > currentRetryAttempts;
}
private static ZonedDateTime fromDate(Date date) {
return ZonedDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
private static TaskStatus getTaskStatus(JsonObject jsonObject) {
if (!jsonObject.containsKey("status")) {
throw new IllegalArgumentException("Invalid JSON, requires a 'status' property");
} else {
return TaskStatus.valueOf(jsonObject.getString("status"));
}
}
private static String getMessage(JsonObject jsonObject) {
if (jsonObject.containsKey("message")) {
return jsonObject.getString("message");
} else {
return null;
}
}
private static int getPercentComplete(JsonObject jsonObject) {
if (jsonObject.containsKey("percent_complete")) {
return jsonObject.getInt("percent_complete");
} else {
return -1;
}
}
private static TaskOutput getTaskOutput(JsonObject jsonObject, TaskOutput outputInstance) {
if (jsonObject.containsKey("output")) {
outputInstance.fromJson(jsonObject.getJsonObject("output").toString());
return outputInstance;
} else {
return null;
}
}
}
| |
package mcjty.rftools.items;
import mcjty.rftools.RFTools;
import mcjty.rftools.items.devdelight.DevelopersDelightItem;
import mcjty.rftools.items.devdelight.ShardWandItem;
import mcjty.rftools.items.dimensionmonitor.DimensionMonitorItem;
import mcjty.rftools.items.dimensionmonitor.PhasedFieldGeneratorItem;
import mcjty.rftools.items.dimlets.*;
import mcjty.rftools.items.envmodules.*;
import mcjty.rftools.items.manual.RFToolsManualDimensionItem;
import mcjty.rftools.items.manual.RFToolsManualItem;
import mcjty.rftools.items.netmonitor.NetworkMonitorItem;
import mcjty.rftools.items.parts.*;
import mcjty.rftools.items.screenmodules.*;
import mcjty.rftools.items.teleportprobe.ChargedPorterItem;
import mcjty.rftools.items.teleportprobe.TeleportProbeItem;
import cpw.mods.fml.common.registry.GameRegistry;
public final class ModItems {
public static NetworkMonitorItem networkMonitorItem;
public static TeleportProbeItem teleportProbeItem;
public static ChargedPorterItem chargedPorterItem;
public static RFToolsManualItem rfToolsManualItem;
public static RFToolsManualDimensionItem rfToolsManualDimensionItem;
public static DevelopersDelightItem developersDelightItem;
public static ShardWandItem shardWandItem;
public static UnknownDimlet unknownDimlet;
public static DimletTemplate dimletTemplate;
public static KnownDimlet knownDimlet;
public static EmptyDimensionTab emptyDimensionTab;
public static RealizedDimensionTab realizedDimensionTab;
public static DimensionMonitorItem dimensionMonitorItem;
public static PhasedFieldGeneratorItem phasedFieldGeneratorItem;
public static DimensionalShard dimensionalShard;
public static TextModuleItem textModuleItem;
public static EnergyModuleItem energyModuleItem;
public static EnergyPlusModuleItem energyPlusModuleItem;
public static DimensionModuleItem dimensionModuleItem;
public static InventoryModuleItem inventoryModuleItem;
public static InventoryPlusModuleItem inventoryPlusModuleItem;
public static ClockModuleItem clockModuleItem;
public static FluidModuleItem fluidModuleItem;
public static FluidPlusModuleItem fluidPlusModuleItem;
public static CounterModuleItem counterModuleItem;
public static CounterPlusModuleItem counterPlusModuleItem;
public static RedstoneModuleItem redstoneModuleItem;
public static MachineInformationModuleItem machineInformationModuleItem;
public static ComputerModuleItem computerModuleItem;
public static RegenerationEModuleItem regenerationEModuleItem;
public static RegenerationPlusEModuleItem regenerationPlusEModuleItem;
public static SpeedEModuleItem speedEModuleItem;
public static SpeedPlusEModuleItem speedPlusEModuleItem;
public static HasteEModuleItem hasteEModuleItem;
public static HastePlusEModuleItem hastePlusEModuleItem;
public static SaturationEModuleItem saturationEModuleItem;
public static SaturationPlusEModuleItem saturationPlusEModuleItem;
public static FeatherFallingEModuleItem featherFallingEModuleItem;
public static FeatherFallingPlusEModuleItem featherFallingPlusEModuleItem;
public static FlightEModuleItem flightEModuleItem;
public static PeacefulEModuleItem peacefulEModuleItem;
public static DimletBaseItem dimletBaseItem;
public static DimletControlCircuitItem dimletControlCircuitItem;
public static DimletEnergyModuleItem dimletEnergyModuleItem;
public static DimletMemoryUnitItem dimletMemoryUnitItem;
public static DimletTypeControllerItem dimletTypeControllerItem;
public static SyringeItem syringeItem;
public static PeaceEssenceItem peaceEssenceItem;
public static EfficiencyEssenceItem efficiencyEssenceItem;
public static MediocreEfficiencyEssenceItem mediocreEfficiencyEssenceItem;
public static void init() {
networkMonitorItem = new NetworkMonitorItem();
networkMonitorItem.setUnlocalizedName("NetworkMonitor");
networkMonitorItem.setCreativeTab(RFTools.tabRfTools);
networkMonitorItem.setTextureName(RFTools.MODID + ":networkMonitorItem");
GameRegistry.registerItem(networkMonitorItem, "networkMonitorItem");
teleportProbeItem = new TeleportProbeItem();
teleportProbeItem.setUnlocalizedName("TeleportProbe");
teleportProbeItem.setCreativeTab(RFTools.tabRfTools);
teleportProbeItem.setTextureName(RFTools.MODID + ":teleportProbeItem");
GameRegistry.registerItem(teleportProbeItem, "teleportProbeItem");
chargedPorterItem = new ChargedPorterItem();
chargedPorterItem.setUnlocalizedName("ChargedPorter");
chargedPorterItem.setCreativeTab(RFTools.tabRfTools);
GameRegistry.registerItem(chargedPorterItem, "chargedPorterItem");
rfToolsManualItem = new RFToolsManualItem();
rfToolsManualItem.setUnlocalizedName("RFToolsManual");
rfToolsManualItem.setCreativeTab(RFTools.tabRfTools);
rfToolsManualItem.setTextureName(RFTools.MODID + ":rftoolsManual");
GameRegistry.registerItem(rfToolsManualItem, "rfToolsManualItem");
rfToolsManualDimensionItem = new RFToolsManualDimensionItem();
rfToolsManualDimensionItem.setUnlocalizedName("RFToolsManualDimension");
rfToolsManualDimensionItem.setCreativeTab(RFTools.tabRfTools);
rfToolsManualDimensionItem.setTextureName(RFTools.MODID + ":rftoolsManualDimension");
GameRegistry.registerItem(rfToolsManualDimensionItem, "rfToolsManualDimensionItem");
developersDelightItem = new DevelopersDelightItem();
developersDelightItem.setUnlocalizedName("DevelopersDelight");
developersDelightItem.setCreativeTab(RFTools.tabRfTools);
developersDelightItem.setTextureName(RFTools.MODID + ":developersDelightItem");
GameRegistry.registerItem(developersDelightItem, "developersDelightItem");
shardWandItem = new ShardWandItem();
shardWandItem.setUnlocalizedName("ShardWand");
shardWandItem.setCreativeTab(RFTools.tabRfTools);
shardWandItem.setTextureName(RFTools.MODID + ":shardWandItem");
GameRegistry.registerItem(shardWandItem, "shardWandItem");
initEnvironmentModuleItems();
initScreenModuleItems();
initDimensionItems();
initDimletPartItems();
}
private static void initDimletPartItems() {
dimletBaseItem = new DimletBaseItem();
dimletBaseItem.setUnlocalizedName("DimletBase");
dimletBaseItem.setCreativeTab(RFTools.tabRfTools);
dimletBaseItem.setTextureName(RFTools.MODID + ":parts/dimletBase");
GameRegistry.registerItem(dimletBaseItem, "dimletBaseItem");
dimletControlCircuitItem = new DimletControlCircuitItem();
dimletControlCircuitItem.setUnlocalizedName("DimletControlCircuit");
dimletControlCircuitItem.setCreativeTab(RFTools.tabRfTools);
GameRegistry.registerItem(dimletControlCircuitItem, "dimletControlCircuitItem");
dimletEnergyModuleItem = new DimletEnergyModuleItem();
dimletEnergyModuleItem.setUnlocalizedName("DimletEnergyModule");
dimletEnergyModuleItem.setCreativeTab(RFTools.tabRfTools);
GameRegistry.registerItem(dimletEnergyModuleItem, "dimletEnergyModuleItem");
dimletMemoryUnitItem = new DimletMemoryUnitItem();
dimletMemoryUnitItem.setUnlocalizedName("DimletMemoryUnit");
dimletMemoryUnitItem.setCreativeTab(RFTools.tabRfTools);
GameRegistry.registerItem(dimletMemoryUnitItem, "dimletMemoryUnitItem");
dimletTypeControllerItem = new DimletTypeControllerItem();
dimletTypeControllerItem.setUnlocalizedName("DimletTypeController");
dimletTypeControllerItem.setCreativeTab(RFTools.tabRfTools);
GameRegistry.registerItem(dimletTypeControllerItem, "dimletTypeControllerItem");
syringeItem = new SyringeItem();
syringeItem.setUnlocalizedName("SyringeItem");
syringeItem.setCreativeTab(RFTools.tabRfTools);
GameRegistry.registerItem(syringeItem, "syringeItem");
peaceEssenceItem = new PeaceEssenceItem();
peaceEssenceItem.setUnlocalizedName("PeaceEssence");
peaceEssenceItem.setCreativeTab(RFTools.tabRfTools);
peaceEssenceItem.setTextureName(RFTools.MODID + ":parts/peaceEssence");
GameRegistry.registerItem(peaceEssenceItem, "peaceEssenceItem");
efficiencyEssenceItem = new EfficiencyEssenceItem();
efficiencyEssenceItem.setUnlocalizedName("EfficiencyEssence");
efficiencyEssenceItem.setCreativeTab(RFTools.tabRfTools);
efficiencyEssenceItem.setTextureName(RFTools.MODID + ":parts/efficiencyEssence");
GameRegistry.registerItem(efficiencyEssenceItem, "efficiencyEssenceItem");
mediocreEfficiencyEssenceItem = new MediocreEfficiencyEssenceItem();
mediocreEfficiencyEssenceItem.setUnlocalizedName("MediocreEfficiencyEssence");
mediocreEfficiencyEssenceItem.setCreativeTab(RFTools.tabRfTools);
mediocreEfficiencyEssenceItem.setTextureName(RFTools.MODID + ":parts/mediocreEfficiencyEssence");
GameRegistry.registerItem(mediocreEfficiencyEssenceItem, "mediocreEfficiencyEssenceItem");
}
private static void initEnvironmentModuleItems() {
regenerationEModuleItem = new RegenerationEModuleItem();
regenerationEModuleItem.setUnlocalizedName("RegenerationEModule");
regenerationEModuleItem.setCreativeTab(RFTools.tabRfTools);
regenerationEModuleItem.setTextureName(RFTools.MODID + ":envmodules/regenerationEModuleItem");
GameRegistry.registerItem(regenerationEModuleItem, "regenerationEModuleItem");
regenerationPlusEModuleItem = new RegenerationPlusEModuleItem();
regenerationPlusEModuleItem.setUnlocalizedName("RegenerationPlusEModule");
regenerationPlusEModuleItem.setCreativeTab(RFTools.tabRfTools);
regenerationPlusEModuleItem.setTextureName(RFTools.MODID + ":envmodules/regenerationPlusEModuleItem");
GameRegistry.registerItem(regenerationPlusEModuleItem, "regenerationPlusEModuleItem");
speedEModuleItem = new SpeedEModuleItem();
speedEModuleItem.setUnlocalizedName("SpeedEModule");
speedEModuleItem.setCreativeTab(RFTools.tabRfTools);
speedEModuleItem.setTextureName(RFTools.MODID + ":envmodules/speedEModuleItem");
GameRegistry.registerItem(speedEModuleItem, "speedEModuleItem");
speedPlusEModuleItem = new SpeedPlusEModuleItem();
speedPlusEModuleItem.setUnlocalizedName("SpeedPlusEModule");
speedPlusEModuleItem.setCreativeTab(RFTools.tabRfTools);
speedPlusEModuleItem.setTextureName(RFTools.MODID + ":envmodules/speedPlusEModuleItem");
GameRegistry.registerItem(speedPlusEModuleItem, "speedPlusEModuleItem");
hasteEModuleItem = new HasteEModuleItem();
hasteEModuleItem.setUnlocalizedName("HasteEModule");
hasteEModuleItem.setCreativeTab(RFTools.tabRfTools);
hasteEModuleItem.setTextureName(RFTools.MODID + ":envmodules/hasteEModuleItem");
GameRegistry.registerItem(hasteEModuleItem, "hasteEModuleItem");
hastePlusEModuleItem = new HastePlusEModuleItem();
hastePlusEModuleItem.setUnlocalizedName("HastePlusEModule");
hastePlusEModuleItem.setCreativeTab(RFTools.tabRfTools);
hastePlusEModuleItem.setTextureName(RFTools.MODID + ":envmodules/hastePlusEModuleItem");
GameRegistry.registerItem(hastePlusEModuleItem, "hastePlusEModuleItem");
saturationEModuleItem = new SaturationEModuleItem();
saturationEModuleItem.setUnlocalizedName("SaturationEModule");
saturationEModuleItem.setCreativeTab(RFTools.tabRfTools);
saturationEModuleItem.setTextureName(RFTools.MODID + ":envmodules/saturationEModuleItem");
GameRegistry.registerItem(saturationEModuleItem, "saturationEModuleItem");
saturationPlusEModuleItem = new SaturationPlusEModuleItem();
saturationPlusEModuleItem.setUnlocalizedName("SaturationPlusEModule");
saturationPlusEModuleItem.setCreativeTab(RFTools.tabRfTools);
saturationPlusEModuleItem.setTextureName(RFTools.MODID + ":envmodules/saturationPlusEModuleItem");
GameRegistry.registerItem(saturationPlusEModuleItem, "saturationPlusEModuleItem");
featherFallingEModuleItem = new FeatherFallingEModuleItem();
featherFallingEModuleItem.setUnlocalizedName("FeatherFallingEModule");
featherFallingEModuleItem.setCreativeTab(RFTools.tabRfTools);
featherFallingEModuleItem.setTextureName(RFTools.MODID + ":envmodules/featherfallingEModuleItem");
GameRegistry.registerItem(featherFallingEModuleItem, "featherFallingEModuleItem");
featherFallingPlusEModuleItem = new FeatherFallingPlusEModuleItem();
featherFallingPlusEModuleItem.setUnlocalizedName("FeatherFallingPlusEModule");
featherFallingPlusEModuleItem.setCreativeTab(RFTools.tabRfTools);
featherFallingPlusEModuleItem.setTextureName(RFTools.MODID + ":envmodules/featherfallingPlusEModuleItem");
GameRegistry.registerItem(featherFallingPlusEModuleItem, "featherFallingPlusEModuleItem");
flightEModuleItem = new FlightEModuleItem();
flightEModuleItem.setUnlocalizedName("FlightEModule");
flightEModuleItem.setCreativeTab(RFTools.tabRfTools);
flightEModuleItem.setTextureName(RFTools.MODID + ":envmodules/flightEModuleItem");
GameRegistry.registerItem(flightEModuleItem, "flightEModuleItem");
peacefulEModuleItem = new PeacefulEModuleItem();
peacefulEModuleItem.setUnlocalizedName("PeacefulEModule");
peacefulEModuleItem.setCreativeTab(RFTools.tabRfTools);
peacefulEModuleItem.setTextureName(RFTools.MODID + ":envmodules/peacefulEModuleItem");
GameRegistry.registerItem(peacefulEModuleItem, "peacefulEModuleItem");
}
private static void initScreenModuleItems() {
textModuleItem = new TextModuleItem();
textModuleItem.setUnlocalizedName("TextModule");
textModuleItem.setCreativeTab(RFTools.tabRfTools);
textModuleItem.setTextureName(RFTools.MODID + ":modules/textModuleItem");
GameRegistry.registerItem(textModuleItem, "textModuleItem");
inventoryModuleItem = new InventoryModuleItem();
inventoryModuleItem.setUnlocalizedName("InventoryModule");
inventoryModuleItem.setCreativeTab(RFTools.tabRfTools);
inventoryModuleItem.setTextureName(RFTools.MODID + ":modules/inventoryModuleItem");
GameRegistry.registerItem(inventoryModuleItem, "inventoryModuleItem");
inventoryPlusModuleItem = new InventoryPlusModuleItem();
inventoryPlusModuleItem.setUnlocalizedName("InventoryPlusModule");
inventoryPlusModuleItem.setCreativeTab(RFTools.tabRfTools);
inventoryPlusModuleItem.setTextureName(RFTools.MODID + ":modules/inventoryPlusModuleItem");
GameRegistry.registerItem(inventoryPlusModuleItem, "inventoryPlusModuleItem");
energyModuleItem = new EnergyModuleItem();
energyModuleItem.setUnlocalizedName("EnergyModule");
energyModuleItem.setCreativeTab(RFTools.tabRfTools);
energyModuleItem.setTextureName(RFTools.MODID + ":modules/energyModuleItem");
GameRegistry.registerItem(energyModuleItem, "energyModuleItem");
energyPlusModuleItem = new EnergyPlusModuleItem();
energyPlusModuleItem.setUnlocalizedName("EnergyPlusModule");
energyPlusModuleItem.setCreativeTab(RFTools.tabRfTools);
energyPlusModuleItem.setTextureName(RFTools.MODID + ":modules/energyPlusModuleItem");
GameRegistry.registerItem(energyPlusModuleItem, "energyPlusModuleItem");
dimensionModuleItem = new DimensionModuleItem();
dimensionModuleItem.setUnlocalizedName("DimensionModule");
dimensionModuleItem.setCreativeTab(RFTools.tabRfTools);
dimensionModuleItem.setTextureName(RFTools.MODID + ":modules/dimensionModuleItem");
GameRegistry.registerItem(dimensionModuleItem, "dimensionModuleItem");
clockModuleItem = new ClockModuleItem();
clockModuleItem.setUnlocalizedName("ClockModule");
clockModuleItem.setCreativeTab(RFTools.tabRfTools);
clockModuleItem.setTextureName(RFTools.MODID + ":modules/clockModuleItem");
GameRegistry.registerItem(clockModuleItem, "clockModuleItem");
fluidModuleItem = new FluidModuleItem();
fluidModuleItem.setUnlocalizedName("FluidModule");
fluidModuleItem.setCreativeTab(RFTools.tabRfTools);
fluidModuleItem.setTextureName(RFTools.MODID + ":modules/fluidModuleItem");
GameRegistry.registerItem(fluidModuleItem, "fluidModuleItem");
fluidPlusModuleItem = new FluidPlusModuleItem();
fluidPlusModuleItem.setUnlocalizedName("FluidPlusModule");
fluidPlusModuleItem.setCreativeTab(RFTools.tabRfTools);
fluidPlusModuleItem.setTextureName(RFTools.MODID + ":modules/fluidPlusModuleItem");
GameRegistry.registerItem(fluidPlusModuleItem, "fluidPlusModuleItem");
counterModuleItem = new CounterModuleItem();
counterModuleItem.setUnlocalizedName("CounterModule");
counterModuleItem.setCreativeTab(RFTools.tabRfTools);
counterModuleItem.setTextureName(RFTools.MODID + ":modules/counterModuleItem");
GameRegistry.registerItem(counterModuleItem, "counterModuleItem");
counterPlusModuleItem = new CounterPlusModuleItem();
counterPlusModuleItem.setUnlocalizedName("CounterPlusModule");
counterPlusModuleItem.setCreativeTab(RFTools.tabRfTools);
counterPlusModuleItem.setTextureName(RFTools.MODID + ":modules/counterPlusModuleItem");
GameRegistry.registerItem(counterPlusModuleItem, "counterPlusModuleItem");
redstoneModuleItem = new RedstoneModuleItem();
redstoneModuleItem.setUnlocalizedName("RedstoneModule");
redstoneModuleItem.setCreativeTab(RFTools.tabRfTools);
redstoneModuleItem.setTextureName(RFTools.MODID + ":modules/redstoneModuleItem");
GameRegistry.registerItem(redstoneModuleItem, "redstoneModuleItem");
machineInformationModuleItem = new MachineInformationModuleItem();
machineInformationModuleItem.setUnlocalizedName("MachineInformationModule");
machineInformationModuleItem.setCreativeTab(RFTools.tabRfTools);
machineInformationModuleItem.setTextureName(RFTools.MODID + ":modules/machineInformationModuleItem");
GameRegistry.registerItem(machineInformationModuleItem, "machineInformationModuleItem");
computerModuleItem = new ComputerModuleItem();
computerModuleItem.setUnlocalizedName("ComputerModule");
computerModuleItem.setCreativeTab(RFTools.tabRfTools);
computerModuleItem.setTextureName(RFTools.MODID + ":modules/computerModuleItem");
GameRegistry.registerItem(computerModuleItem, "computerModuleItem");
}
private static void initDimensionItems() {
unknownDimlet = new UnknownDimlet();
unknownDimlet.setUnlocalizedName("UnknownDimlet");
unknownDimlet.setCreativeTab(RFTools.tabRfToolsDimlets);
unknownDimlet.setTextureName(RFTools.MODID + ":unknownDimletItem");
GameRegistry.registerItem(unknownDimlet, "unknownDimlet");
knownDimlet = new KnownDimlet();
knownDimlet.setUnlocalizedName("KnownDimlet");
knownDimlet.setCreativeTab(RFTools.tabRfToolsDimlets);
GameRegistry.registerItem(knownDimlet, "knownDimlet");
dimletTemplate = new DimletTemplate();
dimletTemplate.setUnlocalizedName("DimletTemplate");
dimletTemplate.setCreativeTab(RFTools.tabRfToolsDimlets);
dimletTemplate.setTextureName(RFTools.MODID + ":dimletTemplateItem");
GameRegistry.registerItem(dimletTemplate, "dimletTemplate");
emptyDimensionTab = new EmptyDimensionTab();
emptyDimensionTab.setUnlocalizedName("EmptyDimensionTab");
emptyDimensionTab.setCreativeTab(RFTools.tabRfTools);
emptyDimensionTab.setTextureName(RFTools.MODID + ":emptyDimensionTabItem");
GameRegistry.registerItem(emptyDimensionTab, "emptyDimensionTab");
realizedDimensionTab = new RealizedDimensionTab();
realizedDimensionTab.setUnlocalizedName("RealizedDimensionTab");
realizedDimensionTab.setCreativeTab(RFTools.tabRfTools);
realizedDimensionTab.setTextureName(RFTools.MODID + ":realizedDimensionTabItem");
GameRegistry.registerItem(realizedDimensionTab, "realizedDimensionTab");
dimensionMonitorItem = new DimensionMonitorItem();
dimensionMonitorItem.setUnlocalizedName("DimensionMonitor");
dimensionMonitorItem.setCreativeTab(RFTools.tabRfTools);
GameRegistry.registerItem(dimensionMonitorItem, "dimensionMonitorItem");
phasedFieldGeneratorItem = new PhasedFieldGeneratorItem();
phasedFieldGeneratorItem.setUnlocalizedName("PhasedFieldGenerator");
phasedFieldGeneratorItem.setCreativeTab(RFTools.tabRfTools);
GameRegistry.registerItem(phasedFieldGeneratorItem, "phasedFieldGeneratorItem");
dimensionalShard = new DimensionalShard();
dimensionalShard.setUnlocalizedName("DimensionalShard");
dimensionalShard.setCreativeTab(RFTools.tabRfTools);
dimensionalShard.setTextureName(RFTools.MODID + ":dimensionalShardItem");
GameRegistry.registerItem(dimensionalShard, "dimensionalShardItem");
}
}
| |
package com.alvin.sdappmanager;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.content.pm.IPackageStatsObserver;
import android.graphics.drawable.Drawable;
import android.os.RemoteException;
import android.widget.Toast;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.concurrent.Semaphore;
abstract class ISizable implements Comparable {
public long size;
public String name;
public String getSize() {
long s = size;
String suf = " b";
if (s>1024) { s /= 1024; suf=" Kb";}
if (s>1024) { s /= 1024; suf=" Mb";}
if (s>1024) { s /= 1024; suf=" Gb";}
return String.valueOf(s)+suf;
}
public String toString() {
return this.name;
}
@Override
public int compareTo(Object o) {
return ((Long)((ISizable)o).size).compareTo(size);
}
}
class Dir extends ISizable {
public String path;
public String owner;
public String link;
//public Application parent;
public Dir(String n){name=n;}
public Dir(long s){size=s;}
public static void find_and_add_child(Application parent, String name, String path) {
if (DirectoryData.instance.containsKey(path)) {
Dir old = DirectoryData.instance.get(path);
old.name = name;
old.path = path;
//old.parent = parent;
if (old.link != null) parent.selection.add(name);
parent.children.add(old);
}
}
}
public class Application extends ISizable{
public ArrayList<Dir> children;
public ArrayList<String> selection_initial;
public ArrayList<String> selection;
public String pack;
public Drawable icon;
public Boolean sys;
public Application() {
children = new ArrayList<Dir>();
selection = new ArrayList<String>();
}
public Application(String name) {
this();
this.name = name;
}
public Application(ApplicationInfo applicationInfo, PackageManager pm, Context context) {
this();
name = applicationInfo.loadLabel(pm).toString();
pack = applicationInfo.packageName;
icon = applicationInfo.loadIcon(pm);
sys = (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
Dir.find_and_add_child(this, context.getString(R.string.app_apk), applicationInfo.sourceDir);//publicSourceDir
Dir.find_and_add_child(this, context.getString(R.string.app_data), applicationInfo.dataDir);
Dir.find_and_add_child(this, context.getString(R.string.app_native), applicationInfo.nativeLibraryDir);
for(Dir c:children) size+=c.size;
Dir.find_and_add_child(this, context.getString(R.string.app_obb), DirectoryData.obb+pack);
Collections.sort(children);
selection_initial = new ArrayList<String>(selection);
}
/** Deprecated.
* generate some random amount of child objects (1..10)
*/
private void generateChildren() {
Random rand = new Random();
for(int i=0; i < rand.nextInt(9)+1; i++) {
Dir cat = new Dir("Child "+i);
this.children.add(cat);
}
}
/** Deprecated.
* generate some random objects (1..10)
*/
public static ArrayList<Application> getRandom() {
ArrayList<Application> apps = new ArrayList<Application>();
for(int i = 0; i < 10 ; i++) {
Application cat = new Application("Application "+i);
cat.generateChildren();
apps.add(cat);
}
return apps;
}
/** Deprecated.
* Getting installed app size - wtf it does not work for me?
* @browse http://stackoverflow.com/questions/1806286/getting-installed-app-size
*/
public static ArrayList<Application> getList_(Context context) {
final PackageManager packageManager = context.getPackageManager();
ArrayList<Application> apps = new ArrayList<Application>();
List<ApplicationInfo> installedApplications =
packageManager.getInstalledApplications(PackageManager.GET_META_DATA);
// Semaphore to handle concurrency
final Semaphore codeSizeSemaphore = new Semaphore(1, true);
// Code size will be here
final long[] sizes = new long[8];
for (ApplicationInfo appInfo : installedApplications)
{
try {codeSizeSemaphore.acquire();}
catch (InterruptedException e) {e.printStackTrace(System.err);}
try
{
Method getPackageSizeInfo =
packageManager.getClass().getMethod("getPackageSizeInfo",
String.class,
IPackageStatsObserver.class);
getPackageSizeInfo.invoke(packageManager, appInfo.packageName,
new IPackageStatsObserver.Stub()
{
// Examples in the Internet usually have this method as @Override.
// I got an error with @Override. Perfectly works without it.
public void onGetStatsCompleted(PackageStats pStats, boolean succeedded)
throws RemoteException
{
sizes[0] = pStats.codeSize;
sizes[1] = pStats.dataSize;
sizes[2] = pStats.cacheSize;
sizes[3] = pStats.externalCodeSize;
sizes[4] = pStats.externalDataSize;
sizes[5] = pStats.externalCacheSize;
sizes[6] = pStats.externalObbSize;
sizes[7] = pStats.externalMediaSize;
codeSizeSemaphore.release();
}
});
}
catch (Exception e) {e.printStackTrace(System.err);}
Application cat = new Application(appInfo, packageManager, context);
//cat.size = sizes[0];
cat.size = sizes[0]+sizes[1]+sizes[2]+sizes[3]+sizes[4]+sizes[5]+sizes[6]+sizes[7];
apps.add(cat);
}
return apps;
}
public static ArrayList<Application> getList(Context context) {
ArrayList<Application> apps = new ArrayList<Application>();
final PackageManager pm = context.getPackageManager();
List<ApplicationInfo> packages = pm.getInstalledApplications(PackageManager.GET_META_DATA);
for (ApplicationInfo packageInfo : packages) {
Application cat = new Application(packageInfo, pm, context);
apps.add(cat);
}
return apps;
}
}
| |
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v8/common/bidding.proto
package com.google.ads.googleads.v8.common;
/**
* <pre>
* An automated bidding strategy that helps you maximize revenue while
* averaging a specific target return on ad spend (ROAS).
* </pre>
*
* Protobuf type {@code google.ads.googleads.v8.common.TargetRoas}
*/
public final class TargetRoas extends
com.google.protobuf.GeneratedMessageV3 implements
// @@protoc_insertion_point(message_implements:google.ads.googleads.v8.common.TargetRoas)
TargetRoasOrBuilder {
private static final long serialVersionUID = 0L;
// Use TargetRoas.newBuilder() to construct.
private TargetRoas(com.google.protobuf.GeneratedMessageV3.Builder<?> builder) {
super(builder);
}
private TargetRoas() {
}
@java.lang.Override
@SuppressWarnings({"unused"})
protected java.lang.Object newInstance(
UnusedPrivateParameter unused) {
return new TargetRoas();
}
@java.lang.Override
public final com.google.protobuf.UnknownFieldSet
getUnknownFields() {
return this.unknownFields;
}
private TargetRoas(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
this();
if (extensionRegistry == null) {
throw new java.lang.NullPointerException();
}
int mutable_bitField0_ = 0;
com.google.protobuf.UnknownFieldSet.Builder unknownFields =
com.google.protobuf.UnknownFieldSet.newBuilder();
try {
boolean done = false;
while (!done) {
int tag = input.readTag();
switch (tag) {
case 0:
done = true;
break;
case 33: {
bitField0_ |= 0x00000001;
targetRoas_ = input.readDouble();
break;
}
case 40: {
bitField0_ |= 0x00000002;
cpcBidCeilingMicros_ = input.readInt64();
break;
}
case 48: {
bitField0_ |= 0x00000004;
cpcBidFloorMicros_ = input.readInt64();
break;
}
default: {
if (!parseUnknownField(
input, unknownFields, extensionRegistry, tag)) {
done = true;
}
break;
}
}
}
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
throw e.setUnfinishedMessage(this);
} catch (java.io.IOException e) {
throw new com.google.protobuf.InvalidProtocolBufferException(
e).setUnfinishedMessage(this);
} finally {
this.unknownFields = unknownFields.build();
makeExtensionsImmutable();
}
}
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v8.common.BiddingProto.internal_static_google_ads_googleads_v8_common_TargetRoas_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v8.common.BiddingProto.internal_static_google_ads_googleads_v8_common_TargetRoas_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v8.common.TargetRoas.class, com.google.ads.googleads.v8.common.TargetRoas.Builder.class);
}
private int bitField0_;
public static final int TARGET_ROAS_FIELD_NUMBER = 4;
private double targetRoas_;
/**
* <pre>
* Required. The desired revenue (based on conversion data) per unit of spend.
* Value must be between 0.01 and 1000.0, inclusive.
* </pre>
*
* <code>optional double target_roas = 4;</code>
* @return Whether the targetRoas field is set.
*/
@java.lang.Override
public boolean hasTargetRoas() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Required. The desired revenue (based on conversion data) per unit of spend.
* Value must be between 0.01 and 1000.0, inclusive.
* </pre>
*
* <code>optional double target_roas = 4;</code>
* @return The targetRoas.
*/
@java.lang.Override
public double getTargetRoas() {
return targetRoas_;
}
public static final int CPC_BID_CEILING_MICROS_FIELD_NUMBER = 5;
private long cpcBidCeilingMicros_;
/**
* <pre>
* Maximum bid limit that can be set by the bid strategy.
* The limit applies to all keywords managed by the strategy.
* This should only be set for portfolio bid strategies.
* </pre>
*
* <code>optional int64 cpc_bid_ceiling_micros = 5;</code>
* @return Whether the cpcBidCeilingMicros field is set.
*/
@java.lang.Override
public boolean hasCpcBidCeilingMicros() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Maximum bid limit that can be set by the bid strategy.
* The limit applies to all keywords managed by the strategy.
* This should only be set for portfolio bid strategies.
* </pre>
*
* <code>optional int64 cpc_bid_ceiling_micros = 5;</code>
* @return The cpcBidCeilingMicros.
*/
@java.lang.Override
public long getCpcBidCeilingMicros() {
return cpcBidCeilingMicros_;
}
public static final int CPC_BID_FLOOR_MICROS_FIELD_NUMBER = 6;
private long cpcBidFloorMicros_;
/**
* <pre>
* Minimum bid limit that can be set by the bid strategy.
* The limit applies to all keywords managed by the strategy.
* This should only be set for portfolio bid strategies.
* </pre>
*
* <code>optional int64 cpc_bid_floor_micros = 6;</code>
* @return Whether the cpcBidFloorMicros field is set.
*/
@java.lang.Override
public boolean hasCpcBidFloorMicros() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
* <pre>
* Minimum bid limit that can be set by the bid strategy.
* The limit applies to all keywords managed by the strategy.
* This should only be set for portfolio bid strategies.
* </pre>
*
* <code>optional int64 cpc_bid_floor_micros = 6;</code>
* @return The cpcBidFloorMicros.
*/
@java.lang.Override
public long getCpcBidFloorMicros() {
return cpcBidFloorMicros_;
}
private byte memoizedIsInitialized = -1;
@java.lang.Override
public final boolean isInitialized() {
byte isInitialized = memoizedIsInitialized;
if (isInitialized == 1) return true;
if (isInitialized == 0) return false;
memoizedIsInitialized = 1;
return true;
}
@java.lang.Override
public void writeTo(com.google.protobuf.CodedOutputStream output)
throws java.io.IOException {
if (((bitField0_ & 0x00000001) != 0)) {
output.writeDouble(4, targetRoas_);
}
if (((bitField0_ & 0x00000002) != 0)) {
output.writeInt64(5, cpcBidCeilingMicros_);
}
if (((bitField0_ & 0x00000004) != 0)) {
output.writeInt64(6, cpcBidFloorMicros_);
}
unknownFields.writeTo(output);
}
@java.lang.Override
public int getSerializedSize() {
int size = memoizedSize;
if (size != -1) return size;
size = 0;
if (((bitField0_ & 0x00000001) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeDoubleSize(4, targetRoas_);
}
if (((bitField0_ & 0x00000002) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(5, cpcBidCeilingMicros_);
}
if (((bitField0_ & 0x00000004) != 0)) {
size += com.google.protobuf.CodedOutputStream
.computeInt64Size(6, cpcBidFloorMicros_);
}
size += unknownFields.getSerializedSize();
memoizedSize = size;
return size;
}
@java.lang.Override
public boolean equals(final java.lang.Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof com.google.ads.googleads.v8.common.TargetRoas)) {
return super.equals(obj);
}
com.google.ads.googleads.v8.common.TargetRoas other = (com.google.ads.googleads.v8.common.TargetRoas) obj;
if (hasTargetRoas() != other.hasTargetRoas()) return false;
if (hasTargetRoas()) {
if (java.lang.Double.doubleToLongBits(getTargetRoas())
!= java.lang.Double.doubleToLongBits(
other.getTargetRoas())) return false;
}
if (hasCpcBidCeilingMicros() != other.hasCpcBidCeilingMicros()) return false;
if (hasCpcBidCeilingMicros()) {
if (getCpcBidCeilingMicros()
!= other.getCpcBidCeilingMicros()) return false;
}
if (hasCpcBidFloorMicros() != other.hasCpcBidFloorMicros()) return false;
if (hasCpcBidFloorMicros()) {
if (getCpcBidFloorMicros()
!= other.getCpcBidFloorMicros()) return false;
}
if (!unknownFields.equals(other.unknownFields)) return false;
return true;
}
@java.lang.Override
public int hashCode() {
if (memoizedHashCode != 0) {
return memoizedHashCode;
}
int hash = 41;
hash = (19 * hash) + getDescriptor().hashCode();
if (hasTargetRoas()) {
hash = (37 * hash) + TARGET_ROAS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
java.lang.Double.doubleToLongBits(getTargetRoas()));
}
if (hasCpcBidCeilingMicros()) {
hash = (37 * hash) + CPC_BID_CEILING_MICROS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getCpcBidCeilingMicros());
}
if (hasCpcBidFloorMicros()) {
hash = (37 * hash) + CPC_BID_FLOOR_MICROS_FIELD_NUMBER;
hash = (53 * hash) + com.google.protobuf.Internal.hashLong(
getCpcBidFloorMicros());
}
hash = (29 * hash) + unknownFields.hashCode();
memoizedHashCode = hash;
return hash;
}
public static com.google.ads.googleads.v8.common.TargetRoas parseFrom(
java.nio.ByteBuffer data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v8.common.TargetRoas parseFrom(
java.nio.ByteBuffer data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v8.common.TargetRoas parseFrom(
com.google.protobuf.ByteString data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v8.common.TargetRoas parseFrom(
com.google.protobuf.ByteString data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v8.common.TargetRoas parseFrom(byte[] data)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data);
}
public static com.google.ads.googleads.v8.common.TargetRoas parseFrom(
byte[] data,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return PARSER.parseFrom(data, extensionRegistry);
}
public static com.google.ads.googleads.v8.common.TargetRoas parseFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v8.common.TargetRoas parseFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v8.common.TargetRoas parseDelimitedFrom(java.io.InputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v8.common.TargetRoas parseDelimitedFrom(
java.io.InputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseDelimitedWithIOException(PARSER, input, extensionRegistry);
}
public static com.google.ads.googleads.v8.common.TargetRoas parseFrom(
com.google.protobuf.CodedInputStream input)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input);
}
public static com.google.ads.googleads.v8.common.TargetRoas parseFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
return com.google.protobuf.GeneratedMessageV3
.parseWithIOException(PARSER, input, extensionRegistry);
}
@java.lang.Override
public Builder newBuilderForType() { return newBuilder(); }
public static Builder newBuilder() {
return DEFAULT_INSTANCE.toBuilder();
}
public static Builder newBuilder(com.google.ads.googleads.v8.common.TargetRoas prototype) {
return DEFAULT_INSTANCE.toBuilder().mergeFrom(prototype);
}
@java.lang.Override
public Builder toBuilder() {
return this == DEFAULT_INSTANCE
? new Builder() : new Builder().mergeFrom(this);
}
@java.lang.Override
protected Builder newBuilderForType(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
Builder builder = new Builder(parent);
return builder;
}
/**
* <pre>
* An automated bidding strategy that helps you maximize revenue while
* averaging a specific target return on ad spend (ROAS).
* </pre>
*
* Protobuf type {@code google.ads.googleads.v8.common.TargetRoas}
*/
public static final class Builder extends
com.google.protobuf.GeneratedMessageV3.Builder<Builder> implements
// @@protoc_insertion_point(builder_implements:google.ads.googleads.v8.common.TargetRoas)
com.google.ads.googleads.v8.common.TargetRoasOrBuilder {
public static final com.google.protobuf.Descriptors.Descriptor
getDescriptor() {
return com.google.ads.googleads.v8.common.BiddingProto.internal_static_google_ads_googleads_v8_common_TargetRoas_descriptor;
}
@java.lang.Override
protected com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
internalGetFieldAccessorTable() {
return com.google.ads.googleads.v8.common.BiddingProto.internal_static_google_ads_googleads_v8_common_TargetRoas_fieldAccessorTable
.ensureFieldAccessorsInitialized(
com.google.ads.googleads.v8.common.TargetRoas.class, com.google.ads.googleads.v8.common.TargetRoas.Builder.class);
}
// Construct using com.google.ads.googleads.v8.common.TargetRoas.newBuilder()
private Builder() {
maybeForceBuilderInitialization();
}
private Builder(
com.google.protobuf.GeneratedMessageV3.BuilderParent parent) {
super(parent);
maybeForceBuilderInitialization();
}
private void maybeForceBuilderInitialization() {
if (com.google.protobuf.GeneratedMessageV3
.alwaysUseFieldBuilders) {
}
}
@java.lang.Override
public Builder clear() {
super.clear();
targetRoas_ = 0D;
bitField0_ = (bitField0_ & ~0x00000001);
cpcBidCeilingMicros_ = 0L;
bitField0_ = (bitField0_ & ~0x00000002);
cpcBidFloorMicros_ = 0L;
bitField0_ = (bitField0_ & ~0x00000004);
return this;
}
@java.lang.Override
public com.google.protobuf.Descriptors.Descriptor
getDescriptorForType() {
return com.google.ads.googleads.v8.common.BiddingProto.internal_static_google_ads_googleads_v8_common_TargetRoas_descriptor;
}
@java.lang.Override
public com.google.ads.googleads.v8.common.TargetRoas getDefaultInstanceForType() {
return com.google.ads.googleads.v8.common.TargetRoas.getDefaultInstance();
}
@java.lang.Override
public com.google.ads.googleads.v8.common.TargetRoas build() {
com.google.ads.googleads.v8.common.TargetRoas result = buildPartial();
if (!result.isInitialized()) {
throw newUninitializedMessageException(result);
}
return result;
}
@java.lang.Override
public com.google.ads.googleads.v8.common.TargetRoas buildPartial() {
com.google.ads.googleads.v8.common.TargetRoas result = new com.google.ads.googleads.v8.common.TargetRoas(this);
int from_bitField0_ = bitField0_;
int to_bitField0_ = 0;
if (((from_bitField0_ & 0x00000001) != 0)) {
result.targetRoas_ = targetRoas_;
to_bitField0_ |= 0x00000001;
}
if (((from_bitField0_ & 0x00000002) != 0)) {
result.cpcBidCeilingMicros_ = cpcBidCeilingMicros_;
to_bitField0_ |= 0x00000002;
}
if (((from_bitField0_ & 0x00000004) != 0)) {
result.cpcBidFloorMicros_ = cpcBidFloorMicros_;
to_bitField0_ |= 0x00000004;
}
result.bitField0_ = to_bitField0_;
onBuilt();
return result;
}
@java.lang.Override
public Builder clone() {
return super.clone();
}
@java.lang.Override
public Builder setField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.setField(field, value);
}
@java.lang.Override
public Builder clearField(
com.google.protobuf.Descriptors.FieldDescriptor field) {
return super.clearField(field);
}
@java.lang.Override
public Builder clearOneof(
com.google.protobuf.Descriptors.OneofDescriptor oneof) {
return super.clearOneof(oneof);
}
@java.lang.Override
public Builder setRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
int index, java.lang.Object value) {
return super.setRepeatedField(field, index, value);
}
@java.lang.Override
public Builder addRepeatedField(
com.google.protobuf.Descriptors.FieldDescriptor field,
java.lang.Object value) {
return super.addRepeatedField(field, value);
}
@java.lang.Override
public Builder mergeFrom(com.google.protobuf.Message other) {
if (other instanceof com.google.ads.googleads.v8.common.TargetRoas) {
return mergeFrom((com.google.ads.googleads.v8.common.TargetRoas)other);
} else {
super.mergeFrom(other);
return this;
}
}
public Builder mergeFrom(com.google.ads.googleads.v8.common.TargetRoas other) {
if (other == com.google.ads.googleads.v8.common.TargetRoas.getDefaultInstance()) return this;
if (other.hasTargetRoas()) {
setTargetRoas(other.getTargetRoas());
}
if (other.hasCpcBidCeilingMicros()) {
setCpcBidCeilingMicros(other.getCpcBidCeilingMicros());
}
if (other.hasCpcBidFloorMicros()) {
setCpcBidFloorMicros(other.getCpcBidFloorMicros());
}
this.mergeUnknownFields(other.unknownFields);
onChanged();
return this;
}
@java.lang.Override
public final boolean isInitialized() {
return true;
}
@java.lang.Override
public Builder mergeFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws java.io.IOException {
com.google.ads.googleads.v8.common.TargetRoas parsedMessage = null;
try {
parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry);
} catch (com.google.protobuf.InvalidProtocolBufferException e) {
parsedMessage = (com.google.ads.googleads.v8.common.TargetRoas) e.getUnfinishedMessage();
throw e.unwrapIOException();
} finally {
if (parsedMessage != null) {
mergeFrom(parsedMessage);
}
}
return this;
}
private int bitField0_;
private double targetRoas_ ;
/**
* <pre>
* Required. The desired revenue (based on conversion data) per unit of spend.
* Value must be between 0.01 and 1000.0, inclusive.
* </pre>
*
* <code>optional double target_roas = 4;</code>
* @return Whether the targetRoas field is set.
*/
@java.lang.Override
public boolean hasTargetRoas() {
return ((bitField0_ & 0x00000001) != 0);
}
/**
* <pre>
* Required. The desired revenue (based on conversion data) per unit of spend.
* Value must be between 0.01 and 1000.0, inclusive.
* </pre>
*
* <code>optional double target_roas = 4;</code>
* @return The targetRoas.
*/
@java.lang.Override
public double getTargetRoas() {
return targetRoas_;
}
/**
* <pre>
* Required. The desired revenue (based on conversion data) per unit of spend.
* Value must be between 0.01 and 1000.0, inclusive.
* </pre>
*
* <code>optional double target_roas = 4;</code>
* @param value The targetRoas to set.
* @return This builder for chaining.
*/
public Builder setTargetRoas(double value) {
bitField0_ |= 0x00000001;
targetRoas_ = value;
onChanged();
return this;
}
/**
* <pre>
* Required. The desired revenue (based on conversion data) per unit of spend.
* Value must be between 0.01 and 1000.0, inclusive.
* </pre>
*
* <code>optional double target_roas = 4;</code>
* @return This builder for chaining.
*/
public Builder clearTargetRoas() {
bitField0_ = (bitField0_ & ~0x00000001);
targetRoas_ = 0D;
onChanged();
return this;
}
private long cpcBidCeilingMicros_ ;
/**
* <pre>
* Maximum bid limit that can be set by the bid strategy.
* The limit applies to all keywords managed by the strategy.
* This should only be set for portfolio bid strategies.
* </pre>
*
* <code>optional int64 cpc_bid_ceiling_micros = 5;</code>
* @return Whether the cpcBidCeilingMicros field is set.
*/
@java.lang.Override
public boolean hasCpcBidCeilingMicros() {
return ((bitField0_ & 0x00000002) != 0);
}
/**
* <pre>
* Maximum bid limit that can be set by the bid strategy.
* The limit applies to all keywords managed by the strategy.
* This should only be set for portfolio bid strategies.
* </pre>
*
* <code>optional int64 cpc_bid_ceiling_micros = 5;</code>
* @return The cpcBidCeilingMicros.
*/
@java.lang.Override
public long getCpcBidCeilingMicros() {
return cpcBidCeilingMicros_;
}
/**
* <pre>
* Maximum bid limit that can be set by the bid strategy.
* The limit applies to all keywords managed by the strategy.
* This should only be set for portfolio bid strategies.
* </pre>
*
* <code>optional int64 cpc_bid_ceiling_micros = 5;</code>
* @param value The cpcBidCeilingMicros to set.
* @return This builder for chaining.
*/
public Builder setCpcBidCeilingMicros(long value) {
bitField0_ |= 0x00000002;
cpcBidCeilingMicros_ = value;
onChanged();
return this;
}
/**
* <pre>
* Maximum bid limit that can be set by the bid strategy.
* The limit applies to all keywords managed by the strategy.
* This should only be set for portfolio bid strategies.
* </pre>
*
* <code>optional int64 cpc_bid_ceiling_micros = 5;</code>
* @return This builder for chaining.
*/
public Builder clearCpcBidCeilingMicros() {
bitField0_ = (bitField0_ & ~0x00000002);
cpcBidCeilingMicros_ = 0L;
onChanged();
return this;
}
private long cpcBidFloorMicros_ ;
/**
* <pre>
* Minimum bid limit that can be set by the bid strategy.
* The limit applies to all keywords managed by the strategy.
* This should only be set for portfolio bid strategies.
* </pre>
*
* <code>optional int64 cpc_bid_floor_micros = 6;</code>
* @return Whether the cpcBidFloorMicros field is set.
*/
@java.lang.Override
public boolean hasCpcBidFloorMicros() {
return ((bitField0_ & 0x00000004) != 0);
}
/**
* <pre>
* Minimum bid limit that can be set by the bid strategy.
* The limit applies to all keywords managed by the strategy.
* This should only be set for portfolio bid strategies.
* </pre>
*
* <code>optional int64 cpc_bid_floor_micros = 6;</code>
* @return The cpcBidFloorMicros.
*/
@java.lang.Override
public long getCpcBidFloorMicros() {
return cpcBidFloorMicros_;
}
/**
* <pre>
* Minimum bid limit that can be set by the bid strategy.
* The limit applies to all keywords managed by the strategy.
* This should only be set for portfolio bid strategies.
* </pre>
*
* <code>optional int64 cpc_bid_floor_micros = 6;</code>
* @param value The cpcBidFloorMicros to set.
* @return This builder for chaining.
*/
public Builder setCpcBidFloorMicros(long value) {
bitField0_ |= 0x00000004;
cpcBidFloorMicros_ = value;
onChanged();
return this;
}
/**
* <pre>
* Minimum bid limit that can be set by the bid strategy.
* The limit applies to all keywords managed by the strategy.
* This should only be set for portfolio bid strategies.
* </pre>
*
* <code>optional int64 cpc_bid_floor_micros = 6;</code>
* @return This builder for chaining.
*/
public Builder clearCpcBidFloorMicros() {
bitField0_ = (bitField0_ & ~0x00000004);
cpcBidFloorMicros_ = 0L;
onChanged();
return this;
}
@java.lang.Override
public final Builder setUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.setUnknownFields(unknownFields);
}
@java.lang.Override
public final Builder mergeUnknownFields(
final com.google.protobuf.UnknownFieldSet unknownFields) {
return super.mergeUnknownFields(unknownFields);
}
// @@protoc_insertion_point(builder_scope:google.ads.googleads.v8.common.TargetRoas)
}
// @@protoc_insertion_point(class_scope:google.ads.googleads.v8.common.TargetRoas)
private static final com.google.ads.googleads.v8.common.TargetRoas DEFAULT_INSTANCE;
static {
DEFAULT_INSTANCE = new com.google.ads.googleads.v8.common.TargetRoas();
}
public static com.google.ads.googleads.v8.common.TargetRoas getDefaultInstance() {
return DEFAULT_INSTANCE;
}
private static final com.google.protobuf.Parser<TargetRoas>
PARSER = new com.google.protobuf.AbstractParser<TargetRoas>() {
@java.lang.Override
public TargetRoas parsePartialFrom(
com.google.protobuf.CodedInputStream input,
com.google.protobuf.ExtensionRegistryLite extensionRegistry)
throws com.google.protobuf.InvalidProtocolBufferException {
return new TargetRoas(input, extensionRegistry);
}
};
public static com.google.protobuf.Parser<TargetRoas> parser() {
return PARSER;
}
@java.lang.Override
public com.google.protobuf.Parser<TargetRoas> getParserForType() {
return PARSER;
}
@java.lang.Override
public com.google.ads.googleads.v8.common.TargetRoas getDefaultInstanceForType() {
return DEFAULT_INSTANCE;
}
}
| |
/*
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.flex.compiler.clients;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import org.apache.commons.io.FilenameUtils;
import org.apache.flex.compiler.codegen.as.IASWriter;
import org.apache.flex.compiler.driver.IBackend;
import org.apache.flex.compiler.driver.js.IJSApplication;
import org.apache.flex.compiler.exceptions.ConfigurationException;
import org.apache.flex.compiler.exceptions.ConfigurationException.IOError;
import org.apache.flex.compiler.exceptions.ConfigurationException.MustSpecifyTarget;
import org.apache.flex.compiler.internal.codegen.js.JSSharedData;
import org.apache.flex.compiler.internal.driver.as.ASBackend;
import org.apache.flex.compiler.internal.driver.js.amd.AMDBackend;
import org.apache.flex.compiler.internal.driver.js.goog.GoogBackend;
import org.apache.flex.compiler.internal.driver.mxml.flexjs.MXMLFlexJSSWCBackend;
import org.apache.flex.compiler.internal.driver.mxml.jsc.MXMLJSCJSSWCBackend;
import org.apache.flex.compiler.internal.driver.mxml.vf2js.MXMLVF2JSSWCBackend;
import org.apache.flex.compiler.internal.projects.CompilerProject;
import org.apache.flex.compiler.internal.targets.FlexJSSWCTarget;
import org.apache.flex.compiler.internal.targets.JSTarget;
import org.apache.flex.compiler.problems.ICompilerProblem;
import org.apache.flex.compiler.problems.InternalCompilerProblem;
import org.apache.flex.compiler.problems.UnableToBuildSWFProblem;
import org.apache.flex.compiler.targets.ITarget.TargetType;
import org.apache.flex.compiler.targets.ITargetSettings;
import org.apache.flex.compiler.units.ICompilationUnit;
import sun.reflect.generics.reflectiveObjects.NotImplementedException;
/**
* @author Erik de Bruin
* @author Michael Schmalle
*/
public class COMPJSC extends MXMLJSC
{
/*
* Exit code enumerations.
*/
static enum ExitCode
{
SUCCESS(0),
PRINT_HELP(1),
FAILED_WITH_PROBLEMS(2),
FAILED_WITH_EXCEPTIONS(3),
FAILED_WITH_CONFIG_PROBLEMS(4);
ExitCode(int code)
{
this.code = code;
}
final int code;
}
@Override
public String getName()
{
return FLEX_TOOL_COMPC;
}
@Override
public int execute(String[] args)
{
return staticMainNoExit(args);
}
/**
* Java program entry point.
*
* @param args command line arguments
*/
public static void main(final String[] args)
{
int exitCode = staticMainNoExit(args);
System.exit(exitCode);
}
/**
* Entry point for the {@code <compc>} Ant task.
*
* @param args Command line arguments.
* @return An exit code.
*/
public static int staticMainNoExit(final String[] args)
{
long startTime = System.nanoTime();
IBackend backend = new ASBackend();
for (String s : args)
{
if (s.contains("-js-output-type"))
{
jsOutputType = JSOutputType.fromString(s.split("=")[1]);
switch (jsOutputType)
{
case AMD:
backend = new AMDBackend();
break;
case JSC:
backend = new MXMLJSCJSSWCBackend();
break;
case FLEXJS:
case FLEXJS_DUAL:
backend = new MXMLFlexJSSWCBackend();
break;
case GOOG:
backend = new GoogBackend();
break;
case VF2JS:
backend = new MXMLVF2JSSWCBackend();
break;
default:
throw new NotImplementedException();
}
}
}
final COMPJSC mxmlc = new COMPJSC(backend);
final List<ICompilerProblem> problems = new ArrayList<ICompilerProblem>();
final int exitCode = mxmlc.mainNoExit(args, problems, true);
long endTime = System.nanoTime();
JSSharedData.instance.stdout((endTime - startTime) / 1e9 + " seconds");
return exitCode;
}
public COMPJSC(IBackend backend)
{
super(backend);
}
/**
* Main body of this program. This method is called from the public static
* method's for this program.
*
* @return true if compiler succeeds
* @throws IOException
* @throws InterruptedException
*/
@Override
protected boolean compile()
{
boolean compilationSuccess = false;
try
{
project.getSourceCompilationUnitFactory().addHandler(asFileHandler);
if (setupTargetFile())
buildArtifact();
if (jsTarget != null)
{
Collection<ICompilerProblem> errors = new ArrayList<ICompilerProblem>();
Collection<ICompilerProblem> warnings = new ArrayList<ICompilerProblem>();
if (!config.getCreateTargetWithErrors())
{
problems.getErrorsAndWarnings(errors, warnings);
if (errors.size() > 0)
return false;
}
File outputFolder = new File(getOutputFilePath());
Set<String> externs = config.getExterns();
Collection<ICompilationUnit> roots = ((FlexJSSWCTarget)target).getReachableCompilationUnits(errors);
Collection<ICompilationUnit> reachableCompilationUnits = project.getReachableCompilationUnitsInSWFOrder(roots);
for (final ICompilationUnit cu : reachableCompilationUnits)
{
ICompilationUnit.UnitType cuType = cu.getCompilationUnitType();
if (cuType == ICompilationUnit.UnitType.AS_UNIT
|| cuType == ICompilationUnit.UnitType.MXML_UNIT)
{
String symbol = cu.getQualifiedNames().get(0);
if (externs.contains(symbol)) continue;
final File outputClassFile = getOutputClassFile(
cu.getQualifiedNames().get(0), outputFolder);
System.out.println("Compiling file: " + outputClassFile);
ICompilationUnit unit = cu;
IASWriter writer;
if (cuType == ICompilationUnit.UnitType.AS_UNIT)
{
writer = JSSharedData.backend.createWriter(project,
(List<ICompilerProblem>) errors, unit,
false);
}
else
{
writer = JSSharedData.backend.createMXMLWriter(
project, (List<ICompilerProblem>) errors,
unit, false);
}
problems.addAll(errors);
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(outputClassFile));
writer.writeTo(out);
out.flush();
out.close();
writer.close();
}
}
compilationSuccess = true;
}
}
catch (Exception e)
{
final ICompilerProblem problem = new InternalCompilerProblem(e);
problems.add(problem);
}
return compilationSuccess;
}
/**
* Build target artifact.
*
* @throws InterruptedException threading error
* @throws IOException IO error
* @throws ConfigurationException
*/
@Override
protected void buildArtifact() throws InterruptedException, IOException,
ConfigurationException
{
jsTarget = buildJSTarget();
}
private IJSApplication buildJSTarget() throws InterruptedException,
FileNotFoundException, ConfigurationException
{
final List<ICompilerProblem> problemsBuildingSWF = new ArrayList<ICompilerProblem>();
final IJSApplication app = buildApplication(project,
config.getMainDefinition(), null, problemsBuildingSWF);
problems.addAll(problemsBuildingSWF);
if (app == null)
{
ICompilerProblem problem = new UnableToBuildSWFProblem(
getOutputFilePath());
problems.add(problem);
}
return app;
}
/**
* Replaces FlexApplicationProject::buildSWF()
*
* @param applicationProject
* @param rootClassName
* @param problems
* @return
* @throws InterruptedException
*/
private IJSApplication buildApplication(CompilerProject applicationProject,
String rootClassName, ICompilationUnit mainCU,
Collection<ICompilerProblem> problems) throws InterruptedException,
ConfigurationException, FileNotFoundException
{
Collection<ICompilerProblem> fatalProblems = applicationProject.getFatalProblems();
if (!fatalProblems.isEmpty())
{
problems.addAll(fatalProblems);
return null;
}
return ((JSTarget) target).build(mainCU, problems);
}
/**
* Get the output file path. If {@code -output} is specified, use its value;
* otherwise, use the same base name as the target file.
*
* @return output file path
*/
private String getOutputFilePath()
{
if (config.getOutput() == null)
{
final String extension = "." + JSSharedData.OUTPUT_EXTENSION;
return FilenameUtils.removeExtension(config.getTargetFile()).concat(
extension);
}
else
{
String outputFolderName = config.getOutput();
if (outputFolderName.endsWith(".swc"))
{
File outputFolder = new File(outputFolderName);
outputFolderName = outputFolder.getParent();
}
return outputFolderName;
}
}
/**
* Get the output class file. This includes the (sub)directory in which the
* original class file lives. If the directory structure doesn't exist, it
* is created.
*
* @author Erik de Bruin
* @param qname
* @param outputFolder
* @return output class file path
*/
private File getOutputClassFile(String qname, File outputFolder)
{
String[] cname = qname.split("\\.");
String sdirPath = outputFolder + File.separator;
if (cname.length > 0)
{
for (int i = 0, n = cname.length - 1; i < n; i++)
{
sdirPath += cname[i] + File.separator;
}
File sdir = new File(sdirPath);
if (!sdir.exists())
sdir.mkdirs();
qname = cname[cname.length - 1];
}
return new File(sdirPath + qname + "." + JSSharedData.OUTPUT_EXTENSION);
}
/**
* Mxmlc uses target file as the main compilation unit and derive the output
* SWF file name from this file.
*
* @return true if successful, false otherwise.
* @throws InterruptedException
*/
@Override
protected boolean setupTargetFile() throws InterruptedException
{
config.getTargetFile();
ITargetSettings settings = getTargetSettings();
if (settings != null)
project.setTargetSettings(settings);
else
return false;
target = JSSharedData.backend.createTarget(project,
getTargetSettings(), null);
return true;
}
private ITargetSettings getTargetSettings()
{
if (targetSettings == null)
targetSettings = projectConfigurator.getTargetSettings(getTargetType());
if (targetSettings == null)
problems.addAll(projectConfigurator.getConfigurationProblems());
return targetSettings;
}
/**
* Validate target file.
*
* @throws MustSpecifyTarget
* @throws IOError
*/
@Override
protected void validateTargetFile() throws ConfigurationException
{
}
protected String getProgramName()
{
return "compc";
}
protected boolean isCompc()
{
return true;
}
@Override
protected TargetType getTargetType()
{
return TargetType.SWC;
}
}
| |
package org.insightech.er.editor.view.figure.layout;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.draw2d.AbstractHintLayout;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.Polyline;
import org.eclipse.draw2d.geometry.Dimension;
import org.eclipse.draw2d.geometry.Point;
import org.eclipse.draw2d.geometry.Rectangle;
public class TableLayout extends AbstractHintLayout {
private int colnum;
private int separatorWidth;
private List<IFigure> separators;
public TableLayout(int colnum) {
super();
this.colnum = colnum;
if (this.colnum <= 0) {
this.colnum = 1;
}
this.separators = new ArrayList<IFigure>();
this.separatorWidth = 1;
}
public void setSeparator() {
}
public void layout(IFigure parent) {
List children = this.clearSeparator(parent);
List<List<IFigure>> table = this.getTable(children);
int[] columnWidth = this.getColumnWidth(table);
int[] rowHeight = this.getRowHeight(table);
Rectangle rect = parent.getBounds();
int x = rect.x + 1;
int y = rect.y + 1;
for (int i = 0; i < table.size(); i++) {
List<IFigure> tableRow = table.get(i);
for (int j = 0; j < tableRow.size(); j++) {
Rectangle childRect = new Rectangle(x, y, columnWidth[j],
rowHeight[i]);
IFigure figure = tableRow.get(j);
figure.setBounds(childRect);
x += columnWidth[j];
if (j != tableRow.size() - 1) {
Rectangle separetorRect = new Rectangle(x, y,
separatorWidth, rowHeight[i]);
this.addVerticalSeparator(parent, separetorRect);
x += separatorWidth;
}
}
x = rect.x + 1;
y += rowHeight[i];
if (i != table.size() - 1) {
Rectangle separetorRect = new Rectangle(x, y, rect.width,
separatorWidth);
this.addHorizontalSeparator(parent, separetorRect);
y += separatorWidth;
}
}
}
private List<List<IFigure>> getTable(List children) {
int numChildren = children.size();
List<List<IFigure>> table = new ArrayList<List<IFigure>>();
List<IFigure> row = null;
for (int i = 0; i < numChildren; i++) {
if (i % colnum == 0) {
row = new ArrayList<IFigure>();
table.add(row);
}
row.add((IFigure) children.get(i));
}
return table;
}
private int[] getColumnWidth(List<List<IFigure>> table) {
int[] columnWidth = new int[this.colnum];
for (int i = 0; i < colnum; i++) {
for (List<IFigure> tableRow : table) {
if (tableRow.size() > i) {
IFigure figure = tableRow.get(i);
int width = figure.getPreferredSize().width;
if (width > columnWidth[i]) {
columnWidth[i] = (int) (width * 1.3);
}
}
}
}
return columnWidth;
}
private int[] getRowHeight(List<List<IFigure>> table) {
int[] rowHeight = new int[table.size()];
for (int i = 0; i < rowHeight.length; i++) {
for (IFigure cell : table.get(i)) {
int height = cell.getPreferredSize().height;
if (height > rowHeight[i]) {
rowHeight[i] = height;
}
}
}
return rowHeight;
}
private List<IFigure> getChildren(IFigure parent) {
List<IFigure> children = new ArrayList<IFigure>();
for (Iterator iter = parent.getChildren().iterator(); iter.hasNext();) {
IFigure child = (IFigure) iter.next();
if (!this.separators.contains(child)) {
children.add(child);
}
}
return children;
}
private List clearSeparator(IFigure parent) {
for (Iterator iter = parent.getChildren().iterator(); iter.hasNext();) {
IFigure child = (IFigure) iter.next();
if (this.separators.contains(child)) {
iter.remove();
}
}
this.separators.clear();
return parent.getChildren();
}
/**
* {@inheritDoc}
*/
@Override
protected Dimension calculatePreferredSize(IFigure container, int wHint,
int hHint) {
List children = this.getChildren(container);
List<List<IFigure>> table = this.getTable(children);
int[] columnWidth = this.getColumnWidth(table);
int[] rowHeight = this.getRowHeight(table);
int width = 0;
for (int i = 0; i < columnWidth.length; i++) {
width += columnWidth[i];
if (i != columnWidth.length - 1) {
width += this.separatorWidth;
}
}
width++;
width++;
int height = 0;
for (int i = 0; i < rowHeight.length; i++) {
height += rowHeight[i];
if (i != rowHeight.length - 1) {
height += this.separatorWidth;
}
}
height++;
height++;
return new Dimension(width, height);
}
@SuppressWarnings("unchecked")
private void addVerticalSeparator(IFigure figure, Rectangle rect) {
Polyline separator = new Polyline();
separator.setLineWidth(separatorWidth);
separator.addPoint(new Point(rect.x, rect.y));
separator.addPoint(new Point(rect.x, rect.y + rect.height));
figure.getChildren().add(separator);
separator.setParent(figure);
this.separators.add(separator);
}
@SuppressWarnings("unchecked")
private void addHorizontalSeparator(IFigure figure, Rectangle rect) {
Polyline separator = new Polyline();
separator.setLineWidth(separatorWidth);
separator.addPoint(new Point(rect.x, rect.y));
separator.addPoint(new Point(rect.x + rect.width, rect.y));
figure.getChildren().add(separator);
separator.setParent(figure);
this.separators.add(separator);
}
}
| |
/*
* Copyright 2002-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.security.config.annotation.web.configurers;
import org.junit.Rule;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationTrustResolver;
import org.springframework.security.authentication.TestingAuthenticationToken;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.test.SpringTestRule;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.PasswordEncodedUser;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.springframework.security.config.Customizer.withDefaults;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestBuilders.formLogin;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.user;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
/**
* Tests for {@link ServletApiConfigurer}
*
* @author Rob Winch
* @author Eleftheria Stein
*/
public class ServletApiConfigurerTests {
@Rule
public final SpringTestRule spring = new SpringTestRule();
@Autowired
MockMvc mvc;
@Test
public void configureWhenRegisteringObjectPostProcessorThenInvokedOnSecurityContextHolderAwareRequestFilter() {
this.spring.register(ObjectPostProcessorConfig.class).autowire();
verify(ObjectPostProcessorConfig.objectPostProcessor)
.postProcess(any(SecurityContextHolderAwareRequestFilter.class));
}
@EnableWebSecurity
static class ObjectPostProcessorConfig extends WebSecurityConfigurerAdapter {
static ObjectPostProcessor<Object> objectPostProcessor = spy(ReflectingObjectPostProcessor.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.servletApi();
// @formatter:on
}
@Bean
static ObjectPostProcessor<Object> objectPostProcessor() {
return objectPostProcessor;
}
}
static class ReflectingObjectPostProcessor implements ObjectPostProcessor<Object> {
@Override
public <O> O postProcess(O object) {
return object;
}
}
// SEC-2215
@Test
public void configureWhenUsingDefaultsThenAuthenticationManagerIsNotNull() {
this.spring.register(ServletApiConfig.class).autowire();
assertThat(this.spring.getContext().getBean("customAuthenticationManager")).isNotNull();
}
@Test
public void configureWhenUsingDefaultsThenAuthenticationEntryPointIsLogin() throws Exception {
this.spring.register(ServletApiConfig.class).autowire();
this.mvc.perform(formLogin())
.andExpect(status().isFound());
}
// SEC-2926
@Test
public void configureWhenUsingDefaultsThenRolePrefixIsSet() throws Exception {
this.spring.register(ServletApiConfig.class, AdminController.class).autowire();
this.mvc.perform(get("/admin")
.with(authentication(new TestingAuthenticationToken("user", "pass", "ROLE_ADMIN"))))
.andExpect(status().isOk());
}
@EnableWebSecurity
static class ServletApiConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser(PasswordEncodedUser.user());
// @formatter:on
}
@Bean
public AuthenticationManager customAuthenticationManager() throws Exception {
return super.authenticationManagerBean();
}
}
@Test
public void requestWhenCustomAuthenticationEntryPointThenEntryPointUsed() throws Exception {
this.spring.register(CustomEntryPointConfig.class).autowire();
this.mvc.perform(get("/"));
verify(CustomEntryPointConfig.ENTRYPOINT)
.commence(any(HttpServletRequest.class),
any(HttpServletResponse.class), any(AuthenticationException.class));
}
@EnableWebSecurity
static class CustomEntryPointConfig extends WebSecurityConfigurerAdapter {
static AuthenticationEntryPoint ENTRYPOINT = spy(AuthenticationEntryPoint.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.exceptionHandling()
.authenticationEntryPoint(ENTRYPOINT)
.and()
.formLogin();
// @formatter:on
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
// @formatter:off
auth
.inMemoryAuthentication()
.withUser("user").password("password").roles("USER");
// @formatter:on
}
}
@Test
public void servletApiWhenInvokedTwiceThenUsesOriginalRole() throws Exception {
this.spring.register(DuplicateInvocationsDoesNotOverrideConfig.class, AdminController.class).autowire();
this.mvc.perform(get("/admin")
.with(user("user").authorities(AuthorityUtils.createAuthorityList("PERMISSION_ADMIN"))))
.andExpect(status().isOk());
this.mvc.perform(get("/admin")
.with(user("user").authorities(AuthorityUtils.createAuthorityList("ROLE_ADMIN"))))
.andExpect(status().isForbidden());
}
@EnableWebSecurity
static class DuplicateInvocationsDoesNotOverrideConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.servletApi()
.rolePrefix("PERMISSION_")
.and()
.servletApi();
// @formatter:on
}
}
@Test
public void configureWhenSharedObjectTrustResolverThenTrustResolverUsed() throws Exception {
this.spring.register(SharedTrustResolverConfig.class).autowire();
this.mvc.perform(get("/"));
verify(SharedTrustResolverConfig.TR, atLeastOnce()).isAnonymous(any());
}
@EnableWebSecurity
static class SharedTrustResolverConfig extends WebSecurityConfigurerAdapter {
static AuthenticationTrustResolver TR = spy(AuthenticationTrustResolver.class);
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.setSharedObject(AuthenticationTrustResolver.class, TR);
// @formatter:on
}
}
@Test
public void requestWhenServletApiWithDefaultsInLambdaThenUsesDefaultRolePrefix() throws Exception {
this.spring.register(ServletApiWithDefaultsInLambdaConfig.class, AdminController.class).autowire();
this.mvc.perform(get("/admin")
.with(user("user").authorities(AuthorityUtils.createAuthorityList("ROLE_ADMIN"))))
.andExpect(status().isOk());
}
@EnableWebSecurity
static class ServletApiWithDefaultsInLambdaConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.servletApi(withDefaults());
// @formatter:on
}
}
@Test
public void requestWhenRolePrefixInLambdaThenUsesCustomRolePrefix() throws Exception {
this.spring.register(RolePrefixInLambdaConfig.class, AdminController.class).autowire();
this.mvc.perform(get("/admin")
.with(user("user").authorities(AuthorityUtils.createAuthorityList("PERMISSION_ADMIN"))))
.andExpect(status().isOk());
this.mvc.perform(get("/admin")
.with(user("user").authorities(AuthorityUtils.createAuthorityList("ROLE_ADMIN"))))
.andExpect(status().isForbidden());
}
@EnableWebSecurity
static class RolePrefixInLambdaConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http
.servletApi(servletApi ->
servletApi
.rolePrefix("PERMISSION_")
);
// @formatter:on
}
}
@RestController
static class AdminController {
@GetMapping("/admin")
public void admin(HttpServletRequest request) {
if (!request.isUserInRole("ADMIN")) {
throw new AccessDeniedException("This resource is only available to admins");
}
}
}
}
| |
/*
* Copyright 2016 SEARCH-The National Consortium for Justice Information and Statistics
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.search.nibrs.report.service;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.PrintSetup;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;
import org.apache.poi.xssf.usermodel.XSSFFont;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.search.nibrs.model.reports.cargotheft.CargoTheftFormRow;
import org.search.nibrs.model.reports.cargotheft.CargoTheftReport;
import org.search.nibrs.report.SummaryReportProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class CargoTheftReportExporter {
private static final Log log = LogFactory.getLog(CargoTheftReportExporter.class);
@Autowired
private SummaryReportProperties appProperties;
XSSFFont boldFont;
XSSFFont normalWeightFont;
CellStyle wrappedStyle;
CellStyle vTopWrappedStyle;
CellStyle wrappedBorderedStyle;
CellStyle centeredWrappedBorderedStyle;
CellStyle centeredStyle;
CellStyle yellowForeGround;
public void exportCargoTheftReport(CargoTheftReport cargoTheftReport){
XSSFWorkbook workbook = createWorkbook(cargoTheftReport);
try {
String fileName = appProperties.getSummaryReportOutputPath() + "/CargoTheftReport-" + cargoTheftReport.getOri() + "-" + cargoTheftReport.getYear() + "-" + StringUtils.leftPad(String.valueOf(cargoTheftReport.getMonth()), 2, '0') + ".xlsx";
FileOutputStream outputStream = new FileOutputStream(fileName);
workbook.write(outputStream);
workbook.close();
System.out.println("The Supplementary Homicide Report is writen to fileName: " + fileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
public XSSFWorkbook createWorkbook(CargoTheftReport cargoTheftReport) {
XSSFWorkbook workbook = new XSSFWorkbook();
wrappedStyle = workbook.createCellStyle();
wrappedStyle.setWrapText(true);
vTopWrappedStyle = workbook.createCellStyle();
vTopWrappedStyle.cloneStyleFrom(wrappedStyle);
vTopWrappedStyle.setVerticalAlignment(VerticalAlignment.TOP);
wrappedBorderedStyle = workbook.createCellStyle();
wrappedBorderedStyle.cloneStyleFrom(wrappedStyle);
wrappedBorderedStyle.setBorderBottom(BorderStyle.THIN);
wrappedBorderedStyle.setBorderTop(BorderStyle.THIN);
wrappedBorderedStyle.setBorderRight(BorderStyle.THIN);
wrappedBorderedStyle.setBorderLeft(BorderStyle.THIN);
wrappedBorderedStyle.setVerticalAlignment(VerticalAlignment.BOTTOM);
centeredWrappedBorderedStyle = workbook.createCellStyle();
centeredWrappedBorderedStyle.cloneStyleFrom(wrappedBorderedStyle);
centeredWrappedBorderedStyle.setAlignment(HorizontalAlignment.CENTER);
centeredStyle = workbook.createCellStyle();
centeredStyle.setAlignment(HorizontalAlignment.CENTER);
centeredStyle.setVerticalAlignment(VerticalAlignment.CENTER);
boldFont = workbook.createFont();
boldFont.setBold(true);
normalWeightFont = workbook.createFont();
normalWeightFont.setBold(false);
yellowForeGround = workbook.createCellStyle();
yellowForeGround.cloneStyleFrom(centeredWrappedBorderedStyle);
yellowForeGround.setFillForegroundColor(IndexedColors.YELLOW.index);
yellowForeGround.setFillPattern(FillPatternType.SOLID_FOREGROUND);
createWorkSheet(cargoTheftReport, workbook);
return workbook;
}
private void createWorkSheet(CargoTheftReport cargoTheftReport, XSSFWorkbook workbook) {
XSSFSheet sheet = workbook.createSheet("Cargo Theft Incident Reports");
sheet.setFitToPage(true);
PrintSetup ps = sheet.getPrintSetup();
ps.setFitWidth( (short) 1);
ps.setFitHeight( (short) 1);
int rowNum = 0;
log.info("Write to the excel file");
rowNum = createTitleRow(sheet, rowNum);
rowNum = createHeaderRow(sheet, rowNum, true);
for (CargoTheftFormRow cargoTheftFormRow: cargoTheftReport.getCargoTheftRows()){
writeCargoTheftFormRow(sheet, cargoTheftFormRow, rowNum++);
}
if (cargoTheftReport.getCargoTheftRows().isEmpty()) {
rowNum = createEmptyRow(sheet, rowNum++);
}
setColumnsWidth(sheet);
}
private int createEmptyRow(XSSFSheet sheet, int rowNum) {
Row row = sheet.createRow(rowNum);
for (int colNum = 0; colNum < 3; colNum++) {
Cell cell = row.createCell(colNum);
cell.setCellStyle(wrappedBorderedStyle);
}
return rowNum;
}
private void setColumnsWidth(XSSFSheet sheet) {
sheet.setColumnWidth(0, 900 * sheet.getDefaultColumnWidth());
for (int i = 1; i < 4; i++) {
sheet.setColumnWidth(i, 475 * sheet.getDefaultColumnWidth());
}
}
private int createTitleRow(XSSFSheet sheet, int rowNum) {
Row row = sheet.createRow(rowNum++);
row.setHeightInPoints((3*sheet.getDefaultRowHeightInPoints()));
Cell cell = row.createCell(0);
cell.setCellStyle(centeredStyle);
XSSFRichTextString s1 = new XSSFRichTextString("Cargo Theft Incident Reports");
s1.applyFont(boldFont);
cell.setCellValue(s1);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));
return rowNum;
}
private int createHeaderRow(XSSFSheet sheet, int rowNum, boolean nonNegligent) {
CellRangeAddress mergedRegions = new CellRangeAddress(rowNum, rowNum, 0, 2);
sheet.addMergedRegion(mergedRegions);
Row row = sheet.createRow(rowNum++);
Cell cell = row.createCell(0);
cell.setCellStyle(yellowForeGround);
cell.setCellValue("INCIDENT INFORMATION");
row = sheet.createRow(rowNum++);
row.setHeightInPoints((2*sheet.getDefaultRowHeightInPoints()));
cell=row.createCell(0);
cell.setCellStyle(yellowForeGround);
cell.setCellValue("INCIDENT NUMBER");
cell=row.createCell(1);
cell.setCellStyle(yellowForeGround);
cell.setCellValue("INCIDENT DATE\n(YYYYMMDD)");
cell=row.createCell(2);
cell.setCellStyle(yellowForeGround);
cell.setCellValue("SUBMISSION TYPE");
RegionUtil.setBorderLeft(BorderStyle.THIN, mergedRegions, sheet);
RegionUtil.setBorderRight(BorderStyle.THIN, mergedRegions, sheet);
RegionUtil.setBorderTop(BorderStyle.THIN, mergedRegions, sheet);
RegionUtil.setBorderBottom(BorderStyle.THIN, mergedRegions, sheet);
return rowNum;
}
private void writeCargoTheftFormRow(XSSFSheet sheet, CargoTheftFormRow cargoTheftFormRow, int rowNum) {
Row row = sheet.createRow(rowNum);
int colNum = 0;
Cell cell = row.createCell(colNum++);
cell.setCellStyle(wrappedBorderedStyle);
cell.setCellValue(cargoTheftFormRow.getIncidentNumber());
cell = row.createCell(colNum++);
cell.setCellStyle(wrappedBorderedStyle);
cell.setCellValue(cargoTheftFormRow.getIncidentDateString());
cell = row.createCell(colNum++);
cell.setCellStyle(wrappedBorderedStyle);
cell.setCellValue(cargoTheftFormRow.getSegmentActionType());
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.usecases;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.util.Map;
import java.util.Vector;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.activemq.ActiveMQSession;
import org.apache.activemq.JmsMultipleBrokersTestSupport;
import org.apache.activemq.broker.BrokerService;
import org.apache.activemq.broker.TransportConnector;
import org.apache.activemq.broker.region.RegionBroker;
import org.apache.activemq.broker.region.policy.PolicyEntry;
import org.apache.activemq.broker.region.policy.PolicyMap;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTempQueue;
import org.apache.activemq.network.NetworkConnector;
import org.apache.activemq.util.Wait;
import org.apache.activemq.xbean.XBeanBrokerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class RequestReplyNoAdvisoryNetworkTest extends JmsMultipleBrokersTestSupport {
private static final transient Logger LOG = LoggerFactory.getLogger(RequestReplyNoAdvisoryNetworkTest.class);
Vector<BrokerService> brokers = new Vector<BrokerService>();
BrokerService a, b;
ActiveMQQueue sendQ = new ActiveMQQueue("sendQ");
static final String connectionIdMarker = "ID:marker.";
ActiveMQTempQueue replyQWildcard = new ActiveMQTempQueue(connectionIdMarker + ">");
private final long receiveTimeout = 30000;
public void testNonAdvisoryNetworkRequestReplyXmlConfig() throws Exception {
final String xmlConfigString = new String(
"<beans" +
" xmlns=\"http://www.springframework.org/schema/beans\"" +
" xmlns:amq=\"http://activemq.apache.org/schema/core\"" +
" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"" +
" xsi:schemaLocation=\"http://www.springframework.org/schema/beans" +
" http://www.springframework.org/schema/beans/spring-beans-2.0.xsd" +
" http://activemq.apache.org/schema/core" +
" http://activemq.apache.org/schema/core/activemq-core.xsd\">" +
" <broker xmlns=\"http://activemq.apache.org/schema/core\" id=\"broker\"" +
" allowTempAutoCreationOnSend=\"true\" schedulePeriodForDestinationPurge=\"1000\"" +
" brokerName=\"%HOST%\" persistent=\"false\" advisorySupport=\"false\" useJmx=\"false\" >" +
" <destinationPolicy>" +
" <policyMap>" +
" <policyEntries>" +
" <policyEntry optimizedDispatch=\"true\" gcInactiveDestinations=\"true\" gcWithNetworkConsumers=\"true\" inactiveTimoutBeforeGC=\"1000\">"+
" <destination>"+
" <tempQueue physicalName=\"" + replyQWildcard.getPhysicalName() + "\"/>" +
" </destination>" +
" </policyEntry>" +
" </policyEntries>" +
" </policyMap>" +
" </destinationPolicy>" +
" <networkConnectors>" +
" <networkConnector uri=\"multicast://default\">" +
" <staticallyIncludedDestinations>" +
" <queue physicalName=\"" + sendQ.getPhysicalName() + "\"/>" +
" <tempQueue physicalName=\"" + replyQWildcard.getPhysicalName() + "\"/>" +
" </staticallyIncludedDestinations>" +
" </networkConnector>" +
" </networkConnectors>" +
" <transportConnectors>" +
" <transportConnector uri=\"tcp://0.0.0.0:0\" discoveryUri=\"multicast://default\" />" +
" </transportConnectors>" +
" </broker>" +
"</beans>");
final String localProtocolScheme = "inline";
URL.setURLStreamHandlerFactory(new URLStreamHandlerFactory() {
@Override
public URLStreamHandler createURLStreamHandler(String protocol) {
if (localProtocolScheme.equalsIgnoreCase(protocol)) {
return new URLStreamHandler() {
@Override
protected URLConnection openConnection(URL u) throws IOException {
return new URLConnection(u) {
@Override
public void connect() throws IOException {
}
@Override
public InputStream getInputStream() throws IOException {
return new ByteArrayInputStream(xmlConfigString.replace("%HOST%", url.getFile()).getBytes("UTF-8"));
}
};
}
};
}
return null;
}
});
a = new XBeanBrokerFactory().createBroker(new URI("xbean:" + localProtocolScheme + ":A"));
b = new XBeanBrokerFactory().createBroker(new URI("xbean:" + localProtocolScheme + ":B"));
brokers.add(a);
brokers.add(b);
doTestNonAdvisoryNetworkRequestReply();
}
public void testNonAdvisoryNetworkRequestReply() throws Exception {
createBridgeAndStartBrokers();
doTestNonAdvisoryNetworkRequestReply();
}
public void testNonAdvisoryNetworkRequestReplyWithPIM() throws Exception {
a = configureBroker("A");
b = configureBroker("B");
BrokerService hub = configureBroker("M");
hub.setAllowTempAutoCreationOnSend(true);
configureForPiggyInTheMiddle(bridge(a, hub));
configureForPiggyInTheMiddle(bridge(b, hub));
startBrokers();
waitForBridgeFormation(hub, 2, 0);
doTestNonAdvisoryNetworkRequestReply();
}
private void configureForPiggyInTheMiddle(NetworkConnector bridge) {
bridge.setDuplex(true);
bridge.setNetworkTTL(2);
}
public void doTestNonAdvisoryNetworkRequestReply() throws Exception {
waitForBridgeFormation(a, 1, 0);
waitForBridgeFormation(b, 1, 0);
ActiveMQConnectionFactory sendFactory = createConnectionFactory(a);
ActiveMQConnection sendConnection = createConnection(sendFactory);
ActiveMQSession sendSession = (ActiveMQSession)sendConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageProducer producer = sendSession.createProducer(sendQ);
ActiveMQTempQueue realReplyQ = (ActiveMQTempQueue) sendSession.createTemporaryQueue();
TextMessage message = sendSession.createTextMessage("1");
message.setJMSReplyTo(realReplyQ);
producer.send(message);
LOG.info("request sent");
// responder
ActiveMQConnectionFactory consumerFactory = createConnectionFactory(b);
ActiveMQConnection consumerConnection = createConnection(consumerFactory);
ActiveMQSession consumerSession = (ActiveMQSession)consumerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
MessageConsumer consumer = consumerSession.createConsumer(sendQ);
TextMessage received = (TextMessage) consumer.receive(receiveTimeout);
assertNotNull("got request from sender ok", received);
LOG.info("got request, sending reply");
MessageProducer consumerProducer = consumerSession.createProducer(received.getJMSReplyTo());
consumerProducer.send(consumerSession.createTextMessage("got " + received.getText()));
// temp dest on reply broker tied to this connection, setOptimizedDispatch=true ensures
// message gets delivered before destination is removed
consumerConnection.close();
// reply consumer
MessageConsumer replyConsumer = sendSession.createConsumer(realReplyQ);
TextMessage reply = (TextMessage) replyConsumer.receive(receiveTimeout);
assertNotNull("expected reply message", reply);
assertEquals("text is as expected", "got 1", reply.getText());
sendConnection.close();
LOG.info("checking for dangling temp destinations");
// ensure all temp dests get cleaned up on all brokers
for (BrokerService brokerService : brokers) {
final RegionBroker regionBroker = (RegionBroker) brokerService.getRegionBroker();
assertTrue("all temps are gone on " + regionBroker.getBrokerName(), Wait.waitFor(new Wait.Condition(){
@Override
public boolean isSatisified() throws Exception {
Map<?,?> tempTopics = regionBroker.getTempTopicRegion().getDestinationMap();
LOG.info("temp topics on " + regionBroker.getBrokerName() + ", " + tempTopics);
Map<?,?> tempQ = regionBroker.getTempQueueRegion().getDestinationMap();
LOG.info("temp queues on " + regionBroker.getBrokerName() + ", " + tempQ);
return tempQ.isEmpty() && tempTopics.isEmpty();
}
}));
}
}
private ActiveMQConnection createConnection(ActiveMQConnectionFactory factory) throws Exception {
ActiveMQConnection c =(ActiveMQConnection) factory.createConnection();
c.start();
return c;
}
private ActiveMQConnectionFactory createConnectionFactory(BrokerService brokerService) throws Exception {
String target = brokerService.getTransportConnectors().get(0).getPublishableConnectString();
ActiveMQConnectionFactory factory =
new ActiveMQConnectionFactory(target);
factory.setWatchTopicAdvisories(false);
factory.setConnectionIDPrefix(connectionIdMarker + brokerService.getBrokerName());
return factory;
}
public void createBridgeAndStartBrokers() throws Exception {
a = configureBroker("A");
b = configureBroker("B");
bridge(a, b);
bridge(b, a);
startBrokers();
}
private void startBrokers() throws Exception {
for (BrokerService broker: brokers) {
broker.start();
}
}
@Override
public void tearDown() throws Exception {
for (BrokerService broker: brokers) {
broker.stop();
}
brokers.clear();
}
private NetworkConnector bridge(BrokerService from, BrokerService to) throws Exception {
TransportConnector toConnector = to.getTransportConnectors().get(0);
NetworkConnector bridge =
from.addNetworkConnector("static://" + toConnector.getPublishableConnectString());
bridge.addStaticallyIncludedDestination(sendQ);
bridge.addStaticallyIncludedDestination(replyQWildcard);
return bridge;
}
private BrokerService configureBroker(String brokerName) throws Exception {
BrokerService broker = new BrokerService();
broker.setBrokerName(brokerName);
broker.setAdvisorySupport(false);
broker.setPersistent(false);
broker.setUseJmx(false);
broker.setSchedulePeriodForDestinationPurge(1000);
broker.setAllowTempAutoCreationOnSend(true);
PolicyMap map = new PolicyMap();
PolicyEntry tempReplyQPolicy = new PolicyEntry();
tempReplyQPolicy.setOptimizedDispatch(true);
tempReplyQPolicy.setGcInactiveDestinations(true);
tempReplyQPolicy.setGcWithNetworkConsumers(true);
tempReplyQPolicy.setInactiveTimoutBeforeGC(1000);
map.put(replyQWildcard, tempReplyQPolicy);
broker.setDestinationPolicy(map);
broker.addConnector("tcp://localhost:0");
brokers.add(broker);
return broker;
}
}
| |
package org.davidmoten.rx.jdbc;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.invoke.MethodHandles;
import java.lang.invoke.MethodType;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Proxy;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Collectors;
import javax.annotation.RegEx;
import javax.sql.DataSource;
import org.apache.commons.io.IOUtils;
import org.davidmoten.rx.jdbc.annotations.Column;
import org.davidmoten.rx.jdbc.annotations.Index;
import org.davidmoten.rx.jdbc.callable.internal.OutParameterPlaceholder;
import org.davidmoten.rx.jdbc.callable.internal.ParameterPlaceholder;
import org.davidmoten.rx.jdbc.exceptions.AnnotationsNotFoundException;
import org.davidmoten.rx.jdbc.exceptions.AutomappedInterfaceInaccessibleException;
import org.davidmoten.rx.jdbc.exceptions.ColumnIndexOutOfRangeException;
import org.davidmoten.rx.jdbc.exceptions.ColumnNotFoundException;
import org.davidmoten.rx.jdbc.exceptions.MoreColumnsRequestedThanExistException;
import org.davidmoten.rx.jdbc.exceptions.NamedParameterFoundButSqlDoesNotHaveNamesException;
import org.davidmoten.rx.jdbc.exceptions.NamedParameterMissingException;
import org.davidmoten.rx.jdbc.exceptions.ParameterMissingNameException;
import org.davidmoten.rx.jdbc.exceptions.SQLRuntimeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.github.davidmoten.guavamini.annotations.VisibleForTesting;
public enum Util {
;
private static final Logger log = LoggerFactory.getLogger(Util.class);
public static final int QUERY_TIMEOUT_NOT_SET = -1;
/**
* Sets parameters for the {@link PreparedStatement}.
*
* @param ps
* @param params
* @throws SQLException
*/
@VisibleForTesting
static void setParameters(PreparedStatement ps, List<Parameter> params, boolean namesAllowed) throws SQLException {
int j = 1;
for (int i = 0; i < params.size(); i++) {
Parameter p = params.get(i);
if (p.hasName() && !namesAllowed) {
throw new NamedParameterFoundButSqlDoesNotHaveNamesException(
"named parameter found but sql does not contain names ps=" + ps);
}
Object v = p.value();
if (p.isCollection()) {
for (Object o : ((Collection<?>) v)) {
setParameter(ps, j, o);
j++;
}
} else {
setParameter(ps, j, v);
j++;
}
}
}
static void setParameter(PreparedStatement ps, int i, Object o) throws SQLException {
log.debug("setting parameter {} to {}", i, o);
try {
if (o == null)
ps.setObject(i, null);
else if (o == Database.NULL_CLOB)
ps.setNull(i, Types.CLOB);
else if (o == Database.NULL_BLOB)
ps.setNull(i, Types.BLOB);
else {
Class<?> cls = o.getClass();
if (Clob.class.isAssignableFrom(cls)) {
setClob(ps, i, o, cls);
} else if (Blob.class.isAssignableFrom(cls)) {
setBlob(ps, i, o, cls);
} else if (Calendar.class.isAssignableFrom(cls)) {
Calendar cal = (Calendar) o;
Timestamp t = new Timestamp(cal.getTimeInMillis());
ps.setTimestamp(i, t);
} else if (Time.class.isAssignableFrom(cls)) {
Calendar cal = Calendar.getInstance();
ps.setTime(i, (Time) o, cal);
} else if (Timestamp.class.isAssignableFrom(cls)) {
Calendar cal = Calendar.getInstance();
ps.setTimestamp(i, (Timestamp) o, cal);
} else if (java.sql.Date.class.isAssignableFrom(cls)) {
ps.setDate(i, (java.sql.Date) o, Calendar.getInstance());
} else if (java.util.Date.class.isAssignableFrom(cls)) {
Calendar cal = Calendar.getInstance();
java.util.Date date = (java.util.Date) o;
ps.setTimestamp(i, new Timestamp(date.getTime()), cal);
} else if (Instant.class.isAssignableFrom(cls)) {
Calendar cal = Calendar.getInstance();
Instant instant = (Instant) o;
ps.setTimestamp(i, new Timestamp(instant.toEpochMilli()), cal);
} else if (ZonedDateTime.class.isAssignableFrom(cls)) {
Calendar cal = Calendar.getInstance();
ZonedDateTime d = (ZonedDateTime) o;
ps.setTimestamp(i, new Timestamp(d.toInstant().toEpochMilli()), cal);
} else
ps.setObject(i, o);
}
} catch (SQLException e) {
log.debug("{} when setting ps.setObject({},{})", e.getMessage(), i, o);
throw e;
}
}
/**
* Sets a blob parameter for the prepared statement.
*
* @param ps
* @param i
* @param o
* @param cls
* @throws SQLException
*/
private static void setBlob(PreparedStatement ps, int i, Object o, Class<?> cls) throws SQLException {
// if (o instanceof Blob) {
ps.setBlob(i, (Blob) o);
// } else {
// final InputStream is;
// if (o instanceof byte[]) {
// is = new ByteArrayInputStream((byte[]) o);
// } else if (o instanceof InputStream)
// is = (InputStream) o;
// else
// throw new RuntimeException("cannot insert parameter of type " + cls + " into
// blob column " + i);
// Blob c = ps.getConnection().createBlob();
// OutputStream os = c.setBinaryStream(1);
// copy(is, os);
// ps.setBlob(i, c);
// }
}
/**
* Sets the clob parameter for the prepared statement.
*
* @param ps
* @param i
* @param o
* @param cls
* @throws SQLException
*/
private static void setClob(PreparedStatement ps, int i, Object o, Class<?> cls) throws SQLException {
// if (o instanceof Clob) {
ps.setClob(i, (Clob) o);
// } else {
// final Reader r;
// if (o instanceof String)
// r = new StringReader((String) o);
// else if (o instanceof Reader)
// r = (Reader) o;
// else
// throw new RuntimeException("cannot insert parameter of type " + cls + " into
// clob column " + i);
// Clob c = ps.getConnection().createClob();
// Writer w = c.setCharacterStream(1);
// copy(r, w);
// ps.setClob(i, c);
// }
}
static void setNamedParameters(PreparedStatement ps, List<Parameter> parameters, List<String> names)
throws SQLException {
Map<String, Parameter> map = createMap(parameters);
List<Parameter> list = new ArrayList<Parameter>();
for (String name : names) {
if (!map.containsKey(name))
throw new NamedParameterMissingException("named parameter is missing for '" + name + "'");
Parameter p = map.get(name);
list.add(p);
}
Util.setParameters(ps, list, true);
}
@VisibleForTesting
static Map<String, Parameter> createMap(List<Parameter> parameters) {
Map<String, Parameter> map = new HashMap<String, Parameter>();
for (Parameter p : parameters) {
if (p.hasName()) {
map.put(p.name(), p);
} else {
throw new ParameterMissingNameException(
"named parameters were expected but this parameter did not have a name: " + p);
}
}
return map;
}
static PreparedStatement convertAndSetParameters(PreparedStatement ps, List<Object> parameters, List<String> names)
throws SQLException {
return setParameters(ps, toParameters(parameters), names);
}
static PreparedStatement setParameters(PreparedStatement ps, List<Parameter> parameters, List<String> names)
throws SQLException {
if (names.isEmpty()) {
Util.setParameters(ps, parameters, false);
} else {
Util.setNamedParameters(ps, parameters, names);
}
return ps;
}
static List<Parameter> toParameters(List<Object> parameters) {
return parameters.stream().map(o -> {
if (o instanceof Parameter) {
return (Parameter) o;
} else {
return new Parameter(o);
}
}).collect(Collectors.toList());
}
static void incrementCounter(Connection connection) {
if (connection instanceof TransactedConnection) {
TransactedConnection c = (TransactedConnection) connection;
c.incrementCounter();
}
}
public static void closeSilently(AutoCloseable c) {
if (c != null) {
try {
log.debug("closing {}", c);
c.close();
} catch (Exception e) {
log.debug("ignored exception {}, {}, {}", e.getMessage(), e.getClass(), e);
}
}
}
static void closePreparedStatementAndConnection(PreparedStatement ps) {
Connection con = null;
try {
con = ps.getConnection();
} catch (SQLException e) {
log.warn(e.getMessage(), e);
}
closeSilently(ps);
closeSilently(con);
}
static void closePreparedStatementAndConnection(NamedPreparedStatement ps) {
closePreparedStatementAndConnection(ps.ps);
}
static void closeCallableStatementAndConnection(NamedCallableStatement stmt) {
closePreparedStatementAndConnection(stmt.stmt);
}
static NamedPreparedStatement prepare(Connection con, String sql, int queryTimeoutSec) throws SQLException {
return prepare(con, 0, sql, queryTimeoutSec);
}
static NamedPreparedStatement prepare(Connection con, int fetchSize, String sql, int queryTimeoutSec) throws SQLException {
// TODO can we parse SqlInfo through because already calculated by
// builder?
SqlInfo info = SqlInfo.parse(sql);
log.debug("preparing statement: {}", sql);
return prepare(con, fetchSize, info, queryTimeoutSec);
}
static PreparedStatement prepare(Connection connection, int fetchSize, String sql, List<Parameter> parameters, int queryTimeoutSec)
throws SQLException {
// should only get here when parameters contains a collection
SqlInfo info = SqlInfo.parse(sql, parameters);
log.debug("preparing statement: {}", info.sql());
return createPreparedStatement(connection, fetchSize, info, queryTimeoutSec);
}
private static NamedPreparedStatement prepare(Connection con, int fetchSize, SqlInfo info, int queryTimeoutSec) throws SQLException {
PreparedStatement ps = createPreparedStatement(con, fetchSize, info, queryTimeoutSec);
return new NamedPreparedStatement(ps, info.names());
}
private static PreparedStatement createPreparedStatement(Connection con, int fetchSize, SqlInfo info, int queryTimeoutSec)
throws SQLException {
PreparedStatement ps = null;
try {
ps = con.prepareStatement(info.sql(), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
if (fetchSize > 0) {
ps.setFetchSize(fetchSize);
}
if (queryTimeoutSec != QUERY_TIMEOUT_NOT_SET) {
ps.setQueryTimeout(queryTimeoutSec);
}
} catch (RuntimeException | SQLException e) {
if (ps != null) {
ps.close();
}
throw e;
}
return ps;
}
static NamedCallableStatement prepareCall(Connection con, String sql,
List<ParameterPlaceholder> parameterPlaceholders) throws SQLException {
return prepareCall(con, 0, sql, parameterPlaceholders);
}
// TODO is fetchSize required for callablestatement
static NamedCallableStatement prepareCall(Connection con, int fetchSize, String sql,
List<ParameterPlaceholder> parameterPlaceholders) throws SQLException {
// TODO can we parse SqlInfo through because already calculated by
// builder?
SqlInfo s = SqlInfo.parse(sql);
log.debug("preparing statement: {}", sql);
CallableStatement ps = null;
try {
ps = con.prepareCall(s.sql(), ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
for (int i = 0; i < parameterPlaceholders.size(); i++) {
ParameterPlaceholder p = parameterPlaceholders.get(i);
if (p instanceof OutParameterPlaceholder) {
ps.registerOutParameter(i + 1, ((OutParameterPlaceholder) p).type().value());
}
}
if (fetchSize > 0) {
ps.setFetchSize(fetchSize);
}
return new NamedCallableStatement(ps, s.names());
} catch (RuntimeException | SQLException e) {
if (ps != null) {
ps.close();
}
throw e;
}
}
static NamedPreparedStatement prepareReturnGeneratedKeys(Connection con, String sql) throws SQLException {
SqlInfo s = SqlInfo.parse(sql);
return new NamedPreparedStatement(con.prepareStatement(s.sql(), Statement.RETURN_GENERATED_KEYS), s.names());
}
@VisibleForTesting
static int countQuestionMarkParameters(String sql) {
// was originally using regular expressions, but they didn't work well
// for ignoring parameter-like strings inside quotes.
int count = 0;
int length = sql.length();
boolean inSingleQuote = false;
boolean inDoubleQuote = false;
for (int i = 0; i < length; i++) {
char c = sql.charAt(i);
if (inSingleQuote) {
if (c == '\'') {
inSingleQuote = false;
}
} else if (inDoubleQuote) {
if (c == '"') {
inDoubleQuote = false;
}
} else {
if (c == '\'') {
inSingleQuote = true;
} else if (c == '"') {
inDoubleQuote = true;
} else if (c == '?') {
count++;
}
}
}
return count;
}
public static void commit(PreparedStatement ps) throws SQLException {
Connection c = ps.getConnection();
if (!c.getAutoCommit()) {
c.commit();
}
}
public static void rollback(PreparedStatement ps) throws SQLException {
Connection c = ps.getConnection();
if (!c.getAutoCommit()) {
c.rollback();
}
}
// auto-mapping
/**
* Converts from java.sql Types to common java types like java.util.Date and
* numeric types.
*
* @param o
* object to map to new object of type {@code cls}
* @param cls
* object return type
* @return object of type {@code cls}
*/
public static Object autoMap(Object o, Class<?> cls) {
if (o == null)
return o;
else if (cls.isAssignableFrom(o.getClass())) {
return o;
} else {
if (o instanceof java.sql.Date) {
java.sql.Date d = (java.sql.Date) o;
if (cls.isAssignableFrom(Long.class))
return d.getTime();
else if (cls.isAssignableFrom(BigInteger.class))
return BigInteger.valueOf(d.getTime());
else if (cls.isAssignableFrom(Instant.class))
return Instant.ofEpochMilli(d.getTime());
else
return o;
} else if (o instanceof Timestamp) {
Timestamp t = (Timestamp) o;
if (cls.isAssignableFrom(Long.class))
return t.getTime();
else if (cls.isAssignableFrom(BigInteger.class))
return BigInteger.valueOf(t.getTime());
else if (cls.isAssignableFrom(Instant.class))
return t.toInstant();
else
return o;
} else if (o instanceof Time) {
Time t = (Time) o;
if (cls.isAssignableFrom(Long.class))
return t.getTime();
else if (cls.isAssignableFrom(BigInteger.class))
return BigInteger.valueOf(t.getTime());
else if (cls.isAssignableFrom(Instant.class))
return t.toInstant();
else
return o;
} else if (o instanceof Blob && cls.isAssignableFrom(byte[].class)) {
return toBytes((Blob) o);
} else if (o instanceof Clob && cls.isAssignableFrom(String.class)) {
return toString((Clob) o);
} else if (o instanceof BigInteger && cls.isAssignableFrom(Long.class)) {
return ((BigInteger) o).longValue();
} else if (o instanceof BigInteger && cls.isAssignableFrom(Integer.class)) {
return ((BigInteger) o).intValue();
} else if (o instanceof BigInteger && cls.isAssignableFrom(Double.class)) {
return ((BigInteger) o).doubleValue();
} else if (o instanceof BigInteger && cls.isAssignableFrom(Float.class)) {
return ((BigInteger) o).floatValue();
} else if (o instanceof BigInteger && cls.isAssignableFrom(Short.class)) {
return ((BigInteger) o).shortValue();
} else if (o instanceof BigInteger && cls.isAssignableFrom(BigDecimal.class)) {
return new BigDecimal((BigInteger) o);
} else if (o instanceof BigDecimal && cls.isAssignableFrom(Double.class)) {
return ((BigDecimal) o).doubleValue();
} else if (o instanceof BigDecimal && cls.isAssignableFrom(Integer.class)) {
return ((BigDecimal) o).toBigInteger().intValue();
} else if (o instanceof BigDecimal && cls.isAssignableFrom(Float.class)) {
return ((BigDecimal) o).floatValue();
} else if (o instanceof BigDecimal && cls.isAssignableFrom(Short.class)) {
return ((BigDecimal) o).toBigInteger().shortValue();
} else if (o instanceof BigDecimal && cls.isAssignableFrom(Long.class)) {
return ((BigDecimal) o).toBigInteger().longValue();
} else if (o instanceof BigDecimal && cls.isAssignableFrom(BigInteger.class)) {
return ((BigDecimal) o).toBigInteger();
} else if ((o instanceof Short || o instanceof Integer || o instanceof Long)
&& cls.isAssignableFrom(BigInteger.class)) {
return new BigInteger(o.toString());
} else if (o instanceof Number && cls.isAssignableFrom(BigDecimal.class)) {
return new BigDecimal(o.toString());
} else if (o instanceof Number && cls.isAssignableFrom(Short.class))
return ((Number) o).shortValue();
else if (o instanceof Number && cls.isAssignableFrom(Integer.class))
return ((Number) o).intValue();
else if (o instanceof Number && cls.isAssignableFrom(Integer.class))
return ((Number) o).intValue();
else if (o instanceof Number && cls.isAssignableFrom(Long.class))
return ((Number) o).longValue();
else if (o instanceof Number && cls.isAssignableFrom(Float.class))
return ((Number) o).floatValue();
else if (o instanceof Number && cls.isAssignableFrom(Double.class))
return ((Number) o).doubleValue();
else
return o;
}
}
@SuppressWarnings("unchecked")
public static <T> T mapObject(final ResultSet rs, Class<T> cls, int i) {
return (T) autoMap(getObject(rs, cls, i), cls);
}
@SuppressWarnings("unchecked")
public static <T> T mapObject(final CallableStatement cs, Class<T> cls, int i, Type type) {
return (T) autoMap(getObject(cs, cls, i, type), cls);
}
private static <T> Object getObject(final ResultSet rs, Class<T> cls, int i) {
try {
int colCount = rs.getMetaData().getColumnCount();
if (i > colCount) {
throw new MoreColumnsRequestedThanExistException(
"only " + colCount + " columns exist in ResultSet and column " + i + " was requested");
}
if (rs.getObject(i) == null) {
return null;
}
final int type = rs.getMetaData().getColumnType(i);
// TODO java.util.Calendar support
// TODO XMLGregorian Calendar support
if (type == Types.DATE)
return rs.getDate(i, Calendar.getInstance());
else if (type == Types.TIME)
return rs.getTime(i, Calendar.getInstance());
else if (type == Types.TIMESTAMP)
return rs.getTimestamp(i, Calendar.getInstance());
else if (type == Types.CLOB && cls.equals(String.class)) {
return toString(rs.getClob(i));
} else if (type == Types.CLOB && Reader.class.isAssignableFrom(cls)) {
Clob c = rs.getClob(i);
Reader r = c.getCharacterStream();
return createFreeOnCloseReader(c, r);
} else if (type == Types.BLOB && cls.equals(byte[].class)) {
return toBytes(rs.getBlob(i));
} else if (type == Types.BLOB && InputStream.class.isAssignableFrom(cls)) {
final Blob b = rs.getBlob(i);
final InputStream is = rs.getBlob(i).getBinaryStream();
return createFreeOnCloseInputStream(b, is);
} else
return rs.getObject(i);
} catch (SQLException e) {
throw new SQLRuntimeException(e);
}
}
private static <T> Object getObject(final CallableStatement cs, Class<T> cls, int i, Type typ) {
try {
if (cs.getObject(i) == null) {
return null;
}
final int type = typ.value();
// TODO java.util.Calendar support
// TODO XMLGregorian Calendar support
if (type == Types.DATE)
return cs.getDate(i, Calendar.getInstance());
else if (type == Types.TIME)
return cs.getTime(i, Calendar.getInstance());
else if (type == Types.TIMESTAMP)
return cs.getTimestamp(i, Calendar.getInstance());
else if (type == Types.CLOB && cls.equals(String.class)) {
return toString(cs.getClob(i));
} else if (type == Types.CLOB && Reader.class.isAssignableFrom(cls)) {
Clob c = cs.getClob(i);
Reader r = c.getCharacterStream();
return createFreeOnCloseReader(c, r);
} else if (type == Types.BLOB && cls.equals(byte[].class)) {
return toBytes(cs.getBlob(i));
} else if (type == Types.BLOB && InputStream.class.isAssignableFrom(cls)) {
final Blob b = cs.getBlob(i);
final InputStream is = cs.getBlob(i).getBinaryStream();
return createFreeOnCloseInputStream(b, is);
} else
return cs.getObject(i);
} catch (SQLException e) {
throw new SQLRuntimeException(e);
}
}
/**
* Returns the bytes of a {@link Blob} and frees the blob resource.
*
* @param b
* blob
* @return
*/
@VisibleForTesting
static byte[] toBytes(Blob b) {
try {
InputStream is = b.getBinaryStream();
byte[] result = IOUtils.toByteArray(is);
is.close();
b.free();
return result;
} catch (IOException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new SQLRuntimeException(e);
}
}
/**
* Returns the String of a {@link Clob} and frees the clob resource.
*
* @param c
* @return
*/
@VisibleForTesting
static String toString(Clob c) {
try {
Reader reader = c.getCharacterStream();
String result = IOUtils.toString(reader);
reader.close();
c.free();
return result;
} catch (IOException e) {
throw new RuntimeException(e);
} catch (SQLException e) {
throw new SQLRuntimeException(e);
}
}
/**
* Automatically frees the blob (<code>blob.free()</code>) once the blob
* {@link InputStream} is closed.
*
* @param blob
* @param is
* @return
*/
private static InputStream createFreeOnCloseInputStream(final Blob blob, final InputStream is) {
return new InputStream() {
@Override
public int read() throws IOException {
return is.read();
}
@Override
public void close() throws IOException {
try {
is.close();
} finally {
try {
blob.free();
} catch (SQLException e) {
log.debug(e.getMessage());
}
}
}
};
}
/**
* Automatically frees the clob (<code>Clob.free()</code>) once the clob Reader
* is closed.
*
* @param clob
* @param reader
* @return
*/
private static Reader createFreeOnCloseReader(final Clob clob, final Reader reader) {
return new Reader() {
@Override
public void close() throws IOException {
try {
reader.close();
} finally {
try {
clob.free();
} catch (SQLException e) {
log.debug(e.getMessage());
}
}
}
@Override
public int read(char[] cbuf, int off, int len) throws IOException {
return reader.read(cbuf, off, len);
}
};
}
/**
* Returns a function that converts the ResultSet column values into parameters
* to the constructor (with number of parameters equals the number of columns)
* of type <code>cls</code> then returns an instance of type <code>cls</code>.
* See {@link SelectBuilder#autoMap(Class)}.
*
* @param cls
* @return
*/
static <T> ResultSetMapper<T> autoMap(Class<T> cls) {
return new ResultSetMapper<T>() {
ProxyService<T> proxyService;
private ResultSet rs;
@Override
public T apply(ResultSet rs) {
// access to this method will be serialized
// only create a new ProxyService when the ResultSet changes
// for example with the second run of a PreparedStatement
if (rs != this.rs) {
this.rs = rs;
proxyService = new ProxyService<T>(rs, cls);
}
return autoMap(rs, cls, proxyService);
}
};
}
/**
* Converts the ResultSet column values into parameters to the constructor (with
* number of parameters equals the number of columns) of type <code>T</code>
* then returns an instance of type <code>T</code>. See See
* {@link SelectBuilder#autoMap(Class)}.
*
* @param rs
* @param cls
* the class of the resultant instance
* @param proxyService
* @return an automapped instance
*/
static <T> T autoMap(ResultSet rs, Class<T> cls, ProxyService<T> proxyService) {
return proxyService.newInstance();
}
interface Col {
Class<?> returnType();
}
static class NamedCol implements Col {
final String name;
private final Class<?> returnType;
public NamedCol(String name, Class<?> returnType) {
this.name = name;
this.returnType = returnType;
}
@Override
public Class<?> returnType() {
return returnType;
}
}
static class IndexedCol implements Col {
final int index;
private final Class<?> returnType;
public IndexedCol(int index, Class<?> returnType) {
this.index = index;
this.returnType = returnType;
}
@Override
public Class<?> returnType() {
return returnType;
}
}
private static class ProxyService<T> {
private final Map<String, Integer> colIndexes;
private final Map<String, Col> methodCols;
private final Class<T> cls;
private final ResultSet rs;
public ProxyService(ResultSet rs, Class<T> cls) {
this(rs, collectColIndexes(rs), getMethodCols(cls), cls);
}
public ProxyService(ResultSet rs, Map<String, Integer> colIndexes, Map<String, Col> methodCols, Class<T> cls) {
this.rs = rs;
this.colIndexes = colIndexes;
this.methodCols = methodCols;
this.cls = cls;
}
private Map<String, Object> values() {
Map<String, Object> values = new HashMap<String, Object>();
// calculate values for all the interface methods and put them in a
// map
for (Method m : cls.getMethods()) {
String methodName = m.getName();
Col column = methodCols.get(methodName);
if (column != null) {
Integer index;
if (column instanceof NamedCol) {
String name = ((NamedCol) column).name;
index = colIndexes.get(name.toUpperCase());
if (index == null) {
throw new ColumnNotFoundException("query column names do not include '" + name
+ "' which is a named column in the automapped interface " + cls.getName());
}
} else {
IndexedCol col = ((IndexedCol) column);
index = col.index;
if (index < 1) {
throw new ColumnIndexOutOfRangeException(
"value for Index annotation (on autoMapped interface " + cls.getName()
+ ") must be > 0");
} else {
int count = getColumnCount(rs);
if (index > count) {
throw new ColumnIndexOutOfRangeException("value " + index
+ " for Index annotation (on autoMapped interface " + cls.getName()
+ ") must be between 1 and the number of columns in the result set (" + count
+ ")");
}
}
}
Object value = autoMap(getObject(rs, column.returnType(), index), column.returnType());
values.put(methodName, value);
}
}
if (values.isEmpty()) {
throw new AnnotationsNotFoundException(
"Did you forget to add @Column or @Index annotations to " + cls.getName() + "?");
}
return values;
}
@SuppressWarnings("unchecked")
public T newInstance() {
return (T) Proxy.newProxyInstance(cls.getClassLoader(), new Class[] { cls },
new ProxyInstance<T>(cls, values()));
}
}
private static int getColumnCount(ResultSet rs) {
try {
return rs.getMetaData().getColumnCount();
} catch (SQLException e) {
throw new SQLRuntimeException(e);
}
}
private static final class ProxyInstance<T> implements java.lang.reflect.InvocationHandler {
private static boolean JAVA_9 = false;
private static final String METHOD_TO_STRING = "toString";
private final Class<T> cls;
private final Map<String, Object> values;
ProxyInstance(Class<T> cls, Map<String, Object> values) {
this.cls = cls;
this.values = values;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (METHOD_TO_STRING.equals(method.getName()) && isEmpty(args)) {
return Util.toString(cls.getSimpleName(), values);
} else if ("equals".equals(method.getName()) && args != null && args.length == 1) {
if (args[0] == null) {
return false;
} else if (args[0] instanceof Proxy) {
ProxyInstance<?> handler = (ProxyInstance<?>) Proxy.getInvocationHandler(args[0]);
if (!handler.cls.equals(cls)) {
// is a proxied object for a different interface!
return false;
} else {
return handler.values.equals(values);
}
} else {
return false;
}
} else if (isHashCode(method, args)) {
return values.hashCode();
} else if (values.containsKey(method.getName()) && isEmpty(args)) {
return values.get(method.getName());
} else if (method.isDefault()) {
final Class<?> declaringClass = method.getDeclaringClass();
if (!Modifier.isPublic(declaringClass.getModifiers())) {
throw new AutomappedInterfaceInaccessibleException(
"An automapped interface must be public for you to call default methods on that interface");
}
// TODO java 9 support (fix IllegalAccessException)
if (JAVA_9) {
MethodType methodType = MethodType.methodType(method.getReturnType(), method.getParameterTypes());
return MethodHandles.lookup() //
.findSpecial( //
declaringClass, //
method.getName(), //
methodType, //
declaringClass) //
.bindTo(proxy) //
.invoke(args);
} else {
Constructor<MethodHandles.Lookup> constructor = //
MethodHandles.Lookup.class //
.getDeclaredConstructor(Class.class, int.class);
constructor.setAccessible(true);
return constructor //
.newInstance(declaringClass, MethodHandles.Lookup.PRIVATE)
.unreflectSpecial(method, declaringClass) //
.bindTo(proxy) //
.invokeWithArguments(args);
}
} else {
throw new RuntimeException("unexpected");
}
}
}
@VisibleForTesting
static boolean isHashCode(Method method, Object[] args) {
return "hashCode".equals(method.getName()) && isEmpty(args);
}
private static boolean isEmpty(Object[] args) {
return args == null || args.length == 0;
}
private static String toString(String clsSimpleName, Map<String, Object> values) {
StringBuilder s = new StringBuilder();
s.append(clsSimpleName);
s.append("[");
boolean first = true;
for (Entry<String, Object> entry : new TreeMap<String, Object>(values).entrySet()) {
if (!first) {
s.append(", ");
}
s.append(entry.getKey());
s.append("=");
s.append(entry.getValue());
first = false;
}
s.append("]");
return s.toString();
}
private static Map<String, Col> getMethodCols(Class<?> cls) {
Map<String, Col> methodCols = new HashMap<String, Col>();
for (Method method : cls.getMethods()) {
String name = method.getName();
Column column = method.getAnnotation(Column.class);
if (column != null) {
checkHasNoParameters(method);
// TODO check method has a mappable return type
String col = column.value();
if (col.equals(Column.NOT_SPECIFIED))
col = Util.camelCaseToUnderscore(name);
methodCols.put(name, new NamedCol(col, method.getReturnType()));
} else {
Index index = method.getAnnotation(Index.class);
if (index != null) {
// TODO check method has a mappable return type
checkHasNoParameters(method);
methodCols.put(name, new IndexedCol(index.value(), method.getReturnType()));
}
}
}
return methodCols;
}
private static void checkHasNoParameters(Method method) {
if (method.getParameterTypes().length > 0) {
throw new RuntimeException("mapped interface method cannot have parameters");
}
}
private static Map<String, Integer> collectColIndexes(ResultSet rs) {
HashMap<String, Integer> map = new HashMap<String, Integer>();
try {
ResultSetMetaData metadata = rs.getMetaData();
for (int i = 1; i <= metadata.getColumnCount(); i++) {
map.put(metadata.getColumnName(i).toUpperCase(), i);
}
return map;
} catch (SQLException e) {
throw new SQLRuntimeException(e);
}
}
static String camelCaseToUnderscore(String camelCased) {
// guava has best solution for this with CaseFormat class
// but don't want to add dependency just for this method
final @RegEx String regex = "([a-z])([A-Z]+)";
final String replacement = "$1_$2";
return camelCased.replaceAll(regex, replacement);
}
public static ConnectionProvider connectionProvider(String url, Properties properties) {
return new ConnectionProvider() {
@Override
public Connection get() {
try {
return DriverManager.getConnection(url, properties);
} catch (SQLException e) {
throw new SQLRuntimeException(e);
}
}
@Override
public void close() {
//
}
};
}
static Connection toTransactedConnection(AtomicReference<Connection> connection, Connection c) throws SQLException {
if (c instanceof TransactedConnection) {
connection.set(c);
return c;
} else {
c.setAutoCommit(false);
log.debug("creating new TransactedConnection");
TransactedConnection c2 = new TransactedConnection(c);
connection.set(c2);
return c2;
}
}
public static ConnectionProvider connectionProvider(DataSource dataSource) {
return new ConnectionProvider() {
@Override
public Connection get() {
return getConnection(dataSource);
}
@Override
public void close() {
// do nothing
}
};
}
@VisibleForTesting
static Connection getConnection(DataSource ds) {
try {
return ds.getConnection();
} catch (SQLException e) {
throw new SQLRuntimeException(e);
}
}
public static boolean hasCollection(List<Parameter> params) {
return params.stream().anyMatch(x -> x.isCollection());
}
}
| |
/*
* Licensed to Apereo under one or more contributor license
* agreements. See the NOTICE file distributed with this work
* for additional information regarding copyright ownership.
* Apereo licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a
* copy of the License at the following location:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.jasig.cas.adaptors.x509.authentication.handler.support;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.net.URLDecoder;
import java.security.cert.X509CRL;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.jasig.cas.adaptors.x509.util.CertUtils;
import org.springframework.core.io.ByteArrayResource;
import edu.vt.middleware.crypt.x509.ExtensionReader;
import edu.vt.middleware.crypt.x509.types.DistributionPoint;
import edu.vt.middleware.crypt.x509.types.DistributionPointList;
import edu.vt.middleware.crypt.x509.types.GeneralName;
import edu.vt.middleware.crypt.x509.types.GeneralNameList;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import javax.validation.constraints.NotNull;
/**
* Performs CRL-based revocation checking by consulting resources defined in
* the CRLDistributionPoints extension field on the certificate. Although RFC
* 2459 allows the distribution point name to have arbitrary meaning, this class
* expects the name to define an absolute URL, which is the most common
* implementation. This implementation caches CRL resources fetched from remote
* URLs to improve performance by avoiding CRL fetching on every revocation
* check.
*
* @author Marvin S. Addison
* @since 3.4.6
*
*/
public class CRLDistributionPointRevocationChecker extends AbstractCRLRevocationChecker {
/** CRL cache. */
private final Cache crlCache;
/** The CRL fetcher instance. **/
private final CRLFetcher fetcher;
private boolean throwOnFetchFailure;
/**
* Creates a new instance that uses the given cache instance for CRL caching.
*
* @param crlCache Cache for CRL data.
*/
public CRLDistributionPointRevocationChecker(@NotNull final Cache crlCache) {
this(crlCache, new ResourceCRLFetcher());
}
/**
* Creates a new instance that uses the given cache instance for CRL caching.
*
* @param crlCache Cache for CRL data.
* @param throwOnFetchFailure the throw on fetch failure
*/
public CRLDistributionPointRevocationChecker(@NotNull final Cache crlCache,
final boolean throwOnFetchFailure) {
this(crlCache, new ResourceCRLFetcher());
setThrowOnFetchFailure(throwOnFetchFailure);
}
/**
* Instantiates a new CRL distribution point revocation checker.
*
* @param crlCache the crl cache
* @param fetcher the fetcher
*/
public CRLDistributionPointRevocationChecker(@NotNull final Cache crlCache,
@NotNull final CRLFetcher fetcher) {
this.crlCache = crlCache;
this.fetcher = fetcher;
}
/**
* Throws exceptions if fetching crl fails. Defaults to false.
*
* @param throwOnFetchFailure the throw on fetch failure
*/
public void setThrowOnFetchFailure(final boolean throwOnFetchFailure) {
this.throwOnFetchFailure = throwOnFetchFailure;
}
/**
* {@inheritDoc}
* @see AbstractCRLRevocationChecker#getCRL(X509Certificate)
*/
@Override
protected List<X509CRL> getCRLs(final X509Certificate cert) {
final URI[] urls = getDistributionPoints(cert);
logger.debug("Distribution points for {}: {}.", CertUtils.toString(cert), Arrays.asList(urls));
final List<X509CRL> listOfLocations = new ArrayList<>(urls.length);
boolean stopFetching = false;
try {
for (int index = 0; !stopFetching && index < urls.length; index++) {
final URI url = urls[index];
final Element item = this.crlCache.get(url);
if (item != null) {
logger.debug("Found CRL in cache for {}", CertUtils.toString(cert));
final byte[] encodedCrl = (byte[]) item.getObjectValue();
final X509CRL crlFetched = this.fetcher.fetch(new ByteArrayResource(encodedCrl));
if (crlFetched != null) {
listOfLocations.add(crlFetched);
} else {
logger.warn("Could fetch X509 CRL for {}. Returned value is null", url);
}
} else {
logger.debug("CRL for {} is not cached. Fetching and caching...", CertUtils.toString(cert));
try {
final X509CRL crl = this.fetcher.fetch(url);
if (crl != null) {
logger.info("Success. Caching fetched CRL at {}.", url);
addCRL(url, crl);
listOfLocations.add(crl);
}
} catch (final Exception e) {
logger.error("Error fetching CRL at {}", url, e);
if (this.throwOnFetchFailure) {
throw new RuntimeException(e);
}
}
}
if (!this.checkAll && !listOfLocations.isEmpty()) {
logger.debug("CRL fetching is configured to not check all locations.");
stopFetching = true;
}
}
} catch (final Exception e) {
throw new RuntimeException(e);
}
logger.debug("Found {} CRLs", listOfLocations.size());
return listOfLocations;
}
@Override
protected boolean addCRL(final Object id, final X509CRL crl) {
try {
if (crl == null) {
logger.debug("No CRL was passed. Removing {} from cache...", id);
return this.crlCache.remove(id);
}
this.crlCache.put(new Element(id, crl.getEncoded()));
return this.crlCache.get(id) != null;
} catch (final Exception e) {
logger.warn("Failed to add the crl entry [{}] to the cache", crl);
throw new RuntimeException(e);
}
}
/**
* Gets the distribution points.
*
* @param cert the cert
* @return the url distribution points
*/
private URI[] getDistributionPoints(final X509Certificate cert) {
final DistributionPointList points;
try {
points = new ExtensionReader(cert).readCRLDistributionPoints();
} catch (final Exception e) {
logger.error("Error reading CRLDistributionPoints extension field on {}", CertUtils.toString(cert), e);
return new URI[0];
}
final List<URI> urls = new ArrayList<>();
for (final DistributionPoint point : points.getItems()) {
final Object location = point.getDistributionPoint();
if (location instanceof String) {
addURL(urls, (String) location);
} else if (location instanceof GeneralNameList) {
for (final GeneralName gn : ((GeneralNameList) location).getItems()) {
addURL(urls, gn.getName());
}
} else {
logger.warn("{} not supported. String or GeneralNameList expected.", location);
}
}
return urls.toArray(new URI[urls.size()]);
}
/**
* Adds the url to the list.
* Build URI by components to facilitate proper encoding of querystring.
* e.g. http://example.com:8085/ca?action=crl&issuer=CN=CAS Test User CA
*
* <p>If <code>uriString</code> is encoded, it will be decoded with <code>UTF-8</code>
* first before it's added to the list.</p>
* @param list the list
* @param uriString the uri string
*/
private void addURL(final List<URI> list, final String uriString) {
try {
URI uri = null;
try {
final URL url = new URL(URLDecoder.decode(uriString, "UTF-8"));
uri = new URI(url.getProtocol(), url.getAuthority(), url.getPath(), url.getQuery(), null);
} catch (final MalformedURLException e) {
uri = new URI(uriString);
}
list.add(uri);
} catch (final Exception e) {
logger.warn("{} is not a valid distribution point URI.", uriString);
}
}
}
| |
/*******************************************************************************
* Copyright 2009-2016 Amazon Services. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
*
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at: http://aws.amazon.com/apache2.0
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*******************************************************************************
* Create Inbound Shipment Request
* API Version: 2010-10-01
* Library Version: 2016-10-05
* Generated: Wed Oct 05 06:15:34 PDT 2016
*/
package com.amazonservices.mws.FulfillmentInboundShipment.model;
import javax.xml.bind.annotation.*;
import com.amazonservices.mws.client.*;
/**
* CreateInboundShipmentRequest complex type.
*
* XML schema:
*
* <pre>
* <complexType name="CreateInboundShipmentRequest">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="SellerId" type="{http://www.w3.org/2001/XMLSchema}string"/>
* <element name="MWSAuthToken" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="Marketplace" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="ShipmentId" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="InboundShipmentHeader" type="{http://mws.amazonaws.com/FulfillmentInboundShipment/2010-10-01/}InboundShipmentHeader"/>
* <element name="InboundShipmentItems" type="{http://mws.amazonaws.com/FulfillmentInboundShipment/2010-10-01/}InboundShipmentItemList"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name="CreateInboundShipmentRequest", propOrder={
"sellerId",
"mwsAuthToken",
"marketplace",
"shipmentId",
"inboundShipmentHeader",
"inboundShipmentItems"
})
@XmlRootElement(name = "CreateInboundShipmentRequest")
public class CreateInboundShipmentRequest extends AbstractMwsObject {
@XmlElement(name="SellerId",required=true)
private String sellerId;
@XmlElement(name="MWSAuthToken")
private String mwsAuthToken;
@XmlElement(name="Marketplace")
private String marketplace;
@XmlElement(name="ShipmentId")
private String shipmentId;
@XmlElement(name="InboundShipmentHeader",required=true)
private InboundShipmentHeader inboundShipmentHeader;
@XmlElement(name="InboundShipmentItems",required=true)
private InboundShipmentItemList inboundShipmentItems;
/**
* Get the value of SellerId.
*
* @return The value of SellerId.
*/
public String getSellerId() {
return sellerId;
}
/**
* Set the value of SellerId.
*
* @param sellerId
* The new value to set.
*/
public void setSellerId(String sellerId) {
this.sellerId = sellerId;
}
/**
* Check to see if SellerId is set.
*
* @return true if SellerId is set.
*/
public boolean isSetSellerId() {
return sellerId != null;
}
/**
* Set the value of SellerId, return this.
*
* @param sellerId
* The new value to set.
*
* @return This instance.
*/
public CreateInboundShipmentRequest withSellerId(String sellerId) {
this.sellerId = sellerId;
return this;
}
/**
* Get the value of MWSAuthToken.
*
* @return The value of MWSAuthToken.
*/
public String getMWSAuthToken() {
return mwsAuthToken;
}
/**
* Set the value of MWSAuthToken.
*
* @param mwsAuthToken
* The new value to set.
*/
public void setMWSAuthToken(String mwsAuthToken) {
this.mwsAuthToken = mwsAuthToken;
}
/**
* Check to see if MWSAuthToken is set.
*
* @return true if MWSAuthToken is set.
*/
public boolean isSetMWSAuthToken() {
return mwsAuthToken != null;
}
/**
* Set the value of MWSAuthToken, return this.
*
* @param mwsAuthToken
* The new value to set.
*
* @return This instance.
*/
public CreateInboundShipmentRequest withMWSAuthToken(String mwsAuthToken) {
this.mwsAuthToken = mwsAuthToken;
return this;
}
/**
* Get the value of Marketplace.
*
* @return The value of Marketplace.
*/
public String getMarketplace() {
return marketplace;
}
/**
* Set the value of Marketplace.
*
* @param marketplace
* The new value to set.
*/
public void setMarketplace(String marketplace) {
this.marketplace = marketplace;
}
/**
* Check to see if Marketplace is set.
*
* @return true if Marketplace is set.
*/
public boolean isSetMarketplace() {
return marketplace != null;
}
/**
* Set the value of Marketplace, return this.
*
* @param marketplace
* The new value to set.
*
* @return This instance.
*/
public CreateInboundShipmentRequest withMarketplace(String marketplace) {
this.marketplace = marketplace;
return this;
}
/**
* Get the value of ShipmentId.
*
* @return The value of ShipmentId.
*/
public String getShipmentId() {
return shipmentId;
}
/**
* Set the value of ShipmentId.
*
* @param shipmentId
* The new value to set.
*/
public void setShipmentId(String shipmentId) {
this.shipmentId = shipmentId;
}
/**
* Check to see if ShipmentId is set.
*
* @return true if ShipmentId is set.
*/
public boolean isSetShipmentId() {
return shipmentId != null;
}
/**
* Set the value of ShipmentId, return this.
*
* @param shipmentId
* The new value to set.
*
* @return This instance.
*/
public CreateInboundShipmentRequest withShipmentId(String shipmentId) {
this.shipmentId = shipmentId;
return this;
}
/**
* Get the value of InboundShipmentHeader.
*
* @return The value of InboundShipmentHeader.
*/
public InboundShipmentHeader getInboundShipmentHeader() {
return inboundShipmentHeader;
}
/**
* Set the value of InboundShipmentHeader.
*
* @param inboundShipmentHeader
* The new value to set.
*/
public void setInboundShipmentHeader(InboundShipmentHeader inboundShipmentHeader) {
this.inboundShipmentHeader = inboundShipmentHeader;
}
/**
* Check to see if InboundShipmentHeader is set.
*
* @return true if InboundShipmentHeader is set.
*/
public boolean isSetInboundShipmentHeader() {
return inboundShipmentHeader != null;
}
/**
* Set the value of InboundShipmentHeader, return this.
*
* @param inboundShipmentHeader
* The new value to set.
*
* @return This instance.
*/
public CreateInboundShipmentRequest withInboundShipmentHeader(InboundShipmentHeader inboundShipmentHeader) {
this.inboundShipmentHeader = inboundShipmentHeader;
return this;
}
/**
* Get the value of InboundShipmentItems.
*
* @return The value of InboundShipmentItems.
*/
public InboundShipmentItemList getInboundShipmentItems() {
return inboundShipmentItems;
}
/**
* Set the value of InboundShipmentItems.
*
* @param inboundShipmentItems
* The new value to set.
*/
public void setInboundShipmentItems(InboundShipmentItemList inboundShipmentItems) {
this.inboundShipmentItems = inboundShipmentItems;
}
/**
* Check to see if InboundShipmentItems is set.
*
* @return true if InboundShipmentItems is set.
*/
public boolean isSetInboundShipmentItems() {
return inboundShipmentItems != null;
}
/**
* Set the value of InboundShipmentItems, return this.
*
* @param inboundShipmentItems
* The new value to set.
*
* @return This instance.
*/
public CreateInboundShipmentRequest withInboundShipmentItems(InboundShipmentItemList inboundShipmentItems) {
this.inboundShipmentItems = inboundShipmentItems;
return this;
}
/**
* Read members from a MwsReader.
*
* @param r
* The reader to read from.
*/
@Override
public void readFragmentFrom(MwsReader r) {
sellerId = r.read("SellerId", String.class);
mwsAuthToken = r.read("MWSAuthToken", String.class);
marketplace = r.read("Marketplace", String.class);
shipmentId = r.read("ShipmentId", String.class);
inboundShipmentHeader = r.read("InboundShipmentHeader", InboundShipmentHeader.class);
inboundShipmentItems = r.read("InboundShipmentItems", InboundShipmentItemList.class);
}
/**
* Write members to a MwsWriter.
*
* @param w
* The writer to write to.
*/
@Override
public void writeFragmentTo(MwsWriter w) {
w.write("SellerId", sellerId);
w.write("MWSAuthToken", mwsAuthToken);
w.write("Marketplace", marketplace);
w.write("ShipmentId", shipmentId);
w.write("InboundShipmentHeader", inboundShipmentHeader);
w.write("InboundShipmentItems", inboundShipmentItems);
}
/**
* Write tag, xmlns and members to a MwsWriter.
*
* @param w
* The Writer to write to.
*/
@Override
public void writeTo(MwsWriter w) {
w.write("http://mws.amazonaws.com/FulfillmentInboundShipment/2010-10-01/", "CreateInboundShipmentRequest",this);
}
/** Value constructor. */
public CreateInboundShipmentRequest(String sellerId,String mwsAuthToken,String marketplace,String shipmentId,InboundShipmentHeader inboundShipmentHeader,InboundShipmentItemList inboundShipmentItems) {
this.sellerId = sellerId;
this.mwsAuthToken = mwsAuthToken;
this.marketplace = marketplace;
this.shipmentId = shipmentId;
this.inboundShipmentHeader = inboundShipmentHeader;
this.inboundShipmentItems = inboundShipmentItems;
}
/** Legacy value constructor. */
public CreateInboundShipmentRequest(String sellerId,String marketplace,String shipmentId,InboundShipmentHeader inboundShipmentHeader,InboundShipmentItemList inboundShipmentItems) {
this.sellerId = sellerId;
this.marketplace = marketplace;
this.shipmentId = shipmentId;
this.inboundShipmentHeader = inboundShipmentHeader;
this.inboundShipmentItems = inboundShipmentItems;
}
/** Value constructor. */
public CreateInboundShipmentRequest(String sellerId,InboundShipmentHeader inboundShipmentHeader,InboundShipmentItemList inboundShipmentItems) {
this.sellerId = sellerId;
this.inboundShipmentHeader = inboundShipmentHeader;
this.inboundShipmentItems = inboundShipmentItems;
}
/** Default constructor. */
public CreateInboundShipmentRequest() {
super();
}
}
| |
/*
* Copyright 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy
* of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.google.gwt.debugpanel.models;
import com.google.gwt.debugpanel.common.ExceptionData;
import com.google.gwt.debugpanel.common.StatisticsEvent;
import junit.framework.TestCase;
import org.jmock.Expectations;
import org.jmock.Mockery;
/**
* Tests the {@link GwtExceptionModel}.
*/
public class GwtExceptionModelTest extends TestCase {
private Mockery mockery;
private GwtExceptionModel model;
@Override
protected void setUp() throws Exception {
super.setUp();
mockery = new Mockery();
model = new GwtExceptionModel();
}
public void testModelIsInitiallyEmpty() {
assertEquals(0, model.getExceptionEventCount());
}
public void testNonErrorSubSystemEventsAreIgnored() {
final StatisticsEvent event = mockery.mock(StatisticsEvent.class);
mockery.checking(new Expectations() {{
oneOf(event).getSubSystem(); will(returnValue("system"));
}});
model.onStatisticsEvent(event);
assertEquals(0, model.getExceptionEventCount());
mockery.assertIsSatisfied();
}
public void testNonErrorEventGroupEventsAreIgnored() {
final StatisticsEvent event = mockery.mock(StatisticsEvent.class);
mockery.checking(new Expectations() {{
oneOf(event).getSubSystem(); will(returnValue("error"));
oneOf(event).getEventGroupKey(); will(returnValue("group"));
}});
model.onStatisticsEvent(event);
assertEquals(0, model.getExceptionEventCount());
mockery.assertIsSatisfied();
}
public void testNonErrorTypeEventsAreIgnored() {
final StatisticsEvent event = mockery.mock(StatisticsEvent.class);
mockery.checking(new Expectations() {{
oneOf(event).getSubSystem(); will(returnValue("error"));
oneOf(event).getEventGroupKey(); will(returnValue("error"));
oneOf(event).getExtraParameter("type"); will(returnValue("type"));
}});
model.onStatisticsEvent(event);
assertEquals(0, model.getExceptionEventCount());
mockery.assertIsSatisfied();
}
public void testEventsWithEmptyDataAreIgnored() {
final StatisticsEvent event = mockery.mock(StatisticsEvent.class);
mockery.checking(new Expectations() {{
oneOf(event).getSubSystem(); will(returnValue("error"));
oneOf(event).getEventGroupKey(); will(returnValue("error"));
oneOf(event).getExtraParameter("type"); will(returnValue("error"));
oneOf(event).getExtraParameter("error"); will(returnValue(null));
}});
model.onStatisticsEvent(event);
assertEquals(0, model.getExceptionEventCount());
mockery.assertIsSatisfied();
}
public void testNonJavaSrciptObjectsAreIgnored() {
final StatisticsEvent event = mockery.mock(StatisticsEvent.class);
mockery.checking(new Expectations() {{
oneOf(event).getSubSystem(); will(returnValue("error"));
oneOf(event).getEventGroupKey(); will(returnValue("error"));
oneOf(event).getExtraParameter("type"); will(returnValue("error"));
oneOf(event).getExtraParameter("error"); will(returnValue("aString"));
}});
model.onStatisticsEvent(event);
assertEquals(0, model.getExceptionEventCount());
mockery.assertIsSatisfied();
}
public void testJavaScriptObjectIsNotIgnored() {
final StatisticsEvent event = mockery.mock(StatisticsEvent.class);
mockery.checking(new Expectations() {{
oneOf(event).getSubSystem(); will(returnValue("error"));
oneOf(event).getEventGroupKey(); will(returnValue("error"));
oneOf(event).getExtraParameter("type"); will(returnValue("error"));
oneOf(event).getExtraParameter("error"); will(returnValue(new ExceptionData() {}));
oneOf(event).getModuleName(); will(returnValue("module"));
oneOf(event).getMillis(); will(returnValue(123.0));
}});
model.onStatisticsEvent(event);
assertEquals(1, model.getExceptionEventCount());
mockery.assertIsSatisfied();
}
public void testRemoveOfOnlyEvent() {
model.add(new ExceptionModel.ExceptionEvent(null, 0, null));
assertEquals(1, model.getExceptionEventCount());
model.removeExceptionEvent(0);
assertEquals(0, model.getExceptionEventCount());
}
public void testRemoveOfEvent() {
model.add(new ExceptionModel.ExceptionEvent(null, 0, null));
model.add(new ExceptionModel.ExceptionEvent(null, 1, null));
model.add(new ExceptionModel.ExceptionEvent(null, 2, null));
assertEquals(3, model.getExceptionEventCount());
model.removeExceptionEvent(1);
assertEquals(2, model.getExceptionEventCount());
assertEquals(0.0, model.getExceptionEvent(0).time);
assertEquals(2.0, model.getExceptionEvent(1).time);
}
public void testAddFiresEvent() {
final ExceptionModelListener listener = mockery.mock(ExceptionModelListener.class);
final ExceptionModel.ExceptionEvent ev0 = new ExceptionModel.ExceptionEvent(null, 0, null);
final ExceptionModel.ExceptionEvent ev1 = new ExceptionModel.ExceptionEvent(null, 1, null);
final ExceptionModel.ExceptionEvent ev2 = new ExceptionModel.ExceptionEvent(null, 2, null);
mockery.checking(new Expectations() {{
oneOf(listener).exceptionAdded(0, ev0);
oneOf(listener).exceptionAdded(1, ev1);
oneOf(listener).exceptionAdded(2, ev2);
}});
model.addListener(listener);
model.add(ev0);
model.add(ev1);
model.add(ev2);
assertEquals(3, model.getExceptionEventCount());
assertEquals(0.0, model.getExceptionEvent(0).time);
assertEquals(1.0, model.getExceptionEvent(1).time);
assertEquals(2.0, model.getExceptionEvent(2).time);
mockery.assertIsSatisfied();
}
public void testRemoveFiresEvent() {
final ExceptionModelListener listener = mockery.mock(ExceptionModelListener.class);
final ExceptionModel.ExceptionEvent ev0 = new ExceptionModel.ExceptionEvent(null, 0, null);
final ExceptionModel.ExceptionEvent ev1 = new ExceptionModel.ExceptionEvent(null, 1, null);
final ExceptionModel.ExceptionEvent ev2 = new ExceptionModel.ExceptionEvent(null, 2, null);
mockery.checking(new Expectations() {{
allowing(listener).exceptionAdded(
with(any(Integer.class)), with(any(ExceptionModel.ExceptionEvent.class)));
oneOf(listener).exceptionRemoved(1);
}});
model.addListener(listener);
model.add(ev0);
model.add(ev1);
model.add(ev2);
model.removeExceptionEvent(1);
assertEquals(2, model.getExceptionEventCount());
assertEquals(0.0, model.getExceptionEvent(0).time);
assertEquals(2.0, model.getExceptionEvent(1).time);
mockery.assertIsSatisfied();
}
public void testRemovedListenerNoLongerReceivesEvents() {
final ExceptionModelListener listener = mockery.mock(ExceptionModelListener.class);
model.addListener(listener);
model.removeListener(listener);
model.add(new ExceptionModel.ExceptionEvent(null, 0, null));
model.add(new ExceptionModel.ExceptionEvent(null, 1, null));
model.add(new ExceptionModel.ExceptionEvent(null, 2, null));
model.removeExceptionEvent(1);
mockery.assertIsSatisfied();
}
}
| |
package water.rapids;
import water.H2O;
import water.MRTask;
import water.fvec.Chunk;
import water.fvec.Frame;
import water.fvec.NewChunk;
import water.fvec.Vec;
import water.parser.ValueString;
import water.util.ArrayUtils;
import water.util.MathUtils;
import java.util.Arrays;
/**
* Subclasses auto-widen between scalars and Frames, and have exactly two arguments
*/
abstract class ASTBinOp extends ASTPrim {
@Override
public String[] args() { return new String[]{"leftArg", "rightArg"}; }
@Override int nargs() { return 1+2; }
@Override Val apply( Env env, Env.StackHelp stk, AST asts[] ) {
Val left = stk.track(asts[1].exec(env));
Val rite = stk.track(asts[2].exec(env));
return prim_apply(left,rite);
}
Val prim_apply( Val left, Val rite ) {
switch( left.type() ) {
case Val.NUM:
final double dlf = left.getNum();
switch( rite.type() ) {
case Val.NUM: return new ValNum( op (dlf,rite.getNum()));
case Val.FRM: return scalar_op_frame(dlf,rite.getFrame());
case Val.STR: throw H2O.unimpl();
default: throw H2O.fail();
}
case Val.FRM:
Frame flf = left.getFrame();
switch( rite.type() ) {
case Val.NUM: return frame_op_scalar(flf,rite.getNum());
case Val.STR: return frame_op_scalar(flf,rite.getStr());
case Val.FRM: return frame_op_frame (flf,rite.getFrame());
default: throw H2O.fail();
}
case Val.STR:
String slf = left.getStr();
switch( rite.type() ) {
case Val.NUM: throw H2O.unimpl();
case Val.STR: throw H2O.unimpl();
case Val.FRM: return scalar_op_frame(slf,rite.getFrame());
default: throw H2O.fail();
}
case Val.ROW:
double dslf[] = left.getRow();
switch( rite.type() ) {
case Val.NUM: throw H2O.unimpl();
case Val.ROW: return row_op_row(dslf,rite.getRow());
default: throw H2O.fail();
}
default: throw H2O.fail();
}
}
/** Override to express a basic math primitive */
abstract double op( double l, double r );
double str_op( ValueString l, ValueString r ) { throw H2O.fail(); }
/** Auto-widen the scalar to every element of the frame */
private ValFrame scalar_op_frame( final double d, Frame fr ) {
Frame res = new MRTask() {
@Override public void map( Chunk[] chks, NewChunk[] cress ) {
for( int c=0; c<chks.length; c++ ) {
Chunk chk = chks[c];
NewChunk cres = cress[c];
for( int i=0; i<chk._len; i++ )
cres.addNum(op(d,chk.atd(i)));
}
}
}.doAll(fr.numCols(),fr).outputFrame(fr._names,null);
return cleanEnum( fr, res ); // Cleanup enum misuse
}
/** Auto-widen the scalar to every element of the frame */
ValFrame frame_op_scalar( Frame fr, final double d ) {
Frame res = new MRTask() {
@Override public void map( Chunk[] chks, NewChunk[] cress ) {
for( int c=0; c<chks.length; c++ ) {
Chunk chk = chks[c];
NewChunk cres = cress[c];
for( int i=0; i<chk._len; i++ )
cres.addNum(op(chk.atd(i),d));
}
}
}.doAll(fr.numCols(),fr).outputFrame(fr._names,null);
return cleanEnum( fr, res ); // Cleanup enum misuse
}
// Ops do not make sense on Enums, except EQ/NE; flip such ops to NAs
private ValFrame cleanEnum( Frame oldfr, Frame newfr ) {
final boolean enumOK = enumOK();
final Vec oldvecs[] = oldfr.vecs();
final Vec newvecs[] = newfr.vecs();
for( int i=0; i<oldvecs.length; i++ )
if( !oldvecs[i].isNumeric() && // Must be numeric OR
!oldvecs[i].isTime() && // time OR
!(oldvecs[i].isEnum() && enumOK) ) // Enum and enums are OK (op is EQ/NE)
newvecs[i] = newvecs[i].makeCon(Double.NaN);
return new ValFrame(newfr);
}
/** Auto-widen the scalar to every element of the frame */
private ValFrame frame_op_scalar( Frame fr, final String str ) {
Frame res = new MRTask() {
@Override public void map( Chunk[] chks, NewChunk[] cress ) {
ValueString vstr = new ValueString();
for( int c=0; c<chks.length; c++ ) {
Chunk chk = chks[c];
NewChunk cres = cress[c];
Vec vec = chk.vec();
// String Vectors: apply str_op as ValueStrings to all elements
if( vec.isString() ) {
final ValueString conStr = new ValueString(str);
for( int i=0; i<chk._len; i++ )
cres.addNum(str_op(chk.atStr(vstr,i),conStr));
} else if( vec.isEnum() ) {
// Enum Vectors: convert string to domain value; apply op (not
// str_op). Not sure what the "right" behavior here is, can
// easily argue that should instead apply str_op to the Enum
// string domain value - except that this whole operation only
// makes sense for EQ/NE, and is much faster when just comparing
// doubles vs comparing strings. Note that if the string is not
// part of the Enum domain, the find op returns -1 which is never
// equal to any Enum dense integer (which are always 0+).
final double d = (double)ArrayUtils.find(vec.domain(),str);
for( int i=0; i<chk._len; i++ )
cres.addNum(op(chk.atd(i),d));
} else { // mixing string and numeric
final double d = op(1,2); // false or true only
for( int i=0; i<chk._len; i++ )
cres.addNum(d);
}
}
}
}.doAll(fr.numCols(),fr).outputFrame(fr._names,null);
return new ValFrame(res);
}
/** Auto-widen the scalar to every element of the frame */
private ValFrame scalar_op_frame( final String str, Frame fr ) {
Frame res = new MRTask() {
@Override public void map( Chunk[] chks, NewChunk[] cress ) {
ValueString vstr = new ValueString();
for( int c=0; c<chks.length; c++ ) {
Chunk chk = chks[c];
NewChunk cres = cress[c];
Vec vec = chk.vec();
// String Vectors: apply str_op as ValueStrings to all elements
if( vec.isString() ) {
final ValueString conStr = new ValueString(str);
for( int i=0; i<chk._len; i++ )
cres.addNum(str_op(conStr,chk.atStr(vstr,i)));
} else if( vec.isEnum() ) {
// Enum Vectors: convert string to domain value; apply op (not
// str_op). Not sure what the "right" behavior here is, can
// easily argue that should instead apply str_op to the Enum
// string domain value - except that this whole operation only
// makes sense for EQ/NE, and is much faster when just comparing
// doubles vs comparing strings.
final double d = (double)ArrayUtils.find(vec.domain(),str);
for( int i=0; i<chk._len; i++ )
cres.addNum(op(d,chk.atd(i)));
} else { // mixing string and numeric
final double d = op(1,2); // false or true only
for( int i=0; i<chk._len; i++ )
cres.addNum(d);
}
}
}
}.doAll(fr.numCols(),fr).outputFrame(fr._names,null);
return new ValFrame(res);
}
/** Auto-widen: If one frame has only 1 column, auto-widen that 1 column to
* the rest. Otherwise the frames must have the same column count, and
* auto-widen element-by-element. Short-cut if one frame has zero
* columns. */
private ValFrame frame_op_frame( Frame lf, Frame rt ) {
if( lf.numRows() != rt.numRows() )
throw new IllegalArgumentException("Frames must have same rows, found "+lf.numRows()+" rows and "+rt.numRows()+" rows.");
if( lf.numCols() == 0 ) return new ValFrame(lf);
if( rt.numCols() == 0 ) return new ValFrame(rt);
if( lf.numCols() == 1 && rt.numCols() > 1 ) return vec_op_frame(lf.vecs()[0],rt);
if( rt.numCols() == 1 && lf.numCols() > 1 ) return frame_op_vec(lf,rt.vecs()[0]);
if( lf.numCols() != rt.numCols() )
throw new IllegalArgumentException("Frames must have same columns, found "+lf.numCols()+" columns and "+rt.numCols()+" columns.");
return new ValFrame(new MRTask() {
@Override public void map( Chunk[] chks, NewChunk[] cress ) {
assert (cress.length<<1) == chks.length;
for( int c=0; c<cress.length; c++ ) {
Chunk clf = chks[c];
Chunk crt = chks[c+cress.length];
NewChunk cres = cress[c];
for( int i=0; i<clf._len; i++ )
cres.addNum(op(clf.atd(i),crt.atd(i)));
}
}
}.doAll(lf.numCols(),new Frame(lf).add(rt)).outputFrame(lf._names,null));
}
private ValRow row_op_row( double[] lf, double[] rt ) {
double[] res = new double[lf.length];
for( int i=0; i<lf.length; i++ )
res[i] = op(lf[i],rt[i]);
return new ValRow(res);
}
private ValFrame vec_op_frame( Vec vec, Frame fr ) {
throw H2O.unimpl();
}
private ValFrame frame_op_vec( Frame fr, Vec vec ) {
throw H2O.unimpl();
}
// Make sense to run this OP on an enm?
boolean enumOK() { return false; }
}
// ----------------------------------------------------------------------------
// Expressions that auto-widen between NUM and FRM
class ASTAnd extends ASTBinOp { public String str() { return "&" ; } double op( double l, double r ) { return ASTLAnd.and_op(l,r); } }
class ASTDiv extends ASTBinOp { public String str() { return "/" ; } double op( double l, double r ) { return l/r;}}
class ASTMod extends ASTBinOp { public String str() { return "mod";} double op( double l, double r ) { return l%r;}}
class ASTMul extends ASTBinOp { public String str() { return "*" ; } double op( double l, double r ) { return l*r;}}
class ASTOr extends ASTBinOp { public String str() { return "|" ; } double op( double l, double r ) { return ASTLOr . or_op(l,r); } }
class ASTPlus extends ASTBinOp { public String str() { return "+" ; } double op( double l, double r ) { return l+ r; } }
class ASTPow extends ASTBinOp { public String str() { return "^" ; } double op( double l, double r ) { return Math.pow(l,r); } }
class ASTSub extends ASTBinOp { public String str() { return "-" ; } double op( double l, double r ) { return l- r; } }
class ASTIntDiv extends ASTBinOp { public String str() { return "intDiv"; } double op(double l, double r) { return (int)l/(int)r;}}
class ASTRound extends ASTBinOp {
public String str() { return "round"; }
double op(double x, double digits) {
// e.g.: floor(2.676*100 + 0.5) / 100 => 2.68
if(Double.isNaN(x)) return x;
double sgn = x < 0 ? -1 : 1;
x = Math.abs(x);
double power_of_10 = (int)Math.pow(10, (int)digits);
return sgn*(digits == 0
// go to the even digit
? (x % 1 >= 0.5 && !(Math.floor(x)%2==0))
? Math.ceil(x)
: Math.floor(x)
: Math.floor(x * power_of_10 + 0.5) / power_of_10);
}
}
class ASTSignif extends ASTBinOp {
public String str() { return "signif"; }
double op(double x, double digits) {
if(Double.isNaN(x)) return x;
java.math.BigDecimal bd = new java.math.BigDecimal(x);
bd = bd.round(new java.math.MathContext((int)digits, java.math.RoundingMode.HALF_EVEN));
return bd.doubleValue();
}
}
class ASTGE extends ASTBinOp { public String str() { return ">="; } double op( double l, double r ) { return l>=r?1:0; } }
class ASTGT extends ASTBinOp { public String str() { return ">" ; } double op( double l, double r ) { return l> r?1:0; } }
class ASTLE extends ASTBinOp { public String str() { return "<="; } double op( double l, double r ) { return l<=r?1:0; } }
class ASTLT extends ASTBinOp { public String str() { return "<" ; } double op( double l, double r ) { return l< r?1:0; } }
class ASTEQ extends ASTBinOp { public String str() { return "=="; } double op( double l, double r ) { return MathUtils.equalsWithinOneSmallUlp(l,r)?1:0; }
double str_op( ValueString l, ValueString r ) { return l==null ? (r==null?1:0) : (l.equals(r) ? 1 : 0); }
@Override ValFrame frame_op_scalar( Frame fr, final double d ) {
return new ValFrame(new MRTask() {
@Override public void map( Chunk[] chks, NewChunk[] cress ) {
for( int c=0; c<chks.length; c++ ) {
Chunk chk = chks[c];
NewChunk cres = cress[c];
if( !chk.vec().isNumeric() ) cres.addZeros(chk._len);
else
for( int i=0; i<chk._len; i++ )
cres.addNum(op(chk.atd(i),d));
}
}
}.doAll(fr.numCols(),fr).outputFrame());
}
@Override boolean enumOK() { return true; } // Make sense to run this OP on an enm?
}
class ASTNE extends ASTBinOp { public String str() { return "!="; } double op( double l, double r ) { return MathUtils.equalsWithinOneSmallUlp(l,r)?0:1; }
double str_op( ValueString l, ValueString r ) { return l==null ? (r==null?0:1) : (l.equals(r) ? 0 : 1); }
@Override boolean enumOK() { return true; } // Make sense to run this OP on an enm?
}
// ----------------------------------------------------------------------------
// Logical-AND. If the first arg is false, do not execute the 2nd arg.
class ASTLAnd extends ASTBinOp {
public String str() { return "&&"; }
@Override Val apply( Env env, Env.StackHelp stk, AST asts[] ) {
Val left = stk.track(asts[1].exec(env));
// If the left is zero or NA, do not evaluate the right, just return the left
if( left.isNum() ) {
double d = ((ValNum)left)._d;
if( d==0 || Double.isNaN(d) ) return left;
}
Val rite = stk.track(asts[2].exec(env));
return prim_apply(left,rite);
}
// Weird R semantics, zero trumps NA
double op( double l, double r ) { return and_op(l,r); }
static double and_op( double l, double r ) {
return (l==0||r==0) ? 0 : (Double.isNaN(l) || Double.isNaN(r) ? Double.NaN : 1);
}
}
// Logical-OR. If the first arg is true, do not execute the 2nd arg.
class ASTLOr extends ASTBinOp {
public String str() { return "||"; }
@Override Val apply( Env env, Env.StackHelp stk, AST asts[] ) {
Val left = stk.track(asts[1].exec(env));
// If the left is non-zero or NA, do not evaluate the right, just return the left
if( left.isNum() ) {
double d = ((ValNum)left)._d;
if( d!=0 || Double.isNaN(d) ) return left;
}
Val rite = stk.track(asts[2].exec(env));
return prim_apply(left,rite);
}
// Weird R semantics, zero trumps NA
double op( double l, double r ) { return or_op(l,r); }
static double or_op( double l, double r ) {
return (l!=0||r!=0) ? 1 : (Double.isNaN(l) || Double.isNaN(r) ? Double.NaN : 0);
}
}
// IfElse.
//
// "NaNs poison". If the test is a NaN, evaluate neither side and return a NaN
//
// "Frames poison". If the test is a Frame, both sides are evaluated and
// selected between according to the test. The result is a Frame. All Frames
// must be compatible, and scalars and 1-column Frames are widened to match the
// widest frame. NaN test values produce NaN results.
//
// If the test is a scalar, then only the returned side is evaluated. If both
// sides are scalars or frames, then the evaluated result is returned. The
// unevaluated side is not checked for being a compatible frame. It is an
// error if one side is typed as a scalar and the other as a Frame.
//
class ASTIfElse extends ASTPrim {
@Override
public String[] args() { return new String[]{"test","true","false"}; }
@Override int nargs() { return 1+3; } // (ifelse test true false)
public String str() { return "ifelse"; }
@Override Val apply( Env env, Env.StackHelp stk, AST asts[] ) {
Val val = stk.track(asts[1].exec(env));
if( val.isNum() ) { // Scalar test, scalar result
double d = val.getNum();
if( Double.isNaN(d) ) return new ValNum(Double.NaN);
Val res = stk.track(asts[d==0 ? 3 : 2].exec(env)); // exec only 1 of false and true
return res.isFrame() ? new ValNum(res.getFrame().vec(0).at(0)) : res;
}
// Frame test. Frame result.
Frame tst = val.getFrame();
// If all zero's, return false and never execute true.
Frame fr = new Frame(tst);
Val tval = null;
for( Vec vec : tst.vecs() )
if( vec.min()!=0 || vec.max()!= 0 ) {
tval = exec_check(env,stk,tst,asts[2],fr);
break;
}
final boolean has_tfr = tval != null && tval.isFrame();
final double td = (tval != null && tval.isNum()) ? tval.getNum() : Double.NaN;
// If all nonzero's (or NA's), then never execute false.
Val fval = null;
for( Vec vec : tst.vecs() )
if( vec.nzCnt()+vec.naCnt() < vec.length() ) {
fval = exec_check(env,stk,tst,asts[3],fr);
break;
}
final boolean has_ffr = fval != null && fval.isFrame();
final double fd = (fval != null && fval.isNum()) ? fval.getNum() : Double.NaN;
// Now pick from left-or-right in the new frame
Frame res = new MRTask() {
@Override public void map( Chunk chks[], NewChunk nchks[] ) {
assert nchks.length+(has_tfr ? nchks.length : 0)+(has_ffr ? nchks.length : 0) == chks.length;
for( int i=0; i<nchks.length; i++ ) {
Chunk ctst = chks[i];
NewChunk res = nchks[i];
for( int row=0; row<ctst._len; row++ ) {
double d;
if( ctst.isNA(row) ) d = Double.NaN;
else if( ctst.atd(row)==0 ) d = has_ffr ? chks[i+nchks.length+(has_tfr ? nchks.length : 0)].atd(row) : fd;
else d = has_tfr ? chks[i+nchks.length ].atd(row) : td;
res.addNum(d);
}
}
}
}.doAll(tst.numCols(),fr).outputFrame();
return new ValFrame(res);
}
Val exec_check( Env env, Env.StackHelp stk, Frame tst, AST ast, Frame xfr ) {
Val val = ast.exec(env);
if( val.isFrame() ) {
Frame fr = stk.track(val).getFrame();
if( tst.numCols() != fr.numCols() || tst.numRows() != fr.numRows() )
throw new IllegalArgumentException("ifelse test frame and other frames must match dimensions, found "+tst+" and "+fr);
xfr.add(fr);
}
return val;
}
}
// Center and scale a frame. Can be passed in the centers and scales (one per
// column in an number list), or a TRUE/FALSE.
class ASTScale extends ASTPrim {
@Override
public String[] args() { return new String[]{"ary", "center", "scale"}; }
@Override int nargs() { return 1+3; } // (scale x center scale)
@Override
public String str() { return "scale"; }
@Override Val apply( Env env, Env.StackHelp stk, AST asts[] ) {
Frame fr = stk.track(asts[1].exec(env)).getFrame();
int ncols = fr.numCols();
// Peel out the bias/shift/mean
double[] means;
if( asts[2] instanceof ASTNumList ) {
means = ((ASTNumList)asts[2]).expand();
if( means.length != ncols )
throw new IllegalArgumentException("Numlist must be the same length as the columns of the Frame");
} else {
double d = asts[2].exec(env).getNum();
if( d==0 ) means = new double[ncols]; // No change on means, so zero-filled
else if( d==1 ) means = fr.means();
else throw new IllegalArgumentException("Only true or false allowed");
}
// Peel out the scale/stddev
double[] mults;
if( asts[3] instanceof ASTNumList ) {
mults = ((ASTNumList)asts[3]).expand();
if( mults.length != ncols )
throw new IllegalArgumentException("Numlist must be the same length as the columns of the Frame");
} else {
Val v = asts[3].exec(env);
if( v instanceof ValFrame ) {
mults = toArray(v.getFrame().anyVec());
} else {
double d = v.getNum();
if (d == 0)
Arrays.fill(mults = new double[ncols], 1.0); // No change on mults, so one-filled
else if (d == 1) mults = fr.mults();
else throw new IllegalArgumentException("Only true or false allowed");
}
}
// Update in-place.
final double[] fmeans = means; // Make final copy for closure
final double[] fmults = mults; // Make final copy for closure
new MRTask() {
@Override public void map( Chunk[] cs ) {
for( int i=0; i<cs.length; i++ )
for( int row=0; row<cs[i]._len; row++ )
cs[i].set(row,(cs[i].atd(row)-fmeans[i])*fmults[i]);
}
}.doAll(fr);
return new ValFrame(fr);
}
private static double[] toArray(Vec v) {
double[] res = new double[(int)v.length()];
for(int i=0;i<res.length;++i)
res[i] = v.at(i);
return res;
}
}
| |
/*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.cloudfront.model;
import java.io.Serializable;
import com.amazonaws.AmazonWebServiceRequest;
/**
* Container for the parameters to the {@link com.amazonaws.services.cloudfront.AmazonCloudFront#updateCloudFrontOriginAccessIdentity(UpdateCloudFrontOriginAccessIdentityRequest) UpdateCloudFrontOriginAccessIdentity operation}.
* <p>
* Update an origin access identity.
* </p>
*
* @see com.amazonaws.services.cloudfront.AmazonCloudFront#updateCloudFrontOriginAccessIdentity(UpdateCloudFrontOriginAccessIdentityRequest)
*/
public class UpdateCloudFrontOriginAccessIdentityRequest extends AmazonWebServiceRequest implements Serializable, Cloneable {
/**
* The identity's configuration information.
*/
private CloudFrontOriginAccessIdentityConfig cloudFrontOriginAccessIdentityConfig;
/**
* The identity's id.
*/
private String id;
/**
* The value of the ETag header you received when retrieving the
* identity's configuration. For example: E2QWRUHAPOMQZL.
*/
private String ifMatch;
/**
* Default constructor for a new UpdateCloudFrontOriginAccessIdentityRequest object. Callers should use the
* setter or fluent setter (with...) methods to initialize this object after creating it.
*/
public UpdateCloudFrontOriginAccessIdentityRequest() {}
/**
* Constructs a new UpdateCloudFrontOriginAccessIdentityRequest object.
* Callers should use the setter or fluent setter (with...) methods to
* initialize any additional object members.
*
* @param cloudFrontOriginAccessIdentityConfig The identity's
* configuration information.
* @param id The identity's id.
* @param ifMatch The value of the ETag header you received when
* retrieving the identity's configuration. For example: E2QWRUHAPOMQZL.
*/
public UpdateCloudFrontOriginAccessIdentityRequest(CloudFrontOriginAccessIdentityConfig cloudFrontOriginAccessIdentityConfig, String id, String ifMatch) {
setCloudFrontOriginAccessIdentityConfig(cloudFrontOriginAccessIdentityConfig);
setId(id);
setIfMatch(ifMatch);
}
/**
* The identity's configuration information.
*
* @return The identity's configuration information.
*/
public CloudFrontOriginAccessIdentityConfig getCloudFrontOriginAccessIdentityConfig() {
return cloudFrontOriginAccessIdentityConfig;
}
/**
* The identity's configuration information.
*
* @param cloudFrontOriginAccessIdentityConfig The identity's configuration information.
*/
public void setCloudFrontOriginAccessIdentityConfig(CloudFrontOriginAccessIdentityConfig cloudFrontOriginAccessIdentityConfig) {
this.cloudFrontOriginAccessIdentityConfig = cloudFrontOriginAccessIdentityConfig;
}
/**
* The identity's configuration information.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param cloudFrontOriginAccessIdentityConfig The identity's configuration information.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public UpdateCloudFrontOriginAccessIdentityRequest withCloudFrontOriginAccessIdentityConfig(CloudFrontOriginAccessIdentityConfig cloudFrontOriginAccessIdentityConfig) {
this.cloudFrontOriginAccessIdentityConfig = cloudFrontOriginAccessIdentityConfig;
return this;
}
/**
* The identity's id.
*
* @return The identity's id.
*/
public String getId() {
return id;
}
/**
* The identity's id.
*
* @param id The identity's id.
*/
public void setId(String id) {
this.id = id;
}
/**
* The identity's id.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param id The identity's id.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public UpdateCloudFrontOriginAccessIdentityRequest withId(String id) {
this.id = id;
return this;
}
/**
* The value of the ETag header you received when retrieving the
* identity's configuration. For example: E2QWRUHAPOMQZL.
*
* @return The value of the ETag header you received when retrieving the
* identity's configuration. For example: E2QWRUHAPOMQZL.
*/
public String getIfMatch() {
return ifMatch;
}
/**
* The value of the ETag header you received when retrieving the
* identity's configuration. For example: E2QWRUHAPOMQZL.
*
* @param ifMatch The value of the ETag header you received when retrieving the
* identity's configuration. For example: E2QWRUHAPOMQZL.
*/
public void setIfMatch(String ifMatch) {
this.ifMatch = ifMatch;
}
/**
* The value of the ETag header you received when retrieving the
* identity's configuration. For example: E2QWRUHAPOMQZL.
* <p>
* Returns a reference to this object so that method calls can be chained together.
*
* @param ifMatch The value of the ETag header you received when retrieving the
* identity's configuration. For example: E2QWRUHAPOMQZL.
*
* @return A reference to this updated object so that method calls can be chained
* together.
*/
public UpdateCloudFrontOriginAccessIdentityRequest withIfMatch(String ifMatch) {
this.ifMatch = ifMatch;
return this;
}
/**
* Returns a string representation of this object; useful for testing and
* debugging.
*
* @return A string representation of this object.
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("{");
if (getCloudFrontOriginAccessIdentityConfig() != null) sb.append("CloudFrontOriginAccessIdentityConfig: " + getCloudFrontOriginAccessIdentityConfig() + ",");
if (getId() != null) sb.append("Id: " + getId() + ",");
if (getIfMatch() != null) sb.append("IfMatch: " + getIfMatch() );
sb.append("}");
return sb.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int hashCode = 1;
hashCode = prime * hashCode + ((getCloudFrontOriginAccessIdentityConfig() == null) ? 0 : getCloudFrontOriginAccessIdentityConfig().hashCode());
hashCode = prime * hashCode + ((getId() == null) ? 0 : getId().hashCode());
hashCode = prime * hashCode + ((getIfMatch() == null) ? 0 : getIfMatch().hashCode());
return hashCode;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (obj instanceof UpdateCloudFrontOriginAccessIdentityRequest == false) return false;
UpdateCloudFrontOriginAccessIdentityRequest other = (UpdateCloudFrontOriginAccessIdentityRequest)obj;
if (other.getCloudFrontOriginAccessIdentityConfig() == null ^ this.getCloudFrontOriginAccessIdentityConfig() == null) return false;
if (other.getCloudFrontOriginAccessIdentityConfig() != null && other.getCloudFrontOriginAccessIdentityConfig().equals(this.getCloudFrontOriginAccessIdentityConfig()) == false) return false;
if (other.getId() == null ^ this.getId() == null) return false;
if (other.getId() != null && other.getId().equals(this.getId()) == false) return false;
if (other.getIfMatch() == null ^ this.getIfMatch() == null) return false;
if (other.getIfMatch() != null && other.getIfMatch().equals(this.getIfMatch()) == false) return false;
return true;
}
@Override
public UpdateCloudFrontOriginAccessIdentityRequest clone() {
return (UpdateCloudFrontOriginAccessIdentityRequest) super.clone();
}
}
| |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.ui.tablet;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.BaseActivity;
import com.google.android.apps.iosched.ui.MapFragment;
import com.google.android.apps.iosched.ui.SessionDetailFragment;
import com.google.android.apps.iosched.ui.SessionsFragment;
import com.google.android.apps.iosched.ui.VendorDetailFragment;
import com.google.android.apps.iosched.ui.VendorsFragment;
import android.annotation.TargetApi;
import android.app.FragmentBreadCrumbs;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
/**
* A multi-pane activity, where the full-screen content is a {@link MapFragment} and popup content
* may be visible at any given time, containing either a {@link SessionsFragment} (representing
* sessions for a given room) or a {@link SessionDetailFragment}.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class MapMultiPaneActivity extends BaseActivity implements
FragmentManager.OnBackStackChangedListener,
MapFragment.Callbacks,
SessionsFragment.Callbacks,
LoaderManager.LoaderCallbacks<Cursor> {
private boolean mPauseBackStackWatcher = false;
private FragmentBreadCrumbs mFragmentBreadCrumbs;
private String mSelectedRoomName;
private MapFragment mMapFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
FragmentManager fm = getSupportFragmentManager();
fm.addOnBackStackChangedListener(this);
mFragmentBreadCrumbs = (FragmentBreadCrumbs) findViewById(R.id.breadcrumbs);
mFragmentBreadCrumbs.setActivity(this);
mMapFragment = (MapFragment) fm.findFragmentByTag("map");
if (mMapFragment == null) {
mMapFragment = new MapFragment();
mMapFragment.setArguments(intentToFragmentArguments(getIntent()));
fm.beginTransaction()
.add(R.id.fragment_container_map, mMapFragment, "map")
.commit();
}
findViewById(R.id.close_button).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
clearBackStack(false);
}
});
updateBreadCrumbs();
onConfigurationChanged(getResources().getConfiguration());
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
boolean landscape = (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE);
LinearLayout spacerView = (LinearLayout) findViewById(R.id.map_detail_spacer);
spacerView.setOrientation(landscape ? LinearLayout.HORIZONTAL : LinearLayout.VERTICAL);
spacerView.setGravity(landscape ? Gravity.RIGHT : Gravity.BOTTOM);
View popupView = findViewById(R.id.map_detail_popup);
LinearLayout.LayoutParams popupLayoutParams = (LinearLayout.LayoutParams)
popupView.getLayoutParams();
popupLayoutParams.width = landscape ? 0 : ViewGroup.LayoutParams.MATCH_PARENT;
popupLayoutParams.height = landscape ? ViewGroup.LayoutParams.MATCH_PARENT : 0;
popupView.setLayoutParams(popupLayoutParams);
popupView.requestLayout();
}
private void clearBackStack(boolean pauseWatcher) {
if (pauseWatcher) {
mPauseBackStackWatcher = true;
}
FragmentManager fm = getSupportFragmentManager();
while (fm.getBackStackEntryCount() > 0) {
fm.popBackStackImmediate();
}
if (pauseWatcher) {
mPauseBackStackWatcher = false;
}
}
public void onBackStackChanged() {
if (mPauseBackStackWatcher) {
return;
}
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
showDetailPane(false);
}
updateBreadCrumbs();
}
private void showDetailPane(boolean show) {
View detailPopup = findViewById(R.id.map_detail_spacer);
if (show != (detailPopup.getVisibility() == View.VISIBLE)) {
detailPopup.setVisibility(show ? View.VISIBLE : View.GONE);
// Pan the map left or up depending on the orientation.
boolean landscape = getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE;
mMapFragment.panBy(
landscape ? (show ? 0.25f : -0.25f) : 0,
landscape ? 0 : (show ? 0.25f : -0.25f));
}
}
public void updateBreadCrumbs() {
final String title = (mSelectedRoomName != null)
? mSelectedRoomName
: getString(R.string.title_sessions);
final String detailTitle = getString(R.string.title_session_detail);
if (getSupportFragmentManager().getBackStackEntryCount() >= 2) {
mFragmentBreadCrumbs.setParentTitle(title, title, mFragmentBreadCrumbsClickListener);
mFragmentBreadCrumbs.setTitle(detailTitle, detailTitle);
} else {
mFragmentBreadCrumbs.setParentTitle(null, null, null);
mFragmentBreadCrumbs.setTitle(title, title);
}
}
private View.OnClickListener mFragmentBreadCrumbsClickListener = new View.OnClickListener() {
@Override
public void onClick(View view) {
getSupportFragmentManager().popBackStack();
}
};
@Override
public void onRoomSelected(String roomId) {
// Load room details
mSelectedRoomName = null;
Bundle loadRoomDataArgs = new Bundle();
loadRoomDataArgs.putString("room_id", roomId);
getSupportLoaderManager().restartLoader(0, loadRoomDataArgs, this); // force load
// Show the sessions in the room
clearBackStack(true);
showDetailPane(true);
SessionsFragment fragment = new SessionsFragment();
fragment.setArguments(BaseActivity.intentToFragmentArguments(
new Intent(Intent.ACTION_VIEW,
ScheduleContract.Rooms.buildSessionsDirUri(roomId))));
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container_detail, fragment)
.addToBackStack(null)
.commit();
updateBreadCrumbs();
}
@Override
public boolean onSessionSelected(String sessionId) {
// Show the session details
showDetailPane(true);
SessionDetailFragment fragment = new SessionDetailFragment();
Intent intent = new Intent(Intent.ACTION_VIEW,
ScheduleContract.Sessions.buildSessionUri(sessionId));
intent.putExtra(SessionDetailFragment.EXTRA_VARIABLE_HEIGHT_HEADER, true);
fragment.setArguments(BaseActivity.intentToFragmentArguments(intent));
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container_detail, fragment)
.addToBackStack(null)
.commit();
updateBreadCrumbs();
return false;
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle data) {
return new CursorLoader(this,
ScheduleContract.Rooms.buildRoomUri(data.getString("room_id")),
RoomsQuery.PROJECTION,
null, null, null);
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
try {
if (!cursor.moveToFirst()) {
return;
}
mSelectedRoomName = cursor.getString(RoomsQuery.ROOM_NAME);
updateBreadCrumbs();
} finally {
cursor.close();
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
}
private interface RoomsQuery {
String[] PROJECTION = {
ScheduleContract.Rooms.ROOM_ID,
ScheduleContract.Rooms.ROOM_NAME,
ScheduleContract.Rooms.ROOM_FLOOR,
};
int ROOM_ID = 0;
int ROOM_NAME = 1;
int ROOM_FLOOR = 2;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.artemis.tests.integration.amqp;
import static org.apache.activemq.transport.amqp.AmqpSupport.JMS_SELECTOR_FILTER_IDS;
import static org.apache.activemq.transport.amqp.AmqpSupport.NO_LOCAL_FILTER_IDS;
import static org.apache.activemq.transport.amqp.AmqpSupport.findFilter;
import static org.apache.activemq.transport.amqp.AmqpSupport.contains;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import org.apache.activemq.artemis.core.server.Queue;
import org.apache.activemq.artemis.protocol.amqp.proton.AmqpSupport;
import org.apache.activemq.artemis.tests.util.Wait;
import org.apache.activemq.transport.amqp.client.AmqpClient;
import org.apache.activemq.transport.amqp.client.AmqpConnection;
import org.apache.activemq.transport.amqp.client.AmqpMessage;
import org.apache.activemq.transport.amqp.client.AmqpReceiver;
import org.apache.activemq.transport.amqp.client.AmqpSender;
import org.apache.activemq.transport.amqp.client.AmqpSession;
import org.apache.activemq.transport.amqp.client.AmqpValidator;
import org.apache.qpid.proton.amqp.Symbol;
import org.apache.qpid.proton.amqp.messaging.Source;
import org.apache.qpid.proton.engine.Receiver;
import org.apache.qpid.proton.engine.Sender;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jms.JMSException;
/**
* Test basic send and receive scenarios using only AMQP sender and receiver links.
*/
public class AmqpSendReceiveTest extends AmqpClientTestSupport {
protected static final Logger LOG = LoggerFactory.getLogger(AmqpSendReceiveTest.class);
@Test(timeout = 60000)
public void testCreateQueueReceiver() throws Exception {
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpReceiver receiver = session.createReceiver(getTestName());
Queue queue = getProxyToQueue(getTestName());
assertNotNull(queue);
receiver.close();
connection.close();
}
@Test(timeout = 60000)
public void testCreateQueueReceiverWithJMSSelector() throws Exception {
AmqpClient client = createAmqpClient();
client.setValidator(new AmqpValidator() {
@SuppressWarnings("unchecked")
@Override
public void inspectOpenedResource(Receiver receiver) {
if (receiver.getRemoteSource() == null) {
markAsInvalid("Link opened with null source.");
}
Source source = (Source) receiver.getRemoteSource();
Map<Symbol, Object> filters = source.getFilter();
if (findFilter(filters, JMS_SELECTOR_FILTER_IDS) == null) {
markAsInvalid("Broker did not return the JMS Filter on Attach");
}
}
});
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
session.createReceiver(getTestName(), "JMSPriority > 8");
connection.getStateInspector().assertValid();
connection.close();
}
@Test(timeout = 60000)
public void testCreateQueueReceiverWithNoLocalSet() throws Exception {
AmqpClient client = createAmqpClient();
client.setValidator(new AmqpValidator() {
@SuppressWarnings("unchecked")
@Override
public void inspectOpenedResource(Receiver receiver) {
if (receiver.getRemoteSource() == null) {
markAsInvalid("Link opened with null source.");
}
Source source = (Source) receiver.getRemoteSource();
Map<Symbol, Object> filters = source.getFilter();
// Currently don't support noLocal on a Queue
if (findFilter(filters, NO_LOCAL_FILTER_IDS) != null) {
markAsInvalid("Broker did not return the NoLocal Filter on Attach");
}
}
});
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
session.createReceiver(getTestName(), null, true);
connection.getStateInspector().assertValid();
connection.close();
}
@Test(timeout = 60000)
public void testInvalidFilter() throws Exception {
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
try {
session.createReceiver(getTestName(), "null = 'f''", true);
fail("should throw exception");
} catch (Exception e) {
assertTrue(e.getCause() instanceof JMSException);
//passed
}
connection.close();
}
@Test(timeout = 60000)
public void testQueueReceiverReadMessage() throws Exception {
sendMessages(getTestName(), 1);
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpReceiver receiver = session.createReceiver(getTestName());
Queue queueView = getProxyToQueue(getTestName());
assertEquals(1, queueView.getMessageCount());
receiver.flow(1);
assertNotNull(receiver.receive(5, TimeUnit.SECONDS));
receiver.close();
assertEquals(1, queueView.getMessageCount());
connection.close();
}
@Test(timeout = 60000)
public void testTwoQueueReceiversOnSameConnectionReadMessagesNoDispositions() throws Exception {
int MSG_COUNT = 4;
sendMessages(getTestName(), MSG_COUNT);
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpReceiver receiver1 = session.createReceiver(getTestName());
Queue queueView = getProxyToQueue(getTestName());
assertEquals(MSG_COUNT, queueView.getMessageCount());
receiver1.flow(2);
assertNotNull(receiver1.receive(5, TimeUnit.SECONDS));
assertNotNull(receiver1.receive(5, TimeUnit.SECONDS));
AmqpReceiver receiver2 = session.createReceiver(getTestName());
assertEquals(2, server.getTotalConsumerCount());
receiver2.flow(2);
assertNotNull(receiver2.receive(5, TimeUnit.SECONDS));
assertNotNull(receiver2.receive(5, TimeUnit.SECONDS));
assertEquals(0, queueView.getMessagesAcknowledged());
receiver1.close();
receiver2.close();
assertEquals(MSG_COUNT, queueView.getMessageCount());
connection.close();
}
@Test(timeout = 60000)
public void testTwoQueueReceiversOnSameConnectionReadMessagesAcceptOnEach() throws Exception {
int MSG_COUNT = 4;
sendMessages(getTestName(), MSG_COUNT);
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpReceiver receiver1 = session.createReceiver(getTestName());
final Queue queueView = getProxyToQueue(getTestName());
assertEquals(MSG_COUNT, queueView.getMessageCount());
receiver1.flow(2);
AmqpMessage message = receiver1.receive(5, TimeUnit.SECONDS);
assertNotNull(message);
message.accept();
message = receiver1.receive(5, TimeUnit.SECONDS);
assertNotNull(message);
message.accept();
assertTrue("Should have ack'd two", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisfied() throws Exception {
return queueView.getMessagesAcknowledged() == 2;
}
}, TimeUnit.SECONDS.toMillis(5), TimeUnit.MILLISECONDS.toMillis(50)));
AmqpReceiver receiver2 = session.createReceiver(getTestName());
assertEquals(2, server.getTotalConsumerCount());
receiver2.flow(2);
message = receiver2.receive(5, TimeUnit.SECONDS);
assertNotNull(message);
message.accept();
message = receiver2.receive(5, TimeUnit.SECONDS);
assertNotNull(message);
message.accept();
assertTrue("Queue should be empty now", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisfied() throws Exception {
return queueView.getMessagesAcknowledged() == 4;
}
}, TimeUnit.SECONDS.toMillis(15), TimeUnit.MILLISECONDS.toMillis(10)));
receiver1.close();
receiver2.close();
assertEquals(0, queueView.getMessageCount());
connection.close();
}
@Test(timeout = 60000)
public void testSecondReceiverOnQueueGetsAllUnconsumedMessages() throws Exception {
int MSG_COUNT = 20;
sendMessages(getTestName(), MSG_COUNT);
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpReceiver receiver1 = session.createReceiver(getTestName());
final Queue queueView = getProxyToQueue(getTestName());
assertEquals(MSG_COUNT, queueView.getMessageCount());
receiver1.flow(20);
assertTrue("Should have dispatch to prefetch", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisfied() throws Exception {
return queueView.getDeliveringCount() >= 2;
}
}, TimeUnit.SECONDS.toMillis(5), TimeUnit.MILLISECONDS.toMillis(50)));
receiver1.close();
AmqpReceiver receiver2 = session.createReceiver(getTestName());
assertEquals(1, server.getTotalConsumerCount());
receiver2.flow(MSG_COUNT * 2);
AmqpMessage message = receiver2.receive(5, TimeUnit.SECONDS);
assertNotNull(message);
message.accept();
message = receiver2.receive(5, TimeUnit.SECONDS);
assertNotNull(message);
message.accept();
assertTrue("Should have ack'd two", Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisfied() throws Exception {
return queueView.getMessagesAcknowledged() == 2;
}
}, TimeUnit.SECONDS.toMillis(5), TimeUnit.MILLISECONDS.toMillis(50)));
receiver2.close();
assertEquals(MSG_COUNT - 2, queueView.getMessageCount());
connection.close();
}
@Test(timeout = 60000)
public void testSimpleSendOneReceiveOne() throws Exception {
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(getTestName());
AmqpMessage message = new AmqpMessage();
message.setMessageId("msg" + 1);
message.setMessageAnnotation("serialNo", 1);
message.setText("Test-Message");
sender.send(message);
sender.close();
LOG.info("Attempting to read message with receiver");
AmqpReceiver receiver = session.createReceiver(getTestName());
receiver.flow(2);
AmqpMessage received = receiver.receive(10, TimeUnit.SECONDS);
assertNotNull("Should have read message", received);
assertEquals("msg1", received.getMessageId());
received.accept();
receiver.close();
connection.close();
}
@Test(timeout = 60000)
public void testCloseBusyReceiver() throws Exception {
final int MSG_COUNT = 20;
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(getTestName());
for (int i = 0; i < MSG_COUNT; i++) {
AmqpMessage message = new AmqpMessage();
message.setMessageId("msg" + i);
message.setMessageAnnotation("serialNo", i);
message.setText("Test-Message");
System.out.println("Sending message: " + message.getMessageId());
sender.send(message);
}
sender.close();
Queue queue = getProxyToQueue(getTestName());
assertEquals(MSG_COUNT, queue.getMessageCount());
AmqpReceiver receiver1 = session.createReceiver(getTestName());
receiver1.flow(MSG_COUNT);
AmqpMessage received = receiver1.receive(5, TimeUnit.SECONDS);
assertNotNull("Should have got a message", received);
assertEquals("msg0", received.getMessageId());
receiver1.close();
AmqpReceiver receiver2 = session.createReceiver(getTestName());
receiver2.flow(200);
for (int i = 0; i < MSG_COUNT; ++i) {
received = receiver2.receive(5, TimeUnit.SECONDS);
assertNotNull("Should have got a message", received);
System.out.println("Read message: " + received.getMessageId());
assertEquals("msg" + i, received.getMessageId());
}
receiver2.close();
connection.close();
}
@Test(timeout = 60000)
public void testReceiveWithJMSSelectorFilter() throws Exception {
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpMessage message1 = new AmqpMessage();
message1.setGroupId("abcdefg");
message1.setApplicationProperty("sn", 100);
AmqpMessage message2 = new AmqpMessage();
message2.setGroupId("hijklm");
message2.setApplicationProperty("sn", 200);
AmqpSender sender = session.createSender(getTestName());
sender.send(message1);
sender.send(message2);
sender.close();
AmqpReceiver receiver = session.createReceiver(getTestName(), "sn = 100");
receiver.flow(2);
AmqpMessage received = receiver.receive(5, TimeUnit.SECONDS);
assertNotNull("Should have read a message", received);
assertEquals(100, received.getApplicationProperty("sn"));
assertEquals("abcdefg", received.getGroupId());
received.accept();
assertNull(receiver.receive(1, TimeUnit.SECONDS));
receiver.close();
connection.close();
}
@Test(timeout = 60000)
public void testAdvancedLinkFlowControl() throws Exception {
final int MSG_COUNT = 20;
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(getTestName());
for (int i = 0; i < MSG_COUNT; i++) {
AmqpMessage message = new AmqpMessage();
message.setMessageId("msg" + i);
message.setMessageAnnotation("serialNo", i);
message.setText("Test-Message");
sender.send(message);
}
sender.close();
LOG.info("Attempting to read first two messages with receiver #1");
AmqpReceiver receiver1 = session.createReceiver(getTestName());
receiver1.flow(2);
AmqpMessage message1 = receiver1.receive(10, TimeUnit.SECONDS);
AmqpMessage message2 = receiver1.receive(10, TimeUnit.SECONDS);
assertNotNull("Should have read message 1", message1);
assertNotNull("Should have read message 2", message2);
assertEquals("msg0", message1.getMessageId());
assertEquals("msg1", message2.getMessageId());
message1.accept();
message2.accept();
LOG.info("Attempting to read next two messages with receiver #2");
AmqpReceiver receiver2 = session.createReceiver(getTestName());
receiver2.flow(2);
AmqpMessage message3 = receiver2.receive(10, TimeUnit.SECONDS);
AmqpMessage message4 = receiver2.receive(10, TimeUnit.SECONDS);
assertNotNull("Should have read message 3", message3);
assertNotNull("Should have read message 4", message4);
assertEquals("msg2", message3.getMessageId());
assertEquals("msg3", message4.getMessageId());
message3.accept();
message4.accept();
LOG.info("Attempting to read remaining messages with receiver #1");
receiver1.flow(MSG_COUNT - 4);
for (int i = 4; i < MSG_COUNT; i++) {
AmqpMessage message = receiver1.receive(10, TimeUnit.SECONDS);
assertNotNull("Should have read a message", message);
assertEquals("msg" + i, message.getMessageId());
message.accept();
}
receiver1.close();
receiver2.close();
connection.close();
}
@Test(timeout = 60000)
public void testDispatchOrderWithPrefetchOfOne() throws Exception {
final int MSG_COUNT = 20;
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(getTestName());
for (int i = 0; i < MSG_COUNT; i++) {
AmqpMessage message = new AmqpMessage();
message.setMessageId("msg" + i);
message.setMessageAnnotation("serialNo", i);
message.setText("Test-Message");
sender.send(message);
}
sender.close();
AmqpReceiver receiver1 = session.createReceiver(getTestName());
receiver1.flow(1);
AmqpReceiver receiver2 = session.createReceiver(getTestName());
receiver2.flow(1);
AmqpMessage message1 = receiver1.receive(10, TimeUnit.SECONDS);
AmqpMessage message2 = receiver2.receive(10, TimeUnit.SECONDS);
assertNotNull("Should have read message 1", message1);
assertNotNull("Should have read message 2", message2);
assertEquals("msg0", message1.getMessageId());
assertEquals("msg1", message2.getMessageId());
message1.accept();
message2.accept();
receiver1.flow(1);
AmqpMessage message3 = receiver1.receive(10, TimeUnit.SECONDS);
receiver2.flow(1);
AmqpMessage message4 = receiver2.receive(10, TimeUnit.SECONDS);
assertNotNull("Should have read message 3", message3);
assertNotNull("Should have read message 4", message4);
assertEquals("msg2", message3.getMessageId());
assertEquals("msg3", message4.getMessageId());
message3.accept();
message4.accept();
LOG.info("*** Attempting to read remaining messages with both receivers");
int splitCredit = (MSG_COUNT - 4) / 2;
LOG.info("**** Receiver #1 granting creadit[{}] for its block of messages", splitCredit);
receiver1.flow(splitCredit);
for (int i = 0; i < splitCredit; i++) {
AmqpMessage message = receiver1.receive(10, TimeUnit.SECONDS);
assertNotNull("Receiver #1 should have read a message", message);
LOG.info("Receiver #1 read message: {}", message.getMessageId());
message.accept();
}
LOG.info("**** Receiver #2 granting creadit[{}] for its block of messages", splitCredit);
receiver2.flow(splitCredit);
for (int i = 0; i < splitCredit; i++) {
AmqpMessage message = receiver2.receive(10, TimeUnit.SECONDS);
assertNotNull("Receiver #2 should have read message[" + i + "]", message);
LOG.info("Receiver #2 read message: {}", message.getMessageId());
message.accept();
}
receiver1.close();
receiver2.close();
connection.close();
}
@Test(timeout = 60000)
public void testReceiveMessageAndRefillCreditBeforeAccept() throws Exception {
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
final String address = getTestName();
AmqpReceiver receiver = session.createReceiver(address);
AmqpSender sender = session.createSender(address);
for (int i = 0; i < 2; i++) {
AmqpMessage message = new AmqpMessage();
message.setMessageId("msg" + i);
sender.send(message);
}
sender.close();
receiver.flow(1);
AmqpMessage received = receiver.receive(5, TimeUnit.SECONDS);
assertNotNull(received);
receiver.flow(1);
received.accept();
received = receiver.receive(10, TimeUnit.SECONDS);
assertNotNull(received);
received.accept();
receiver.close();
connection.close();
}
@Test(timeout = 60000)
public void testReceiveMessageAndRefillCreditBeforeAcceptOnQueueAsync() throws Exception {
final AmqpClient client = createAmqpClient();
final LinkedList<Throwable> errors = new LinkedList<>();
final CountDownLatch receiverReady = new CountDownLatch(1);
ExecutorService executorService = Executors.newCachedThreadPool();
final String address = getTestName();
executorService.submit(new Runnable() {
@Override
public void run() {
try {
LOG.info("Starting consumer connection");
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpReceiver receiver = session.createReceiver(address);
receiver.flow(1);
receiverReady.countDown();
AmqpMessage received = receiver.receive(5, TimeUnit.SECONDS);
assertNotNull(received);
receiver.flow(1);
received.accept();
received = receiver.receive(5, TimeUnit.SECONDS);
assertNotNull(received);
received.accept();
receiver.close();
connection.close();
} catch (Exception error) {
errors.add(error);
}
}
});
// producer
executorService.submit(new Runnable() {
@Override
public void run() {
try {
receiverReady.await(20, TimeUnit.SECONDS);
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(address);
for (int i = 0; i < 2; i++) {
AmqpMessage message = new AmqpMessage();
message.setMessageId("msg" + i);
sender.send(message);
}
sender.close();
connection.close();
} catch (Exception ignored) {
ignored.printStackTrace();
}
}
});
executorService.shutdown();
executorService.awaitTermination(20, TimeUnit.SECONDS);
assertTrue("no errors: " + errors, errors.isEmpty());
}
@Test(timeout = 60000)
public void testMessageDurabliltyFollowsSpec() throws Exception {
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(getTestName());
AmqpReceiver receiver1 = session.createReceiver(getTestName());
Queue queue = getProxyToQueue(getTestName());
// Create default message that should be sent as non-durable
AmqpMessage message1 = new AmqpMessage();
message1.setText("Test-Message -> non-durable");
message1.setDurable(false);
message1.setMessageId("ID:Message:1");
sender.send(message1);
assertEquals(1, queue.getMessageCount());
receiver1.flow(1);
message1 = receiver1.receive(50, TimeUnit.SECONDS);
assertNotNull("Should have read a message", message1);
assertFalse("First message sent should not be durable", message1.isDurable());
message1.accept();
// Create default message that should be sent as non-durable
AmqpMessage message2 = new AmqpMessage();
message2.setText("Test-Message -> durable");
message2.setDurable(true);
message2.setMessageId("ID:Message:2");
sender.send(message2);
assertEquals(1, queue.getMessageCount());
receiver1.flow(1);
message2 = receiver1.receive(50, TimeUnit.SECONDS);
assertNotNull("Should have read a message", message2);
assertTrue("Second message sent should be durable", message2.isDurable());
message2.accept();
sender.close();
connection.close();
}
@Test(timeout = 60000)
public void testReceiveMessageBeyondAckedAmountQueue() throws Exception {
final int MSG_COUNT = 50;
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
final String address = getTestName();
AmqpReceiver receiver = session.createReceiver(address);
AmqpSender sender = session.createSender(address);
final Queue destinationView = getProxyToQueue(address);
for (int i = 0; i < MSG_COUNT; i++) {
AmqpMessage message = new AmqpMessage();
message.setMessageId("msg" + i);
sender.send(message);
}
List<AmqpMessage> pendingAcks = new ArrayList<>();
for (int i = 0; i < MSG_COUNT; i++) {
receiver.flow(1);
AmqpMessage received = receiver.receive(5, TimeUnit.SECONDS);
assertNotNull(received);
pendingAcks.add(received);
}
// Send one more to check in-flight stays at zero with no credit and all
// pending messages settled.
AmqpMessage message = new AmqpMessage();
message.setMessageId("msg-final");
sender.send(message);
for (AmqpMessage pendingAck : pendingAcks) {
pendingAck.accept();
}
assertTrue("Should be no inflight messages: " + destinationView.getDeliveringCount(), Wait.waitFor(new Wait.Condition() {
@Override
public boolean isSatisfied() throws Exception {
return destinationView.getDeliveringCount() == 0;
}
}));
sender.close();
receiver.close();
connection.close();
}
@Test(timeout = 60000)
public void testTwoPresettledReceiversReceiveAllMessages() throws Exception {
final int MSG_COUNT = 100;
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
final String address = getTestName();
AmqpSender sender = session.createSender(address);
AmqpReceiver receiver1 = session.createReceiver(address, null, false, true);
AmqpReceiver receiver2 = session.createReceiver(address, null, false, true);
for (int i = 0; i < MSG_COUNT; i++) {
AmqpMessage message = new AmqpMessage();
message.setMessageId("msg" + i);
sender.send(message);
}
LOG.info("Attempting to read first two messages with receiver #1");
receiver1.flow(2);
AmqpMessage message1 = receiver1.receive(10, TimeUnit.SECONDS);
AmqpMessage message2 = receiver1.receive(10, TimeUnit.SECONDS);
assertNotNull("Should have read message 1", message1);
assertNotNull("Should have read message 2", message2);
assertEquals("msg0", message1.getMessageId());
assertEquals("msg1", message2.getMessageId());
message1.accept();
message2.accept();
LOG.info("Attempting to read next two messages with receiver #2");
receiver2.flow(2);
AmqpMessage message3 = receiver2.receive(10, TimeUnit.SECONDS);
AmqpMessage message4 = receiver2.receive(10, TimeUnit.SECONDS);
assertNotNull("Should have read message 3", message3);
assertNotNull("Should have read message 4", message4);
assertEquals("msg2", message3.getMessageId());
assertEquals("msg3", message4.getMessageId());
message3.accept();
message4.accept();
LOG.info("*** Attempting to read remaining messages with both receivers");
int splitCredit = (MSG_COUNT - 4) / 2;
LOG.info("**** Receiver #1 granting credit[{}] for its block of messages", splitCredit);
receiver1.flow(splitCredit);
for (int i = 0; i < splitCredit; i++) {
AmqpMessage message = receiver1.receive(10, TimeUnit.SECONDS);
assertNotNull("Receiver #1 should have read a message", message);
LOG.info("Receiver #1 read message: {}", message.getMessageId());
message.accept();
}
LOG.info("**** Receiver #2 granting credit[{}] for its block of messages", splitCredit);
receiver2.flow(splitCredit);
for (int i = 0; i < splitCredit; i++) {
AmqpMessage message = receiver2.receive(10, TimeUnit.SECONDS);
assertNotNull("Receiver #2 should have read a message[" + i + "]", message);
LOG.info("Receiver #2 read message: {}", message.getMessageId());
message.accept();
}
receiver1.close();
receiver2.close();
connection.close();
}
@Test
public void testDeliveryDelayOfferedWhenRequested() throws Exception {
AmqpClient client = createAmqpClient();
client.setValidator(new AmqpValidator() {
@Override
public void inspectOpenedResource(Sender sender) {
Symbol[] offered = sender.getRemoteOfferedCapabilities();
if (!contains(offered, AmqpSupport.DELAYED_DELIVERY)) {
markAsInvalid("Broker did not indicate it support delayed message delivery");
}
}
});
AmqpConnection connection = addConnection(client.connect());
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender("queue://" + getTestName(), new Symbol[] {AmqpSupport.DELAYED_DELIVERY});
assertNotNull(sender);
connection.getStateInspector().assertValid();
sender.close();
connection.close();
}
public void sendMessages(String destinationName, int count) throws Exception {
AmqpClient client = createAmqpClient();
AmqpConnection connection = addConnection(client.connect());
try {
AmqpSession session = connection.createSession();
AmqpSender sender = session.createSender(destinationName);
for (int i = 0; i < count; ++i) {
AmqpMessage message = new AmqpMessage();
message.setMessageId("MessageID:" + i);
sender.send(message);
}
} finally {
connection.close();
}
}
}
| |
package net.bytebuddy.dynamic;
import net.bytebuddy.description.type.TypeDescription;
import net.bytebuddy.implementation.LoadedTypeInitializer;
import net.bytebuddy.test.utility.JavaVersionRule;
import net.bytebuddy.test.utility.MockitoRule;
import net.bytebuddy.utility.RandomString;
import org.hamcrest.CoreMatchers;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.MethodRule;
import org.junit.rules.TestRule;
import org.mockito.Mock;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.*;
import java.util.jar.*;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.CoreMatchers.notNullValue;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.mockito.Mockito.*;
public class DynamicTypeDefaultTest {
private static final String CLASS_FILE_EXTENSION = ".class";
private static final String FOOBAR = "foo/bar", QUXBAZ = "qux/baz", BARBAZ = "bar/baz", FOO = "foo", BAR = "bar", TEMP = "tmp";
@Rule
public TestRule mockitoRule = new MockitoRule(this);
@Rule
public MethodRule javaVersionRule = new JavaVersionRule();
private static final byte[] BINARY_FIRST = new byte[]{1, 2, 3}, BINARY_SECOND = new byte[]{4, 5, 6}, BINARY_THIRD = new byte[]{7, 8, 9};
@Mock
private LoadedTypeInitializer mainLoadedTypeInitializer, auxiliaryLoadedTypeInitializer;
@Mock
private DynamicType auxiliaryType;
@Mock
private TypeDescription typeDescription, auxiliaryTypeDescription;
private DynamicType dynamicType;
private static void assertFile(File file, byte[] binaryRepresentation) throws IOException {
FileInputStream fileInputStream = new FileInputStream(file);
try {
byte[] buffer = new byte[binaryRepresentation.length + 1];
assertThat(fileInputStream.read(buffer), is(binaryRepresentation.length));
int index = 0;
for (byte b : binaryRepresentation) {
assertThat(buffer[index++], is(b));
}
assertThat(buffer[index], is((byte) 0));
} finally {
fileInputStream.close();
}
assertThat(file.delete(), is(true));
}
private static File makeTemporaryFolder() throws IOException {
File file = File.createTempFile(TEMP, TEMP);
try {
File folder = new File(file.getParentFile(), TEMP + RandomString.make());
assertThat(folder.mkdir(), is(true));
return folder;
} finally {
assertThat(file.delete(), is(true));
}
}
private static void assertJarFile(File file, Manifest manifest, Map<String, byte[]> expectedEntries) throws IOException {
JarInputStream jarInputStream = new JarInputStream(new FileInputStream(file));
try {
assertThat(jarInputStream.getManifest(), is(manifest));
JarEntry jarEntry;
while ((jarEntry = jarInputStream.getNextJarEntry()) != null) {
byte[] binary = expectedEntries.remove(jarEntry.getName());
assertThat(binary, notNullValue());
byte[] buffer = new byte[binary.length];
assertThat(jarInputStream.read(buffer), is(buffer.length));
assertThat(Arrays.equals(buffer, binary), is(true));
assertThat(jarInputStream.read(buffer), is(-1));
jarInputStream.closeEntry();
}
assertThat(expectedEntries.size(), is(0));
} finally {
jarInputStream.close();
}
}
@Before
public void setUp() throws Exception {
dynamicType = new DynamicType.Default(typeDescription,
BINARY_FIRST,
mainLoadedTypeInitializer,
Collections.singletonList(auxiliaryType));
when(typeDescription.getName()).thenReturn(FOOBAR.replace('/', '.'));
when(typeDescription.getInternalName()).thenReturn(FOOBAR);
when(auxiliaryType.saveIn(any(File.class))).thenReturn(Collections.<TypeDescription, File>emptyMap());
when(auxiliaryTypeDescription.getName()).thenReturn(QUXBAZ.replace('/', '.'));
when(auxiliaryTypeDescription.getInternalName()).thenReturn(QUXBAZ);
when(auxiliaryType.getTypeDescription()).thenReturn(auxiliaryTypeDescription);
when(auxiliaryType.getBytes()).thenReturn(BINARY_SECOND);
when(auxiliaryType.getLoadedTypeInitializers()).thenReturn(Collections.singletonMap(auxiliaryTypeDescription, auxiliaryLoadedTypeInitializer));
when(auxiliaryType.getAuxiliaryTypes()).thenReturn(Collections.<TypeDescription, byte[]>emptyMap());
when(auxiliaryType.getAllTypes()).thenReturn(Collections.singletonMap(auxiliaryTypeDescription, BINARY_SECOND));
}
@Test
public void testByteArray() throws Exception {
assertThat(dynamicType.getBytes(), is(BINARY_FIRST));
}
@Test
public void testTypeDescription() throws Exception {
assertThat(dynamicType.getTypeDescription(), is(typeDescription));
}
@Test
public void testRawAuxiliaryTypes() throws Exception {
assertThat(dynamicType.getAuxiliaryTypes().size(), is(1));
assertThat(dynamicType.getAuxiliaryTypes().get(auxiliaryTypeDescription), is(BINARY_SECOND));
}
@Test
public void testTypeInitializersNotAlive() throws Exception {
assertThat(dynamicType.hasAliveLoadedTypeInitializers(), is(false));
}
@Test
public void testTypeInitializersAliveMain() throws Exception {
when(mainLoadedTypeInitializer.isAlive()).thenReturn(true);
assertThat(dynamicType.hasAliveLoadedTypeInitializers(), is(true));
}
@Test
public void testTypeInitializersAliveAuxiliary() throws Exception {
when(auxiliaryLoadedTypeInitializer.isAlive()).thenReturn(true);
assertThat(dynamicType.hasAliveLoadedTypeInitializers(), is(true));
}
@Test
public void testTypeInitializers() throws Exception {
assertThat(dynamicType.getLoadedTypeInitializers().size(), is(2));
assertThat(dynamicType.getLoadedTypeInitializers().get(typeDescription), is(mainLoadedTypeInitializer));
assertThat(dynamicType.getLoadedTypeInitializers().get(auxiliaryTypeDescription), is(auxiliaryLoadedTypeInitializer));
}
@Test
public void testFileSaving() throws Exception {
File folder = makeTemporaryFolder();
boolean folderDeletion, fileDeletion;
try {
Map<TypeDescription, File> files = dynamicType.saveIn(folder);
assertThat(files.size(), is(1));
assertFile(files.get(typeDescription), BINARY_FIRST);
} finally {
folderDeletion = new File(folder, FOO).delete();
fileDeletion = folder.delete();
}
assertThat(folderDeletion, is(true));
assertThat(fileDeletion, is(true));
verify(auxiliaryType).saveIn(folder);
}
@Test
public void testJarCreation() throws Exception {
File file = File.createTempFile(FOO, TEMP);
assertThat(file.delete(), is(true));
boolean fileDeletion;
try {
assertThat(dynamicType.toJar(file), is(file));
assertThat(file.exists(), is(true));
assertThat(file.isFile(), is(true));
assertThat(file.length() > 0L, is(true));
Map<String, byte[]> bytes = new HashMap<String, byte[]>();
bytes.put(FOOBAR + CLASS_FILE_EXTENSION, BINARY_FIRST);
bytes.put(QUXBAZ + CLASS_FILE_EXTENSION, BINARY_SECOND);
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
assertJarFile(file, manifest, bytes);
} finally {
fileDeletion = file.delete();
}
assertThat(fileDeletion, is(true));
}
@Test
public void testJarWithExplicitManifestCreation() throws Exception {
File file = File.createTempFile(FOO, TEMP);
assertThat(file.delete(), is(true));
boolean fileDeletion;
try {
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, BAR);
assertThat(dynamicType.toJar(file, manifest), is(file));
assertThat(file.exists(), is(true));
assertThat(file.isFile(), is(true));
assertThat(file.length() > 0L, is(true));
Map<String, byte[]> bytes = new HashMap<String, byte[]>();
bytes.put(FOOBAR + CLASS_FILE_EXTENSION, BINARY_FIRST);
bytes.put(QUXBAZ + CLASS_FILE_EXTENSION, BINARY_SECOND);
assertJarFile(file, manifest, bytes);
} finally {
fileDeletion = file.delete();
}
assertThat(fileDeletion, is(true));
}
@Test
public void testJarTargetInjection() throws Exception {
File sourceFile = File.createTempFile(BAR, TEMP);
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, BAR);
JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(sourceFile), manifest);
try {
jarOutputStream.putNextEntry(new JarEntry(BARBAZ + CLASS_FILE_EXTENSION));
jarOutputStream.write(BINARY_THIRD);
jarOutputStream.closeEntry();
jarOutputStream.putNextEntry(new JarEntry(FOOBAR + CLASS_FILE_EXTENSION));
jarOutputStream.write(BINARY_THIRD);
jarOutputStream.closeEntry();
} finally {
jarOutputStream.close();
}
File file = File.createTempFile(FOO, TEMP);
assertThat(file.delete(), is(true));
boolean fileDeletion;
try {
assertThat(dynamicType.inject(sourceFile, file), is(file));
assertThat(file.exists(), is(true));
assertThat(file.isFile(), is(true));
assertThat(file.length() > 0L, is(true));
Map<String, byte[]> bytes = new HashMap<String, byte[]>();
bytes.put(FOOBAR + CLASS_FILE_EXTENSION, BINARY_FIRST);
bytes.put(QUXBAZ + CLASS_FILE_EXTENSION, BINARY_SECOND);
bytes.put(BARBAZ + CLASS_FILE_EXTENSION, BINARY_THIRD);
assertJarFile(file, manifest, bytes);
} finally {
fileDeletion = file.delete() & sourceFile.delete();
}
assertThat(fileDeletion, is(true));
}
@Test
public void testJarSelfInjection() throws Exception {
File file = File.createTempFile(BAR, TEMP);
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, BAR);
JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(file), manifest);
try {
jarOutputStream.putNextEntry(new JarEntry(BARBAZ + CLASS_FILE_EXTENSION));
jarOutputStream.write(BINARY_THIRD);
jarOutputStream.closeEntry();
jarOutputStream.putNextEntry(new JarEntry(FOOBAR + CLASS_FILE_EXTENSION));
jarOutputStream.write(BINARY_THIRD);
jarOutputStream.closeEntry();
} finally {
jarOutputStream.close();
}
boolean fileDeletion;
try {
assertThat(dynamicType.inject(file), is(file));
assertThat(file.exists(), is(true));
assertThat(file.isFile(), is(true));
assertThat(file.length() > 0L, is(true));
Map<String, byte[]> bytes = new HashMap<String, byte[]>();
bytes.put(FOOBAR + CLASS_FILE_EXTENSION, BINARY_FIRST);
bytes.put(QUXBAZ + CLASS_FILE_EXTENSION, BINARY_SECOND);
bytes.put(BARBAZ + CLASS_FILE_EXTENSION, BINARY_THIRD);
assertJarFile(file, manifest, bytes);
} finally {
fileDeletion = file.delete();
}
assertThat(fileDeletion, is(true));
}
@Test
public void testJarSelfInjectionWithDuplicateSpecification() throws Exception {
File file = File.createTempFile(BAR, TEMP);
Manifest manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, BAR);
JarOutputStream jarOutputStream = new JarOutputStream(new FileOutputStream(file), manifest);
try {
jarOutputStream.putNextEntry(new JarEntry(BARBAZ + CLASS_FILE_EXTENSION));
jarOutputStream.write(BINARY_THIRD);
jarOutputStream.closeEntry();
jarOutputStream.putNextEntry(new JarEntry(FOOBAR + CLASS_FILE_EXTENSION));
jarOutputStream.write(BINARY_THIRD);
jarOutputStream.closeEntry();
} finally {
jarOutputStream.close();
}
boolean fileDeletion;
try {
assertThat(dynamicType.inject(file, file), is(file));
assertThat(file.exists(), is(true));
assertThat(file.isFile(), is(true));
assertThat(file.length() > 0L, is(true));
Map<String, byte[]> bytes = new HashMap<String, byte[]>();
bytes.put(FOOBAR + CLASS_FILE_EXTENSION, BINARY_FIRST);
bytes.put(QUXBAZ + CLASS_FILE_EXTENSION, BINARY_SECOND);
bytes.put(BARBAZ + CLASS_FILE_EXTENSION, BINARY_THIRD);
assertJarFile(file, manifest, bytes);
} finally {
fileDeletion = file.delete();
}
assertThat(fileDeletion, is(true));
}
@Test
public void testIterationOrder() throws Exception {
Iterator<TypeDescription> types = dynamicType.getAllTypes().keySet().iterator();
assertThat(types.hasNext(), is(true));
assertThat(types.next(), is(typeDescription));
assertThat(types.hasNext(), is(true));
assertThat(types.next(), is(auxiliaryTypeDescription));
assertThat(types.hasNext(), is(false));
}
@Test
@JavaVersionRule.Enforce(7)
public void testDispatcher() {
assertThat(DynamicType.Default.DISPATCHER, instanceOf(DynamicType.Default.Dispatcher.ForJava7CapableVm.class));
}
}
| |
/*
* Copyright (C) 2004-2015 Volker Bergmann (volker.bergmann@bergmann-it.de).
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.databene.commons.ui.swing;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.geom.Rectangle2D;
import javax.swing.Action;
import javax.swing.Icon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.JToolBar;
import javax.swing.JViewport;
import javax.swing.KeyStroke;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableRowSorter;
import org.databene.commons.BeanUtil;
/**
* Provides Swing utilities.
* Created: 23.04.2007 22:41:21
*
* @since 0.5.13
* @author Volker Bergmann
*/
public class SwingUtil {
public static void repaintLater(final Component component) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
component.repaint();
}
});
}
public static void center(Component component) {
Dimension screenSize = getScreenSize();
int x = (screenSize.width - component.getWidth()) / 2;
int y = (screenSize.height - component.getHeight()) / 2;
component.setLocation(x, y);
}
public static Dimension getScreenSize() {
return Toolkit.getDefaultToolkit().getScreenSize();
}
public static <T extends Component> T showInModalDialog(T mainComponent, String title, boolean cancellable,
Component parentComponent) {
return SimpleDialog.showModalDialog(mainComponent, title, cancellable, parentComponent);
}
public static void showInFrame(Component component, String title) {
JFrame frame = new JFrame(title);
frame.getContentPane().add(component, BorderLayout.CENTER);
frame.pack();
center(frame);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
public static Rectangle fitRectangles(Dimension imageSize, Dimension size) {
double aspectX = (double) size.width / imageSize.width;
double aspectY = (double) size.height / imageSize.height;
double aspect = Math.min(aspectX, aspectY);
int paintedWidth = (int) (imageSize.width * aspect);
int paintedHeight = (int) (imageSize.height * aspect);
int x = (size.width - paintedWidth) / 2;
int y = (size.height - paintedHeight) / 2;
return new Rectangle(x, y, paintedWidth, paintedHeight);
}
public static boolean isLookAndFeelNative() {
return UIManager.getSystemLookAndFeelClassName().equals(UIManager.getLookAndFeel().getClass().getName());
}
public static Window getWindowForComponent(Component parentComponent) {
if (parentComponent == null)
return null;
if (parentComponent instanceof Frame || parentComponent instanceof Dialog)
return (Window) parentComponent;
return getWindowForComponent(parentComponent.getParent());
}
public static void equalizeButtonSizes(Graphics g, JButton... buttons) {
String[] labels = BeanUtil.extractProperties(buttons, "text", String.class);
// Get the largest width and height
Dimension maxSize = new Dimension(0, 0);
Rectangle2D textBounds = null;
JButton button0 = buttons[0];
FontMetrics metrics = button0.getFontMetrics(button0.getFont());
for (int i = 0; i < labels.length; ++i) {
textBounds = metrics.getStringBounds(labels[i], g);
maxSize.width = Math.max(maxSize.width, (int) textBounds.getWidth());
maxSize.height = Math.max(maxSize.height, (int) textBounds.getHeight());
}
Insets insets = button0.getBorder().getBorderInsets(button0);
maxSize.width += insets.left + insets.right;
maxSize.height += insets.top + insets.bottom;
// reset preferred and maximum size since BoxLayout takes both into account
for (JButton button : buttons) {
button.setPreferredSize((Dimension) maxSize.clone());
button.setMaximumSize((Dimension) maxSize.clone());
}
}
public static JButton insertTransparentIconButton(Action action, JToolBar toolBar) {
return insertTransparentButton(action, false, toolBar);
}
public static JButton insertTransparentButton(Action action, boolean withText, JToolBar toolBar) {
JButton button = toolBar.add(action);
configureTransparentButton(button, withText);
return button;
}
public static void insertTransparentIconButton(JButton button, JToolBar toolBar) {
insertTransparentButton(button, false, toolBar);
}
public static void insertTransparentButton(JButton button, boolean withText, JToolBar toolBar) {
configureTransparentButton(button, withText);
toolBar.add(button);
}
private static JButton configureTransparentButton(JButton button, boolean withText) {
if (withText) {
button.setVerticalTextPosition(SwingConstants.BOTTOM);
button.setHorizontalTextPosition(SwingConstants.CENTER);
} else {
button.setText("");
button.setMargin(new Insets(0, 0, 0, 0));
}
button.setOpaque(false);
button.setContentAreaFilled(false);
button.setBorderPainted(false);
return button;
}
public static Color getUIPanelBackground() {
return getUIColor("Panel.background");
}
public static Color getUIColor(String code) {
Color color = UIManager.getColor(code);
// workaround for issue with com.apple.laf.AquaNativeResources$CColorPaintUIResource which seems to be rendered with alpha=0
return new Color(color.getRed(), color.getGreen(), color.getBlue(), color.getAlpha());
}
public static Color semiTransparentColor(Color color) {
return applyAlpha(color, 128);
}
public static Color applyAlpha(Color color, int alpha) {
return new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha);
}
public static void bindKeyToAction(int keyCode, int modifiers, Action action, JComponent component) {
bindKeyToAction(keyCode, modifiers, action, component, JComponent.WHEN_FOCUSED);
}
public static void bindKeyToAction(int keyCode, int modifiers, Action action, JComponent component, int condition) {
KeyStroke keyStroke = KeyStroke.getKeyStroke(keyCode, modifiers);
component.getInputMap(condition).put(keyStroke, action);
}
public static void autoSizeTableColumns(JTable table) {
for (int column = 0; column < table.getColumnCount(); column++) {
int columnWidth = 0;
for (int row = 0; row < table.getRowCount(); row++) {
TableCellRenderer renderer = table.getCellRenderer(row, column);
Component comp = table.prepareRenderer(renderer, row, column);
columnWidth = Math.max(comp.getPreferredSize().width, columnWidth);
}
table.getColumnModel().getColumn(column).setPreferredWidth(columnWidth);
}
}
public static void applyRowSorter(JTable table) {
@SuppressWarnings({ "rawtypes", "unchecked" })
TableRowSorter<?> sorter = new TableRowSorter(table.getModel());
sorter.setSortsOnUpdates(true);
table.setRowSorter(sorter);
}
public static void scrollToTableCell(JTable table, int rowIndex, int colIndex) {
if (!(table.getParent() instanceof JViewport))
return;
JViewport viewport = (JViewport) table.getParent();
Rectangle rect = table.getCellRect(rowIndex, colIndex, true);
Point p = viewport.getViewPosition();
rect.setLocation(rect.x - p.x, rect.y - p.y);
table.scrollRectToVisible(rect);
}
public static Icon getDirectoryIcon() {
return UIManager.getIcon("FileView.directoryIcon");
}
public static Icon getHardDriveIcon() {
return UIManager.getIcon("FileView.hardDriveIcon");
}
}
| |
/*
* Copyright (c) 2008-2017, Hazelcast, Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.query.impl.predicates;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.core.IMap;
import com.hazelcast.internal.serialization.InternalSerializationService;
import com.hazelcast.internal.serialization.impl.DefaultSerializationServiceBuilder;
import com.hazelcast.nio.serialization.Data;
import com.hazelcast.query.EntryObject;
import com.hazelcast.query.IndexAwarePredicate;
import com.hazelcast.query.Predicate;
import com.hazelcast.query.PredicateBuilder;
import com.hazelcast.query.Predicates;
import com.hazelcast.query.QueryException;
import com.hazelcast.query.SampleTestObjects.Employee;
import com.hazelcast.query.SampleTestObjects.Value;
import com.hazelcast.query.impl.AttributeType;
import com.hazelcast.query.impl.Index;
import com.hazelcast.query.impl.IndexImpl;
import com.hazelcast.query.impl.QueryContext;
import com.hazelcast.query.impl.QueryEntry;
import com.hazelcast.query.impl.QueryableEntry;
import com.hazelcast.query.impl.getters.Extractors;
import com.hazelcast.query.impl.getters.ReflectionHelper;
import com.hazelcast.test.HazelcastSerialClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.annotation.QuickTest;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import java.math.BigDecimal;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import static com.hazelcast.instance.TestUtil.toData;
import static com.hazelcast.query.Predicates.and;
import static com.hazelcast.query.Predicates.between;
import static com.hazelcast.query.Predicates.equal;
import static com.hazelcast.query.Predicates.greaterEqual;
import static com.hazelcast.query.Predicates.greaterThan;
import static com.hazelcast.query.Predicates.ilike;
import static com.hazelcast.query.Predicates.in;
import static com.hazelcast.query.Predicates.instanceOf;
import static com.hazelcast.query.Predicates.lessEqual;
import static com.hazelcast.query.Predicates.lessThan;
import static com.hazelcast.query.Predicates.like;
import static com.hazelcast.query.Predicates.notEqual;
import static com.hazelcast.query.Predicates.or;
import static com.hazelcast.query.Predicates.regex;
import static java.lang.Boolean.FALSE;
import static java.lang.Boolean.TRUE;
import static org.hamcrest.Matchers.allOf;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(HazelcastSerialClassRunner.class)
@Category(QuickTest.class)
public class PredicatesTest extends HazelcastTestSupport {
private static final String ATTRIBUTE = "DUMMY_ATTRIBUTE_IGNORED";
private final InternalSerializationService ss = new DefaultSerializationServiceBuilder().build();
@Test
@Ignore("now will execute partition number of times")
public void testAndPredicate_whenFirstIndexAwarePredicateIsNotIndexed() throws Exception {
final HazelcastInstance instance = createHazelcastInstance();
final IMap<Object, Object> map = instance.getMap("map");
map.addIndex("name", false);
String name = randomString();
map.put("key", new Value(name));
final ShouldExecuteOncePredicate<?, ?> indexAwareNotIndexedPredicate = new ShouldExecuteOncePredicate<Object, Object>();
final EqualPredicate equalPredicate = new EqualPredicate("name", name);
final AndPredicate andPredicate = new AndPredicate(indexAwareNotIndexedPredicate, equalPredicate);
map.values(andPredicate);
}
static class ShouldExecuteOncePredicate<K, V> implements IndexAwarePredicate<K, V> {
boolean executed = false;
@Override
public boolean apply(Map.Entry<K, V> mapEntry) {
if (!executed) {
executed = true;
return true;
}
throw new RuntimeException();
}
@Override
public Set<QueryableEntry<K, V>> filter(final QueryContext queryContext) {
return null;
}
@Override
public boolean isIndexed(final QueryContext queryContext) {
return false;
}
}
@Test
public void testEqual() {
assertPredicateTrue(equal(ATTRIBUTE, "value"), "value");
assertPredicateFalse(equal(ATTRIBUTE, "value1"), "value");
assertPredicateTrue(equal(ATTRIBUTE, TRUE), true);
assertPredicateTrue(equal(ATTRIBUTE, true), TRUE);
assertPredicateFalse(equal(ATTRIBUTE, true), FALSE);
assertPredicateFalse(equal(ATTRIBUTE, new BigDecimal("1.23E3")), new BigDecimal("1.23E2"));
assertPredicateTrue(equal(ATTRIBUTE, new BigDecimal("1.23E3")), new BigDecimal("1.23E3"));
assertPredicateFalse(equal(ATTRIBUTE, 15.22), 15.23);
assertPredicateTrue(equal(ATTRIBUTE, 15.22), 15.22);
assertPredicateFalse(equal(ATTRIBUTE, 16), 15);
}
@Test
public void testAnd() {
final Predicate and1 = and(greaterThan(ATTRIBUTE, 4), lessThan(ATTRIBUTE, 6));
assertPredicateTrue(and1, 5);
final Predicate and2 = and(greaterThan(ATTRIBUTE, 5), lessThan(ATTRIBUTE, 6));
assertPredicateFalse(and2, 4);
final Predicate and3 = and(greaterThan(ATTRIBUTE, 4), lessThan(ATTRIBUTE, 6), equal(ATTRIBUTE, 5));
assertPredicateTrue(and3, 5);
final Predicate and4 = Predicates.and(greaterThan(ATTRIBUTE, 3), lessThan(ATTRIBUTE, 6), equal(ATTRIBUTE, 4));
assertPredicateFalse(and4, 5);
}
@Test
public void testOr() {
final Predicate or1 = or(equal(ATTRIBUTE, 3), equal(ATTRIBUTE, 4), equal(ATTRIBUTE, 5));
assertPredicateTrue(or1, 4);
assertPredicateFalse(or1, 6);
}
@Test
public void testGreaterEqual() {
assertPredicateTrue(greaterEqual(ATTRIBUTE, 5), 5);
}
@Test
public void testLessThan() {
assertPredicateTrue(lessThan(ATTRIBUTE, 7), 6);
assertPredicateFalse(lessThan(ATTRIBUTE, 3), 4);
assertPredicateFalse(lessThan(ATTRIBUTE, 4), 4);
assertPredicateTrue(lessThan(ATTRIBUTE, "tc"), "bz");
assertPredicateFalse(lessThan(ATTRIBUTE, "gx"), "h0");
}
@Test
public void testGreaterThan() {
assertPredicateTrue(greaterThan(ATTRIBUTE, 5), 6);
assertPredicateFalse(greaterThan(ATTRIBUTE, 5), 4);
assertPredicateFalse(greaterThan(ATTRIBUTE, 5), 5);
assertPredicateTrue(greaterThan(ATTRIBUTE, "aa"), "xa");
assertPredicateFalse(greaterThan(ATTRIBUTE, "da"), "cz");
assertPredicateTrue(greaterThan(ATTRIBUTE, new BigDecimal("1.23E2")), new BigDecimal("1.23E3"));
}
@Test
public void testLessEqual() {
assertPredicateTrue(lessEqual(ATTRIBUTE, 4), 4);
}
@Test
public void testPredicatesAgainstANullField() {
assertFalse_withNullEntry(lessEqual("nullField", 1));
assertFalse_withNullEntry(in("nullField", 1));
assertFalse_withNullEntry(lessThan("nullField", 1));
assertFalse_withNullEntry(greaterEqual("nullField", 1));
assertFalse_withNullEntry(greaterThan("nullField", 1));
assertFalse_withNullEntry(equal("nullField", 1));
assertFalse_withNullEntry(notEqual("nullField", null));
assertFalse_withNullEntry(between("nullField", 1, 1));
assertTrue_withNullEntry(like("nullField", null));
assertTrue_withNullEntry(ilike("nullField", null));
assertTrue_withNullEntry(regex("nullField", null));
assertTrue_withNullEntry(notEqual("nullField", 1));
}
@Test
public void testBetween() {
assertPredicateTrue(between(ATTRIBUTE, 4, 6), 5);
assertPredicateTrue(between(ATTRIBUTE, 5, 6), 5);
assertPredicateTrue(between(ATTRIBUTE, "abc", "xyz"), "prs");
assertPredicateFalse(between(ATTRIBUTE, "klmn", "xyz"), "efgh");
assertPredicateFalse(between(ATTRIBUTE, 6, 7), 5);
}
@Test
public void testIn() {
assertPredicateTrue(in(ATTRIBUTE, 4, 7, 8, 5), 5);
assertPredicateTrue(in(ATTRIBUTE, 5, 7, 8), 5);
assertPredicateFalse(in(ATTRIBUTE, 6, 7, 8), 5);
assertPredicateFalse(in(ATTRIBUTE, 6, 7, 8), 9);
}
@Test
public void testLike() {
assertPredicateTrue(like(ATTRIBUTE, "J%"), "Java");
assertPredicateTrue(like(ATTRIBUTE, "Ja%"), "Java");
assertPredicateTrue(like(ATTRIBUTE, "J_v_"), "Java");
assertPredicateTrue(like(ATTRIBUTE, "_av_"), "Java");
assertPredicateTrue(like(ATTRIBUTE, "_a__"), "Java");
assertPredicateTrue(like(ATTRIBUTE, "J%v_"), "Java");
assertPredicateTrue(like(ATTRIBUTE, "J%_"), "Java");
assertPredicateFalse(like(ATTRIBUTE, "java"), "Java");
assertPredicateFalse(like(ATTRIBUTE, "j%"), "Java");
assertPredicateFalse(like(ATTRIBUTE, "J_a"), "Java");
assertPredicateFalse(like(ATTRIBUTE, "J_ava"), "Java");
assertPredicateFalse(like(ATTRIBUTE, "J_a_a"), "Java");
assertPredicateFalse(like(ATTRIBUTE, "J_av__"), "Java");
assertPredicateFalse(like(ATTRIBUTE, "J_Va"), "Java");
assertPredicateTrue(like(ATTRIBUTE, "Java World"), "Java World");
assertPredicateTrue(like(ATTRIBUTE, "Java%ld"), "Java World");
assertPredicateTrue(like(ATTRIBUTE, "%World"), "Java World");
assertPredicateTrue(like(ATTRIBUTE, "Java_World"), "Java World");
assertPredicateTrue(like(ATTRIBUTE, "J.-*.*\\%"), "J.-*.*%");
assertPredicateTrue(like(ATTRIBUTE, "J\\_"), "J_");
assertPredicateTrue(like(ATTRIBUTE, "J%"), "Java");
}
@Test
public void testILike() {
assertPredicateFalse(like(ATTRIBUTE, "JavaWorld"), "Java World");
assertPredicateTrue(ilike(ATTRIBUTE, "Java_World"), "java World");
assertPredicateTrue(ilike(ATTRIBUTE, "java%ld"), "Java World");
assertPredicateTrue(ilike(ATTRIBUTE, "%world"), "Java World");
assertPredicateFalse(ilike(ATTRIBUTE, "Java_World"), "gava World");
}
@Test
public void testILike_Id() {
ILikePredicate predicate = (ILikePredicate) ilike(ATTRIBUTE, "Java_World");
assertThat(predicate.getId(), allOf(equalTo(6), equalTo(PredicateDataSerializerHook.ILIKE_PREDICATE)));
}
@Test
public void testIsInstanceOf() {
assertTrue(instanceOf(Long.class).apply(new DummyEntry(1L)));
assertFalse(instanceOf(Long.class).apply(new DummyEntry("Java")));
assertTrue(instanceOf(Number.class).apply(new DummyEntry(4)));
}
@Test
public void testCriteriaAPI() {
Object value = new Employee(12, "abc-123-xvz", 34, true, 10D);
EntryObject e = new PredicateBuilder().getEntryObject();
EntryObject e2 = e.get("age");
Predicate predicate = e2.greaterEqual(29).and(e2.lessEqual(36));
assertTrue(predicate.apply(createEntry("1", value)));
e = new PredicateBuilder().getEntryObject();
assertTrue(e.get("id").equal(12).apply(createEntry("1", value)));
}
@Test(expected = NullPointerException.class)
public void testBetweenNull() {
Predicates.between(ATTRIBUTE, null, null);
}
@Test(expected = NullPointerException.class)
public void testLessThanNull() {
Predicates.lessThan(ATTRIBUTE, null);
}
@Test(expected = NullPointerException.class)
public void testLessEqualNull() {
Predicates.lessEqual(ATTRIBUTE, null);
}
@Test(expected = NullPointerException.class)
public void testGreaterThanNull() {
Predicates.greaterThan(ATTRIBUTE, null);
}
@Test(expected = NullPointerException.class)
public void testGreaterEqualNull() {
Predicates.greaterEqual(ATTRIBUTE, null);
}
@Test(expected = NullPointerException.class)
public void testInNullWithNullArray() {
Predicates.in(ATTRIBUTE, null);
}
@Test
public void testNotEqualsPredicateDoesNotUseIndex() {
Index dummyIndex = new IndexImpl("foo", false, ss, Extractors.empty());
QueryContext mockQueryContext = mock(QueryContext.class);
when(mockQueryContext.getIndex(anyString())).thenReturn(dummyIndex);
NotEqualPredicate p = new NotEqualPredicate("foo", "bar");
boolean indexed = p.isIndexed(mockQueryContext);
assertFalse(indexed);
}
private class DummyEntry extends QueryEntry {
DummyEntry(Comparable attribute) {
super(ss, toData("1"), attribute, Extractors.empty());
}
@Override
public Comparable getAttributeValue(String attributeName) throws QueryException {
return (Comparable) getValue();
}
@Override
public AttributeType getAttributeType(String attributeName) {
return ReflectionHelper.getAttributeType(getValue().getClass());
}
}
private class NullDummyEntry extends QueryableEntry {
private Integer nullField;
private NullDummyEntry() {
}
public Integer getNullField() {
return nullField;
}
public void setNullField(Integer nullField) {
this.nullField = nullField;
}
@Override
public Object getValue() {
return null;
}
@Override
public Object setValue(Object value) {
return null;
}
@Override
public Object getKey() {
return 1;
}
@Override
public Comparable getAttributeValue(String attributeName) throws QueryException {
return null;
}
@Override
public AttributeType getAttributeType(String attributeName) {
return AttributeType.INTEGER;
}
@Override
protected Object getTargetObject(boolean key) {
return null;
}
@Override
public Data getKeyData() {
return null;
}
@Override
public Data getValueData() {
return null;
}
}
private Entry createEntry(final Object key, final Object value) {
return new QueryEntry(ss, toData(key), value, Extractors.empty());
}
private void assertPredicateTrue(Predicate p, Comparable comparable) {
assertTrue(p.apply(new DummyEntry(comparable)));
}
private void assertPredicateFalse(Predicate p, Comparable comparable) {
assertFalse(p.apply(new DummyEntry(comparable)));
}
private void assertTrue_withNullEntry(Predicate p) {
assertTrue(p.apply(new NullDummyEntry()));
}
private void assertFalse_withNullEntry(Predicate p) {
assertFalse(p.apply(new NullDummyEntry()));
}
}
| |
/*
* Copyright 2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.kuujo.vertigo.network.impl;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import net.kuujo.vertigo.NetworkFormatException;
import net.kuujo.vertigo.network.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.UUID;
/**
* NetworkConfig implementation.
*
* @author <a href="http://github.com/kuujo">Jordan Halterman</a>
*/
public class NetworkImpl implements NetworkConfig {
private String name;
private final Collection<ComponentConfig> components = new ArrayList<>();
private final Collection<ConnectionConfig> connections = new ArrayList<>();
public NetworkImpl() {
this(UUID.randomUUID().toString());
}
public NetworkImpl(String name) {
this.name = name;
}
public NetworkImpl(JsonObject network) {
update(network);
}
@Override
public String getName() {
return name;
}
@Override
public NetworkConfig setName(String name) {
this.name = name;
return this;
}
@Override
public Collection<ComponentConfig> getComponents() {
return components;
}
@Override
public ComponentConfig getComponent(String name) {
for (ComponentConfig component : components) {
if (component.getName().equals(name)) {
return component;
}
}
return null;
}
@Override
public boolean hasComponent(String name) {
for (ComponentConfig component : components) {
if (component.getName().equals(name)) {
return true;
}
}
return false;
}
@Override
public ComponentConfig addComponent(String name) {
ComponentConfig component = NetworkConfig.component(name).setNetwork(this);
components.add(component);
return component;
}
@Override
public ComponentConfig addComponent(ComponentConfig component) {
components.add(NetworkConfig.component(component).setNetwork(this));
return component;
}
@Override
public ComponentConfig removeComponent(String name) {
Iterator<ComponentConfig> iterator = components.iterator();
while (iterator.hasNext()) {
ComponentConfig component = iterator.next();
if (component.getName() != null && component.getName().equals(name)) {
iterator.remove();
return component;
}
}
return null;
}
@Override
public ComponentConfig removeComponent(ComponentConfig component) {
Iterator<ComponentConfig> iterator = components.iterator();
while (iterator.hasNext()) {
ComponentConfig info = iterator.next();
if (info.equals(component)) {
iterator.remove();
return component;
}
}
return null;
}
@Override
public Collection<ConnectionConfig> getConnections() {
return connections;
}
@Override
public ConnectionConfig createConnection(ConnectionConfig connection) {
connections.add(NetworkConfig.connection(connection));
return connection;
}
@Override
public ConnectionConfig createConnection(OutputPortConfig output, InputPortConfig input) {
ConnectionConfig connection = NetworkConfig.connection(output, input);
connections.add(connection);
return connection;
}
@Override
public ConnectionConfig destroyConnection(ConnectionConfig connection) {
Iterator<ConnectionConfig> iterator = connections.iterator();
while (iterator.hasNext()) {
ConnectionConfig c = iterator.next();
if (c.equals(connection)) {
iterator.remove();
return c;
}
}
return null;
}
@Override
public void update(JsonObject network) {
this.name = network.getString(NETWORK_NAME);
if(this.name == null) {
throw new NetworkFormatException("Network name is mandatory.");
}
JsonObject components = network.getJsonObject(NETWORK_COMPONENTS);
if (components != null) {
for (String name : components.fieldNames()) {
this.components.add(NetworkConfig.component(components.getJsonObject(name)).setName(name).setNetwork(this));
}
}
JsonArray connections = network.getJsonArray(NETWORK_CONNECTIONS);
if (connections != null) {
for (Object connection : connections) {
ConnectionConfig connectionConfig = NetworkConfig.connection((JsonObject) connection);
SourceConfig source = connectionConfig.getSource();
if (!source.getIsNetwork()) {
String componentName = connectionConfig.getSource().getComponent();
if (componentName == null) {
throw new NetworkFormatException("A connection source does not specify a component.");
}
ComponentConfig component = this.getComponent(componentName);
if (component == null) {
throw new NetworkFormatException("No component with name " + componentName + " was found while trying to create source vertigo connection.");
}
OutputConfig output = component.getOutput();
if (output.getPort(source.getPort()) == null) {
output.addPort(source.getPort());
}
}
TargetConfig target = connectionConfig.getTarget();
if (!target.getIsNetwork()) {
String componentName = connectionConfig.getTarget().getComponent();
if (componentName == null) {
throw new NetworkFormatException("A connection target does not specify a component.");
}
ComponentConfig component = this.getComponent(componentName);
if (component == null) {
throw new NetworkFormatException("No target component with name " + componentName + " was found while trying to create target vertigo connection.");
}
InputConfig input = component.getInput();
if (input.getPort(target.getPort()) == null) {
input.addPort(target.getPort());
}
}
this.connections.add(connectionConfig);
}
}
}
@Override
public JsonObject toJson() {
JsonObject json = new JsonObject();
json.put(NETWORK_NAME, name);
JsonObject components = new JsonObject();
for (ComponentConfig component : this.components) {
components.put(component.getName(), component.toJson());
}
json.put(NETWORK_COMPONENTS, components);
JsonArray connections = new JsonArray();
for (ConnectionConfig connection : this.connections) {
connections.add(connection.toJson());
}
json.put(NETWORK_CONNECTIONS, connections);
return json;
}
}
| |
package org.springframework.data.jpa.datatables.repository;
import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.datatables.Config;
import org.springframework.data.jpa.datatables.mapping.DataTablesInput;
import org.springframework.data.jpa.datatables.mapping.DataTablesOutput;
import org.springframework.data.jpa.datatables.mapping.SearchPanes;
import org.springframework.data.jpa.datatables.model.Employee;
import org.springframework.data.jpa.datatables.model.EmployeeDto;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import static java.util.Arrays.asList;
import static java.util.Collections.emptySet;
import static org.assertj.core.api.Assertions.assertThat;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = Config.class)
public class EmployeeRepositoryTest {
protected DataTablesInput input;
@Autowired
private EmployeeRepository employeeRepository;
protected DataTablesOutput<Employee> getOutput(DataTablesInput input) {
return employeeRepository.findAll(input);
}
protected DataTablesOutput<EmployeeDto> getOutput(DataTablesInput input, Function<Employee, EmployeeDto> converter) {
return employeeRepository.findAll(input, converter);
}
@Before
public void init() {
employeeRepository.deleteAll();
employeeRepository.saveAll(Employee.ALL);
input = getBasicInput();
}
@Test
public void basic() {
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getDraw()).isEqualTo(1);
assertThat(output.getError()).isNull();
assertThat(output.getRecordsFiltered()).isEqualTo(Employee.ALL.size());
assertThat(output.getRecordsTotal()).isEqualTo(Employee.ALL.size());
assertThat(output.getData()).containsAll(Employee.ALL);
}
@Test
public void paginated() {
input.setDraw(2);
input.setLength(5);
input.setStart(5);
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getDraw()).isEqualTo(2);
assertThat(output.getRecordsFiltered()).isEqualTo(Employee.ALL.size());
assertThat(output.getRecordsTotal()).isEqualTo(Employee.ALL.size());
assertThat(output.getData()).hasSize(Employee.ALL.size() % 5);
}
@Test
public void sortAscending() {
input.addOrder("age", true);
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getData()).containsExactlyElementsOf(Employee.ALL_SORTED_BY_AGE);
}
@Test
public void sortDescending() {
input.addOrder("age", false);
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getData()).containsExactlyElementsOf(Lists.reverse(Employee.ALL_SORTED_BY_AGE));
}
@Test
public void globalFilter() {
input.getSearch().setValue("William");
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getData()).containsOnly(Employee.BRIELLE_WILLIAMSON);
}
@Test
public void globalFilterIgnoreCaseIgnoreSpace() {
input.getSearch().setValue(" aMoS ");
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getData()).containsOnly(Employee.ANGELICA_RAMOS);
}
@Test
public void columnFilter() {
input.getColumn("lastName").setSearchValue(" AmOs ");
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getData()).containsOnly(Employee.ANGELICA_RAMOS);
}
@Test
public void multipleColumnFilters() {
input.getColumn("age").setSearchValue("28");
input.getColumn("position").setSearchValue("Software");
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getData()).containsOnly(Employee.BRENDEN_WAGNER);
}
@Test
public void columnFilterWithMultipleCases() {
input.getColumn("position").setSearchValue("Accountant+Junior Technical Author");
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getRecordsFiltered()).isEqualTo(2);
assertThat(output.getData()).containsOnly(Employee.AIRI_SATOU, Employee.ASHTON_COX);
}
@Test
public void columnFilterWithNoCase() {
input.getColumn("position").setSearchValue("+");
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getRecordsFiltered()).isEqualTo(Employee.ALL.size());
}
@Test
public void zeroLength() {
input.setLength(0);
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getRecordsFiltered()).isEqualTo(0);
assertThat(output.getData()).hasSize(0);
}
@Test
public void negativeLength() {
input.setLength(-1);
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getRecordsFiltered()).isEqualTo(Employee.ALL.size());
assertThat(output.getRecordsTotal()).isEqualTo(Employee.ALL.size());
}
@Test
public void multipleColumnFiltersOnManyToOneRelationship() {
input.getColumn("office.city").setSearchValue("new york");
input.getColumn("office.country").setSearchValue("USA");
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getRecordsFiltered()).isEqualTo(1);
assertThat(output.getData()).containsOnly(Employee.BRIELLE_WILLIAMSON);
}
@Test
public void withConverter() {
input.getColumn("firstName").setSearchValue("airi");
DataTablesOutput<EmployeeDto> output = getOutput(input, employee ->
new EmployeeDto(employee.getId(), employee.getFirstName(), employee.getLastName()));
assertThat(output.getData()).containsOnly(EmployeeDto.AIRI_SATOU);
}
@Test
public void withAnAdditionalSpecification() {
DataTablesOutput<Employee> output = employeeRepository.findAll(input, new SoftwareEngineersOnly<>());
assertThat(output.getRecordsFiltered()).isEqualTo(2);
assertThat(output.getRecordsTotal()).isEqualTo(Employee.ALL.size());
}
@Test
public void withAPreFilteringSpecification() {
DataTablesOutput<Employee> output = employeeRepository.findAll(input, null, new SoftwareEngineersOnly<>());
assertThat(output.getRecordsFiltered()).isEqualTo(2);
assertThat(output.getRecordsTotal()).isEqualTo(2);
}
private class SoftwareEngineersOnly<T> implements Specification<T> {
@Override
public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
return criteriaBuilder.equal(root.get("position"), "Software Engineer");
}
}
@Test
public void columnFilterWithNull() {
input.getColumn("comment").setSearchValue("NULL");
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getData()).containsOnly(Employee.AIRI_SATOU);
}
@Test
public void columnFilterWithNullEscaped() {
input.getColumn("comment").setSearchValue("\\NULL");
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getData()).containsOnly(Employee.ANGELICA_RAMOS);
}
@Test
public void columnFilterWithEscapeCharacters() {
input.getColumn("comment").setSearchValue("foo~");
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getData()).containsOnly(Employee.ASHTON_COX);
input.getColumn("comment").setSearchValue("foo%");
output = getOutput(input);
assertThat(output.getData()).containsOnly(Employee.BRADLEY_GREER);
input.getColumn("comment").setSearchValue("foo_");
output = getOutput(input);
assertThat(output.getData()).containsOnly(Employee.BRENDEN_WAGNER);
}
@Test
public void columnFilterWithValueOrNull() {
input.getColumn("comment").setSearchValue("@foo@@+NULL");
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getData()).containsOnly(Employee.AIRI_SATOU, Employee.BRIELLE_WILLIAMSON);
}
@Test
public void columnFilterBoolean() {
input.getColumn("isWorkingRemotely").setSearchValue("true");
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getData()).containsOnly(Employee.ASHTON_COX);
}
@Test
public void columnFilterBooleanBothCases() {
input.getColumn("isWorkingRemotely").setSearchValue("true+false");
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getData()).containsAll(Employee.ALL);
}
@Test
public void unknownColumn() {
input.addColumn("unknown", true, true, "test");
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getError()).isNotNull();
}
@Test
public void withSearchPanes() {
Map<String, Set<String>> searchPanes = new HashMap<>();
searchPanes.put("position", new HashSet<>(asList("Software Engineer", "Integration Specialist")));
searchPanes.put("age", emptySet());
input.setSearchPanes(searchPanes);
DataTablesOutput<Employee> output = getOutput(input);
assertThat(output.getRecordsFiltered()).isEqualTo(3);
assertThat(output.getSearchPanes()).isNotNull();
assertThat(output.getSearchPanes().getOptions().get("position")).containsOnly(
new SearchPanes.Item("Software Engineer", "Software Engineer", 2, 2),
new SearchPanes.Item("Integration Specialist", "Integration Specialist", 1, 1)
);
assertThat(output.getSearchPanes().getOptions().get("age")).containsOnly(
new SearchPanes.Item("28", "28", 1, 1),
new SearchPanes.Item("41", "41", 1, 1),
new SearchPanes.Item("61", "61", 1, 1)
);
}
private static DataTablesInput getBasicInput() {
DataTablesInput input = new DataTablesInput();
input.addColumn("id", true, true, "");
input.addColumn("firstName", true, true, "");
input.addColumn("lastName", true, true, "");
input.addColumn("fullName", false, true, "");
input.addColumn("position", true, true, "");
input.addColumn("age", true, true, "");
input.addColumn("isWorkingRemotely", true, true, "");
input.addColumn("comment", true, true, "");
input.addColumn("action_column", false, false, "");
input.addColumn("office.id", true, false, "");
input.addColumn("office.city", true, true, "");
input.addColumn("office.country", true, true, "");
return input;
}
}
| |
package com.collisiongames.polygon.maths;
import java.nio.FloatBuffer;
import org.lwjgl.BufferUtils;
/**
*
* @author Alex Ringhoffer
*
*/
public class Matrix4 {
public float[] elements = new float[4 * 4];
/**
* Default constructor
*/
public Matrix4() {}
/**
*
* @param matrix The matrix this matrix should be set to
*/
public Matrix4(Matrix4 matrix) { set(matrix); }
/**
*
* @param matrix The matrix this matrix should be set to
* @return This matrix
*/
public Matrix4 set(Matrix4 matrix) {
for (int i = 0; i < 16; i++)
elements[i] = matrix.elements[i];
return this;
}
/**
*
* @param matrix The matrix that should be added
* @return This matrix
*/
public Matrix4 add(Matrix4 matrix) {
for (int i = 0; i < 16; i++)
elements[i] += matrix.elements[i];
return this;
}
/**
*
* @param matrix The matrix that should be subtracted
* @return This matrix
*/
public Matrix4 sub(Matrix4 matrix) {
for (int i = 0; i < 16; i++)
elements[i] -= matrix.elements[i];
return this;
}
/**
*
* @param matrix The matrix that should be multiplied
* @return This matrix
*/
public Matrix4 mul(Matrix4 matrix) {
elements[0] = elements[0] * matrix.elements[0] + elements[4] * matrix.elements[1] + elements[8] * matrix.elements[2] + elements[12] * matrix.elements[3];
elements[1] = elements[1] * matrix.elements[0] + elements[5] * matrix.elements[1] + elements[9] * matrix.elements[2] + elements[13] * matrix.elements[3];
elements[2] = elements[2] * matrix.elements[0] + elements[6] * matrix.elements[1] + elements[10] * matrix.elements[2] + elements[14] * matrix.elements[3];
elements[3] = elements[3] * matrix.elements[0] + elements[7] * matrix.elements[1] + elements[11] * matrix.elements[2] + elements[15] * matrix.elements[3];
elements[4] = elements[0] * matrix.elements[4] + elements[4] * matrix.elements[5] + elements[8] * matrix.elements[6] + elements[12] * matrix.elements[7];
elements[5] = elements[1] * matrix.elements[4] + elements[5] * matrix.elements[5] + elements[9] * matrix.elements[6] + elements[13] * matrix.elements[7];
elements[6] = elements[2] * matrix.elements[4] + elements[6] * matrix.elements[5] + elements[10] * matrix.elements[6] + elements[14] * matrix.elements[7];
elements[7] = elements[3] * matrix.elements[4] + elements[7] * matrix.elements[5] + elements[11] * matrix.elements[6] + elements[15] * matrix.elements[7];
elements[8] = elements[0] * matrix.elements[8] + elements[4] * matrix.elements[9] + elements[8] * matrix.elements[10] + elements[12] * matrix.elements[11];
elements[9] = elements[1] * matrix.elements[8] + elements[5] * matrix.elements[9] + elements[9] * matrix.elements[10] + elements[13] * matrix.elements[11];
elements[10] = elements[2] * matrix.elements[8] + elements[6] * matrix.elements[9] + elements[10] * matrix.elements[10] + elements[14] * matrix.elements[11];
elements[11] = elements[3] * matrix.elements[8] + elements[7] * matrix.elements[9] + elements[11] * matrix.elements[10] + elements[15] * matrix.elements[11];
elements[12] = elements[0] * matrix.elements[12] + elements[4] * matrix.elements[13] + elements[8] * matrix.elements[14] + elements[12] * matrix.elements[15];
elements[13] = elements[1] * matrix.elements[12] + elements[5] * matrix.elements[13] + elements[9] * matrix.elements[14] + elements[13] * matrix.elements[15];
elements[14] = elements[2] * matrix.elements[12] + elements[6] * matrix.elements[13] + elements[10] * matrix.elements[14] + elements[14] * matrix.elements[15];
elements[15] = elements[3] * matrix.elements[12] + elements[7] * matrix.elements[13] + elements[11] * matrix.elements[14] + elements[15] * matrix.elements[15];
return this;
}
/**
*
* @return This matrix but inversed
*/
public Matrix4 inverse() {
float[] tmp = new float[16];
tmp[0] = elements[5] * elements[10] * elements[15] -
elements[5] * elements[11] * elements[14] -
elements[9] * elements[6] * elements[15] +
elements[9] * elements[7] * elements[14] +
elements[13] * elements[6] * elements[11] -
elements[13] * elements[7] * elements[10];
tmp[4] = -elements[4] * elements[10] * elements[15] +
elements[4] * elements[11] * elements[14] +
elements[8] * elements[6] * elements[15] -
elements[8] * elements[7] * elements[14] -
elements[12] * elements[6] * elements[11] +
elements[12] * elements[7] * elements[10];
tmp[8] = elements[4] * elements[9] * elements[15] -
elements[4] * elements[11] * elements[13] -
elements[8] * elements[5] * elements[15] +
elements[8] * elements[7] * elements[13] +
elements[12] * elements[5] * elements[11] -
elements[12] * elements[7] * elements[9];
tmp[12] = -elements[4] * elements[9] * elements[14] +
elements[4] * elements[10] * elements[13] +
elements[8] * elements[5] * elements[14] -
elements[8] * elements[6] * elements[13] -
elements[12] * elements[5] * elements[10] +
elements[12] * elements[6] * elements[9];
tmp[1] = -elements[1] * elements[10] * elements[15] +
elements[1] * elements[11] * elements[14] +
elements[9] * elements[2] * elements[15] -
elements[9] * elements[3] * elements[14] -
elements[13] * elements[2] * elements[11] +
elements[13] * elements[3] * elements[10];
tmp[5] = elements[0] * elements[10] * elements[15] -
elements[0] * elements[11] * elements[14] -
elements[8] * elements[2] * elements[15] +
elements[8] * elements[3] * elements[14] +
elements[12] * elements[2] * elements[11] -
elements[12] * elements[3] * elements[10];
tmp[9] = -elements[0] * elements[9] * elements[15] +
elements[0] * elements[11] * elements[13] +
elements[8] * elements[1] * elements[15] -
elements[8] * elements[3] * elements[13] -
elements[12] * elements[1] * elements[11] +
elements[12] * elements[3] * elements[9];
tmp[13] = elements[0] * elements[9] * elements[14] -
elements[0] * elements[10] * elements[13] -
elements[8] * elements[1] * elements[14] +
elements[8] * elements[2] * elements[13] +
elements[12] * elements[1] * elements[10] -
elements[12] * elements[2] * elements[9];
tmp[2] = elements[1] * elements[6] * elements[15] -
elements[1] * elements[7] * elements[14] -
elements[5] * elements[2] * elements[15] +
elements[5] * elements[3] * elements[14] +
elements[13] * elements[2] * elements[7] -
elements[13] * elements[3] * elements[6];
tmp[6] = -elements[0] * elements[6] * elements[15] +
elements[0] * elements[7] * elements[14] +
elements[4] * elements[2] * elements[15] -
elements[4] * elements[3] * elements[14] -
elements[12] * elements[2] * elements[7] +
elements[12] * elements[3] * elements[6];
tmp[10] = elements[0] * elements[5] * elements[15] -
elements[0] * elements[7] * elements[13] -
elements[4] * elements[1] * elements[15] +
elements[4] * elements[3] * elements[13] +
elements[12] * elements[1] * elements[7] -
elements[12] * elements[3] * elements[5];
tmp[14] = -elements[0] * elements[5] * elements[14] +
elements[0] * elements[6] * elements[13] +
elements[4] * elements[1] * elements[14] -
elements[4] * elements[2] * elements[13] -
elements[12] * elements[1] * elements[6] +
elements[12] * elements[2] * elements[5];
tmp[3] = -elements[1] * elements[6] * elements[11] +
elements[1] * elements[7] * elements[10] +
elements[5] * elements[2] * elements[11] -
elements[5] * elements[3] * elements[10] -
elements[9] * elements[2] * elements[7] +
elements[9] * elements[3] * elements[6];
tmp[7] = elements[0] * elements[6] * elements[11] -
elements[0] * elements[7] * elements[10] -
elements[4] * elements[2] * elements[11] +
elements[4] * elements[3] * elements[10] +
elements[8] * elements[2] * elements[7] -
elements[8] * elements[3] * elements[6];
tmp[11] = -elements[0] * elements[5] * elements[11] +
elements[0] * elements[7] * elements[9] +
elements[4] * elements[1] * elements[11] -
elements[4] * elements[3] * elements[9] -
elements[8] * elements[1] * elements[7] +
elements[8] * elements[3] * elements[5];
tmp[15] = elements[0] * elements[5] * elements[10] -
elements[0] * elements[6] * elements[9] -
elements[4] * elements[1] * elements[10] +
elements[4] * elements[2] * elements[9] +
elements[8] * elements[1] * elements[6] -
elements[8] * elements[2] * elements[5];
float determinant = elements[0] * tmp[0] + elements[1] * tmp[4] + elements[2] * tmp[8] + elements[3] * tmp[12];
for (int i = 0; i < 16; i++)
elements[i] = tmp[i] * determinant;
return this;
}
/**
*
* @return An identity matrix
*/
public static Matrix4 identity() {
Matrix4 matrix = new Matrix4();
for (int i = 0; i < 16; i++)
matrix.elements[i] = 0;
matrix.elements[0] = 1;
matrix.elements[5] = 1;
matrix.elements[10] = 1;
matrix.elements[15] = 1;
return matrix;
}
/**
*
* @return This matrix but in a buffer
*/
public FloatBuffer toBuffer() { return (FloatBuffer) BufferUtils.createFloatBuffer(16).put(elements).flip();}
/**
*
* @param vector The vector3 that should be turned into a transformation matrix
* @return The transformation matrix
*/
public static Matrix4 transformation(Vector3 vector) {
Matrix4 matrix = identity();
matrix.elements[12] = vector.x;
matrix.elements[13] = vector.y;
matrix.elements[14] = vector.z;
return matrix;
}
/**
*
* @param angle The z angle for the rotation
* @return The rotation matrix
*/
public static Matrix4 rotation(Vector3 axis, float angle) {
Matrix4 matrix = identity();
float radians = (float) Math.toRadians(angle);
float cos = (float) Math.cos(radians);
float sin = (float) Math.sin(radians);
float omc = 1 - cos;
float x = axis.x, y = axis.y, z = axis.z;
matrix.elements[0] = cos + x * omc;
matrix.elements[1] = y * x * omc - z * sin;
matrix.elements[2] = x * z * omc - y * sin;
matrix.elements[4] = y * x * omc + z * sin;
matrix.elements[5] = cos + y * omc;
matrix.elements[6] = y + z * omc + x * sin;
matrix.elements[8] = z * x * omc + y * sin;
matrix.elements[9] = z * y * omc - x * sin;
matrix.elements[10] = cos + z * omc;
return matrix;
}
public Matrix4 clone() { return new Matrix4().add(this); }
public String toString() {
StringBuilder string = new StringBuilder();
string.append("[");
for (int i = 1; i < 17; i++) {
string.append(" " + elements[i - 1]);
if (i % 4 == 0)
string.append("\n");
}
string.deleteCharAt(1);
string.setLength(string.length() - 1);
string.append("]");
return string.toString();
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.carbondata.hadoop;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.Serializable;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.carbondata.core.constants.CarbonCommonConstants;
import org.apache.carbondata.core.datastore.block.BlockletInfos;
import org.apache.carbondata.core.datastore.block.Distributable;
import org.apache.carbondata.core.datastore.block.TableBlockInfo;
import org.apache.carbondata.core.indexstore.BlockletDetailInfo;
import org.apache.carbondata.core.metadata.ColumnarFormatVersion;
import org.apache.carbondata.core.mutate.UpdateVO;
import org.apache.carbondata.core.util.ByteUtil;
import org.apache.carbondata.core.util.CarbonProperties;
import org.apache.carbondata.core.util.path.CarbonTablePath;
import org.apache.carbondata.hadoop.internal.index.Block;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.Writable;
import org.apache.hadoop.mapreduce.lib.input.FileSplit;
/**
* Carbon input split to allow distributed read of CarbonInputFormat.
*/
public class CarbonInputSplit extends FileSplit
implements Distributable, Serializable, Writable, Block {
private static final long serialVersionUID = 3520344046772190207L;
public String taskId;
private String segmentId;
private String bucketId;
/*
* Invalid segments that need to be removed in task side index
*/
private List<String> invalidSegments;
/*
* Number of BlockLets in a block
*/
private int numberOfBlocklets;
private ColumnarFormatVersion version;
/**
* map of blocklocation and storage id
*/
private Map<String, String> blockStorageIdMap =
new HashMap<>(CarbonCommonConstants.DEFAULT_COLLECTION_SIZE);
private List<UpdateVO> invalidTimestampsList;
/**
* list of delete delta files for split
*/
private String[] deleteDeltaFiles;
private BlockletDetailInfo detailInfo;
public CarbonInputSplit() {
segmentId = null;
taskId = "0";
bucketId = "0";
numberOfBlocklets = 0;
invalidSegments = new ArrayList<>();
version = CarbonProperties.getInstance().getFormatVersion();
}
private CarbonInputSplit(String segmentId, Path path, long start, long length, String[] locations,
ColumnarFormatVersion version, String[] deleteDeltaFiles) {
super(path, start, length, locations);
this.segmentId = segmentId;
String taskNo = CarbonTablePath.DataFileUtil.getTaskNo(path.getName());
if (taskNo.contains("_")) {
taskNo = taskNo.split("_")[0];
}
this.taskId = taskNo;
this.bucketId = CarbonTablePath.DataFileUtil.getBucketNo(path.getName());
this.invalidSegments = new ArrayList<>();
this.version = version;
this.deleteDeltaFiles = deleteDeltaFiles;
}
public CarbonInputSplit(String segmentId, Path path, long start, long length, String[] locations,
int numberOfBlocklets, ColumnarFormatVersion version, String[] deleteDeltaFiles) {
this(segmentId, path, start, length, locations, version, deleteDeltaFiles);
this.numberOfBlocklets = numberOfBlocklets;
}
/**
* Constructor to initialize the CarbonInputSplit with blockStorageIdMap
* @param segmentId
* @param path
* @param start
* @param length
* @param locations
* @param numberOfBlocklets
* @param version
* @param blockStorageIdMap
*/
public CarbonInputSplit(String segmentId, Path path, long start, long length, String[] locations,
int numberOfBlocklets, ColumnarFormatVersion version, Map<String, String> blockStorageIdMap,
String[] deleteDeltaFiles) {
this(segmentId, path, start, length, locations, numberOfBlocklets, version, deleteDeltaFiles);
this.blockStorageIdMap = blockStorageIdMap;
}
public static CarbonInputSplit from(String segmentId, FileSplit split,
ColumnarFormatVersion version)
throws IOException {
return new CarbonInputSplit(segmentId, split.getPath(), split.getStart(), split.getLength(),
split.getLocations(), version, null);
}
public static List<TableBlockInfo> createBlocks(List<CarbonInputSplit> splitList) {
List<TableBlockInfo> tableBlockInfoList = new ArrayList<>();
for (CarbonInputSplit split : splitList) {
BlockletInfos blockletInfos =
new BlockletInfos(split.getNumberOfBlocklets(), 0, split.getNumberOfBlocklets());
try {
TableBlockInfo blockInfo =
new TableBlockInfo(split.getPath().toString(), split.getStart(), split.getSegmentId(),
split.getLocations(), split.getLength(), blockletInfos, split.getVersion(),
split.getDeleteDeltaFiles());
blockInfo.setDetailInfo(split.getDetailInfo());
tableBlockInfoList.add(blockInfo);
} catch (IOException e) {
throw new RuntimeException("fail to get location of split: " + split, e);
}
}
return tableBlockInfoList;
}
public static TableBlockInfo getTableBlockInfo(CarbonInputSplit inputSplit) {
BlockletInfos blockletInfos =
new BlockletInfos(inputSplit.getNumberOfBlocklets(), 0, inputSplit.getNumberOfBlocklets());
try {
TableBlockInfo blockInfo =
new TableBlockInfo(inputSplit.getPath().toString(), inputSplit.getStart(),
inputSplit.getSegmentId(), inputSplit.getLocations(), inputSplit.getLength(),
blockletInfos, inputSplit.getVersion(), inputSplit.getDeleteDeltaFiles());
blockInfo.setDetailInfo(inputSplit.getDetailInfo());
return blockInfo;
} catch (IOException e) {
throw new RuntimeException("fail to get location of split: " + inputSplit, e);
}
}
public String getSegmentId() {
return segmentId;
}
@Override public void readFields(DataInput in) throws IOException {
super.readFields(in);
this.segmentId = in.readUTF();
this.version = ColumnarFormatVersion.valueOf(in.readShort());
this.bucketId = in.readUTF();
int numInvalidSegment = in.readInt();
invalidSegments = new ArrayList<>(numInvalidSegment);
for (int i = 0; i < numInvalidSegment; i++) {
invalidSegments.add(in.readUTF());
}
int numberOfDeleteDeltaFiles = in.readInt();
deleteDeltaFiles = new String[numberOfDeleteDeltaFiles];
for (int i = 0; i < numberOfDeleteDeltaFiles; i++) {
deleteDeltaFiles[i] = in.readUTF();
}
boolean detailInfoExists = in.readBoolean();
if (detailInfoExists) {
detailInfo = new BlockletDetailInfo();
detailInfo.readFields(in);
}
}
@Override public void write(DataOutput out) throws IOException {
super.write(out);
out.writeUTF(segmentId);
out.writeShort(version.number());
out.writeUTF(bucketId);
out.writeInt(invalidSegments.size());
for (String invalidSegment : invalidSegments) {
out.writeUTF(invalidSegment);
}
out.writeInt(null != deleteDeltaFiles ? deleteDeltaFiles.length : 0);
if (null != deleteDeltaFiles) {
for (int i = 0; i < deleteDeltaFiles.length; i++) {
out.writeUTF(deleteDeltaFiles[i]);
}
}
out.writeBoolean(detailInfo != null);
if (detailInfo != null) {
detailInfo.write(out);
}
}
public List<String> getInvalidSegments() {
return invalidSegments;
}
public void setInvalidSegments(List<String> invalidSegments) {
this.invalidSegments = invalidSegments;
}
public void setInvalidTimestampRange(List<UpdateVO> invalidTimestamps) {
invalidTimestampsList = invalidTimestamps;
}
public List<UpdateVO> getInvalidTimestampRange() {
return invalidTimestampsList;
}
/**
* returns the number of blocklets
*
* @return
*/
public int getNumberOfBlocklets() {
return numberOfBlocklets;
}
public ColumnarFormatVersion getVersion() {
return version;
}
public void setVersion(ColumnarFormatVersion version) {
this.version = version;
}
public String getBucketId() {
return bucketId;
}
@Override public int compareTo(Distributable o) {
if (o == null) {
return -1;
}
CarbonInputSplit other = (CarbonInputSplit) o;
int compareResult = 0;
// get the segment id
// converr seg ID to double.
double seg1 = Double.parseDouble(segmentId);
double seg2 = Double.parseDouble(other.getSegmentId());
if (seg1 - seg2 < 0) {
return -1;
}
if (seg1 - seg2 > 0) {
return 1;
}
// Comparing the time task id of the file to other
// if both the task id of the file is same then we need to compare the
// offset of
// the file
String filePath1 = this.getPath().getName();
String filePath2 = other.getPath().getName();
if (CarbonTablePath.isCarbonDataFile(filePath1)) {
byte[] firstTaskId = CarbonTablePath.DataFileUtil.getTaskNo(filePath1)
.getBytes(Charset.forName(CarbonCommonConstants.DEFAULT_CHARSET));
byte[] otherTaskId = CarbonTablePath.DataFileUtil.getTaskNo(filePath2)
.getBytes(Charset.forName(CarbonCommonConstants.DEFAULT_CHARSET));
int compare = ByteUtil.compare(firstTaskId, otherTaskId);
if (compare != 0) {
return compare;
}
int firstBucketNo = Integer.parseInt(CarbonTablePath.DataFileUtil.getBucketNo(filePath1));
int otherBucketNo = Integer.parseInt(CarbonTablePath.DataFileUtil.getBucketNo(filePath2));
if (firstBucketNo != otherBucketNo) {
return firstBucketNo - otherBucketNo;
}
// compare the part no of both block info
int firstPartNo = Integer.parseInt(CarbonTablePath.DataFileUtil.getPartNo(filePath1));
int SecondPartNo = Integer.parseInt(CarbonTablePath.DataFileUtil.getPartNo(filePath2));
compareResult = firstPartNo - SecondPartNo;
} else {
compareResult = filePath1.compareTo(filePath2);
}
if (compareResult != 0) {
return compareResult;
}
return 0;
}
@Override public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof CarbonInputSplit)) {
return false;
}
CarbonInputSplit other = (CarbonInputSplit) obj;
return 0 == this.compareTo(other);
}
@Override public int hashCode() {
int result = taskId.hashCode();
result = 31 * result + segmentId.hashCode();
result = 31 * result + bucketId.hashCode();
result = 31 * result + invalidSegments.hashCode();
result = 31 * result + numberOfBlocklets;
return result;
}
@Override public String getBlockPath() {
return getPath().getName();
}
@Override public List<Long> getMatchedBlocklets() {
return null;
}
@Override public boolean fullScan() {
return true;
}
/**
* returns map of blocklocation and storage id
* @return
*/
public Map<String, String> getBlockStorageIdMap() {
return blockStorageIdMap;
}
public String[] getDeleteDeltaFiles() {
return deleteDeltaFiles;
}
public void setDeleteDeltaFiles(String[] deleteDeltaFiles) {
this.deleteDeltaFiles = deleteDeltaFiles;
}
public BlockletDetailInfo getDetailInfo() {
return detailInfo;
}
public void setDetailInfo(BlockletDetailInfo detailInfo) {
this.detailInfo = detailInfo;
}
}
| |
/*
* Copyright (C) 2015 Zhang Rui <bbcallen@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package tv.danmaku.ijk.media.exo;
import android.content.Context;
import android.net.Uri;
import android.view.Surface;
import android.view.SurfaceHolder;
import com.google.android.exoplayer.ExoPlayer;
import com.google.android.exoplayer.util.Util;
import java.io.FileDescriptor;
import java.util.Map;
import tv.danmaku.ijk.media.exo.demo.EventLogger;
import tv.danmaku.ijk.media.exo.demo.player.DemoPlayer;
import tv.danmaku.ijk.media.exo.demo.player.DemoPlayer.RendererBuilder;
import tv.danmaku.ijk.media.exo.demo.player.ExtractorRendererBuilder;
import tv.danmaku.ijk.media.player.AbstractMediaPlayer;
import tv.danmaku.ijk.media.player.IMediaPlayer;
import tv.danmaku.ijk.media.player.MediaInfo;
import tv.danmaku.ijk.media.player.misc.IjkTrackInfo;
public class IjkExoMediaPlayer extends AbstractMediaPlayer {
private Context mAppContext;
private DemoPlayer mInternalPlayer;
private EventLogger mEventLogger;
private String mDataSource;
private int mVideoWidth;
private int mVideoHeight;
private Surface mSurface;
public static final int TYPE_DASH = 0;
public static final int TYPE_SS = 1;
public static final int TYPE_HLS = 2;
public static final int TYPE_OTHER = 3;
private RendererBuilder mRendererBuilder;
public IjkExoMediaPlayer(Context context) {
mAppContext = context.getApplicationContext();
mDemoListener = new DemoPlayerListener();
mEventLogger = new EventLogger();
mEventLogger.startSession();
}
@Override
public void setDisplay(SurfaceHolder sh) {
if (sh == null)
setSurface(null);
else
setSurface(sh.getSurface());
}
@Override
public void setSurface(Surface surface) {
mSurface = surface;
if (mInternalPlayer != null)
mInternalPlayer.setSurface(surface);
}
@Override
public void setDataSource(Context context, Uri uri) {
mDataSource = uri.toString();
mRendererBuilder = new ExtractorRendererBuilder(context, getUserAgent(), uri);
}
@Override
public void setDataSource(Context context, Uri uri, Map<String, String> headers) {
// TODO: handle headers
setDataSource(context, uri);
}
@Override
public void setDataSource(String path) {
setDataSource(mAppContext, Uri.parse(path));
}
@Override
public void setDataSource(FileDescriptor fd) {
// TODO: no support
throw new UnsupportedOperationException("no support");
}
@Override
public String getDataSource() {
return mDataSource;
}
@Override
public void prepareAsync() throws IllegalStateException {
if (mInternalPlayer != null)
throw new IllegalStateException("can't prepare a prepared player");
mInternalPlayer = new DemoPlayer(mRendererBuilder);
mInternalPlayer.addListener(mDemoListener);
mInternalPlayer.addListener(mEventLogger);
mInternalPlayer.setInfoListener(mEventLogger);
mInternalPlayer.setInternalErrorListener(mEventLogger);
if (mSurface != null)
mInternalPlayer.setSurface(mSurface);
mInternalPlayer.prepare();
mInternalPlayer.setPlayWhenReady(false);
}
@Override
public void start() throws IllegalStateException {
if (mInternalPlayer == null)
return;
mInternalPlayer.setPlayWhenReady(true);
}
@Override
public void stop() throws IllegalStateException {
if (mInternalPlayer == null)
return;
mInternalPlayer.release();
}
@Override
public void pause() throws IllegalStateException {
if (mInternalPlayer == null)
return;
mInternalPlayer.setPlayWhenReady(false);
}
@Override
public void setWakeMode(Context context, int mode) {
// FIXME: implement
}
@Override
public void setScreenOnWhilePlaying(boolean screenOn) {
// TODO: do nothing
}
@Override
public IjkTrackInfo[] getTrackInfo() {
// TODO: implement
return null;
}
@Override
public int getVideoWidth() {
return mVideoWidth;
}
@Override
public int getVideoHeight() {
return mVideoHeight;
}
@Override
public boolean isPlaying() {
if (mInternalPlayer == null)
return false;
int state = mInternalPlayer.getPlaybackState();
switch (state) {
case ExoPlayer.STATE_BUFFERING:
case ExoPlayer.STATE_READY:
return mInternalPlayer.getPlayWhenReady();
case ExoPlayer.STATE_IDLE:
case ExoPlayer.STATE_PREPARING:
case ExoPlayer.STATE_ENDED:
default:
return false;
}
}
@Override
public void seekTo(long msec) throws IllegalStateException {
if (mInternalPlayer == null)
return;
mInternalPlayer.seekTo(msec);
}
@Override
public long getCurrentPosition() {
if (mInternalPlayer == null)
return 0;
return mInternalPlayer.getCurrentPosition();
}
@Override
public long getDuration() {
if (mInternalPlayer == null)
return 0;
return mInternalPlayer.getDuration();
}
@Override
public int getVideoSarNum() {
return 1;
}
@Override
public int getVideoSarDen() {
return 1;
}
@Override
public void reset() {
if (mInternalPlayer != null) {
mInternalPlayer.release();
mInternalPlayer.removeListener(mDemoListener);
mInternalPlayer.removeListener(mEventLogger);
mInternalPlayer.setInfoListener(null);
mInternalPlayer.setInternalErrorListener(null);
mInternalPlayer = null;
}
mSurface = null;
mDataSource = null;
mVideoWidth = 0;
mVideoHeight = 0;
}
@Override
public void setLooping(boolean looping) {
// TODO: no support
throw new UnsupportedOperationException("no support");
}
@Override
public boolean isLooping() {
// TODO: no support
return false;
}
@Override
public void setVolume(float leftVolume, float rightVolume) {
// TODO: no support
}
@Override
public int getAudioSessionId() {
// TODO: no support
return 0;
}
@Override
public MediaInfo getMediaInfo() {
// TODO: no support
return null;
}
@Override
public void setLogEnabled(boolean enable) {
// do nothing
}
@Override
public boolean isPlayable() {
return true;
}
@Override
public void setAudioStreamType(int streamtype) {
// do nothing
}
@Override
public void setKeepInBackground(boolean keepInBackground) {
// do nothing
}
@Override
public void release() {
if (mInternalPlayer != null) {
reset();
mDemoListener = null;
mEventLogger.endSession();
mEventLogger = null;
}
}
private String getUserAgent() {
return Util.getUserAgent(mAppContext, "IjkExoMediaPlayer");
}
private class DemoPlayerListener implements DemoPlayer.Listener {
private boolean mIsPrepareing = false;
private boolean mDidPrepare = false;
private boolean mIsBuffering = false;
public void onStateChanged(boolean playWhenReady, int playbackState)
{
if (mIsBuffering) {
switch (playbackState) {
case ExoPlayer.STATE_ENDED:
case ExoPlayer.STATE_READY:
notifyOnInfo(IMediaPlayer.MEDIA_INFO_BUFFERING_END, mInternalPlayer.getBufferedPercentage());
mIsBuffering = false;
break;
}
}
if (mIsPrepareing) {
switch (playbackState) {
case ExoPlayer.STATE_READY:
notifyOnPrepared();
mIsPrepareing = false;
mDidPrepare = false;
break;
}
}
switch (playbackState) {
case ExoPlayer.STATE_IDLE:
notifyOnCompletion();
break;
case ExoPlayer.STATE_PREPARING:
mIsPrepareing = true;
break;
case ExoPlayer.STATE_BUFFERING:
notifyOnInfo(IMediaPlayer.MEDIA_INFO_BUFFERING_START, mInternalPlayer.getBufferedPercentage());
mIsBuffering = true;
break;
case ExoPlayer.STATE_READY:
break;
case ExoPlayer.STATE_ENDED:
notifyOnCompletion();
break;
default:
break;
}
}
public void onError(Exception e)
{
notifyOnError(IMediaPlayer.MEDIA_ERROR_UNKNOWN, IMediaPlayer.MEDIA_ERROR_UNKNOWN);
}
public void onVideoSizeChanged(int width, int height, int unappliedRotationDegrees,
float pixelWidthHeightRatio)
{
mVideoWidth = width;
mVideoHeight = height;
notifyOnVideoSizeChanged(width, height, 1, 1);
if (unappliedRotationDegrees > 0)
notifyOnInfo(IMediaPlayer.MEDIA_INFO_VIDEO_ROTATION_CHANGED, unappliedRotationDegrees);
}
}
private DemoPlayerListener mDemoListener;
}
| |
package net.alpenblock.bungeeperms.platform.bungee;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import lombok.Getter;
import net.alpenblock.bungeeperms.BungeePerms;
import net.alpenblock.bungeeperms.Color;
import net.alpenblock.bungeeperms.Config;
import net.alpenblock.bungeeperms.platform.MessageEncoder;
import net.alpenblock.bungeeperms.platform.Sender;
import net.alpenblock.bungeeperms.platform.PlatformPlugin;
import net.alpenblock.bungeeperms.platform.PlatformType;
import net.alpenblock.bungeeperms.platform.PluginMessageSender;
import net.alpenblock.bungeeperms.platform.independend.GroupProcessor;
import net.md_5.bungee.api.CommandSender;
import net.md_5.bungee.api.ProxyServer;
import net.md_5.bungee.api.connection.ProxiedPlayer;
import net.md_5.bungee.api.plugin.Command;
import net.md_5.bungee.api.plugin.Plugin;
@Getter
public class BungeePlugin extends Plugin implements PlatformPlugin
{
@Getter
private static BungeePlugin instance;
private BungeeConfig config;
//platform dependend parts
private BungeeEventListener listener;
private BungeeEventDispatcher dispatcher;
private BungeeNotifier notifier;
private PluginMessageSender pmsender;
private BungeePerms bungeeperms;
private final PlatformType platformType = PlatformType.BungeeCord;
@Override
public void onLoad()
{
//static
instance = this;
//load config
Config conf = new Config(this, "/config.yml");
conf.load();
config = new BungeeConfig(conf);
config.load();
//register commands
loadcmds();
listener = new BungeeEventListener(config);
dispatcher = new BungeeEventDispatcher();
notifier = new BungeeNotifier(config);
pmsender = new BungeePluginMessageSender();
bungeeperms = new BungeePerms(this, config, pmsender, notifier, listener, dispatcher);
bungeeperms.load();
bungeeperms.getPermissionsResolver().registerProcessor(new GroupProcessor());
}
@Override
public void onEnable()
{
ProxyServer.getInstance().registerChannel(BungeePerms.CHANNEL);
bungeeperms.enable();
}
@Override
public void onDisable()
{
bungeeperms.disable();
ProxyServer.getInstance().unregisterChannel(BungeePerms.CHANNEL);
}
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
{
return bungeeperms.getCommandHandler().onCommand(new BungeeSender(sender), cmd.getName(), label, args);
}
private void loadcmds()
{
ProxyServer.getInstance().getPluginManager().registerCommand(this,
new Command("bungeeperms", null, "bp")
{
@Override
public void execute(final CommandSender sender, final String[] args)
{
final Command cmd = this;
ProxyServer.getInstance().getScheduler().runAsync(instance, new Runnable()
{
@Override
public void run()
{
if (!BungeePlugin.this.onCommand(sender, cmd, "", args))
{
sender.sendMessage(Color.Error + "[BungeePerms] Command not found");
}
}
});
}
});
}
//plugin info
@Override
public String getPluginName()
{
return this.getDescription().getName();
}
@Override
public String getVersion()
{
return this.getDescription().getVersion();
}
@Override
public String getAuthor()
{
return this.getDescription().getAuthor();
}
@Override
public String getPluginFolderPath()
{
return this.getDataFolder().getAbsolutePath();
}
@Override
public File getPluginFolder()
{
return this.getDataFolder();
}
@Override
public Sender getPlayer(String name)
{
CommandSender sender = ProxyServer.getInstance().getPlayer(name);
Sender s = null;
if (sender != null)
{
s = new BungeeSender(sender);
}
return s;
}
@Override
public Sender getPlayer(UUID uuid)
{
CommandSender sender = ProxyServer.getInstance().getPlayer(uuid);
Sender s = null;
if (sender != null)
{
s = new BungeeSender(sender);
}
return s;
}
@Override
public Sender getConsole()
{
return new BungeeSender(ProxyServer.getInstance().getConsole());
}
@Override
public List<Sender> getPlayers()
{
List<Sender> senders = new ArrayList<>();
for (ProxiedPlayer pp : ProxyServer.getInstance().getPlayers())
{
senders.add(new BungeeSender(pp));
}
return senders;
}
@Override
public boolean isChatApiPresent()
{
try
{
Class.forName("net.md_5.bungee.api.chat.BaseComponent");
return true;
}
catch (Throwable t)
{
return false;
}
}
@Override
public MessageEncoder newMessageEncoder()
{
return new BungeeMessageEncoder("");
}
@Override
public int registerRepeatingTask(Runnable r, long delay, long interval)
{
return ProxyServer.getInstance().getScheduler().schedule(this, r, delay, interval, TimeUnit.MILLISECONDS).getId();
}
@Override
public void cancelTask(int id)
{
ProxyServer.getInstance().getScheduler().cancel(id);
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.hadoop.io.nativeio;
import java.io.File;
import java.io.FileDescriptor;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assume.*;
import static org.junit.Assert.*;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.FileUtil;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.fs.permission.FsPermission;
import org.apache.hadoop.util.NativeCodeLoader;
public class TestNativeIO {
static final Log LOG = LogFactory.getLog(TestNativeIO.class);
static final File TEST_DIR = new File(
System.getProperty("test.build.data"), "testnativeio");
@Before
public void checkLoaded() {
assumeTrue(NativeCodeLoader.isNativeCodeLoaded());
}
@Before
public void setupTestDir() throws IOException {
FileUtil.fullyDelete(TEST_DIR);
TEST_DIR.mkdirs();
}
@Test
public void testFstat() throws Exception {
FileOutputStream fos = new FileOutputStream(
new File(TEST_DIR, "testfstat"));
NativeIO.Stat stat = NativeIO.fstat(fos.getFD());
fos.close();
LOG.info("Stat: " + String.valueOf(stat));
assertEquals(System.getProperty("user.name"), stat.getOwner());
assertEquals(NativeIO.Stat.S_IFREG, stat.getMode() & NativeIO.Stat.S_IFMT);
}
@Test
public void testGetOwner() throws Exception {
FileOutputStream fos = new FileOutputStream(
new File(TEST_DIR, "testfstat"));
String owner = NativeIO.getOwner(fos.getFD());
fos.close();
LOG.info("Owner: " + owner);
assertEquals(System.getProperty("user.name"), owner);
}
@Test
public void testFstatClosedFd() throws Exception {
FileOutputStream fos = new FileOutputStream(
new File(TEST_DIR, "testfstat2"));
fos.close();
try {
NativeIO.Stat stat = NativeIO.fstat(fos.getFD());
} catch (IOException e) {
LOG.info("Got expected exception", e);
}
}
@Test
public void testOpen() throws Exception {
LOG.info("Open a missing file without O_CREAT and it should fail");
try {
FileDescriptor fd = NativeIO.open(
new File(TEST_DIR, "doesntexist").getAbsolutePath(),
NativeIO.O_WRONLY, 0700);
fail("Able to open a new file without O_CREAT");
} catch (IOException ioe) {
// expected
}
LOG.info("Test creating a file with O_CREAT");
FileDescriptor fd = NativeIO.open(
new File(TEST_DIR, "testWorkingOpen").getAbsolutePath(),
NativeIO.O_WRONLY | NativeIO.O_CREAT, 0700);
assertNotNull(true);
assertTrue(fd.valid());
FileOutputStream fos = new FileOutputStream(fd);
fos.write("foo".getBytes());
fos.close();
assertFalse(fd.valid());
LOG.info("Test exclusive create");
try {
fd = NativeIO.open(
new File(TEST_DIR, "testWorkingOpen").getAbsolutePath(),
NativeIO.O_WRONLY | NativeIO.O_CREAT | NativeIO.O_EXCL, 0700);
fail("Was able to create existing file with O_EXCL");
} catch (IOException ioe) {
// expected
}
}
/**
* Test that opens and closes a file 10000 times - this would crash with
* "Too many open files" if we leaked fds using this access pattern.
*/
@Test
public void testFDDoesntLeak() throws IOException {
for (int i = 0; i < 10000; i++) {
FileDescriptor fd = NativeIO.open(
new File(TEST_DIR, "testNoFdLeak").getAbsolutePath(),
NativeIO.O_WRONLY | NativeIO.O_CREAT, 0700);
assertNotNull(true);
assertTrue(fd.valid());
FileOutputStream fos = new FileOutputStream(fd);
fos.write("foo".getBytes());
fos.close();
}
}
/**
* Test basic chmod operation
*/
@Test
public void testChmod() throws Exception {
try {
NativeIO.chmod("/this/file/doesnt/exist", 777);
fail("Chmod of non-existent file didn't fail");
} catch (NativeIOException nioe) {
assertEquals(Errno.ENOENT, nioe.getErrno());
}
File toChmod = new File(TEST_DIR, "testChmod");
assertTrue("Create test subject",
toChmod.exists() || toChmod.mkdir());
NativeIO.chmod(toChmod.getAbsolutePath(), 0777);
assertPermissions(toChmod, 0777);
NativeIO.chmod(toChmod.getAbsolutePath(), 0000);
assertPermissions(toChmod, 0000);
NativeIO.chmod(toChmod.getAbsolutePath(), 0644);
assertPermissions(toChmod, 0644);
}
@Test
public void testPosixFadvise() throws Exception {
FileInputStream fis = new FileInputStream("/dev/zero");
try {
NativeIO.posix_fadvise(fis.getFD(), 0, 0,
NativeIO.POSIX_FADV_SEQUENTIAL);
} catch (UnsupportedOperationException uoe) {
// we should just skip the unit test on machines where we don't
// have fadvise support
assumeTrue(false);
} finally {
fis.close();
}
try {
NativeIO.posix_fadvise(fis.getFD(), 0, 1024,
NativeIO.POSIX_FADV_SEQUENTIAL);
fail("Did not throw on bad file");
} catch (NativeIOException nioe) {
assertEquals(Errno.EBADF, nioe.getErrno());
}
try {
NativeIO.posix_fadvise(null, 0, 1024,
NativeIO.POSIX_FADV_SEQUENTIAL);
fail("Did not throw on null file");
} catch (NullPointerException npe) {
// expected
}
}
@Test
public void testSyncFileRange() throws Exception {
FileOutputStream fos = new FileOutputStream(
new File(TEST_DIR, "testSyncFileRange"));
try {
fos.write("foo".getBytes());
NativeIO.sync_file_range(fos.getFD(), 0, 1024,
NativeIO.SYNC_FILE_RANGE_WRITE);
// no way to verify that this actually has synced,
// but if it doesn't throw, we can assume it worked
} catch (UnsupportedOperationException uoe) {
// we should just skip the unit test on machines where we don't
// have fadvise support
assumeTrue(false);
} finally {
fos.close();
}
try {
NativeIO.sync_file_range(fos.getFD(), 0, 1024,
NativeIO.SYNC_FILE_RANGE_WRITE);
fail("Did not throw on bad file");
} catch (NativeIOException nioe) {
assertEquals(Errno.EBADF, nioe.getErrno());
}
}
private void assertPermissions(File f, int expected) throws IOException {
FileSystem localfs = FileSystem.getLocal(new Configuration());
FsPermission perms = localfs.getFileStatus(
new Path(f.getAbsolutePath())).getPermission();
assertEquals(expected, perms.toShort());
}
}
| |
package btspn.push;
import com.googlecode.concurrenttrees.radix.ConcurrentRadixTree;
import com.googlecode.concurrenttrees.radix.node.Node;
import com.googlecode.concurrenttrees.radix.node.concrete.DefaultCharSequenceNodeFactory;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.*;
import org.slf4j.Logger;
import org.zeromq.*;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.function.Supplier;
public class Subscriptions implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(Subscriptions.class);
private final String pubAddress;
private final String snapshotAddress;
private final String pipeAddress;
private final Supplier<ConcurrentRadixTree<Set<String>>> subscriptionsFactory;
private ConcurrentRadixTree<Set<String>> subscriptions;
private final Map<String, Set<String>> pathSubscriptions;
public Subscriptions(String pubAddress, String snapshotAddress, String pipeAddress, Supplier<ConcurrentRadixTree<Set<String>>> subscriptionsFactory) {
this.pubAddress = pubAddress;
this.snapshotAddress = snapshotAddress;
this.pipeAddress = pipeAddress;
this.subscriptionsFactory = subscriptionsFactory;
this.subscriptions = subscriptionsFactory.get();
this.pathSubscriptions = new HashMap<>();
}
@Override
public void run() {
ZContext ctx = new ZContext();
ZMQ.Socket events = ctx.createSocket(ZMQ.SUB);
events.connect(pubAddress);
events.subscribe("".getBytes());
ZMQ.Socket snapshot = ctx.createSocket(ZMQ.DEALER);
snapshot.connect(snapshotAddress);
ZMQ.Socket pipe = ctx.createSocket(ZMQ.PAIR);
pipe.bind(pipeAddress);
AtomicLong lastClientHugz = new AtomicLong(System.currentTimeMillis());
AtomicLong lastServerHugz = new AtomicLong(System.currentTimeMillis());
ZLoop loop = new ZLoop();
loop.addPoller(new ZMQ.PollItem(events, ZPoller.IN), (loop1, item, arg) -> {
if (item.isReadable()) {
ZMsg msg = ZMsg.recvMsg(item.getSocket());
lastServerHugz.set(System.currentTimeMillis());
if (msg.size() == 1) {
String cmd = msg.peekFirst().toString();
if ("RESET".equals(cmd)) {
subscriptions = subscriptionsFactory.get();
pathSubscriptions.clear();
sendToPipe(pipe, msg, lastClientHugz);
} else if ("HUGZ".equals(cmd)) {
} else {
LOG.warn("Invalid msg {}", msg);
msg.destroy();
}
} else if (msg.size() == 4) {
// KVSYNC
Messages.KvSync kvSync = Messages.KvSync.parse(msg.duplicate());
Set<String> publish = find(subscriptions, kvSync.key);
if (!publish.isEmpty()) {
String publishStr = StringUtils.join(publish, "|");
msg.push(publishStr);
sendToPipe(pipe, msg, lastClientHugz);
} else {
msg.destroy();
}
}
}
return 0;
}, null);
loop.addPoller(new ZMQ.PollItem(snapshot, ZPoller.IN), (loop1, item, arg) -> {
if (item.isReadable()) {
ZMsg msg = ZMsg.recvMsg(item.getSocket());
msg.unwrap();
if (msg.size() == 5) {
// KVSYNCT
sendToPipe(pipe, msg, lastClientHugz);
} else {
LOG.warn("Invalid msg {}", msg);
msg.destroy();
}
}
return 0;
}, null);
loop.addPoller(new ZMQ.PollItem(pipe, ZPoller.IN), (loop1, item, arg) -> {
if (item.isReadable()) {
ZMsg msg = ZMsg.recvMsg(item.getSocket());
String cmd = msg.peekFirst().toString();
LOG.trace("PIPE: {}", msg);
if ("RESET".equals(cmd)) {
LOG.info("Reseting connections");
subscriptions = subscriptionsFactory.get();
pathSubscriptions.clear();
} else if ("SUB".equals(cmd)) {
Messages.Sub sub = Messages.Sub.parse(msg);
Set<String> set = subscriptions.getValueForExactKey(sub.path);
pathSubscriptions.compute(sub.client, (s, strings) -> {
if (strings == null) {
strings = new HashSet<>();
}
strings.add(sub.path);
return strings;
});
if (set == null) {
set = new HashSet<>();
} else {
set = new HashSet<>(set);
}
set.add(sub.client);
subscriptions.put(sub.path, Collections.unmodifiableSet(set));
new Messages.Icanhaz(sub.client, sub.path).send(snapshot);
} else if ("UNSUB".equals(cmd)) {
msg.popString();
String identity = msg.popString();
if (!msg.isEmpty()) {
unsubscribe(identity, msg.popString());
} else {
Set<String> paths = pathSubscriptions.get(identity);
if (paths != null) {
for (String path : paths) {
unsubscribe(identity, path);
}
}
}
}
}
return 0;
}, null);
loop.addTimer(50, 0, (loop1, item, arg) -> {
if (System.currentTimeMillis() - lastClientHugz.get() > 200) {
ZMsg msg = new ZMsg();
msg.add("HUGZ");
sendToPipe(pipe, msg, lastClientHugz);
}
return 0;
}, null);
loop.start();
loop.destroy();
events.close();
snapshot.close();
ctx.close();
}
private static void sendToPipe(ZMQ.Socket pipe, ZMsg msg, AtomicLong lastHugz) {
msg.send(pipe, true);
lastHugz.set(System.currentTimeMillis());
}
public static Set<String> find(ConcurrentRadixTree<Set<String>> subscriptions, String path) {
String originalPath = path;
Node node = subscriptions.getNode();
Set<String> publish = new HashSet<>();
do {
if (node.getValue() != null && path.startsWith(node.getIncomingEdge().toString())) {
publish.addAll((Set<String>) node.getValue());
}
if (!node.getOutgoingEdges().isEmpty()) {
path = path.substring(node.getIncomingEdge().length());
node = node.getOutgoingEdge(path.charAt(0));
} else {
subscriptions.getValuesForKeysStartingWith(originalPath).forEach(publish::addAll);
node = null;
}
} while (node != null);
return publish;
}
private void unsubscribe(String identity, String path) {
Set<String> set = subscriptions.getValueForExactKey(path);
if (set != null) {
set = new HashSet<>(set);
set.remove(identity);
if (set.isEmpty()) {
subscriptions.remove(path);
} else {
subscriptions.put(path, Collections.unmodifiableSet(set));
}
}
}
public static void main(String[] args) {
new Subscriptions("tcp://127.0.0.1:5001", "tcp://127.0.0.1:5002", "tcp://127.0.0.1:5004", () -> new ConcurrentRadixTree<Set<String>>(new DefaultCharSequenceNodeFactory())).run();
}
public static void main1(String[] args) {
Thread t = new Thread(new Subscriptions("tcp://127.0.0.1:5001", "tcp://127.0.0.1:5002", "tcp://127.0.0.1:5004", () -> new ConcurrentRadixTree<Set<String>>(new DefaultCharSequenceNodeFactory())));
t.setDaemon(false);
t.start();
ZContext ctx = new ZContext();
ZMQ.Socket pipe = ctx.createSocket(ZMQ.PAIR);
pipe.connect("tcp://127.0.0.1:5004");
new Messages.Sub("1", "/overview").send(pipe);
ZLoop loop = new ZLoop();
loop.addPoller(new ZMQ.PollItem(pipe, ZPoller.IN), (loop1, item, arg) -> {
if (item.isReadable()) {
ZMsg msg = ZMsg.recvMsg(item.getSocket());
msg.dump();
}
return 0;
}, null);
loop.start();
loop.destroy();
ctx.close();
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.test.junit4;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import javax.naming.Context;
import javax.naming.InitialContext;
import org.apache.camel.CamelContext;
import org.apache.camel.ConsumerTemplate;
import org.apache.camel.Endpoint;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.Message;
import org.apache.camel.NoSuchEndpointException;
import org.apache.camel.Predicate;
import org.apache.camel.Processor;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.RoutesBuilder;
import org.apache.camel.Service;
import org.apache.camel.ServiceStatus;
import org.apache.camel.api.management.mbean.ManagedCamelContextMBean;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.component.properties.PropertiesComponent;
import org.apache.camel.impl.BreakpointSupport;
import org.apache.camel.impl.DefaultCamelBeanPostProcessor;
import org.apache.camel.impl.DefaultCamelContext;
import org.apache.camel.impl.DefaultDebugger;
import org.apache.camel.impl.InterceptSendToMockEndpointStrategy;
import org.apache.camel.impl.JndiRegistry;
import org.apache.camel.management.JmxSystemPropertyKeys;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.model.ProcessorDefinition;
import org.apache.camel.spi.Language;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.StopWatch;
import org.apache.camel.util.TimeUtils;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.Rule;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* A useful base class which creates a {@link org.apache.camel.CamelContext} with some routes
* along with a {@link org.apache.camel.ProducerTemplate} for use in the test case
*
* @version
*/
public abstract class CamelTestSupport extends TestSupport {
private static final Logger LOG = LoggerFactory.getLogger(CamelTestSupport.class);
private static final ThreadLocal<Boolean> INIT = new ThreadLocal<Boolean>();
private static ThreadLocal<ModelCamelContext> threadCamelContext = new ThreadLocal<ModelCamelContext>();
private static ThreadLocal<ProducerTemplate> threadTemplate = new ThreadLocal<ProducerTemplate>();
private static ThreadLocal<ConsumerTemplate> threadConsumer = new ThreadLocal<ConsumerTemplate>();
private static ThreadLocal<Service> threadService = new ThreadLocal<Service>();
protected volatile ModelCamelContext context;
protected volatile ProducerTemplate template;
protected volatile ConsumerTemplate consumer;
protected volatile Service camelContextService;
protected boolean dumpRouteStats;
private boolean useRouteBuilder = true;
private final DebugBreakpoint breakpoint = new DebugBreakpoint();
private final StopWatch watch = new StopWatch();
private final Map<String, String> fromEndpoints = new HashMap<String, String>();
private CamelTestWatcher camelTestWatcher = new CamelTestWatcher();
/**
* Use the RouteBuilder or not
* @return <tt>true</tt> then {@link CamelContext} will be auto started,
* <tt>false</tt> then {@link CamelContext} will <b>not</b> be auto started (you will have to start it manually)
*/
public boolean isUseRouteBuilder() {
return useRouteBuilder;
}
public void setUseRouteBuilder(boolean useRouteBuilder) {
this.useRouteBuilder = useRouteBuilder;
}
/**
* Whether to dump route coverage stats at the end of the test.
* <p/>
* This allows tooling or manual inspection of the stats, so you can generate a route trace diagram of which EIPs
* have been in use and which have not. Similar concepts as a code coverage report.
*
* @return <tt>true</tt> to write route coverage status in an xml file in the <tt>target/camel-route-coverage</tt> directory after the test has finished.
*/
public boolean isDumpRouteCoverage() {
return false;
}
/**
* Override when using <a href="http://camel.apache.org/advicewith.html">advice with</a> and return <tt>true</tt>.
* This helps knowing advice with is to be used, and {@link CamelContext} will not be started before
* the advice with takes place. This helps by ensuring the advice with has been property setup before the
* {@link CamelContext} is started
* <p/>
* <b>Important:</b> Its important to start {@link CamelContext} manually from the unit test
* after you are done doing all the advice with.
*
* @return <tt>true</tt> if you use advice with in your unit tests.
*/
public boolean isUseAdviceWith() {
return false;
}
/**
* Override to control whether {@link CamelContext} should be setup per test or per class.
* <p/>
* By default it will be setup/teardown per test (per test method). If you want to re-use
* {@link CamelContext} between test methods you can override this method and return <tt>true</tt>
* <p/>
* <b>Important:</b> Use this with care as the {@link CamelContext} will carry over state
* from previous tests, such as endpoints, components etc. So you cannot use this in all your tests.
* <p/>
* Setting up {@link CamelContext} uses the {@link #doPreSetup()}, {@link #doSetUp()}, and {@link #doPostSetup()}
* methods in that given order.
*
* @return <tt>true</tt> per class, <tt>false</tt> per test.
*/
public boolean isCreateCamelContextPerClass() {
return false;
}
/**
* Override to enable auto mocking endpoints based on the pattern.
* <p/>
* Return <tt>*</tt> to mock all endpoints.
*
* @see org.apache.camel.util.EndpointHelper#matchEndpoint(String, String)
*/
public String isMockEndpoints() {
return null;
}
/**
* Override to enable auto mocking endpoints based on the pattern, and <b>skip</b> sending
* to original endpoint.
* <p/>
* Return <tt>*</tt> to mock all endpoints.
*
* @see org.apache.camel.util.EndpointHelper#matchEndpoint(String, String)
*/
public String isMockEndpointsAndSkip() {
return null;
}
public void replaceRouteFromWith(String routeId, String fromEndpoint) {
fromEndpoints.put(routeId, fromEndpoint);
}
/**
* Override to enable debugger
* <p/>
* Is default <tt>false</tt>
*/
public boolean isUseDebugger() {
return false;
}
public Service getCamelContextService() {
return camelContextService;
}
public Service camelContextService() {
return camelContextService;
}
public CamelContext context() {
return context;
}
public ProducerTemplate template() {
return template;
}
public ConsumerTemplate consumer() {
return consumer;
}
/**
* Allows a service to be registered a separate lifecycle service to start
* and stop the context; such as for Spring when the ApplicationContext is
* started and stopped, rather than directly stopping the CamelContext
*/
public void setCamelContextService(Service service) {
camelContextService = service;
threadService.set(camelContextService);
}
@Before
public void setUp() throws Exception {
log.info("********************************************************************************");
log.info("Testing: " + getTestMethodName() + "(" + getClass().getName() + ")");
log.info("********************************************************************************");
if (isCreateCamelContextPerClass()) {
// test is per class, so only setup once (the first time)
boolean first = INIT.get() == null;
if (first) {
doPreSetup();
doSetUp();
doPostSetup();
} else {
// and in between tests we must do IoC and reset mocks
postProcessTest();
resetMocks();
}
} else {
// test is per test so always setup
doPreSetup();
doSetUp();
doPostSetup();
}
// only start timing after all the setup
watch.restart();
}
/**
* Strategy to perform any pre setup, before {@link CamelContext} is created
*/
protected void doPreSetup() throws Exception {
// noop
}
/**
* Strategy to perform any post setup after {@link CamelContext} is created
*/
protected void doPostSetup() throws Exception {
// noop
}
private void doSetUp() throws Exception {
log.debug("setUp test");
// jmx is enabled if we have configured to use it, or if dump route coverage is enabled (it requires JMX)
boolean jmx = useJmx() || isDumpRouteCoverage();
if (jmx) {
enableJMX();
} else {
disableJMX();
}
context = (ModelCamelContext)createCamelContext();
threadCamelContext.set(context);
assertNotNull("No context found!", context);
// reduce default shutdown timeout to avoid waiting for 300 seconds
context.getShutdownStrategy().setTimeout(getShutdownTimeout());
// set debugger if enabled
if (isUseDebugger()) {
if (context.getStatus().equals(ServiceStatus.Started)) {
log.info("Cannot setting the Debugger to the starting CamelContext, stop the CamelContext now.");
// we need to stop the context first to setup the debugger
context.stop();
}
context.setDebugger(new DefaultDebugger());
context.getDebugger().addBreakpoint(breakpoint);
// note: when stopping CamelContext it will automatic remove the breakpoint
}
template = context.createProducerTemplate();
template.start();
consumer = context.createConsumerTemplate();
consumer.start();
threadTemplate.set(template);
threadConsumer.set(consumer);
// enable auto mocking if enabled
String pattern = isMockEndpoints();
if (pattern != null) {
context.addRegisterEndpointCallback(new InterceptSendToMockEndpointStrategy(pattern));
}
pattern = isMockEndpointsAndSkip();
if (pattern != null) {
context.addRegisterEndpointCallback(new InterceptSendToMockEndpointStrategy(pattern, true));
}
// configure properties component (mandatory for testing)
PropertiesComponent pc = context.getComponent("properties", PropertiesComponent.class);
Properties extra = useOverridePropertiesWithPropertiesComponent();
if (extra != null && !extra.isEmpty()) {
pc.setOverrideProperties(extra);
}
Boolean ignore = ignoreMissingLocationWithPropertiesComponent();
if (ignore != null) {
pc.setIgnoreMissingLocation(ignore);
}
postProcessTest();
if (isUseRouteBuilder()) {
RoutesBuilder[] builders = createRouteBuilders();
for (RoutesBuilder builder : builders) {
log.debug("Using created route builder: " + builder);
context.addRoutes(builder);
}
replaceFromEndpoints();
boolean skip = "true".equalsIgnoreCase(System.getProperty("skipStartingCamelContext"));
if (skip) {
log.info("Skipping starting CamelContext as system property skipStartingCamelContext is set to be true.");
} else if (isUseAdviceWith()) {
log.info("Skipping starting CamelContext as isUseAdviceWith is set to true.");
} else {
startCamelContext();
}
} else {
replaceFromEndpoints();
log.debug("Using route builder from the created context: " + context);
}
log.debug("Routing Rules are: " + context.getRoutes());
assertValidContext(context);
INIT.set(true);
}
private void replaceFromEndpoints() throws Exception {
for (final Map.Entry<String, String> entry : fromEndpoints.entrySet()) {
context.getRouteDefinition(entry.getKey()).adviceWith(context, new AdviceWithRouteBuilder() {
@Override
public void configure() throws Exception {
replaceFromWith(entry.getValue());
}
});
}
}
@After
public void tearDown() throws Exception {
long time = watch.stop();
log.info("********************************************************************************");
log.info("Testing done: " + getTestMethodName() + "(" + getClass().getName() + ")");
log.info("Took: " + TimeUtils.printDuration(time) + " (" + time + " millis)");
// if we should dump route stats, then write that to a file
if (isDumpRouteCoverage()) {
String className = this.getClass().getSimpleName();
String dir = "target/camel-route-coverage";
String name = className + "-" + getTestMethodName() + ".xml";
ManagedCamelContextMBean managedCamelContext = context.getManagedCamelContext();
if (managedCamelContext == null) {
log.warn("Cannot dump route coverage to file as JMX is not enabled. Override useJmx() method to enable JMX in the unit test classes.");
} else {
String xml = managedCamelContext.dumpRoutesCoverageAsXml();
String combined = "<camelRouteCoverage>\n" + gatherTestDetailsAsXml() + xml + "\n</camelRouteCoverage>";
File file = new File(dir);
// ensure dir exists
file.mkdirs();
file = new File(dir, name);
log.info("Dumping route coverage to file: " + file);
InputStream is = new ByteArrayInputStream(combined.getBytes());
OutputStream os = new FileOutputStream(file, false);
IOHelper.copyAndCloseInput(is, os);
IOHelper.close(os);
}
}
log.info("********************************************************************************");
if (isCreateCamelContextPerClass()) {
// we tear down in after class
return;
}
LOG.debug("tearDown test");
doStopTemplates(consumer, template);
doStopCamelContext(context, camelContextService);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
INIT.remove();
LOG.debug("tearDownAfterClass test");
doStopTemplates(threadConsumer.get(), threadTemplate.get());
doStopCamelContext(threadCamelContext.get(), threadService.get());
}
/**
* Gathers test details as xml
*/
private String gatherTestDetailsAsXml() {
StringBuilder sb = new StringBuilder();
sb.append("<test>\n");
sb.append(" <class>").append(getClass().getName()).append("</class>\n");
sb.append(" <method>").append(getTestMethodName()).append("</method>\n");
sb.append(" <time>").append(getCamelTestWatcher().timeTaken()).append("</time>\n");
sb.append("</test>\n");
return sb.toString();
}
/**
* Returns the timeout to use when shutting down (unit in seconds).
* <p/>
* Will default use 10 seconds.
*
* @return the timeout to use
*/
protected int getShutdownTimeout() {
return 10;
}
/**
* Whether or not JMX should be used during testing.
*
* @return <tt>false</tt> by default.
*/
protected boolean useJmx() {
return false;
}
/**
* Whether or not type converters should be lazy loaded (notice core converters is always loaded)
*
* @return <tt>false</tt> by default.
*/
@Deprecated
protected boolean isLazyLoadingTypeConverter() {
return false;
}
/**
* Override this method to include and override properties
* with the Camel {@link PropertiesComponent}.
*
* @return additional properties to add/override.
*/
protected Properties useOverridePropertiesWithPropertiesComponent() {
return null;
}
@Rule
public CamelTestWatcher getCamelTestWatcher() {
return camelTestWatcher;
}
/**
* Whether to ignore missing locations with the {@link PropertiesComponent}.
* For example when unit testing you may want to ignore locations that are
* not available in the environment you use for testing.
*
* @return <tt>true</tt> to ignore, <tt>false</tt> to not ignore, and <tt>null</tt> to leave as configured
* on the {@link PropertiesComponent}
*/
protected Boolean ignoreMissingLocationWithPropertiesComponent() {
return null;
}
protected void postProcessTest() throws Exception {
context = threadCamelContext.get();
template = threadTemplate.get();
consumer = threadConsumer.get();
camelContextService = threadService.get();
applyCamelPostProcessor();
}
/**
* Applies the {@link DefaultCamelBeanPostProcessor} to this instance.
*
* Derived classes using IoC / DI frameworks may wish to turn this into a NoOp such as for CDI
* we would just use CDI to inject this
*/
protected void applyCamelPostProcessor() throws Exception {
// use the default bean post processor from camel-core
DefaultCamelBeanPostProcessor processor = new DefaultCamelBeanPostProcessor(context);
processor.postProcessBeforeInitialization(this, getClass().getName());
processor.postProcessAfterInitialization(this, getClass().getName());
}
protected void stopCamelContext() throws Exception {
doStopCamelContext(context, camelContextService);
}
private static void doStopCamelContext(CamelContext context, Service camelContextService) throws Exception {
if (camelContextService != null) {
if (camelContextService == threadService.get()) {
threadService.remove();
}
camelContextService.stop();
} else {
if (context != null) {
if (context == threadCamelContext.get()) {
threadCamelContext.remove();
}
context.stop();
}
}
}
private static void doStopTemplates(ConsumerTemplate consumer, ProducerTemplate template) throws Exception {
if (consumer != null) {
if (consumer == threadConsumer.get()) {
threadConsumer.remove();
}
consumer.stop();
}
if (template != null) {
if (template == threadTemplate.get()) {
threadTemplate.remove();
}
template.stop();
}
}
protected void startCamelContext() throws Exception {
if (camelContextService != null) {
camelContextService.start();
} else {
if (context instanceof DefaultCamelContext) {
DefaultCamelContext defaultCamelContext = (DefaultCamelContext)context;
if (!defaultCamelContext.isStarted()) {
defaultCamelContext.start();
}
} else {
context.start();
}
}
}
@SuppressWarnings("deprecation")
protected CamelContext createCamelContext() throws Exception {
CamelContext context = new DefaultCamelContext(createRegistry());
context.setLazyLoadTypeConverters(isLazyLoadingTypeConverter());
return context;
}
protected JndiRegistry createRegistry() throws Exception {
return new JndiRegistry(createJndiContext());
}
protected Context createJndiContext() throws Exception {
Properties properties = new Properties();
// jndi.properties is optional
InputStream in = getClass().getClassLoader().getResourceAsStream("jndi.properties");
if (in != null) {
log.debug("Using jndi.properties from classpath root");
properties.load(in);
} else {
properties.put("java.naming.factory.initial", "org.apache.camel.util.jndi.CamelInitialContextFactory");
}
return new InitialContext(new Hashtable<Object, Object>(properties));
}
/**
* Factory method which derived classes can use to create a {@link RouteBuilder}
* to define the routes for testing
*/
protected RoutesBuilder createRouteBuilder() throws Exception {
return new RouteBuilder() {
@Override
public void configure() {
// no routes added by default
}
};
}
/**
* Factory method which derived classes can use to create an array of
* {@link org.apache.camel.builder.RouteBuilder}s to define the routes for testing
*
* @see #createRouteBuilder()
*/
protected RoutesBuilder[] createRouteBuilders() throws Exception {
return new RoutesBuilder[] {createRouteBuilder()};
}
/**
* Resolves a mandatory endpoint for the given URI or an exception is thrown
*
* @param uri the Camel <a href="">URI</a> to use to create or resolve an endpoint
* @return the endpoint
*/
protected Endpoint resolveMandatoryEndpoint(String uri) {
return resolveMandatoryEndpoint(context, uri);
}
/**
* Resolves a mandatory endpoint for the given URI and expected type or an exception is thrown
*
* @param uri the Camel <a href="">URI</a> to use to create or resolve an endpoint
* @return the endpoint
*/
protected <T extends Endpoint> T resolveMandatoryEndpoint(String uri, Class<T> endpointType) {
return resolveMandatoryEndpoint(context, uri, endpointType);
}
/**
* Resolves the mandatory Mock endpoint using a URI of the form <code>mock:someName</code>
*
* @param uri the URI which typically starts with "mock:" and has some name
* @return the mandatory mock endpoint or an exception is thrown if it could not be resolved
*/
protected MockEndpoint getMockEndpoint(String uri) {
return getMockEndpoint(uri, true);
}
/**
* Resolves the {@link MockEndpoint} using a URI of the form <code>mock:someName</code>, optionally
* creating it if it does not exist.
*
* @param uri the URI which typically starts with "mock:" and has some name
* @param create whether or not to allow the endpoint to be created if it doesn't exist
* @return the mock endpoint or an {@link NoSuchEndpointException} is thrown if it could not be resolved
* @throws NoSuchEndpointException is the mock endpoint does not exists
*/
protected MockEndpoint getMockEndpoint(String uri, boolean create) throws NoSuchEndpointException {
if (create) {
return resolveMandatoryEndpoint(uri, MockEndpoint.class);
} else {
Endpoint endpoint = context.hasEndpoint(uri);
if (endpoint instanceof MockEndpoint) {
return (MockEndpoint) endpoint;
}
throw new NoSuchEndpointException(String.format("MockEndpoint %s does not exist.", uri));
}
}
/**
* Sends a message to the given endpoint URI with the body value
*
* @param endpointUri the URI of the endpoint to send to
* @param body the body for the message
*/
protected void sendBody(String endpointUri, final Object body) {
template.send(endpointUri, new Processor() {
public void process(Exchange exchange) {
Message in = exchange.getIn();
in.setBody(body);
}
});
}
/**
* Sends a message to the given endpoint URI with the body value and specified headers
*
* @param endpointUri the URI of the endpoint to send to
* @param body the body for the message
* @param headers any headers to set on the message
*/
protected void sendBody(String endpointUri, final Object body, final Map<String, Object> headers) {
template.send(endpointUri, new Processor() {
public void process(Exchange exchange) {
Message in = exchange.getIn();
in.setBody(body);
for (Map.Entry<String, Object> entry : headers.entrySet()) {
in.setHeader(entry.getKey(), entry.getValue());
}
}
});
}
/**
* Sends messages to the given endpoint for each of the specified bodies
*
* @param endpointUri the endpoint URI to send to
* @param bodies the bodies to send, one per message
*/
protected void sendBodies(String endpointUri, Object... bodies) {
for (Object body : bodies) {
sendBody(endpointUri, body);
}
}
/**
* Creates an exchange with the given body
*/
protected Exchange createExchangeWithBody(Object body) {
return createExchangeWithBody(context, body);
}
/**
* Asserts that the given language name and expression evaluates to the
* given value on a specific exchange
*/
protected void assertExpression(Exchange exchange, String languageName, String expressionText, Object expectedValue) {
Language language = assertResolveLanguage(languageName);
Expression expression = language.createExpression(expressionText);
assertNotNull("No Expression could be created for text: " + expressionText + " language: " + language, expression);
assertExpression(expression, exchange, expectedValue);
}
/**
* Asserts that the given language name and predicate expression evaluates
* to the expected value on the message exchange
*/
protected void assertPredicate(String languageName, String expressionText, Exchange exchange, boolean expected) {
Language language = assertResolveLanguage(languageName);
Predicate predicate = language.createPredicate(expressionText);
assertNotNull("No Predicate could be created for text: " + expressionText + " language: " + language, predicate);
assertPredicate(predicate, exchange, expected);
}
/**
* Asserts that the language name can be resolved
*/
protected Language assertResolveLanguage(String languageName) {
Language language = context.resolveLanguage(languageName);
assertNotNull("No language found for name: " + languageName, language);
return language;
}
/**
* Asserts that all the expectations of the Mock endpoints are valid
*/
protected void assertMockEndpointsSatisfied() throws InterruptedException {
MockEndpoint.assertIsSatisfied(context);
}
/**
* Asserts that all the expectations of the Mock endpoints are valid
*/
protected void assertMockEndpointsSatisfied(long timeout, TimeUnit unit) throws InterruptedException {
MockEndpoint.assertIsSatisfied(context, timeout, unit);
}
/**
* Reset all Mock endpoints.
*/
protected void resetMocks() {
MockEndpoint.resetMocks(context);
}
protected void assertValidContext(CamelContext context) {
assertNotNull("No context found!", context);
}
protected <T extends Endpoint> T getMandatoryEndpoint(String uri, Class<T> type) {
T endpoint = context.getEndpoint(uri, type);
assertNotNull("No endpoint found for uri: " + uri, endpoint);
return endpoint;
}
protected Endpoint getMandatoryEndpoint(String uri) {
Endpoint endpoint = context.getEndpoint(uri);
assertNotNull("No endpoint found for uri: " + uri, endpoint);
return endpoint;
}
/**
* Disables the JMX agent. Must be called before the {@link #setUp()} method.
*/
protected void disableJMX() {
System.setProperty(JmxSystemPropertyKeys.DISABLED, "true");
}
/**
* Enables the JMX agent. Must be called before the {@link #setUp()} method.
*/
protected void enableJMX() {
System.setProperty(JmxSystemPropertyKeys.DISABLED, "false");
}
/**
* Single step debugs and Camel invokes this method before entering the given processor
*/
protected void debugBefore(Exchange exchange, Processor processor, ProcessorDefinition<?> definition,
String id, String label) {
}
/**
* Single step debugs and Camel invokes this method after processing the given processor
*/
protected void debugAfter(Exchange exchange, Processor processor, ProcessorDefinition<?> definition,
String id, String label, long timeTaken) {
}
/**
* To easily debug by overriding the <tt>debugBefore</tt> and <tt>debugAfter</tt> methods.
*/
private class DebugBreakpoint extends BreakpointSupport {
@Override
public void beforeProcess(Exchange exchange, Processor processor, ProcessorDefinition<?> definition) {
CamelTestSupport.this.debugBefore(exchange, processor, definition, definition.getId(), definition.getLabel());
}
@Override
public void afterProcess(Exchange exchange, Processor processor, ProcessorDefinition<?> definition, long timeTaken) {
CamelTestSupport.this.debugAfter(exchange, processor, definition, definition.getId(), definition.getLabel(), timeTaken);
}
}
}
| |
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.coverage;
import com.intellij.execution.configurations.ModuleBasedConfiguration;
import com.intellij.execution.configurations.RunConfigurationBase;
import com.intellij.openapi.application.ReadAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.project.DumbService;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.InvalidDataException;
import com.intellij.openapi.util.WriteExternalException;
import com.intellij.psi.JavaPsiFacade;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiManager;
import com.intellij.psi.PsiPackage;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.rt.coverage.data.ProjectData;
import com.intellij.util.ArrayUtilRt;
import org.jdom.Element;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author ven
*/
public class JavaCoverageSuite extends BaseCoverageSuite {
private static final Logger LOG = Logger.getInstance(JavaCoverageSuite.class.getName());
private String[] myFilters;
private String mySuiteToMerge;
@NonNls
private static final String FILTER = "FILTER";
private static final String EXCLUDED_FILTER = "EXCLUDED_FILTER";
@NonNls
private static final String MERGE_SUITE = "MERGE_SUITE";
@NonNls
private static final String COVERAGE_RUNNER = "RUNNER";
private String[] myExcludePatterns;
private final CoverageEngine myCoverageEngine;
//read external only
public JavaCoverageSuite(@NotNull final JavaCoverageEngine coverageSupportProvider) {
super();
myCoverageEngine = coverageSupportProvider;
}
public JavaCoverageSuite(final String name,
final CoverageFileProvider coverageDataFileProvider,
final String[] filters,
final String[] excludePatterns,
final long lastCoverageTimeStamp,
final boolean coverageByTestEnabled,
final boolean tracingEnabled,
final boolean trackTestFolders,
final CoverageRunner coverageRunner,
@NotNull final JavaCoverageEngine coverageSupportProvider,
final Project project) {
super(name, coverageDataFileProvider, lastCoverageTimeStamp, coverageByTestEnabled,
tracingEnabled, trackTestFolders,
coverageRunner != null ? coverageRunner : CoverageRunner.getInstance(IDEACoverageRunner.class), project);
myFilters = filters;
myExcludePatterns = excludePatterns;
myCoverageEngine = coverageSupportProvider;
}
public String @NotNull [] getFilteredPackageNames() {
return getPackageNames(myFilters);
}
public String @NotNull [] getExcludedPackageNames() {
return getPackageNames(myExcludePatterns);
}
private static String[] getPackageNames(String[] filters) {
if (filters == null || filters.length == 0) return ArrayUtilRt.EMPTY_STRING_ARRAY;
List<String> result = new ArrayList<>();
for (String filter : filters) {
if (filter.equals("*")) {
result.add(""); //default package
}
else if (filter.endsWith(".*")) result.add(filter.substring(0, filter.length() - 2));
}
return ArrayUtilRt.toStringArray(result);
}
public String @NotNull [] getFilteredClassNames() {
return getClassNames(myFilters);
}
public String @NotNull [] getExcludedClassNames() {
return getClassNames(myExcludePatterns);
}
private static String @NotNull [] getClassNames(final String[] filters) {
if (filters == null) return ArrayUtilRt.EMPTY_STRING_ARRAY;
List<String> result = new ArrayList<>();
for (String filter : filters) {
if (!filter.equals("*") && !filter.endsWith(".*")) result.add(filter);
}
return ArrayUtilRt.toStringArray(result);
}
@Override
public void readExternal(Element element) throws InvalidDataException {
super.readExternal(element);
// filters
myFilters = readFilters(element, FILTER);
myExcludePatterns = readFilters(element, EXCLUDED_FILTER);
// suite to merge
mySuiteToMerge = element.getAttributeValue(MERGE_SUITE);
if (getRunner() == null) {
setRunner(CoverageRunner.getInstance(IDEACoverageRunner.class)); //default
}
}
private static String[] readFilters(Element element, final String tagName) {
final List<Element> children = element.getChildren(tagName);
List<String> filters = new ArrayList<>();
for (Element child : children) {
filters.add(child.getValue());
}
return filters.isEmpty() ? null : ArrayUtilRt.toStringArray(filters);
}
@Override
public void writeExternal(final Element element) throws WriteExternalException {
super.writeExternal(element);
if (mySuiteToMerge != null) {
element.setAttribute(MERGE_SUITE, mySuiteToMerge);
}
writeFilters(element, myFilters, FILTER);
writeFilters(element, myExcludePatterns, EXCLUDED_FILTER);
final CoverageRunner coverageRunner = getRunner();
element.setAttribute(COVERAGE_RUNNER, coverageRunner != null ? coverageRunner.getId() : "emma");
}
private static void writeFilters(Element element, final String[] filters, final String tagName) {
if (filters != null) {
for (String filter : filters) {
final Element filterElement = new Element(tagName);
filterElement.setText(filter);
element.addContent(filterElement);
}
}
}
@Override
@Nullable
public ProjectData getCoverageData(final CoverageDataManager coverageDataManager) {
final ProjectData data = getCoverageData();
if (data != null) return data;
ProjectData map = loadProjectInfo();
if (mySuiteToMerge != null) {
JavaCoverageSuite toMerge = null;
final CoverageSuite[] suites = coverageDataManager.getSuites();
for (CoverageSuite suite : suites) {
if (Comparing.strEqual(suite.getPresentableName(), mySuiteToMerge)) {
if (!Comparing.strEqual(((JavaCoverageSuite)suite).getSuiteToMerge(), getPresentableName())) {
toMerge = (JavaCoverageSuite)suite;
}
break;
}
}
if (toMerge != null) {
final ProjectData projectInfo = toMerge.getCoverageData(coverageDataManager);
if (map != null) {
map.merge(projectInfo);
} else {
map = projectInfo;
}
}
}
setCoverageData(map);
return map;
}
@Override
@NotNull
public CoverageEngine getCoverageEngine() {
return myCoverageEngine;
}
@Nullable
public String getSuiteToMerge() {
return mySuiteToMerge;
}
public boolean isClassFiltered(final String classFQName) {
return isClassFiltered(classFQName, getFilteredClassNames());
}
public boolean isClassFiltered(final String classFQName,
final String[] classPatterns) {
for (final String className : classPatterns) {
if (className.equals(classFQName) || classFQName.startsWith(className) && classFQName.charAt(className.length()) == '$') {
return true;
}
}
return false;
}
public boolean isPackageFiltered(final String packageFQName) {
for (String name : getExcludedPackageNames()) {
if (packageFQName.equals(name) || packageFQName.startsWith(name + ".")) return false;
}
final String[] filteredPackageNames = getFilteredPackageNames();
for (final String packName : filteredPackageNames) {
if (packName.equals(packageFQName) || packageFQName.startsWith(packName) && packageFQName.charAt(packName.length()) == '.') {
return true;
}
}
return filteredPackageNames.length == 0 && getFilteredClassNames().length == 0;
}
public @NotNull List<PsiPackage> getCurrentSuitePackages(final Project project) {
return ReadAction.compute(() -> {
final List<PsiPackage> packages = new ArrayList<>();
final PsiManager psiManager = PsiManager.getInstance(project);
final String[] filters = getFilteredPackageNames();
if (filters.length == 0) {
if (getFilteredClassNames().length > 0) return Collections.emptyList();
final PsiPackage defaultPackage = JavaPsiFacade.getInstance(psiManager.getProject()).findPackage("");
if (defaultPackage != null) {
packages.add(defaultPackage);
}
}
else {
final List<String> nonInherited = new ArrayList<>();
for (final String filter : filters) {
if (!isSubPackage(filters, filter)) {
nonInherited.add(filter);
}
}
for (String filter : nonInherited) {
final PsiPackage psiPackage = JavaPsiFacade.getInstance(psiManager.getProject()).findPackage(filter);
if (psiPackage != null) {
packages.add(psiPackage);
}
}
}
return packages;
});
}
private static boolean isSubPackage(String[] filters, String filter) {
for (String supPackageFilter : filters) {
if (filter.startsWith(supPackageFilter + ".")) {
return true;
}
}
return false;
}
public @NotNull List<PsiClass> getCurrentSuiteClasses(final Project project) {
final List<PsiClass> classes = new ArrayList<>();
final String[] classNames = getFilteredClassNames();
if (classNames.length > 0) {
for (final String className : classNames) {
final PsiClass aClass =
ReadAction.compute(() -> {
final DumbService dumbService = DumbService.getInstance(project);
dumbService.setAlternativeResolveEnabled(true);
try {
GlobalSearchScope searchScope = GlobalSearchScope.allScope(project);
RunConfigurationBase configuration = getConfiguration();
if (configuration instanceof ModuleBasedConfiguration) {
Module module = ((ModuleBasedConfiguration)configuration).getConfigurationModule().getModule();
if (module != null) {
searchScope = GlobalSearchScope.moduleRuntimeScope(module, isTrackTestFolders());
}
}
return JavaPsiFacade.getInstance(project).findClass(className.replace("$", "."), searchScope);
}
finally {
dumbService.setAlternativeResolveEnabled(false);
}
});
if (aClass != null) {
classes.add(aClass);
}
}
}
return classes;
}
}
| |
/*******************************************************************************
* Copyright 2014 See AUTHORS file.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package com.badlogic.ashley.core;
import java.util.Comparator;
import com.badlogic.ashley.signals.Listener;
import com.badlogic.ashley.signals.Signal;
import com.badlogic.ashley.utils.ImmutableArray;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.LongMap;
import com.badlogic.gdx.utils.ObjectMap;
import com.badlogic.gdx.utils.ObjectMap.Entry;
import com.badlogic.gdx.utils.Pool;
import com.badlogic.gdx.utils.SnapshotArray;
/**
* The heart of the Entity framework. It is responsible for keeping track of {@link Entity} and
* managing {@link EntitySystem} objects. The Engine should be updated every tick via the {@link #update(float)} method.
*
* With the Engine you can:
*
* <ul>
* <li>Add/Remove {@link Entity} objects</li>
* <li>Add/Remove {@link EntitySystem}s</li>
* <li>Obtain a list of entities for a specific {@link Family}</li>
* <li>Update the main loop</li>
* <li>Register/unregister {@link EntityListener} objects</li>
* </ul>
*
* @author Stefan Bachmann
*/
public class Engine {
private static SystemComparator comparator = new SystemComparator();
private Array<Entity> entities;
private ImmutableArray<Entity> immutableEntities;
private LongMap<Entity> entitiesById;
private Array<EntityOperation> entityOperations;
private EntityOperationPool entityOperationPool;
private Array<EntitySystem> systems;
private ImmutableArray<EntitySystem> immutableSystems;
private ObjectMap<Class<?>, EntitySystem> systemsByClass;
private ObjectMap<Family, Array<Entity>> families;
private ObjectMap<Family, ImmutableArray<Entity>> immutableFamilies;
private SnapshotArray<EntityListener> listeners;
private ObjectMap<Family,SnapshotArray<EntityListener>> familyListeners;
private final Listener<Entity> componentAdded;
private final Listener<Entity> componentRemoved;
private boolean updating;
private boolean notifying;
private long nextEntityId = 1;
/** Mechanism to delay component addition/removal to avoid affecting system processing */
private ComponentOperationPool componentOperationsPool;
private Array<ComponentOperation> componentOperations;
private ComponentOperationHandler componentOperationHandler;
public Engine(){
entities = new Array<Entity>(false, 16);
immutableEntities = new ImmutableArray<Entity>(entities);
entitiesById = new LongMap<Entity>();
entityOperations = new Array<EntityOperation>(false, 16);
entityOperationPool = new EntityOperationPool();
systems = new Array<EntitySystem>(false, 16);
immutableSystems = new ImmutableArray<EntitySystem>(systems);
systemsByClass = new ObjectMap<Class<?>, EntitySystem>();
families = new ObjectMap<Family, Array<Entity>>();
immutableFamilies = new ObjectMap<Family, ImmutableArray<Entity>>();
listeners = new SnapshotArray<EntityListener>(false, 16);
familyListeners = new ObjectMap<Family,SnapshotArray<EntityListener>>();
componentAdded = new ComponentListener(this);
componentRemoved = new ComponentListener(this);
updating = false;
notifying = false;
componentOperationsPool = new ComponentOperationPool();
componentOperations = new Array<ComponentOperation>();
componentOperationHandler = new ComponentOperationHandler(this);
}
private long obtainEntityId() {
return nextEntityId++;
}
/**
* Adds an entity to this Engine.
*/
public void addEntity(Entity entity){
entity.uuid = obtainEntityId();
if (notifying) {
EntityOperation operation = entityOperationPool.obtain();
operation.entity = entity;
operation.type = EntityOperation.Type.Add;
entityOperations.add(operation);
}
else {
addEntityInternal(entity);
}
}
/**
* Removes an entity from this Engine.
*/
public void removeEntity(Entity entity){
if (updating || notifying) {
if(entity.scheduledForRemoval) {
return;
}
entity.scheduledForRemoval = true;
EntityOperation operation = entityOperationPool.obtain();
operation.entity = entity;
operation.type = EntityOperation.Type.Remove;
entityOperations.add(operation);
}
else {
removeEntityInternal(entity);
}
}
/**
* Removes all entities registered with this Engine.
*/
public void removeAllEntities() {
if (updating || notifying) {
for(Entity entity: entities) {
entity.scheduledForRemoval = true;
}
EntityOperation operation = entityOperationPool.obtain();
operation.type = EntityOperation.Type.RemoveAll;
entityOperations.add(operation);
}
else {
while(entities.size > 0) {
removeEntity(entities.first());
}
}
}
public Entity getEntity(long id) {
return entitiesById.get(id);
}
public ImmutableArray<Entity> getEntities() {
return immutableEntities;
}
/**
* Adds the {@link EntitySystem} to this Engine.
*/
public void addSystem(EntitySystem system){
Class<? extends EntitySystem> systemType = system.getClass();
if (!systemsByClass.containsKey(systemType)) {
systems.add(system);
systemsByClass.put(systemType, system);
system.addedToEngine(this);
systems.sort(comparator);
}
}
/**
* Removes the {@link EntitySystem} from this Engine.
*/
public void removeSystem(EntitySystem system){
if(systems.removeValue(system, true)) {
systemsByClass.remove(system.getClass());
system.removedFromEngine(this);
}
}
/**
* Quick {@link EntitySystem} retrieval.
*/
@SuppressWarnings("unchecked")
public <T extends EntitySystem> T getSystem(Class<T> systemType) {
return (T) systemsByClass.get(systemType);
}
/**
* @return immutable array of all entity systems managed by the {@link Engine}.
*/
public ImmutableArray<EntitySystem> getSystems() {
return immutableSystems;
}
/**
* Returns immutable collection of entities for the specified {@link Family}. Will return the same instance every time.
*/
public ImmutableArray<Entity> getEntitiesFor(Family family){
return registerFamily(family);
}
/**
* Adds an {@link EntityListener}.
*
* The listener will be notified every time an entity is added/removed to/from the engine.
*/
public void addEntityListener(EntityListener listener) {
listeners.add(listener);
}
/**
* Adds an {@link EntityListener} for a specific {@link Family}.
*
* The listener will be notified every time an entity is added/removed to/from the given family.
*/
public void addEntityListener(Family family, EntityListener listener) {
registerFamily(family);
SnapshotArray<EntityListener> listeners = familyListeners.get(family);
if (listeners == null) {
listeners = new SnapshotArray<EntityListener>(false, 16);
familyListeners.put(family, listeners);
}
listeners.add(listener);
}
/**
* Removes an {@link EntityListener}
*/
public void removeEntityListener(EntityListener listener) {
listeners.removeValue(listener, true);
for (SnapshotArray<EntityListener> familyListenerArray : familyListeners.values()) {
familyListenerArray.removeValue(listener, true);
}
}
/**
* Updates all the systems in this Engine.
* @param deltaTime The time passed since the last frame.
*/
public void update(float deltaTime){
updating = true;
for(int i=0; i<systems.size; i++){
EntitySystem system = systems.get(i);
if (system.checkProcessing()) {
system.update(deltaTime);
}
processComponentOperations();
processPendingEntityOperations();
}
updating = false;
}
private void updateFamilyMembership(Entity entity){
for (Entry<Family, Array<Entity>> entry : families.entries()) {
Family family = entry.key;
Array<Entity> familyEntities = entry.value;
int familyIndex = family.getIndex();
boolean belongsToFamily = entity.getFamilyBits().get(familyIndex);
boolean matches = family.matches(entity);
if (!belongsToFamily && matches) {
familyEntities.add(entity);
entity.getFamilyBits().set(familyIndex);
notifyFamilyListenersAdd(family, entity);
}
else if (belongsToFamily && !matches) {
familyEntities.removeValue(entity, true);
entity.getFamilyBits().clear(familyIndex);
notifyFamilyListenersRemove(family, entity);
}
}
}
protected void removeEntityInternal(Entity entity) {
entity.scheduledForRemoval = false;
entities.removeValue(entity, true);
entitiesById.remove(entity.getId());
if(!entity.getFamilyBits().isEmpty()){
for (Entry<Family, Array<Entity>> entry : families.entries()) {
Family family = entry.key;
Array<Entity> familyEntities = entry.value;
if(family.matches(entity)){
familyEntities.removeValue(entity, true);
entity.getFamilyBits().clear(family.getIndex());
notifyFamilyListenersRemove(family, entity);
}
}
}
entity.componentAdded.remove(componentAdded);
entity.componentRemoved.remove(componentRemoved);
entity.componentOperationHandler = null;
notifying = true;
Object[] items = listeners.begin();
for (int i = 0, n = listeners.size; i < n; i++) {
EntityListener listener = (EntityListener)items[i];
listener.entityRemoved(entity);
}
listeners.end();
notifying = false;
}
protected void addEntityInternal(Entity entity) {
entities.add(entity);
entitiesById.put(entity.getId(), entity);
updateFamilyMembership(entity);
entity.componentAdded.add(componentAdded);
entity.componentRemoved.add(componentRemoved);
entity.componentOperationHandler = componentOperationHandler;
notifying = true;
Object[] items = listeners.begin();
for (int i = 0, n = listeners.size; i < n; i++) {
EntityListener listener = (EntityListener)items[i];
listener.entityAdded(entity);
}
listeners.end();
notifying = false;
}
private void notifyFamilyListenersAdd(Family family, Entity entity) {
SnapshotArray<EntityListener> listeners = familyListeners.get(family);
if (listeners != null) {
notifying = true;
Object[] items = listeners.begin();
for (int i = 0, n = listeners.size; i < n; i++) {
EntityListener listener = (EntityListener)items[i];
listener.entityAdded(entity);
}
listeners.end();
notifying = false;
}
}
private void notifyFamilyListenersRemove(Family family, Entity entity) {
SnapshotArray<EntityListener> listeners = familyListeners.get(family);
if (listeners != null) {
notifying = true;
Object[] items = listeners.begin();
for (int i = 0, n = listeners.size; i < n; i++) {
EntityListener listener = (EntityListener)items[i];
listener.entityRemoved(entity);
}
listeners.end();
notifying = false;
}
}
private ImmutableArray<Entity> registerFamily(Family family) {
ImmutableArray<Entity> immutableEntities = immutableFamilies.get(family);
if (immutableEntities == null) {
Array<Entity> familyEntities = new Array<Entity>(false, 16);
immutableEntities = new ImmutableArray<Entity>(familyEntities);
families.put(family, familyEntities);
immutableFamilies.put(family, immutableEntities);
for(Entity e : this.entities){
if(family.matches(e)) {
familyEntities.add(e);
e.getFamilyBits().set(family.getIndex());
}
}
}
return immutableEntities;
}
private void processPendingEntityOperations() {
while (entityOperations.size > 0) {
EntityOperation operation = entityOperations.removeIndex(entityOperations.size - 1);
switch(operation.type) {
case Add: addEntityInternal(operation.entity); break;
case Remove: removeEntityInternal(operation.entity); break;
case RemoveAll:
while(entities.size > 0) {
removeEntityInternal(entities.first());
}
break;
}
entityOperationPool.free(operation);
}
entityOperations.clear();
}
private void processComponentOperations() {
for (int i = 0; i < componentOperations.size; ++i) {
ComponentOperation operation = componentOperations.get(i);
switch(operation.type) {
case Add: operation.entity.addInternal(operation.component); break;
case Remove: operation.entity.removeInternal(operation.componentClass); break;
}
componentOperationsPool.free(operation);
}
componentOperations.clear();
}
private static class ComponentListener implements Listener<Entity> {
private Engine engine;
public ComponentListener(Engine engine) {
this.engine = engine;
}
@Override
public void receive(Signal<Entity> signal, Entity object) {
engine.updateFamilyMembership(object);
}
}
static class ComponentOperationHandler {
private Engine engine;
public ComponentOperationHandler(Engine engine) {
this.engine = engine;
}
public void add(Entity entity, Component component) {
if (engine.updating) {
ComponentOperation operation = engine.componentOperationsPool.obtain();
operation.makeAdd(entity, component);
engine.componentOperations.add(operation);
}
else {
entity.addInternal(component);
}
}
public void remove(Entity entity, Class<? extends Component> componentClass) {
if (engine.updating) {
ComponentOperation operation = engine.componentOperationsPool.obtain();
operation.makeRemove(entity, componentClass);
engine.componentOperations.add(operation);
}
else {
entity.removeInternal(componentClass);
}
}
}
private static class ComponentOperation implements Pool.Poolable {
public enum Type {
Add,
Remove,
}
public Type type;
public Entity entity;
public Component component;
public Class<? extends Component> componentClass;
public void makeAdd(Entity entity, Component component) {
this.type = Type.Add;
this.entity = entity;
this.component = component;
this.componentClass = null;
}
public void makeRemove(Entity entity, Class<? extends Component> componentClass) {
this.type = Type.Remove;
this.entity = entity;
this.component = null;
this.componentClass = componentClass;
}
@Override
public void reset() {
entity = null;
component = null;
}
}
private static class ComponentOperationPool extends Pool<ComponentOperation> {
@Override
protected ComponentOperation newObject() {
return new ComponentOperation();
}
}
private static class SystemComparator implements Comparator<EntitySystem>{
@Override
public int compare(EntitySystem a, EntitySystem b) {
return a.priority > b.priority ? 1 : (a.priority == b.priority) ? 0 : -1;
}
}
private static class EntityOperation implements Pool.Poolable {
public enum Type {
Add,
Remove,
RemoveAll
}
public Type type;
public Entity entity;
@Override
public void reset() {
entity = null;
}
}
private static class EntityOperationPool extends Pool<EntityOperation> {
@Override
protected EntityOperation newObject() {
return new EntityOperation();
}
}
}
| |
package net.gmbx.w2v;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map.Entry;
public class Distance
{
private static final int DEFAULT_NEIGHBORHOOD = 40;
public static void main(String[] args) throws ClassNotFoundException,
IOException
{
if (args.length < 1 || args.length > 2)
{
System.err
.println("Usage: path/to/word2vec_model [N-neighbors]");
System.exit(1);
}
int N = DEFAULT_NEIGHBORHOOD;
if (args.length == 2)
{
try
{
N = Integer.parseInt(args[1]);
}
catch (NumberFormatException nfe)
{
System.err
.println("Usage: path/to/binary_word2vec_model [N-neighbors]");
System.exit(1);
}
}
long t0 = System.currentTimeMillis();
VectorModel model;
if (args[0].endsWith(".bin"))
{
model = Word2VecUtils.loadGoogleBinary(args[0], Charset
.defaultCharset(), true);
}
else
{
model = Word2VecUtils.loadVectorModelFromText(args[0], true);
}
long t1 = System.currentTimeMillis();
String time = (t1 - t0) / 1000 + "." + (t1 - t0) % 1000 + "s";
System.out.println(time + " to load " + model.getVocabSize() + " "
+ model.getVectorSize()
+ "-dimensional word vectors");
InputStream in = System.in;
String prompt = "\nEnter a word or short phrase (EXIT to break): ";
System.out.print(prompt);
BufferedReader br = new BufferedReader(new InputStreamReader(in,
Charset.forName("UTF-8")));
String line = null;
while ((line = br.readLine()) != null && !"EXIT".equals(line))
{
String input = Word2VecUtils.normalizePreservingUnderscores(line);
List<Integer> ids = new ArrayList<Integer>();
Integer index = model.getIndex(input);
if (index != null)
{
ids.add(index);
}
if (index == null)
{
for (String token : input.split("\\s+"))
{
index = model.getIndex(token);
if (index != null)
{
ids.add(index);
}
}
}
if (ids.isEmpty())
{
System.out.println("\nOut of dictionary word!");
}
else
{
int[] searchIDs = new int[ids.size()];
for (int i = 0; i < ids.size(); i++)
{
searchIDs[i] = ids.get(i).intValue();
}
printNearestNeighbors(line, searchIDs, model, N);
}
System.out.print(prompt);
}
}
private static void printNearestNeighbors(String input,
int[] searchIDs,
VectorModel model,
int k)
{
for (Integer id : searchIDs)
{
System.out.println(String
.format("\nWord: %s "
+ "Position in vocabulary: %d", model.getTerm(id), id));
}
float[] target = getTargetVector(model, searchIDs);
LinkedHashMap<String, Double> results =
findNearestNeighbors(model, target, searchIDs, k);
System.out
.println("\n "
+ "Related Term Cosine Similarity");
System.out
.println("----------------------------------------"
+ "------------------------------------");
for (Entry<String, Double> result : results.entrySet())
{
System.out.println(String.format("%50s%22.6f", result.getKey(),
result.getValue()));
}
}
private static float[] getTargetVector(VectorModel model,
int[] searchIDs)
{
float[] target = null;
if (searchIDs.length == 1)
{
target = model.getVector(searchIDs[0]);
}
else if (searchIDs.length > 1)
{
target = model.composeUnitVector(searchIDs);
}
return target;
}
private static LinkedHashMap<String, Double> findNearestNeighbors(VectorModel model,
float[] target,
int[] searchIDs,
int radius)
{
LinkedHashMap<String, Double> result = new LinkedHashMap<String, Double>();
int[] nearestNeighbors = new int[radius];
double[] score = new double[radius];
// initialize array to hold k-nearest neighbors
for (int i = 0; i < radius; i++)
{
score[i] = Double.MIN_VALUE;
}
for (int i = 0; i < model.getVocabSize(); i++)
{
if (isContainedIn(i, searchIDs))
{
continue;
}
else
{
double cos_sim = dotProduct(target, model.getVector(i));
for (int j = 0; j < radius; j++)
{
if (cos_sim > score[j])
{
for (int k = radius - 1; k > j; k--)
{
score[k] = score[k - 1];
nearestNeighbors[k] = nearestNeighbors[k - 1];
}
score[j] = cos_sim;
nearestNeighbors[j] = i;
break;
}
}
}
}
for (int i = 0; i < radius; i++)
{
String term = model.getTerm(nearestNeighbors[i]);
result.put(term, score[i]);
}
return result;
}
private static boolean isContainedIn(int id, int[] searchIDs)
{
for (int i = 0; i < searchIDs.length; i++)
{
if (searchIDs[i] == id)
{
return true;
}
}
return false;
}
private static double dotProduct(float[] u, float[] v)
{
double res = 0;
for (int i = 0; i < u.length; i++)
{
res += (u[i] * v[i]);
}
return res;
}
}
| |
package org.apache.maven.plugin.war;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.war.stub.MavenProject4CopyConstructor;
import org.apache.maven.plugin.war.stub.ProjectHelperStub;
import org.apache.maven.plugin.war.stub.WarArtifact4CCStub;
import org.codehaus.plexus.util.IOUtil;
import java.io.File;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.zip.ZipEntry;
/**
* comprehensive test on buildExplodedWebApp is done on WarExplodedMojoTest
*/
public class WarMojoTest
extends AbstractWarMojoTest
{
WarMojo mojo;
private static File pomFile =
new File( getBasedir(), "target/test-classes/unit/warmojotest/plugin-config-primary-artifact.xml" );
protected File getTestDirectory()
{
return new File( getBasedir(), "target/test-classes/unit/warmojotest" );
}
public void setUp()
throws Exception
{
super.setUp();
mojo = (WarMojo) lookupMojo( "war", pomFile );
}
public void testEnvironment()
throws Exception
{
// see setup
}
public void testSimpleWar()
throws Exception
{
String testId = "SimpleWar";
MavenProject4CopyConstructor project = new MavenProject4CopyConstructor();
String outputDir = getTestDirectory().getAbsolutePath() + "/" + testId + "-output";
File webAppDirectory = new File( getTestDirectory(), testId );
WarArtifact4CCStub warArtifact = new WarArtifact4CCStub( getBasedir() );
String warName = "simple";
File webAppSource = createWebAppSource( testId );
File classesDir = createClassesDir( testId, true );
File xmlSource = createXMLConfigDir( testId, new String[]{"web.xml"} );
project.setArtifact( warArtifact );
this.configureMojo( mojo, new LinkedList(), classesDir, webAppSource, webAppDirectory, project );
setVariableValueToObject( mojo, "outputDirectory", outputDir );
setVariableValueToObject( mojo, "warName", warName );
mojo.setWebXml( new File( xmlSource, "web.xml" ) );
mojo.execute();
//validate jar file
File expectedJarFile = new File( outputDir, "simple.war" );
assertJarContent( expectedJarFile, new String[]{"META-INF/MANIFEST.MF", "WEB-INF/web.xml", "pansit.jsp",
"org/web/app/last-exile.jsp", "META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.xml",
"META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.properties"},
new String[]{null, mojo.getWebXml().toString(), null, null, null, null} );
}
public void testSimpleWarPackagingExcludeWithIncludesRegEx()
throws Exception
{
String testId = "SimpleWarPackagingExcludeWithIncludesRegEx";
MavenProject4CopyConstructor project = new MavenProject4CopyConstructor();
String outputDir = getTestDirectory().getAbsolutePath() + "/" + testId + "-output";
File webAppDirectory = new File( getTestDirectory(), testId );
WarArtifact4CCStub warArtifact = new WarArtifact4CCStub( getBasedir() );
String warName = "simple";
File webAppSource = createWebAppSource( testId );
File classesDir = createClassesDir( testId, true );
File xmlSource = createXMLConfigDir( testId, new String[]{"web.xml"} );
project.setArtifact( warArtifact );
this.configureMojo( mojo, new LinkedList(), classesDir, webAppSource, webAppDirectory, project );
setVariableValueToObject( mojo, "outputDirectory", outputDir );
setVariableValueToObject( mojo, "warName", warName );
mojo.setWebXml( new File( xmlSource, "web.xml" ) );
setVariableValueToObject( mojo,"packagingIncludes","%regex[(.(?!exile))+]" );
mojo.execute();
//validate jar file
File expectedJarFile = new File( outputDir, "simple.war" );
assertJarContent( expectedJarFile, new String[]{"META-INF/MANIFEST.MF", "WEB-INF/web.xml", "pansit.jsp",
"META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.xml",
"META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.properties"},
new String[]{null, mojo.getWebXml().toString(), null, null, null, },
new String[]{"org/web/app/last-exile.jsp"} );
}
public void testClassifier()
throws Exception
{
String testId = "Classifier";
MavenProject4CopyConstructor project = new MavenProject4CopyConstructor();
String outputDir = getTestDirectory().getAbsolutePath() + "/" + testId + "-output";
File webAppDirectory = new File( getTestDirectory(), testId );
WarArtifact4CCStub warArtifact = new WarArtifact4CCStub( getBasedir() );
ProjectHelperStub projectHelper = new ProjectHelperStub();
String warName = "simple";
File webAppSource = createWebAppSource( testId );
File classesDir = createClassesDir( testId, true );
File xmlSource = createXMLConfigDir( testId, new String[]{"web.xml"} );
project.setArtifact( warArtifact );
this.configureMojo( mojo, new LinkedList(), classesDir, webAppSource, webAppDirectory, project );
setVariableValueToObject( mojo, "projectHelper", projectHelper );
setVariableValueToObject( mojo, "classifier", "test-classifier" );
setVariableValueToObject( mojo, "outputDirectory", outputDir );
setVariableValueToObject( mojo, "warName", warName );
mojo.setWebXml( new File( xmlSource, "web.xml" ) );
mojo.execute();
//validate jar file
File expectedJarFile = new File( outputDir, "simple-test-classifier.war" );
assertJarContent( expectedJarFile, new String[]{"META-INF/MANIFEST.MF", "WEB-INF/web.xml", "pansit.jsp",
"org/web/app/last-exile.jsp", "META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.xml",
"META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.properties"},
new String[]{null, mojo.getWebXml().toString(), null, null, null, null} );
}
public void testPrimaryArtifact()
throws Exception
{
String testId = "PrimaryArtifact";
MavenProject4CopyConstructor project = new MavenProject4CopyConstructor();
String outputDir = getTestDirectory().getAbsolutePath() + "/" + testId + "-output";
File webAppDirectory = new File( getTestDirectory(), testId );
WarArtifact4CCStub warArtifact = new WarArtifact4CCStub( getBasedir() );
ProjectHelperStub projectHelper = new ProjectHelperStub();
String warName = "simple";
File webAppSource = createWebAppSource( testId );
File classesDir = createClassesDir( testId, true );
File xmlSource = createXMLConfigDir( testId, new String[]{"web.xml"} );
warArtifact.setFile( new File( "error.war" ) );
project.setArtifact( warArtifact );
this.configureMojo( mojo, new LinkedList(), classesDir, webAppSource, webAppDirectory, project );
setVariableValueToObject( mojo, "projectHelper", projectHelper );
setVariableValueToObject( mojo, "outputDirectory", outputDir );
setVariableValueToObject( mojo, "warName", warName );
mojo.setWebXml( new File( xmlSource, "web.xml" ) );
mojo.execute();
//validate jar file
File expectedJarFile = new File( outputDir, "simple.war" );
assertJarContent( expectedJarFile, new String[]{"META-INF/MANIFEST.MF", "WEB-INF/web.xml", "pansit.jsp",
"org/web/app/last-exile.jsp", "META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.xml",
"META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.properties"},
new String[]{null, mojo.getWebXml().toString(), null, null, null, null} );
}
public void testNotPrimaryArtifact()
throws Exception
{
// use a different pom
File pom = new File( getBasedir(), "target/test-classes/unit/warmojotest/not-primary-artifact.xml" );
mojo = (WarMojo) lookupMojo( "war", pom );
String testId = "NotPrimaryArtifact";
MavenProject4CopyConstructor project = new MavenProject4CopyConstructor();
String outputDir = getTestDirectory().getAbsolutePath() + "/" + testId + "-output";
File webAppDirectory = new File( getTestDirectory(), testId );
WarArtifact4CCStub warArtifact = new WarArtifact4CCStub( getBasedir() );
ProjectHelperStub projectHelper = new ProjectHelperStub();
String warName = "simple";
File webAppSource = createWebAppSource( testId );
File classesDir = createClassesDir( testId, true );
File xmlSource = createXMLConfigDir( testId, new String[]{"web.xml"} );
warArtifact.setFile( new File( "error.war" ) );
project.setArtifact( warArtifact );
this.configureMojo( mojo, new LinkedList(), classesDir, webAppSource, webAppDirectory, project );
setVariableValueToObject( mojo, "projectHelper", projectHelper );
setVariableValueToObject( mojo, "outputDirectory", outputDir );
setVariableValueToObject( mojo, "warName", warName );
mojo.setWebXml( new File( xmlSource, "web.xml" ) );
mojo.execute();
//validate jar file
File expectedJarFile = new File( outputDir, "simple.war" );
assertJarContent( expectedJarFile, new String[]{"META-INF/MANIFEST.MF", "WEB-INF/web.xml", "pansit.jsp",
"org/web/app/last-exile.jsp", "META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.xml",
"META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.properties"},
new String[]{null, mojo.getWebXml().toString(), null, null, null, null} );
}
public void testMetaInfContent()
throws Exception
{
String testId = "SimpleWarWithMetaInfContent";
MavenProject4CopyConstructor project = new MavenProject4CopyConstructor();
String outputDir = getTestDirectory().getAbsolutePath() + "/" + testId + "-output";
File webAppDirectory = new File( getTestDirectory(), testId );
WarArtifact4CCStub warArtifact = new WarArtifact4CCStub( getBasedir() );
String warName = "simple";
File webAppSource = createWebAppSource( testId );
File classesDir = createClassesDir( testId, true );
File xmlSource = createXMLConfigDir( testId, new String[]{"web.xml"} );
// Create the sample config.xml
final File configFile = new File( webAppSource, "META-INF/config.xml" );
createFile( configFile, "<config></config>" );
project.setArtifact( warArtifact );
this.configureMojo( mojo, new LinkedList(), classesDir, webAppSource, webAppDirectory, project );
setVariableValueToObject( mojo, "outputDirectory", outputDir );
setVariableValueToObject( mojo, "warName", warName );
mojo.setWebXml( new File( xmlSource, "web.xml" ) );
mojo.execute();
//validate jar file
File expectedJarFile = new File( outputDir, "simple.war" );
assertJarContent( expectedJarFile, new String[]{"META-INF/MANIFEST.MF", "META-INF/config.xml",
"WEB-INF/web.xml", "pansit.jsp", "org/web/app/last-exile.jsp",
"META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.xml",
"META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.properties"}, new String[]{null, null,
mojo.getWebXml().toString(), null, null, null, null} );
}
public void testMetaInfContentWithContainerConfig()
throws Exception
{
String testId = "SimpleWarWithContainerConfig";
MavenProject4CopyConstructor project = new MavenProject4CopyConstructor();
String outputDir = getTestDirectory().getAbsolutePath() + "/" + testId + "-output";
File webAppDirectory = new File( getTestDirectory(), testId );
WarArtifact4CCStub warArtifact = new WarArtifact4CCStub( getBasedir() );
String warName = "simple";
File webAppSource = createWebAppSource( testId );
File classesDir = createClassesDir( testId, true );
File xmlSource = createXMLConfigDir( testId, new String[]{"web.xml"} );
// Create the sample config.xml
final File configFile = new File( webAppSource, "META-INF/config.xml" );
createFile( configFile, "<config></config>" );
project.setArtifact( warArtifact );
this.configureMojo( mojo, new LinkedList(), classesDir, webAppSource, webAppDirectory, project );
setVariableValueToObject( mojo, "outputDirectory", outputDir );
setVariableValueToObject( mojo, "warName", warName );
mojo.setWebXml( new File( xmlSource, "web.xml" ) );
mojo.setContainerConfigXML( configFile );
mojo.execute();
//validate jar file
File expectedJarFile = new File( outputDir, "simple.war" );
assertJarContent( expectedJarFile, new String[]{"META-INF/MANIFEST.MF", "META-INF/config.xml",
"WEB-INF/web.xml", "pansit.jsp", "org/web/app/last-exile.jsp",
"META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.xml",
"META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.properties"}, new String[]{null, null,
mojo.getWebXml().toString(), null, null, null, null} );
}
public void testFailOnMissingWebXmlFalse()
throws Exception
{
String testId = "SimpleWarMissingWebXmlFalse";
MavenProject4CopyConstructor project = new MavenProject4CopyConstructor();
String outputDir = getTestDirectory().getAbsolutePath() + "/" + testId + "-output";
File webAppDirectory = new File( getTestDirectory(), testId );
WarArtifact4CCStub warArtifact = new WarArtifact4CCStub( getBasedir() );
String warName = "simple";
File webAppSource = createWebAppSource( testId );
File classesDir = createClassesDir( testId, true );
project.setArtifact( warArtifact );
this.configureMojo( mojo, new LinkedList(), classesDir, webAppSource, webAppDirectory, project );
setVariableValueToObject( mojo, "outputDirectory", outputDir );
setVariableValueToObject( mojo, "warName", warName );
mojo.setFailOnMissingWebXml( false );
mojo.execute();
//validate jar file
File expectedJarFile = new File( outputDir, "simple.war" );
final Map jarContent = assertJarContent( expectedJarFile, new String[]{"META-INF/MANIFEST.MF", "pansit.jsp",
"org/web/app/last-exile.jsp", "META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.xml",
"META-INF/maven/org.apache.maven.test/maven-test-plugin/pom.properties"},
new String[]{null, null, null, null, null} );
assertFalse( "web.xml should be missing", jarContent.containsKey( "WEB-INF/web.xml" ) );
}
public void testFailOnMissingWebXmlTrue()
throws Exception
{
String testId = "SimpleWarMissingWebXmlTrue";
MavenProject4CopyConstructor project = new MavenProject4CopyConstructor();
String outputDir = getTestDirectory().getAbsolutePath() + "/" + testId + "-output";
File webAppDirectory = new File( getTestDirectory(), testId );
WarArtifact4CCStub warArtifact = new WarArtifact4CCStub( getBasedir() );
String warName = "simple";
File webAppSource = createWebAppSource( testId );
File classesDir = createClassesDir( testId, true );
project.setArtifact( warArtifact );
this.configureMojo( mojo, new LinkedList(), classesDir, webAppSource, webAppDirectory, project );
setVariableValueToObject( mojo, "outputDirectory", outputDir );
setVariableValueToObject( mojo, "warName", warName );
mojo.setFailOnMissingWebXml( true );
try
{
mojo.execute();
fail( "Building of the war isn't possible because web.xml is missing" );
}
catch ( MojoExecutionException e )
{
//expected behaviour
}
}
public void testAttachClasses()
throws Exception
{
String testId = "AttachClasses";
MavenProject4CopyConstructor project = new MavenProject4CopyConstructor();
String outputDir = getTestDirectory().getAbsolutePath() + "/" + testId + "-output";
File webAppDirectory = new File( getTestDirectory(), testId );
WarArtifact4CCStub warArtifact = new WarArtifact4CCStub( getBasedir() );
String warName = "simple";
File webAppSource = createWebAppSource( testId );
File classesDir = createClassesDir( testId, false );
File xmlSource = createXMLConfigDir( testId, new String[]{"web.xml"} );
project.setArtifact( warArtifact );
this.configureMojo( mojo, new LinkedList(), classesDir, webAppSource, webAppDirectory, project );
setVariableValueToObject( mojo, "outputDirectory", outputDir );
setVariableValueToObject( mojo, "warName", warName );
mojo.setWebXml( new File( xmlSource, "web.xml" ) );
mojo.setAttachClasses( true );
mojo.execute();
//validate jar file
File expectedJarFile = new File( outputDir, "simple-classes.jar" );
assertJarContent( expectedJarFile, new String[]{"META-INF/MANIFEST.MF", "sample-servlet.class"},
new String[]{null, null} );
}
public void testAttachClassesWithCustomClassifier()
throws Exception
{
String testId = "AttachClassesCustomClassifier";
MavenProject4CopyConstructor project = new MavenProject4CopyConstructor();
String outputDir = getTestDirectory().getAbsolutePath() + "/" + testId + "-output";
File webAppDirectory = new File( getTestDirectory(), testId );
WarArtifact4CCStub warArtifact = new WarArtifact4CCStub( getBasedir() );
String warName = "simple";
File webAppSource = createWebAppSource( testId );
File classesDir = createClassesDir( testId, false );
File xmlSource = createXMLConfigDir( testId, new String[]{"web.xml"} );
project.setArtifact( warArtifact );
this.configureMojo( mojo, new LinkedList(), classesDir, webAppSource, webAppDirectory, project );
setVariableValueToObject( mojo, "outputDirectory", outputDir );
setVariableValueToObject( mojo, "warName", warName );
mojo.setWebXml( new File( xmlSource, "web.xml" ) );
mojo.setAttachClasses( true );
mojo.setClassesClassifier( "mystuff" );
mojo.execute();
//validate jar file
File expectedJarFile = new File( outputDir, "simple-mystuff.jar" );
assertJarContent( expectedJarFile, new String[]{"META-INF/MANIFEST.MF", "sample-servlet.class"},
new String[]{null, null} );
}
protected Map assertJarContent( final File expectedJarFile, final String[] files, final String[] filesContent )
throws IOException
{
return assertJarContent( expectedJarFile, files, filesContent, null );
}
protected Map assertJarContent( final File expectedJarFile, final String[] files, final String[] filesContent, final String[] mustNotBeInJar )
throws IOException
{
// Sanity check
assertEquals( "Could not test, files and filesContent lenght does not match", files.length,
filesContent.length );
assertTrue( "war file not created: " + expectedJarFile.toString(), expectedJarFile.exists() );
final Map jarContent = new HashMap();
final JarFile jarFile = new JarFile( expectedJarFile );
JarEntry entry;
Enumeration enumeration = jarFile.entries();
while ( enumeration.hasMoreElements() )
{
entry = (JarEntry) enumeration.nextElement();
Object previousValue = jarContent.put( entry.getName(), entry );
assertNull( "Duplicate Entry in Jar File: " + entry.getName(), previousValue );
}
for ( int i = 0; i < files.length; i++ )
{
String file = files[i];
assertTrue( "File[" + file + "] not found in archive", jarContent.containsKey( file ) );
if ( filesContent[i] != null )
{
assertEquals( "Content of file[" + file + "] does not match", filesContent[i],
IOUtil.toString( jarFile.getInputStream( (ZipEntry) jarContent.get( file ) ) ) );
}
}
if( mustNotBeInJar!=null )
{
for ( int i = 0; i < mustNotBeInJar.length; i++ )
{
String file = mustNotBeInJar[i];
assertFalse( "File[" + file + "] found in archive", jarContent.containsKey( file ) );
}
}
return jarContent;
}
}
| |
package org.vitrivr.cineast.core.features.neuralnet;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.vitrivr.cineast.core.config.ReadableQueryConfig;
import org.vitrivr.cineast.core.data.providers.primitive.PrimitiveTypeProvider;
import org.vitrivr.cineast.core.data.score.ScoreElement;
import org.vitrivr.cineast.core.data.score.SegmentScoreElement;
import org.vitrivr.cineast.core.data.segments.SegmentContainer;
import org.vitrivr.cineast.core.db.DBSelector;
import org.vitrivr.cineast.core.db.DBSelectorSupplier;
import org.vitrivr.cineast.core.db.PersistencyWriter;
import org.vitrivr.cineast.core.db.PersistencyWriterSupplier;
import org.vitrivr.cineast.core.db.PersistentTuple;
import org.vitrivr.cineast.core.features.abstracts.AbstractFeatureModule;
import org.vitrivr.cineast.core.features.neuralnet.classification.NeuralNet;
import org.vitrivr.cineast.core.features.neuralnet.label.ConceptReader;
import org.vitrivr.cineast.core.setup.AttributeDefinition;
import org.vitrivr.cineast.core.setup.AttributeDefinition.AttributeType;
import org.vitrivr.cineast.core.setup.EntityCreator;
import org.vitrivr.cineast.core.util.TimeHelper;
/**
* NeuralNet Feature modules should extend this class
* It provides a table where neuralnets can access wordNet-labels and human labels
*/
@Deprecated
public abstract class NeuralNetFeature extends AbstractFeatureModule {
private static final Logger LOGGER = LogManager.getLogger();
private PersistencyWriter<?> classWriter;
private DBSelector classSelector;
/**
* Table-name where the labels are stored
*/
private static final String classTableName = "features_neuralnet_classlabels";
/**
* Column-name for the WordNet labels
*/
private static final String wnLabel = "wnlabel";
/**
* Column-name for the human language label corresponding to a WordNet label
*/
private static final String humanLabelColName = "humanlabel";
/**
* Just passes the tableName to super
**/
public NeuralNetFeature(String tableName) {
super(tableName, 1f);
}
/**
* Returns the Table-name where the labels are stored
*/
public static String getClassTableName() {
return classTableName;
}
/**
* Checks if labels have been specified. If no labels have been specified, takes the query image.
* Might perform knn on the 1k-vector in the future.
* It's also not clear yet if we could combine labels and input image
*/
public List<ScoreElement> getSimilar(SegmentContainer sc, ReadableQueryConfig qc, DBSelector classificationSelector, float defaultCutoff) {
LOGGER.traceEntry();
TimeHelper.tic();
List<ScoreElement> _return = new ArrayList<>();
if (!sc.getTags().isEmpty()) {
Set<String> wnLabels = new HashSet<>();
wnLabels.addAll(getClassSelector().getRows(getHumanLabelColName(), sc.getTags().toArray(new String[sc.getTags().size()])).stream().map(row -> row.get(getWnLabelColName()).getString()).collect(Collectors.toList()));
LOGGER.debug("Looking for labels: {}", String.join(", ",wnLabels.toArray(new String[wnLabels.size()])));
for (Map<String, PrimitiveTypeProvider> row :
classificationSelector.getRows(getWnLabelColName(), wnLabels.toArray(new String[wnLabels.size()]))) {
String segmentId = row.get("segmentid").getString();
float probability = row.get("probability").getFloat();
LOGGER.debug("Found hit for query {}: {} {} ",
segmentId, probability, row.get(getWnLabelColName()).toString());
_return.add(new SegmentScoreElement(segmentId, probability));
}
} else {
LOGGER.debug("Starting Sketch-based lookup");
NeuralNet _net = null;
// if (qc.getNet().isPresent()) {
// _net = qc.getNet().get();
// }
if (_net == null) {
_net = getNet();
}
float[] classified = _net.classify(sc.getMostRepresentativeFrame().getImage().getBufferedImage());
List<String> hits = new ArrayList<>();
for (int i = 0; i < classified.length; i++) {
if (classified[i] > /*qc.getCutoff().orElse(*/defaultCutoff/*)*/) {
hits.add(_net.getSynSetLabels()[i]);
}
}
for (Map<String, PrimitiveTypeProvider> row : classificationSelector.getRows(getWnLabelColName(), hits.toArray(new String[hits.size()]))) {
String segmentId = row.get("segmentid").getString();
float probability = row.get("probability").getFloat();
LOGGER.debug("Found hit for query {}: {} {} ",
segmentId, probability, row.get(getWnLabelColName()).toString());
_return.add(new SegmentScoreElement(segmentId, probability));
}
}
_return = ScoreElement.filterMaximumScores(_return.stream());
LOGGER.trace("NeuralNetFeature.getSimilar() done in {}",
TimeHelper.toc());
return LOGGER.traceExit(_return);
}
protected abstract NeuralNet getNet();
@Override
public void init(DBSelectorSupplier selectorSupplier) {
super.init(selectorSupplier);
this.classSelector = selectorSupplier.get();
this.classSelector.open(classTableName);
}
/**
* TODO This method needs heavy refactoring along with the entitycode because creating entities this way is not really pretty, we're relying on the AdamGRPC
* Currently wnLabel is a string. That is because we get a unique id which has the shape n+....
* Schema:
* Table 0: segmentid | classificationvector - handled by super
* Table 1: wnLabel | humanlabel
* Table 1 is only touched for API-Calls about available labels and at init-time - not during extraction
* It is also used at querytime for the nn-features to determine the wnLabel associated with the concepts they should query for.
*/
@Override
public void initalizePersistentLayer(Supplier<EntityCreator> supply) {
super.initalizePersistentLayer(supply);
EntityCreator ec = supply.get();
//TODO Set pk / Create idx -> Logic in the ecCreator
ec.createIdEntity(classTableName, new AttributeDefinition(wnLabel, AttributeType.STRING), new AttributeDefinition(getHumanLabelColName(), AttributeType.STRING));
ec.close();
}
/**
* Table 1: segmentid | wnLabel | confidence (ex. 4014 | n203843 | 0.4) - Stores specific hits from the Neuralnet
*/
public void createLabelsTable(Supplier<EntityCreator> supply, String tableName){
EntityCreator ec = supply.get();
//TODO Set pk / Create idx -> Logic in the ecCreator
ec.createIdEntity(tableName, new AttributeDefinition("segmentid", AttributeType.STRING), new AttributeDefinition(getWnLabelColName(), AttributeType.STRING), new AttributeDefinition("probability", AttributeType.FLOAT));
ec.close();
}
@Override
public void init(PersistencyWriterSupplier phandlerSupply) {
super.init(phandlerSupply);
classWriter = phandlerSupply.get();
classWriter.open(classTableName);
classWriter.setFieldNames("id", wnLabel, getHumanLabelColName());
}
@Override
public void finish() {
super.finish();
if (this.classWriter != null) {
this.classWriter.close();
this.classWriter = null;
}
if (this.classSelector != null) {
this.classSelector.close();
this.classSelector = null;
}
}
/**
* Fills general concepts into the DB. Concepts are provided at conceptsPath and parsed by the ConceptReader
* NeuralNets must fill their own labels into the DB. If their labels are not generally applicable, they should use their own table.
*/
public void fillConcepts(String conceptsPath) {
ConceptReader cr = new ConceptReader(conceptsPath);
LOGGER.info("Filling Labels");
//Fill Concept map with batch-inserting
List<PersistentTuple> tuples = new ArrayList<>(10000);
for (Map.Entry<String, String[]> entry : cr.getConceptMap().entrySet()) {
for (String label : entry.getValue()) {
String id = UUID.randomUUID().toString();
PersistentTuple tuple = classWriter.generateTuple(id, label, entry.getKey());
tuples.add(tuple);
if (tuples.size() == 9500) {
LOGGER.debug("Batch-inserting");
classWriter.persist(tuples);
tuples.clear();
}
}
}
classWriter.persist(tuples);
tuples.clear();
}
/**
* Fills Labels of the neuralNet
*
* @param options pass Options to the neuralNet such as filepath
*/
public abstract void fillLabels(Map<String, String> options);
/**
* Use this writer to fill in your own labels into the table which is available to all neural nets
*/
protected PersistencyWriter<?> getClassWriter() {
return this.classWriter;
}
/**
* Get wnLabels associated with concepts from this selector
*/
protected DBSelector getClassSelector() {
return this.classSelector;
}
/**
* Column name for the wnLabel. Example: n2348
*/
protected String getWnLabelColName() {
return wnLabel;
}
/**
* Column name for the concept/human label column
*/
public static String getHumanLabelColName() {
return humanLabelColName;
}
/**
* @return The table name where generated data is stored (not the full 1k-vector)
*/
abstract public String getClassificationTable();
}
| |
/*
* Copyright (C) 2014 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package androidx.leanback.widget;
import android.view.View;
import android.view.ViewGroup;
import androidx.leanback.app.HeadersFragment;
import androidx.leanback.graphics.ColorOverlayDimmer;
/**
* An abstract {@link Presenter} that renders an Object in RowsFragment, the object can be
* subclass {@link Row} or a generic one. When the object is not {@link Row} class,
* {@link ViewHolder#getRow()} returns null.
*
* <h3>Customize UI widgets</h3>
* When a subclass of RowPresenter adds UI widgets, it should subclass
* {@link RowPresenter.ViewHolder} and override {@link #createRowViewHolder(ViewGroup)}
* and {@link #initializeRowViewHolder(ViewHolder)}. The subclass must use layout id
* "row_content" for the widget that will be aligned to the title of any {@link HeadersFragment}
* that may exist in the parent fragment. RowPresenter contains an optional and
* replaceable {@link RowHeaderPresenter} that renders the header. You can disable
* the default rendering or replace the Presenter with a new header presenter
* by calling {@link #setHeaderPresenter(RowHeaderPresenter)}.
*
* <h3>UI events from fragments</h3>
* RowPresenter receives calls from its parent (typically a Fragment) when:
* <ul>
* <li>
* A row is selected via {@link #setRowViewSelected(Presenter.ViewHolder, boolean)}. The event
* is triggered immediately when there is a row selection change before the selection
* animation is started. Selected status may control activated status of the row (see
* "Activated status" below).
* Subclasses of RowPresenter may override {@link #onRowViewSelected(ViewHolder, boolean)}.
* </li>
* <li>
* A row is expanded to full height via {@link #setRowViewExpanded(Presenter.ViewHolder, boolean)}
* when BrowseFragment hides fast lane on the left.
* The event is triggered immediately before the expand animation is started.
* Row title is shown when row is expanded. Expanded status may control activated status
* of the row (see "Activated status" below).
* Subclasses of RowPresenter may override {@link #onRowViewExpanded(ViewHolder, boolean)}.
* </li>
* </ul>
*
* <h3>Activated status</h3>
* The activated status of a row is applied to the row view and its children via
* {@link View#setActivated(boolean)}.
* The activated status is typically used to control {@link BaseCardView} info region visibility.
* The row's activated status can be controlled by selected status and/or expanded status.
* Call {@link #setSyncActivatePolicy(int)} and choose one of the four policies:
* <ul>
* <li>{@link #SYNC_ACTIVATED_TO_EXPANDED} Activated status is synced with row expanded status</li>
* <li>{@link #SYNC_ACTIVATED_TO_SELECTED} Activated status is synced with row selected status</li>
* <li>{@link #SYNC_ACTIVATED_TO_EXPANDED_AND_SELECTED} Activated status is set to true
* when both expanded and selected status are true</li>
* <li>{@link #SYNC_ACTIVATED_CUSTOM} Activated status is not controlled by selected status
* or expanded status, application can control activated status by its own.
* Application should call {@link RowPresenter.ViewHolder#setActivated(boolean)} to change
* activated status of row view.
* </li>
* </ul>
*
* <h3>User events</h3>
* RowPresenter provides {@link OnItemViewSelectedListener} and {@link OnItemViewClickedListener}.
* If a subclass wants to add its own {@link View.OnFocusChangeListener} or
* {@link View.OnClickListener}, it must do that in {@link #createRowViewHolder(ViewGroup)}
* to be properly chained by the library. Adding View listeners after
* {@link #createRowViewHolder(ViewGroup)} is undefined and may result in
* incorrect behavior by the library's listeners.
*
* <h3>Selection animation</h3>
* <p>
* When a user scrolls through rows, a fragment will initiate animation and call
* {@link #setSelectLevel(Presenter.ViewHolder, float)} with float value between
* 0 and 1. By default, the RowPresenter draws a dim overlay on top of the row
* view for views that are not selected. Subclasses may override this default effect
* by having {@link #isUsingDefaultSelectEffect()} return false and overriding
* {@link #onSelectLevelChanged(ViewHolder)} to apply a different selection effect.
* </p>
* <p>
* Call {@link #setSelectEffectEnabled(boolean)} to enable/disable the select effect,
* This will not only enable/disable the default dim effect but also subclasses must
* respect this flag as well.
* </p>
*/
public abstract class RowPresenter extends Presenter {
/**
* Don't synchronize row view activated status with selected status or expanded status,
* application will do its own through {@link RowPresenter.ViewHolder#setActivated(boolean)}.
*/
public static final int SYNC_ACTIVATED_CUSTOM = 0;
/**
* Synchronizes row view's activated status to expand status of the row view holder.
*/
public static final int SYNC_ACTIVATED_TO_EXPANDED = 1;
/**
* Synchronizes row view's activated status to selected status of the row view holder.
*/
public static final int SYNC_ACTIVATED_TO_SELECTED = 2;
/**
* Sets the row view's activated status to true when both expand and selected are true.
*/
public static final int SYNC_ACTIVATED_TO_EXPANDED_AND_SELECTED = 3;
static class ContainerViewHolder extends Presenter.ViewHolder {
/**
* wrapped row view holder
*/
final ViewHolder mRowViewHolder;
public ContainerViewHolder(RowContainerView containerView, ViewHolder rowViewHolder) {
super(containerView);
containerView.addRowView(rowViewHolder.view);
if (rowViewHolder.mHeaderViewHolder != null) {
containerView.addHeaderView(rowViewHolder.mHeaderViewHolder.view);
}
mRowViewHolder = rowViewHolder;
mRowViewHolder.mContainerViewHolder = this;
}
}
/**
* A ViewHolder for a {@link Row}.
*/
public static class ViewHolder extends Presenter.ViewHolder {
private static final int ACTIVATED_NOT_ASSIGNED = 0;
private static final int ACTIVATED = 1;
private static final int NOT_ACTIVATED = 2;
ContainerViewHolder mContainerViewHolder;
RowHeaderPresenter.ViewHolder mHeaderViewHolder;
Row mRow;
Object mRowObject;
int mActivated = ACTIVATED_NOT_ASSIGNED;
boolean mSelected;
boolean mExpanded;
boolean mInitialzed;
float mSelectLevel = 0f; // initially unselected
protected final ColorOverlayDimmer mColorDimmer;
private View.OnKeyListener mOnKeyListener;
BaseOnItemViewSelectedListener mOnItemViewSelectedListener;
private BaseOnItemViewClickedListener mOnItemViewClickedListener;
/**
* Constructor for ViewHolder.
*
* @param view The View bound to the Row.
*/
public ViewHolder(View view) {
super(view);
mColorDimmer = ColorOverlayDimmer.createDefault(view.getContext());
}
/**
* Returns the row bound to this ViewHolder. Returns null if the row is not an instance of
* {@link Row}.
* @return The row bound to this ViewHolder. Returns null if the row is not an instance of
* {@link Row}.
*/
public final Row getRow() {
return mRow;
}
/**
* Returns the Row object bound to this ViewHolder.
* @return The row object bound to this ViewHolder.
*/
public final Object getRowObject() {
return mRowObject;
}
/**
* Returns whether the Row is in its expanded state.
*
* @return true if the Row is expanded, false otherwise.
*/
public final boolean isExpanded() {
return mExpanded;
}
/**
* Returns whether the Row is selected.
*
* @return true if the Row is selected, false otherwise.
*/
public final boolean isSelected() {
return mSelected;
}
/**
* Returns the current selection level of the Row.
*/
public final float getSelectLevel() {
return mSelectLevel;
}
/**
* Returns the view holder for the Row header for this Row.
*/
public final RowHeaderPresenter.ViewHolder getHeaderViewHolder() {
return mHeaderViewHolder;
}
/**
* Sets the row view's activated status. The status will be applied to children through
* {@link #syncActivatedStatus(View)}. Application should only call this function
* when {@link RowPresenter#getSyncActivatePolicy()} is
* {@link RowPresenter#SYNC_ACTIVATED_CUSTOM}; otherwise the value will
* be overwritten when expanded or selected status changes.
*/
public final void setActivated(boolean activated) {
mActivated = activated ? ACTIVATED : NOT_ACTIVATED;
}
/**
* Synchronizes the activated status of view to the last value passed through
* {@link RowPresenter.ViewHolder#setActivated(boolean)}. No operation if
* {@link RowPresenter.ViewHolder#setActivated(boolean)} is never called. Normally
* application does not need to call this method, {@link ListRowPresenter} automatically
* calls this method when a child is attached to list row. However if
* application writes its own custom RowPresenter, it should call this method
* when attaches a child to the row view.
*/
public final void syncActivatedStatus(View view) {
if (mActivated == ACTIVATED) {
view.setActivated(true);
} else if (mActivated == NOT_ACTIVATED) {
view.setActivated(false);
}
}
/**
* Sets a key listener.
*/
public void setOnKeyListener(View.OnKeyListener keyListener) {
mOnKeyListener = keyListener;
}
/**
* Returns the key listener.
*/
public View.OnKeyListener getOnKeyListener() {
return mOnKeyListener;
}
/**
* Sets the listener for item or row selection. RowPresenter fires row selection
* event with null item. A subclass of RowPresenter e.g. {@link ListRowPresenter} may
* fire a selection event with selected item.
*/
public final void setOnItemViewSelectedListener(BaseOnItemViewSelectedListener listener) {
mOnItemViewSelectedListener = listener;
}
/**
* Returns the listener for item or row selection.
*/
public final BaseOnItemViewSelectedListener getOnItemViewSelectedListener() {
return mOnItemViewSelectedListener;
}
/**
* Sets the listener for item click event. RowPresenter does nothing but subclass of
* RowPresenter may fire item click event if it has the concept of item.
* OnItemViewClickedListener will override {@link View.OnClickListener} that
* item presenter sets during {@link Presenter#onCreateViewHolder(ViewGroup)}.
*/
public final void setOnItemViewClickedListener(BaseOnItemViewClickedListener listener) {
mOnItemViewClickedListener = listener;
}
/**
* Returns the listener for item click event.
*/
public final BaseOnItemViewClickedListener getOnItemViewClickedListener() {
return mOnItemViewClickedListener;
}
/**
* Return {@link ViewHolder} of currently selected item inside a row ViewHolder.
* @return The selected item's ViewHolder.
*/
public Presenter.ViewHolder getSelectedItemViewHolder() {
return null;
}
/**
* Return currently selected item inside a row ViewHolder.
* @return The selected item.
*/
public Object getSelectedItem() {
return null;
}
}
private RowHeaderPresenter mHeaderPresenter = new RowHeaderPresenter();
boolean mSelectEffectEnabled = true;
int mSyncActivatePolicy = SYNC_ACTIVATED_TO_EXPANDED;
/**
* Constructs a RowPresenter.
*/
public RowPresenter() {
mHeaderPresenter.setNullItemVisibilityGone(true);
}
@Override
public final Presenter.ViewHolder onCreateViewHolder(ViewGroup parent) {
ViewHolder vh = createRowViewHolder(parent);
vh.mInitialzed = false;
Presenter.ViewHolder result;
if (needsRowContainerView()) {
RowContainerView containerView = new RowContainerView(parent.getContext());
if (mHeaderPresenter != null) {
vh.mHeaderViewHolder = (RowHeaderPresenter.ViewHolder)
mHeaderPresenter.onCreateViewHolder((ViewGroup) vh.view);
}
result = new ContainerViewHolder(containerView, vh);
} else {
result = vh;
}
initializeRowViewHolder(vh);
if (!vh.mInitialzed) {
throw new RuntimeException("super.initializeRowViewHolder() must be called");
}
return result;
}
/**
* Called to create a ViewHolder object for a Row. Subclasses will override
* this method to return a different concrete ViewHolder object.
*
* @param parent The parent View for the Row's view holder.
* @return A ViewHolder for the Row's View.
*/
protected abstract ViewHolder createRowViewHolder(ViewGroup parent);
/**
* Returns true if the Row view should clip its children. The clipChildren
* flag is set on view in {@link #initializeRowViewHolder(ViewHolder)}. Note that
* Slide transition or explode transition need turn off clipChildren.
* Default value is false.
*/
protected boolean isClippingChildren() {
return false;
}
/**
* Called after a {@link RowPresenter.ViewHolder} is created for a Row.
* Subclasses may override this method and start by calling
* super.initializeRowViewHolder(ViewHolder).
*
* @param vh The ViewHolder to initialize for the Row.
*/
protected void initializeRowViewHolder(ViewHolder vh) {
vh.mInitialzed = true;
if (!isClippingChildren()) {
// set clip children to false for slide transition
if (vh.view instanceof ViewGroup) {
((ViewGroup) vh.view).setClipChildren(false);
}
if (vh.mContainerViewHolder != null) {
((ViewGroup) vh.mContainerViewHolder.view).setClipChildren(false);
}
}
}
/**
* Sets the Presenter used for rendering the header. Can be null to disable
* header rendering. The method must be called before creating any Row Views.
*/
public final void setHeaderPresenter(RowHeaderPresenter headerPresenter) {
mHeaderPresenter = headerPresenter;
}
/**
* Returns the Presenter used for rendering the header, or null if none has been
* set.
*/
public final RowHeaderPresenter getHeaderPresenter() {
return mHeaderPresenter;
}
/**
* Returns the {@link RowPresenter.ViewHolder} from the given RowPresenter
* ViewHolder.
*/
public final ViewHolder getRowViewHolder(Presenter.ViewHolder holder) {
if (holder instanceof ContainerViewHolder) {
return ((ContainerViewHolder) holder).mRowViewHolder;
} else {
return (ViewHolder) holder;
}
}
/**
* Sets the expanded state of a Row view.
*
* @param holder The Row ViewHolder to set expanded state on.
* @param expanded True if the Row is expanded, false otherwise.
*/
public final void setRowViewExpanded(Presenter.ViewHolder holder, boolean expanded) {
ViewHolder rowViewHolder = getRowViewHolder(holder);
rowViewHolder.mExpanded = expanded;
onRowViewExpanded(rowViewHolder, expanded);
}
/**
* Sets the selected state of a Row view.
*
* @param holder The Row ViewHolder to set expanded state on.
* @param selected True if the Row is expanded, false otherwise.
*/
public final void setRowViewSelected(Presenter.ViewHolder holder, boolean selected) {
ViewHolder rowViewHolder = getRowViewHolder(holder);
rowViewHolder.mSelected = selected;
onRowViewSelected(rowViewHolder, selected);
}
/**
* Called when the row view's expanded state changes. A subclass may override this method to
* respond to expanded state changes of a Row.
* The default implementation will hide/show the header view. Subclasses may
* make visual changes to the Row View but must not create animation on the
* Row view.
*/
protected void onRowViewExpanded(ViewHolder vh, boolean expanded) {
updateHeaderViewVisibility(vh);
updateActivateStatus(vh, vh.view);
}
/**
* Updates the view's activate status according to {@link #getSyncActivatePolicy()} and the
* selected status and expanded status of the RowPresenter ViewHolder.
*/
private void updateActivateStatus(ViewHolder vh, View view) {
switch (mSyncActivatePolicy) {
case SYNC_ACTIVATED_TO_EXPANDED:
vh.setActivated(vh.isExpanded());
break;
case SYNC_ACTIVATED_TO_SELECTED:
vh.setActivated(vh.isSelected());
break;
case SYNC_ACTIVATED_TO_EXPANDED_AND_SELECTED:
vh.setActivated(vh.isExpanded() && vh.isSelected());
break;
}
vh.syncActivatedStatus(view);
}
/**
* Sets the policy of updating row view activated status. Can be one of:
* <li> Default value {@link #SYNC_ACTIVATED_TO_EXPANDED}
* <li> {@link #SYNC_ACTIVATED_TO_SELECTED}
* <li> {@link #SYNC_ACTIVATED_TO_EXPANDED_AND_SELECTED}
* <li> {@link #SYNC_ACTIVATED_CUSTOM}
*/
public final void setSyncActivatePolicy(int syncActivatePolicy) {
mSyncActivatePolicy = syncActivatePolicy;
}
/**
* Returns the policy of updating row view activated status. Can be one of:
* <li> Default value {@link #SYNC_ACTIVATED_TO_EXPANDED}
* <li> {@link #SYNC_ACTIVATED_TO_SELECTED}
* <li> {@link #SYNC_ACTIVATED_TO_EXPANDED_AND_SELECTED}
* <li> {@link #SYNC_ACTIVATED_CUSTOM}
*/
public final int getSyncActivatePolicy() {
return mSyncActivatePolicy;
}
/**
* This method is only called from
* {@link #onRowViewSelected(ViewHolder, boolean)} onRowViewSelected.
* The default behavior is to signal row selected events with a null item parameter.
* A Subclass of RowPresenter having child items should override this method and dispatch
* events with item information.
*/
protected void dispatchItemSelectedListener(ViewHolder vh, boolean selected) {
if (selected) {
if (vh.mOnItemViewSelectedListener != null) {
vh.mOnItemViewSelectedListener.onItemSelected(null, null, vh, vh.getRowObject());
}
}
}
/**
* Called when the given row view changes selection state. A subclass may override this to
* respond to selected state changes of a Row. A subclass may make visual changes to Row view
* but must not create animation on the Row view.
*/
protected void onRowViewSelected(ViewHolder vh, boolean selected) {
dispatchItemSelectedListener(vh, selected);
updateHeaderViewVisibility(vh);
updateActivateStatus(vh, vh.view);
}
private void updateHeaderViewVisibility(ViewHolder vh) {
if (mHeaderPresenter != null && vh.mHeaderViewHolder != null) {
RowContainerView containerView = ((RowContainerView) vh.mContainerViewHolder.view);
containerView.showHeader(vh.isExpanded());
}
}
/**
* Sets the current select level to a value between 0 (unselected) and 1 (selected).
* Subclasses may override {@link #onSelectLevelChanged(ViewHolder)} to
* respond to changes in the selected level.
*/
public final void setSelectLevel(Presenter.ViewHolder vh, float level) {
ViewHolder rowViewHolder = getRowViewHolder(vh);
rowViewHolder.mSelectLevel = level;
onSelectLevelChanged(rowViewHolder);
}
/**
* Returns the current select level. The value will be between 0 (unselected)
* and 1 (selected).
*/
public final float getSelectLevel(Presenter.ViewHolder vh) {
return getRowViewHolder(vh).mSelectLevel;
}
/**
* Callback when the select level changes. The default implementation applies
* the select level to {@link RowHeaderPresenter#setSelectLevel(RowHeaderPresenter.ViewHolder, float)}
* when {@link #getSelectEffectEnabled()} is true. Subclasses may override
* this function and implement a different select effect. In this case,
* the method {@link #isUsingDefaultSelectEffect()} should also be overridden to disable
* the default dimming effect.
*/
protected void onSelectLevelChanged(ViewHolder vh) {
if (getSelectEffectEnabled()) {
vh.mColorDimmer.setActiveLevel(vh.mSelectLevel);
if (vh.mHeaderViewHolder != null) {
mHeaderPresenter.setSelectLevel(vh.mHeaderViewHolder, vh.mSelectLevel);
}
if (isUsingDefaultSelectEffect()) {
((RowContainerView) vh.mContainerViewHolder.view).setForegroundColor(
vh.mColorDimmer.getPaint().getColor());
}
}
}
/**
* Enables or disables the row selection effect.
* This will not only affect the default dim effect, but subclasses must
* respect this flag as well.
*/
public final void setSelectEffectEnabled(boolean applyDimOnSelect) {
mSelectEffectEnabled = applyDimOnSelect;
}
/**
* Returns true if the row selection effect is enabled.
* This value not only determines whether the default dim implementation is
* used, but subclasses must also respect this flag.
*/
public final boolean getSelectEffectEnabled() {
return mSelectEffectEnabled;
}
/**
* Returns true if this RowPresenter is using the default dimming effect.
* A subclass may (most likely) return false and
* override {@link #onSelectLevelChanged(ViewHolder)}.
*/
public boolean isUsingDefaultSelectEffect() {
return true;
}
final boolean needsDefaultSelectEffect() {
return isUsingDefaultSelectEffect() && getSelectEffectEnabled();
}
final boolean needsRowContainerView() {
return mHeaderPresenter != null || needsDefaultSelectEffect();
}
@Override
public final void onBindViewHolder(Presenter.ViewHolder viewHolder, Object item) {
onBindRowViewHolder(getRowViewHolder(viewHolder), item);
}
/**
* Binds the given row object to the given ViewHolder.
* Derived classes of {@link RowPresenter} overriding
* {@link #onBindRowViewHolder(ViewHolder, Object)} must call through the super class's
* implementation of this method.
*/
protected void onBindRowViewHolder(ViewHolder vh, Object item) {
vh.mRowObject = item;
vh.mRow = item instanceof Row ? (Row) item : null;
if (vh.mHeaderViewHolder != null && vh.getRow() != null) {
mHeaderPresenter.onBindViewHolder(vh.mHeaderViewHolder, item);
}
}
@Override
public final void onUnbindViewHolder(Presenter.ViewHolder viewHolder) {
onUnbindRowViewHolder(getRowViewHolder(viewHolder));
}
/**
* Unbinds the given ViewHolder.
* Derived classes of {@link RowPresenter} overriding {@link #onUnbindRowViewHolder(ViewHolder)}
* must call through the super class's implementation of this method.
*/
protected void onUnbindRowViewHolder(ViewHolder vh) {
if (vh.mHeaderViewHolder != null) {
mHeaderPresenter.onUnbindViewHolder(vh.mHeaderViewHolder);
}
vh.mRow = null;
vh.mRowObject = null;
}
@Override
public final void onViewAttachedToWindow(Presenter.ViewHolder holder) {
onRowViewAttachedToWindow(getRowViewHolder(holder));
}
/**
* Invoked when the row view is attached to the window.
*/
protected void onRowViewAttachedToWindow(ViewHolder vh) {
if (vh.mHeaderViewHolder != null) {
mHeaderPresenter.onViewAttachedToWindow(vh.mHeaderViewHolder);
}
}
@Override
public final void onViewDetachedFromWindow(Presenter.ViewHolder holder) {
onRowViewDetachedFromWindow(getRowViewHolder(holder));
}
/**
* Invoked when the row view is detached from the window.
*/
protected void onRowViewDetachedFromWindow(ViewHolder vh) {
if (vh.mHeaderViewHolder != null) {
mHeaderPresenter.onViewDetachedFromWindow(vh.mHeaderViewHolder);
}
cancelAnimationsRecursive(vh.view);
}
/**
* Freezes/unfreezes the row, typically used when a transition starts/ends.
* This method is called by the fragment, it should not call it directly by the application.
*/
public void freeze(ViewHolder holder, boolean freeze) {
}
/**
* Changes the visibility of views. The entrance transition will be run against the views that
* change visibilities. A subclass may override and begin with calling
* super.setEntranceTransitionState(). This method is called by the fragment,
* it should not be called directly by the application.
*
* @param holder The ViewHolder of the row.
* @param afterEntrance true if children of row participating in entrance transition
* should be set to visible, false otherwise.
*/
public void setEntranceTransitionState(ViewHolder holder, boolean afterEntrance) {
if (holder.mHeaderViewHolder != null
&& holder.mHeaderViewHolder.view.getVisibility() != View.GONE) {
holder.mHeaderViewHolder.view.setVisibility(afterEntrance
? View.VISIBLE : View.INVISIBLE);
}
}
}
| |
package org.xbib.netty.http.client;
import io.netty.channel.WriteBufferWaterMark;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.codec.http2.Http2Settings;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.proxy.HttpProxyHandler;
import io.netty.handler.ssl.CipherSuiteFilter;
import io.netty.handler.ssl.SslProvider;
import org.xbib.netty.http.client.api.Pool;
import org.xbib.netty.http.client.api.BackOff;
import org.xbib.netty.http.common.HttpAddress;
import org.xbib.netty.http.common.security.SecurityUtil;
import javax.net.ssl.TrustManagerFactory;
import java.io.InputStream;
import java.security.KeyStore;
import java.security.Provider;
import java.util.ArrayList;
import java.util.List;
public class ClientConfig {
interface Defaults {
/**
* If frame logging /traffic logging is enabled or not.
*/
boolean DEBUG = false;
/**
* Default debug log level.
*/
LogLevel DEFAULT_DEBUG_LOG_LEVEL = LogLevel.DEBUG;
/**
* The transport provider
*/
String DEFAULT_TRANSPORT_PROVIDER = null;
/**
* If set to 0, then Netty will decide about thread count.
* Default is Runtime.getRuntime().availableProcessors() * 2
*/
int THREAD_COUNT = 0;
/**
* Default for TCP_NODELAY.
*/
boolean TCP_NODELAY = true;
/**
* Default for SO_KEEPALIVE.
*/
boolean SO_KEEPALIVE = true;
/**
* Default for SO_REUSEADDR.
*/
boolean SO_REUSEADDR = true;
/**
* Set TCP send buffer to 64k per socket.
*/
int TCP_SEND_BUFFER_SIZE = 64 * 1024;
/**
* Set TCP receive buffer to 64k per socket.
*/
int TCP_RECEIVE_BUFFER_SIZE = 64 * 1024;
/**
* Set HTTP chunk maximum size to 8k.
* See {@link io.netty.handler.codec.http.HttpClientCodec}.
*/
int MAX_CHUNK_SIZE = 8 * 1024;
/**
* Set HTTP initial line length to 4k.
* See {@link io.netty.handler.codec.http.HttpClientCodec}.
*/
int MAX_INITIAL_LINE_LENGTH = 4 * 1024;
/**
* Set HTTP maximum headers size to 8k.
* See {@link io.netty.handler.codec.http.HttpClientCodec}.
*/
int MAX_HEADERS_SIZE = 8 * 1024;
/**
* Set maximum content length to 100 MB.
*/
int MAX_CONTENT_LENGTH = 100 * 1024 * 1024;
/**
* This is Netty's default.
* See {@link io.netty.handler.codec.MessageAggregator}.
*/
int MAX_COMPOSITE_BUFFER_COMPONENTS = 1024;
/**
* Default read/write timeout in milliseconds.
*/
int TIMEOUT_MILLIS = 5000;
/**
* Default for gzip codec.
*/
boolean ENABLE_GZIP = true;
/**
* Default SSL provider.
*/
SslProvider SSL_PROVIDER = SecurityUtil.Defaults.DEFAULT_SSL_PROVIDER;
/**
* Default SSL context provider (for JDK SSL only).
*/
Provider SSL_CONTEXT_PROVIDER = null;
/**
* Transport layer security protocol versions.
*/
String[] PROTOCOLS = new String[] { "TLSv1.3", "TLSv1.2" };
/**
* Default ciphers. We care about HTTP/2.
*/
Iterable<String> CIPHERS = SecurityUtil.Defaults.DEFAULT_CIPHERS;
/**
* Default cipher suite filter.
*/
CipherSuiteFilter CIPHER_SUITE_FILTER = SecurityUtil.Defaults.DEFAULT_CIPHER_SUITE_FILTER;
/**
* Default for SSL client authentication.
*/
ClientAuthMode SSL_CLIENT_AUTH_MODE = ClientAuthMode.NONE;
/**
* Default for pool retries per node.
*/
Integer RETRIES_PER_NODE = 0;
/**
* Default pool HTTP version.
*/
HttpVersion POOL_VERSION = HttpVersion.HTTP_1_1;
Pool.PoolKeySelectorType POOL_KEY_SELECTOR_TYPE = Pool.PoolKeySelectorType.ROUNDROBIN;
/**
* Default connection pool security.
*/
Boolean POOL_SECURE = false;
/**
* Default HTTP/2 settings.
*/
Http2Settings HTTP2_SETTINGS = Http2Settings.defaultSettings();
/**
* Default write buffer water mark.
*/
WriteBufferWaterMark WRITE_BUFFER_WATER_MARK = WriteBufferWaterMark.DEFAULT;
/**
* Default for backoff.
*/
BackOff BACK_OFF = BackOff.ZERO_BACKOFF;
Boolean ENABLE_NEGOTIATION = false;
}
private boolean debug = Defaults.DEBUG;
private LogLevel debugLogLevel = Defaults.DEFAULT_DEBUG_LOG_LEVEL;
private String transportProviderName = Defaults.DEFAULT_TRANSPORT_PROVIDER;
private int threadCount = Defaults.THREAD_COUNT;
private boolean tcpNodelay = Defaults.TCP_NODELAY;
private boolean keepAlive = Defaults.SO_KEEPALIVE;
private boolean reuseAddr = Defaults.SO_REUSEADDR;
private int tcpSendBufferSize = Defaults.TCP_SEND_BUFFER_SIZE;
private int tcpReceiveBufferSize = Defaults.TCP_RECEIVE_BUFFER_SIZE;
private int maxInitialLineLength = Defaults.MAX_INITIAL_LINE_LENGTH;
private int maxHeadersSize = Defaults.MAX_HEADERS_SIZE;
private int maxChunkSize = Defaults.MAX_CHUNK_SIZE;
private int maxContentLength = Defaults.MAX_CONTENT_LENGTH;
private int maxCompositeBufferComponents = Defaults.MAX_COMPOSITE_BUFFER_COMPONENTS;
private int connectTimeoutMillis = Defaults.TIMEOUT_MILLIS;
private int readTimeoutMillis = Defaults.TIMEOUT_MILLIS;
private boolean enableGzip = Defaults.ENABLE_GZIP;
private SslProvider sslProvider = Defaults.SSL_PROVIDER;
private Provider sslContextProvider = Defaults.SSL_CONTEXT_PROVIDER;
private String[] protocols = Defaults.PROTOCOLS;
private Iterable<String> ciphers = Defaults.CIPHERS;
private CipherSuiteFilter cipherSuiteFilter = Defaults.CIPHER_SUITE_FILTER;
private TrustManagerFactory trustManagerFactory = SecurityUtil.Defaults.DEFAULT_TRUST_MANAGER_FACTORY;
private KeyStore trustManagerKeyStore = null;
private ClientAuthMode clientAuthMode = Defaults.SSL_CLIENT_AUTH_MODE;
private InputStream keyCertChainInputStream;
private InputStream keyInputStream;
private String keyPassword;
private HttpProxyHandler httpProxyHandler;
private List<HttpAddress> poolNodes = new ArrayList<>();
private Pool.PoolKeySelectorType poolKeySelectorType = Defaults.POOL_KEY_SELECTOR_TYPE;
private Integer poolNodeConnectionLimit;
private Integer retriesPerPoolNode = Defaults.RETRIES_PER_NODE;
private HttpVersion poolVersion = Defaults.POOL_VERSION;
private Boolean poolSecure = Defaults.POOL_SECURE;
private List<String> serverNamesForIdentification = new ArrayList<>();
private Http2Settings http2Settings = Defaults.HTTP2_SETTINGS;
private WriteBufferWaterMark writeBufferWaterMark = Defaults.WRITE_BUFFER_WATER_MARK;
private BackOff backOff = Defaults.BACK_OFF;
private boolean enableNegotiation = Defaults.ENABLE_NEGOTIATION;
public ClientConfig setDebug(boolean debug) {
this.debug = debug;
return this;
}
public ClientConfig enableDebug() {
this.debug = true;
return this;
}
public ClientConfig disableDebug() {
this.debug = false;
return this;
}
public boolean isDebug() {
return debug;
}
public ClientConfig setDebugLogLevel(LogLevel debugLogLevel) {
this.debugLogLevel = debugLogLevel;
return this;
}
public LogLevel getDebugLogLevel() {
return debugLogLevel;
}
public ClientConfig setTransportProviderName(String transportProviderName) {
this.transportProviderName = transportProviderName;
return this;
}
public String getTransportProviderName() {
return transportProviderName;
}
public ClientConfig setThreadCount(int threadCount) {
this.threadCount = threadCount;
return this;
}
public int getThreadCount() {
return threadCount;
}
public ClientConfig setTcpNodelay(boolean tcpNodelay) {
this.tcpNodelay = tcpNodelay;
return this;
}
public boolean isTcpNodelay() {
return tcpNodelay;
}
public ClientConfig setKeepAlive(boolean keepAlive) {
this.keepAlive = keepAlive;
return this;
}
public boolean isKeepAlive() {
return keepAlive;
}
public ClientConfig setReuseAddr(boolean reuseAddr) {
this.reuseAddr = reuseAddr;
return this;
}
public boolean isReuseAddr() {
return reuseAddr;
}
public ClientConfig setTcpSendBufferSize(int tcpSendBufferSize) {
this.tcpSendBufferSize = tcpSendBufferSize;
return this;
}
public int getTcpSendBufferSize() {
return tcpSendBufferSize;
}
public ClientConfig setTcpReceiveBufferSize(int tcpReceiveBufferSize) {
this.tcpReceiveBufferSize = tcpReceiveBufferSize;
return this;
}
public int getTcpReceiveBufferSize() {
return tcpReceiveBufferSize;
}
public ClientConfig setMaxInitialLineLength(int maxInitialLineLength) {
this.maxInitialLineLength = maxInitialLineLength;
return this;
}
public int getMaxInitialLineLength() {
return maxInitialLineLength;
}
public ClientConfig setMaxHeadersSize(int maxHeadersSize) {
this.maxHeadersSize = maxHeadersSize;
return this;
}
public int getMaxHeadersSize() {
return maxHeadersSize;
}
public ClientConfig setMaxChunkSize(int maxChunkSize) {
this.maxChunkSize = maxChunkSize;
return this;
}
public int getMaxChunkSize() {
return maxChunkSize;
}
public ClientConfig setMaxContentLength(int maxContentLength) {
this.maxContentLength = maxContentLength;
return this;
}
public int getMaxContentLength() {
return maxContentLength;
}
public ClientConfig setMaxCompositeBufferComponents(int maxCompositeBufferComponents) {
this.maxCompositeBufferComponents = maxCompositeBufferComponents;
return this;
}
public int getMaxCompositeBufferComponents() {
return maxCompositeBufferComponents;
}
public ClientConfig setConnectTimeoutMillis(int connectTimeoutMillis) {
this.connectTimeoutMillis = connectTimeoutMillis;
return this;
}
public int getConnectTimeoutMillis() {
return connectTimeoutMillis;
}
public ClientConfig setReadTimeoutMillis(int readTimeoutMillis) {
this.readTimeoutMillis = readTimeoutMillis;
return this;
}
public int getReadTimeoutMillis() {
return readTimeoutMillis;
}
public ClientConfig setEnableGzip(boolean enableGzip) {
this.enableGzip = enableGzip;
return this;
}
public boolean isEnableGzip() {
return enableGzip;
}
public ClientConfig setHttp2Settings(Http2Settings http2Settings) {
this.http2Settings = http2Settings;
return this;
}
public Http2Settings getHttp2Settings() {
return http2Settings;
}
public ClientConfig setTrustManagerFactory(TrustManagerFactory trustManagerFactory) {
this.trustManagerFactory = trustManagerFactory;
return this;
}
public TrustManagerFactory getTrustManagerFactory() {
return trustManagerFactory;
}
public ClientConfig setTrustManagerKeyStore(KeyStore trustManagerKeyStore) {
this.trustManagerKeyStore = trustManagerKeyStore;
return this;
}
public KeyStore getTrustManagerKeyStore() {
return trustManagerKeyStore;
}
public ClientConfig setSslProvider(SslProvider sslProvider) {
this.sslProvider = sslProvider;
return this;
}
public SslProvider getSslProvider() {
return sslProvider;
}
public ClientConfig setJdkSslProvider() {
this.sslProvider = SslProvider.JDK;
return this;
}
public ClientConfig setOpenSSLSslProvider() {
this.sslProvider = SslProvider.OPENSSL;
return this;
}
public ClientConfig setSslContextProvider(Provider sslContextProvider) {
this.sslContextProvider = sslContextProvider;
return this;
}
public Provider getSslContextProvider() {
return sslContextProvider;
}
public ClientConfig setProtocols(String[] protocols) {
this.protocols = protocols;
return this;
}
public String[] getProtocols() {
return protocols;
}
public ClientConfig setCiphers(Iterable<String> ciphers) {
this.ciphers = ciphers;
return this;
}
public Iterable<String> getCiphers() {
return ciphers;
}
public ClientConfig setCipherSuiteFilter(CipherSuiteFilter cipherSuiteFilter) {
this.cipherSuiteFilter = cipherSuiteFilter;
return this;
}
public CipherSuiteFilter getCipherSuiteFilter() {
return cipherSuiteFilter;
}
public ClientConfig setKeyCert(InputStream keyCertChainInputStream, InputStream keyInputStream) {
this.keyCertChainInputStream = keyCertChainInputStream;
this.keyInputStream = keyInputStream;
return this;
}
public InputStream getKeyCertChainInputStream() {
return keyCertChainInputStream;
}
public InputStream getKeyInputStream() {
return keyInputStream;
}
public ClientConfig setKeyCert(InputStream keyCertChainInputStream, InputStream keyInputStream,
String keyPassword) {
this.keyCertChainInputStream = keyCertChainInputStream;
this.keyInputStream = keyInputStream;
this.keyPassword = keyPassword;
return this;
}
public String getKeyPassword() {
return keyPassword;
}
public ClientConfig setClientAuthMode(ClientAuthMode clientAuthMode) {
this.clientAuthMode = clientAuthMode;
return this;
}
public ClientAuthMode getClientAuthMode() {
return clientAuthMode;
}
public ClientConfig setHttpProxyHandler(HttpProxyHandler httpProxyHandler) {
this.httpProxyHandler = httpProxyHandler;
return this;
}
public HttpProxyHandler getHttpProxyHandler() {
return httpProxyHandler;
}
public ClientConfig setPoolNodes(List<HttpAddress> poolNodes) {
this.poolNodes = poolNodes;
return this;
}
public List<HttpAddress> getPoolNodes() {
return poolNodes;
}
public ClientConfig setPoolKeySelectorType(Pool.PoolKeySelectorType poolKeySelectorType) {
this.poolKeySelectorType = poolKeySelectorType;
return this;
}
public Pool.PoolKeySelectorType getPoolKeySelectorType() {
return poolKeySelectorType;
}
public ClientConfig addPoolNode(HttpAddress poolNodeAddress) {
this.poolNodes.add(poolNodeAddress);
return this;
}
public ClientConfig setPoolNodeConnectionLimit(Integer poolNodeConnectionLimit) {
this.poolNodeConnectionLimit = poolNodeConnectionLimit;
return this;
}
public Integer getPoolNodeConnectionLimit() {
return poolNodeConnectionLimit;
}
public ClientConfig setRetriesPerPoolNode(Integer retriesPerPoolNode) {
this.retriesPerPoolNode = retriesPerPoolNode;
return this;
}
public Integer getRetriesPerPoolNode() {
return retriesPerPoolNode;
}
public ClientConfig setPoolVersion(HttpVersion poolVersion) {
this.poolVersion = poolVersion;
return this;
}
public HttpVersion getPoolVersion() {
return poolVersion;
}
public ClientConfig setPoolSecure(boolean poolSecure) {
this.poolSecure = poolSecure;
return this;
}
public boolean isPoolSecure() {
return poolSecure;
}
public ClientConfig addServerNameForIdentification(String serverNameForIdentification) {
this.serverNamesForIdentification.add(serverNameForIdentification);
return this;
}
public List<String> getServerNamesForIdentification() {
return serverNamesForIdentification;
}
public ClientConfig setWriteBufferWaterMark(WriteBufferWaterMark writeBufferWaterMark) {
this.writeBufferWaterMark = writeBufferWaterMark;
return this;
}
public WriteBufferWaterMark getWriteBufferWaterMark() {
return writeBufferWaterMark;
}
public ClientConfig setBackOff(BackOff backOff) {
this.backOff = backOff;
return this;
}
public BackOff getBackOff() {
return backOff;
}
public ClientConfig setEnableNegotiation(boolean enableNegotiation) {
this.enableNegotiation = enableNegotiation;
return this;
}
public boolean isEnableNegotiation() {
return enableNegotiation;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("SSL=").append(sslProvider)
.append(",SSL context provider=").append(sslContextProvider != null ? sslContextProvider.getName() : "<none>");
return sb.toString();
}
}
| |
/*
* The MIT License
* Copyright (c) 2012 Microsoft Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package microsoft.exchange.webservices.data;
import javax.xml.stream.XMLStreamException;
import java.util.HashMap;
import java.util.Map;
/**
* Represents the permissions of a delegate user.
*/
public final class DelegatePermissions extends ComplexProperty {
private Map<String, DelegateFolderPermission> delegateFolderPermissions;
/**
* Initializes a new instance of the class.
*/
protected DelegatePermissions() {
super();
this.delegateFolderPermissions = new HashMap<String,
DelegateFolderPermission>();
delegateFolderPermissions.put(
XmlElementNames.CalendarFolderPermissionLevel,
new DelegateFolderPermission());
delegateFolderPermissions.put(
XmlElementNames.TasksFolderPermissionLevel,
new DelegateFolderPermission());
delegateFolderPermissions.put(
XmlElementNames.InboxFolderPermissionLevel,
new DelegateFolderPermission());
delegateFolderPermissions.put(
XmlElementNames.ContactsFolderPermissionLevel,
new DelegateFolderPermission());
delegateFolderPermissions.put(
XmlElementNames.NotesFolderPermissionLevel,
new DelegateFolderPermission());
delegateFolderPermissions.put(
XmlElementNames.JournalFolderPermissionLevel,
new DelegateFolderPermission());
}
/**
* Gets the delegate user's permission on the principal's calendar.
*
* @return the calendar folder permission level
*/
public DelegateFolderPermissionLevel getCalendarFolderPermissionLevel() {
return this.delegateFolderPermissions.get(XmlElementNames.
CalendarFolderPermissionLevel).getPermissionLevel();
}
/**
* sets the delegate user's permission on the principal's calendar.
*
* @param value the new calendar folder permission level
*/
public void setCalendarFolderPermissionLevel(
DelegateFolderPermissionLevel value) {
this.delegateFolderPermissions.get(XmlElementNames.
CalendarFolderPermissionLevel).setPermissionLevel(value);
}
/**
* Gets the delegate user's permission on the principal's tasks
* folder.
*
* @return the tasks folder permission level
*/
public DelegateFolderPermissionLevel getTasksFolderPermissionLevel() {
return this.delegateFolderPermissions.get(XmlElementNames.
TasksFolderPermissionLevel).getPermissionLevel();
}
/**
* Sets the tasks folder permission level.
*
* @param value the new tasks folder permission level
*/
public void setTasksFolderPermissionLevel(
DelegateFolderPermissionLevel value) {
this.delegateFolderPermissions.get(XmlElementNames.
TasksFolderPermissionLevel).setPermissionLevel(value);
}
/**
* Gets the delegate user's permission on the principal's inbox.
*
* @return the inbox folder permission level
*/
public DelegateFolderPermissionLevel getInboxFolderPermissionLevel() {
return this.delegateFolderPermissions.get(XmlElementNames.
InboxFolderPermissionLevel).
getPermissionLevel();
}
/**
* Sets the inbox folder permission level.
*
* @param value the new inbox folder permission level
*/
public void setInboxFolderPermissionLevel(
DelegateFolderPermissionLevel value) {
this.delegateFolderPermissions.get(XmlElementNames.
InboxFolderPermissionLevel).
setPermissionLevel(value);
}
/**
* Gets the delegate user's permission on the principal's contacts
* folder.
*
* @return the contacts folder permission level
*/
public DelegateFolderPermissionLevel getContactsFolderPermissionLevel() {
return this.delegateFolderPermissions.get(
XmlElementNames.ContactsFolderPermissionLevel).
getPermissionLevel();
}
/**
* Sets the contacts folder permission level.
*
* @param value the new contacts folder permission level
*/
public void setContactsFolderPermissionLevel(
DelegateFolderPermissionLevel value) {
this.delegateFolderPermissions.get(
XmlElementNames.ContactsFolderPermissionLevel).
setPermissionLevel(value);
}
/**
* Gets the delegate user's permission on the principal's notes
* folder.
*
* @return the notes folder permission level
*/
public DelegateFolderPermissionLevel getNotesFolderPermissionLevel() {
return this.delegateFolderPermissions.get(XmlElementNames.
NotesFolderPermissionLevel).
getPermissionLevel();
}
/**
* Sets the notes folder permission level.
*
* @param value the new notes folder permission level
*/
public void setNotesFolderPermissionLevel(
DelegateFolderPermissionLevel value) {
this.delegateFolderPermissions.get(XmlElementNames.
NotesFolderPermissionLevel).
setPermissionLevel(value);
}
/**
* Gets the delegate user's permission on the principal's journal
* folder.
*
* @return the journal folder permission level
*/
public DelegateFolderPermissionLevel getJournalFolderPermissionLevel() {
return this.delegateFolderPermissions.get(XmlElementNames.
JournalFolderPermissionLevel).
getPermissionLevel();
}
/**
* Sets the journal folder permission level.
*
* @param value the new journal folder permission level
*/
public void setJournalFolderPermissionLevel(
DelegateFolderPermissionLevel value) {
this.delegateFolderPermissions.get(XmlElementNames.
JournalFolderPermissionLevel).
setPermissionLevel(value);
}
/**
* Reset.
*/
protected void reset() {
for (DelegateFolderPermission delegateFolderPermission : this.delegateFolderPermissions.values()) {
delegateFolderPermission.reset();
}
}
/**
* Tries to read element from XML.
*
* @param reader the reader
* @return Returns true if element was read.
* @throws Exception the exception
*/
protected boolean tryReadElementFromXml(EwsServiceXmlReader reader)
throws Exception {
DelegateFolderPermission delegateFolderPermission = null;
if (this.delegateFolderPermissions.containsKey(reader.getLocalName())) {
delegateFolderPermission = this.delegateFolderPermissions.
get(reader.getLocalName());
delegateFolderPermission.initialize(reader.
readElementValue(DelegateFolderPermissionLevel.class));
}
return delegateFolderPermission != null;
}
/**
* Writes elements to XML.
*
* @param writer the writer
* @throws Exception the exception
*/
protected void writeElementsToXml(EwsServiceXmlWriter writer)
throws Exception {
this.writePermissionToXml(writer,
XmlElementNames.CalendarFolderPermissionLevel);
this.writePermissionToXml(writer,
XmlElementNames.TasksFolderPermissionLevel);
this.writePermissionToXml(writer,
XmlElementNames.InboxFolderPermissionLevel);
this.writePermissionToXml(writer,
XmlElementNames.ContactsFolderPermissionLevel);
this.writePermissionToXml(writer,
XmlElementNames.NotesFolderPermissionLevel);
this.writePermissionToXml(writer,
XmlElementNames.JournalFolderPermissionLevel);
}
/**
* Write permission to Xml.
*
* @param writer The writer.
* @param xmlElementName The element name.
*/
private void writePermissionToXml(
EwsServiceXmlWriter writer,
String xmlElementName) throws ServiceXmlSerializationException,
XMLStreamException {
DelegateFolderPermissionLevel delegateFolderPermissionLevel =
this.delegateFolderPermissions.
get(xmlElementName).getPermissionLevel();
// E14 Bug 298307: UpdateDelegate fails if
//Custom permission level is round tripped
//
if (delegateFolderPermissionLevel != DelegateFolderPermissionLevel.Custom) {
writer.writeElementValue(
XmlNamespace.Types,
xmlElementName,
delegateFolderPermissionLevel);
}
}
/**
* Validates this instance for AddDelegate.
*
* @throws ServiceValidationException
*/
protected void validateAddDelegate() throws ServiceValidationException {
for (DelegateFolderPermission delegateFolderPermission : this.delegateFolderPermissions.values()) {
if (delegateFolderPermission.getPermissionLevel() == DelegateFolderPermissionLevel.Custom) {
throw new ServiceValidationException(Strings.
CannotSetDelegateFolderPermissionLevelToCustom);
}
}
}
/**
* Validates this instance for UpdateDelegate.
*
* @throws ServiceValidationException
*/
protected void validateUpdateDelegate() throws ServiceValidationException {
for (DelegateFolderPermission delegateFolderPermission : this.delegateFolderPermissions.values()) {
if (delegateFolderPermission.getPermissionLevel() == DelegateFolderPermissionLevel.Custom &&
!delegateFolderPermission.isExistingPermissionLevelCustom) {
throw new ServiceValidationException(Strings.
CannotSetDelegateFolderPermissionLevelToCustom);
}
}
}
/**
* Represents a folder's DelegateFolderPermissionLevel
*/
private static class DelegateFolderPermission {
/**
* Initializes this DelegateFolderPermission.
*
* @param permissionLevel The DelegateFolderPermissionLevel
*/
protected void initialize(
DelegateFolderPermissionLevel permissionLevel) {
this.setPermissionLevel(permissionLevel);
this.setIsExistingPermissionLevelCustom(permissionLevel ==
DelegateFolderPermissionLevel.Custom);
}
/**
* Resets this DelegateFolderPermission.
*/
protected void reset() {
this.initialize(DelegateFolderPermissionLevel.None);
}
private DelegateFolderPermissionLevel permissionLevel = DelegateFolderPermissionLevel.None;
/**
* Gets the delegate user's permission on a principal's folder.
*/
protected DelegateFolderPermissionLevel getPermissionLevel() {
return this.permissionLevel;
}
/**
* Sets the delegate user's permission on a principal's folder.
*/
protected void setPermissionLevel(
DelegateFolderPermissionLevel value) {
this.permissionLevel = value;
}
private boolean isExistingPermissionLevelCustom;
/**
* Gets IsExistingPermissionLevelCustom.
*/
protected boolean getIsExistingPermissionLevelCustom() {
return this.isExistingPermissionLevelCustom;
}
/**
* Sets IsExistingPermissionLevelCustom.
*/
private void setIsExistingPermissionLevelCustom(Boolean value) {
this.isExistingPermissionLevelCustom = value;
}
}
}
| |
package com.krishagni.catissueplus.core.common.access;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import com.krishagni.catissueplus.core.administrative.domain.DistributionOrder;
import com.krishagni.catissueplus.core.administrative.domain.Institute;
import com.krishagni.catissueplus.core.administrative.domain.Site;
import com.krishagni.catissueplus.core.administrative.domain.StorageContainer;
import com.krishagni.catissueplus.core.administrative.domain.User;
import com.krishagni.catissueplus.core.administrative.repository.UserDao;
import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocol;
import com.krishagni.catissueplus.core.biospecimen.domain.CollectionProtocolRegistration;
import com.krishagni.catissueplus.core.biospecimen.domain.Specimen;
import com.krishagni.catissueplus.core.biospecimen.domain.Visit;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.CprErrorCode;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.SpecimenErrorCode;
import com.krishagni.catissueplus.core.biospecimen.domain.factory.VisitErrorCode;
import com.krishagni.catissueplus.core.common.Pair;
import com.krishagni.catissueplus.core.common.errors.OpenSpecimenException;
import com.krishagni.catissueplus.core.common.events.Operation;
import com.krishagni.catissueplus.core.common.events.Resource;
import com.krishagni.catissueplus.core.common.util.AuthUtil;
import com.krishagni.rbac.common.errors.RbacErrorCode;
import com.krishagni.rbac.domain.Subject;
import com.krishagni.rbac.domain.SubjectAccess;
import com.krishagni.rbac.domain.SubjectRole;
import com.krishagni.rbac.repository.DaoFactory;
import com.krishagni.rbac.service.RbacService;
@Configurable
public class AccessCtrlMgr {
@Autowired
private RbacService rbacService;
@Autowired
private DaoFactory daoFactory;
@Autowired
private UserDao userDao;
private static AccessCtrlMgr instance;
private AccessCtrlMgr() {
}
public static AccessCtrlMgr getInstance() {
if (instance == null) {
instance = new AccessCtrlMgr();
}
return instance;
}
public void ensureUserIsAdmin() {
User user = AuthUtil.getCurrentUser();
if (!user.isAdmin()) {
throw OpenSpecimenException.userError(RbacErrorCode.ADMIN_RIGHTS_REQUIRED);
}
}
//////////////////////////////////////////////////////////////////////////////////////
// //
// User object access control helper methods //
// //
//////////////////////////////////////////////////////////////////////////////////////
public void ensureCreateUserRights(User user) {
ensureUserObjectRights(user, Operation.CREATE);
}
public void ensureUpdateUserRights(User user) {
ensureUserObjectRights(user, Operation.UPDATE);
}
public void ensureDeleteUserRights(User user) {
ensureUserObjectRights(user, Operation.DELETE);
}
private void ensureUserObjectRights(User user, Operation op) {
if (AuthUtil.isAdmin()) {
return;
}
Set<Site> sites = getSites(Resource.USER, op);
for (Site site : sites) {
if (site.getInstitute().equals(user.getInstitute())) {
return;
}
}
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
//////////////////////////////////////////////////////////////////////////////////////
// //
// Distribution Protocol object access control helper methods //
// //
//////////////////////////////////////////////////////////////////////////////////////
public void ensureReadDpRights() {
if (AuthUtil.isAdmin()) {
return;
}
User user = AuthUtil.getCurrentUser();
Operation[] ops = {Operation.CREATE, Operation.UPDATE};
if (!canUserPerformOp(user.getId(), Resource.ORDER, ops)) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
}
//////////////////////////////////////////////////////////////////////////////////////
// //
// Collection Protocol object access control helper methods //
// //
//////////////////////////////////////////////////////////////////////////////////////
public Set<Long> getReadableCpIds() {
return getEligibleCpIds(Resource.CP.getName(), Operation.READ.getName(), null);
}
public Set<Long> getRegisterEnabledCpIds(List<String> siteNames) {
return getEligibleCpIds(Resource.PARTICIPANT.getName(), Operation.CREATE.getName(), siteNames);
}
public void ensureCreateCpRights(CollectionProtocol cp) {
ensureCpObjectRights(cp, Operation.CREATE);
}
public void ensureReadCpRights(CollectionProtocol cp) {
ensureCpObjectRights(cp, Operation.READ);
}
public void ensureUpdateCpRights(CollectionProtocol cp) {
ensureCpObjectRights(cp, Operation.UPDATE);
}
public void ensureDeleteCpRights(CollectionProtocol cp) {
ensureCpObjectRights(cp, Operation.DELETE);
}
private void ensureCpObjectRights(CollectionProtocol cp, Operation op) {
if (AuthUtil.isAdmin()) {
return;
}
Long userId = AuthUtil.getCurrentUser().getId();
String resource = Resource.CP.getName();
String[] ops = {op.getName()};
boolean allowed = false;
List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops);
for (SubjectAccess access : accessList) {
Site accessSite = access.getSite();
CollectionProtocol accessCp = access.getCollectionProtocol();
if (accessSite != null && accessCp != null && accessCp.equals(cp)) {
//
// Specific CP
//
allowed = true;
} else if (accessSite != null && accessCp == null && cp.getRepositories().contains(accessSite)) {
//
// TODO:
// Current implementation is at least one site is CP repository. We do not check whether permission is
// for all CP repositories.
//
// All CPs of a site
//
allowed = true;
} else if (accessSite == null && accessCp == null) {
//
// All CPs of all sites of user institute
//
Set<Site> instituteSites = getUserInstituteSites(userId);
if (CollectionUtils.containsAny(instituteSites, cp.getRepositories())) {
allowed = true;
}
}
if (allowed) {
break;
}
}
if (!allowed) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
}
//////////////////////////////////////////////////////////////////////////////////////
// //
// Participant object access control helper methods //
// //
//////////////////////////////////////////////////////////////////////////////////////
public static class ParticipantReadAccess {
public boolean admin;
public Set<Long> siteIds;
public boolean phiAccess;
}
public ParticipantReadAccess getParticipantReadAccess(Long cpId) {
ParticipantReadAccess result = new ParticipantReadAccess();
result.phiAccess = true;
if (AuthUtil.isAdmin()) {
result.admin = true;
return result;
}
Long userId = AuthUtil.getCurrentUser().getId();
String resource = Resource.PARTICIPANT.getName();
String[] ops = {Operation.READ.getName()};
List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, cpId, resource, ops);
if (accessList.isEmpty()) {
resource = Resource.PARTICIPANT_DEID.getName();
accessList = daoFactory.getSubjectDao().getAccessList(userId, cpId, resource, ops);
result.phiAccess = false;
}
Set<Long> siteIds = new HashSet<Long>();
for (SubjectAccess access : accessList) {
Site accessSite = access.getSite();
if (accessSite != null) {
siteIds.add(accessSite.getId());
} else if (accessSite == null) {
Set<Site> sites = getUserInstituteSites(userId);
for (Site site : sites) {
siteIds.add(site.getId());
}
}
}
result.siteIds = siteIds;
return result;
}
public boolean ensureCreateCprRights(Long cprId) {
return ensureCprObjectRights(cprId, Operation.CREATE);
}
public boolean ensureCreateCprRights(CollectionProtocolRegistration cpr) {
return ensureCprObjectRights(cpr, Operation.CREATE);
}
public void ensureReadCprRights(Long cprId) {
ensureCprObjectRights(cprId, Operation.READ);
}
public boolean ensureReadCprRights(CollectionProtocolRegistration cpr) {
return ensureCprObjectRights(cpr, Operation.READ);
}
public void ensureUpdateCprRights(Long cprId) {
ensureCprObjectRights(cprId, Operation.UPDATE);
}
public boolean ensureUpdateCprRights(CollectionProtocolRegistration cpr) {
return ensureCprObjectRights(cpr, Operation.UPDATE);
}
public void ensureDeleteCprRights(Long cprId) {
ensureCprObjectRights(cprId, Operation.DELETE);
}
public boolean ensureDeleteCprRights(CollectionProtocolRegistration cpr) {
return ensureCprObjectRights(cpr, Operation.DELETE);
}
private boolean ensureCprObjectRights(Long cprId, Operation op) {
CollectionProtocolRegistration cpr = daoFactory.getCprDao().getById(cprId);
if (cpr == null) {
throw OpenSpecimenException.userError(CprErrorCode.NOT_FOUND);
}
return ensureCprObjectRights(cpr, op);
}
private boolean ensureCprObjectRights(CollectionProtocolRegistration cpr, Operation op) {
if (AuthUtil.isAdmin()) {
return true;
}
Long userId = AuthUtil.getCurrentUser().getId();
boolean phiAccess = true;
String resource = Resource.PARTICIPANT.getName();
String[] ops = {op.getName()};
boolean allowed = false;
Long cpId = cpr.getCollectionProtocol().getId();
List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, cpId, resource, ops);
if (accessList.isEmpty() && op == Operation.READ) {
phiAccess = false;
resource = Resource.PARTICIPANT_DEID.getName();
accessList = daoFactory.getSubjectDao().getAccessList(userId, cpId, resource, ops);
}
if (accessList.isEmpty()) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
Set<Site> mrnSites = cpr.getParticipant().getMrnSites();
if (mrnSites.isEmpty()) {
return phiAccess;
}
for (SubjectAccess access : accessList) {
Site accessSite = access.getSite();
if (accessSite != null && mrnSites.contains(accessSite)) { // Specific site
allowed = true;
} else if (accessSite == null) { // All user institute sites
Set<Site> instituteSites = getUserInstituteSites(userId);
if (CollectionUtils.containsAny(instituteSites, mrnSites)) {
allowed = true;
}
}
if (allowed) {
break;
}
}
if (!allowed) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
return phiAccess;
}
//////////////////////////////////////////////////////////////////////////////////////
// //
// Visit and Specimen object access control helper methods //
// //
//////////////////////////////////////////////////////////////////////////////////////
public void ensureCreateOrUpdateVisitRights(Long visitId) {
ensureVisitObjectRights(visitId, Operation.UPDATE);
}
public void ensureCreateOrUpdateVisitRights(Visit visit) {
ensureVisitAndSpecimenObjectRights(visit.getRegistration(), Operation.UPDATE);
}
public void ensureReadVisitRights(Long visitId) {
ensureVisitObjectRights(visitId, Operation.READ);
}
public void ensureReadVisitRights(Visit visit) {
ensureReadVisitRights(visit.getRegistration());
}
public void ensureReadVisitRights(CollectionProtocolRegistration cpr) {
ensureVisitAndSpecimenObjectRights(cpr, Operation.READ);
}
public void ensureDeleteVisitRights(Long visitId) {
ensureVisitObjectRights(visitId, Operation.DELETE);
}
public void ensureDeleteVisitRights(Visit visit) {
ensureVisitAndSpecimenObjectRights(visit.getRegistration(), Operation.DELETE);
}
public void ensureCreateOrUpdateSpecimenRights(Long specimenId) {
ensureSpecimenObjectRights(specimenId, Operation.UPDATE);
}
public void ensureCreateOrUpdateSpecimenRights(Specimen specimen) {
ensureVisitAndSpecimenObjectRights(specimen.getRegistration(), Operation.UPDATE);
}
public void ensureReadSpecimenRights(Long specimenId) {
ensureSpecimenObjectRights(specimenId, Operation.READ);
}
public void ensureReadSpecimenRights(Specimen specimen) {
ensureReadSpecimenRights(specimen.getRegistration());
}
public void ensureReadSpecimenRights(CollectionProtocolRegistration cpr) {
ensureVisitAndSpecimenObjectRights(cpr, Operation.READ);
}
public void ensureDeleteSpecimenRights(Long specimenId) {
ensureSpecimenObjectRights(specimenId, Operation.DELETE);
}
public void ensureDeleteSpecimenRights(Specimen specimen) {
ensureVisitAndSpecimenObjectRights(specimen.getRegistration(), Operation.DELETE);
}
public List<Pair<Long, Long>> getReadAccessSpecimenSiteCps() {
if (AuthUtil.isAdmin()) {
return null;
}
String[] ops = {Operation.READ.getName()};
Set<Pair<Long, Long>> siteCpPairs = getVisitAndSpecimenSiteCps(ops);
siteCpPairs.addAll(getDistributionOrderSiteCps(ops));
Set<Long> sitesOfAllCps = new HashSet<Long>();
List<Pair<Long, Long>> result = new ArrayList<Pair<Long, Long>>();
for (Pair<Long, Long> siteCp : siteCpPairs) {
if (siteCp.second() == null) {
sitesOfAllCps.add(siteCp.first());
result.add(siteCp);
}
}
for (Pair<Long, Long> siteCp : siteCpPairs) {
if (sitesOfAllCps.contains(siteCp.first())) {
continue;
}
result.add(siteCp);
}
return result;
}
private void ensureVisitObjectRights(Long visitId, Operation op) {
Visit visit = daoFactory.getVisitDao().getById(visitId);
if (visit == null) {
throw OpenSpecimenException.userError(VisitErrorCode.NOT_FOUND);
}
ensureVisitAndSpecimenObjectRights(visit.getRegistration(), op);
}
private void ensureSpecimenObjectRights(Long specimenId, Operation op) {
Specimen specimen = daoFactory.getSpecimenDao().getById(specimenId);
if (specimen == null) {
throw OpenSpecimenException.userError(SpecimenErrorCode.NOT_FOUND, specimenId);
}
ensureVisitAndSpecimenObjectRights(specimen.getRegistration(), op);
}
private void ensureVisitAndSpecimenObjectRights(CollectionProtocolRegistration cpr, Operation op) {
if (AuthUtil.isAdmin()) {
return;
}
Long userId = AuthUtil.getCurrentUser().getId();
String resource = Resource.VISIT_N_SPECIMEN.getName();
String[] ops = null;
if (op == Operation.CREATE || op == Operation.UPDATE) {
ops = new String[]{Operation.CREATE.getName(), Operation.UPDATE.getName()};
} else {
ops = new String[]{op.getName()};
}
boolean allowed = false;
Long cpId = cpr.getCollectionProtocol().getId();
List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, cpId, resource, ops);
if (accessList.isEmpty()) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
Set<Site> mrnSites = cpr.getParticipant().getMrnSites();
if (mrnSites.isEmpty()) {
return;
}
for (SubjectAccess access : accessList) {
Site accessSite = access.getSite();
if (accessSite != null && mrnSites.contains(accessSite)) { // Specific site
allowed = true;
} else if (accessSite == null) { // All user institute sites
Set<Site> instituteSites = getUserInstituteSites(userId);
if (CollectionUtils.containsAny(instituteSites, mrnSites)) {
allowed = true;
}
}
if (allowed) {
break;
}
}
if (!allowed) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
}
private Set<Pair<Long, Long>> getVisitAndSpecimenSiteCps(String[] ops) {
Long userId = AuthUtil.getCurrentUser().getId();
String resource = Resource.VISIT_N_SPECIMEN.getName();
List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops);
Set<Pair<Long, Long>> siteCpPairs = new HashSet<Pair<Long, Long>>();
for (SubjectAccess access : accessList) {
Set<Site> sites = null;
if (access.getSite() != null) {
sites = Collections.singleton(access.getSite());
} else {
sites = getUserInstituteSites(userId);
}
Long cpId = null;
if (access.getCollectionProtocol() != null) {
cpId = access.getCollectionProtocol().getId();
}
for (Site site : sites) {
siteCpPairs.add(Pair.make(site.getId(), cpId));
}
}
return siteCpPairs;
}
//////////////////////////////////////////////////////////////////////////////////////
// //
// Storage container object access control helper methods //
// //
//////////////////////////////////////////////////////////////////////////////////////
public Set<Long> getReadAccessContainerSites() {
if (AuthUtil.isAdmin()) {
return null;
}
Set<Site> sites = getSites(Resource.STORAGE_CONTAINER, Operation.READ);
Set<Long> result = new HashSet<Long>();
for (Site site : sites) {
result.add(site.getId());
}
return result;
}
public void ensureCreateContainerRights(StorageContainer container) {
ensureStorageContainerObjectRights(container, Operation.CREATE);
}
public void ensureReadContainerRights(StorageContainer container) {
ensureStorageContainerObjectRights(container, Operation.READ);
}
public void ensureUpdateContainerRights(StorageContainer container) {
ensureStorageContainerObjectRights(container, Operation.UPDATE);
}
public void ensureDeleteContainerRights(StorageContainer container) {
ensureStorageContainerObjectRights(container, Operation.DELETE);
}
private void ensureStorageContainerObjectRights(StorageContainer container, Operation op) {
if (AuthUtil.isAdmin()) {
return;
}
Long userId = AuthUtil.getCurrentUser().getId();
String resource = Resource.STORAGE_CONTAINER.getName();
String[] ops = {op.getName()};
boolean allowed = false;
List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops);
if (accessList.isEmpty()) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
Site containerSite = container.getSite();
for (SubjectAccess access : accessList) {
Site accessSite = access.getSite();
if (accessSite != null && accessSite.equals(containerSite)) { // Specific site
allowed = true;
} else if (accessSite == null) { // All user institute sites
Set<Site> instituteSites = getUserInstituteSites(userId);
if (instituteSites.contains(containerSite)) {
allowed = true;
}
}
if (allowed) {
break;
}
}
if (!allowed) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
}
//////////////////////////////////////////////////////////////////////////////////////
// //
// Distribution order access control helper methods //
// //
//////////////////////////////////////////////////////////////////////////////////////
public Set<Long> getReadAccessDistributionOrderInstitutes() {
if (AuthUtil.isAdmin()) {
return null;
}
Set<Site> sites = getSites(Resource.ORDER, Operation.READ);
Set<Long> result = new HashSet<Long>();
for (Site site : sites) {
result.add(site.getInstitute().getId());
}
return result;
}
public void ensureCreateDistributionOrderRights(DistributionOrder order) {
ensureDistributionOrderObjectRights(order, Operation.CREATE);
}
public void ensureReadDistributionOrderRights(DistributionOrder order) {
ensureDistributionOrderObjectRights(order, Operation.READ);
}
public void ensureUpdateDistributionOrderRights(DistributionOrder order) {
ensureDistributionOrderObjectRights(order, Operation.UPDATE);
}
public void ensureDeleteDistributionOrderRights(DistributionOrder order) {
ensureDistributionOrderObjectRights(order, Operation.DELETE);
}
private void ensureDistributionOrderObjectRights(DistributionOrder order, Operation op) {
if (AuthUtil.isAdmin()) {
return;
}
Long userId = AuthUtil.getCurrentUser().getId();
String resource = Resource.ORDER.getName();
String[] ops = {op.getName()};
boolean allowed = false;
List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops);
if (accessList.isEmpty()) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
Institute orderInstitute = order.getInstitute();
for (SubjectAccess access : accessList) {
Site accessSite = access.getSite();
if (accessSite != null && accessSite.getInstitute().equals(orderInstitute)) { // Specific site institute
allowed = true;
} else if (accessSite == null) { // user institute
Institute userInstitute = getUserInstitute(userId);
if (userInstitute.equals(orderInstitute)) {
allowed = true;
}
}
if (allowed) {
break;
}
}
if (!allowed) {
throw OpenSpecimenException.userError(RbacErrorCode.ACCESS_DENIED);
}
}
private Set<Pair<Long, Long>> getDistributionOrderSiteCps(String[] ops) {
Long userId = AuthUtil.getCurrentUser().getId();
String resource = Resource.ORDER.getName();
List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops);
Set<Pair<Long, Long>> siteCpPairs = new HashSet<Pair<Long, Long>>();
for (SubjectAccess access : accessList) {
Set<Site> sites = null;
if (access.getSite() != null) {
sites = access.getSite().getInstitute().getSites();
} else {
sites = getUserInstituteSites(userId);
}
for (Site site : sites) {
siteCpPairs.add(Pair.make(site.getId(), (Long)null));
}
}
return siteCpPairs;
}
public Set<Site> getRoleAssignedSites() {
User user = AuthUtil.getCurrentUser();
Subject subject = daoFactory.getSubjectDao().getById(user.getId());
Set<Site> results = new HashSet<Site>();
boolean allSites = false;
for (SubjectRole role : subject.getRoles()) {
if (role.getSite() == null) {
allSites = true;
break;
}
results.add(role.getSite());
}
if (allSites) {
results.clear();
results.addAll(getUserInstituteSites(user.getId()));
}
return results;
}
public Set<Site> getSites(Resource resource, Operation operation) {
User user = AuthUtil.getCurrentUser();
String[] ops = {operation.getName()};
List<SubjectAccess> accessList = daoFactory.getSubjectDao().getAccessList(user.getId(), resource.getName(), ops);
Set<Site> results = new HashSet<Site>();
boolean allSites = false;
for (SubjectAccess access : accessList) {
if (access.getSite() == null) {
allSites = true;
break;
}
results.add(access.getSite());
}
if (allSites) {
results.clear();
results.addAll(getUserInstituteSites(user.getId()));
}
return results;
}
public Set<Long> getEligibleCpIds(String resource, String op, List<String> siteNames) {
if (AuthUtil.isAdmin()) {
return null;
}
Long userId = AuthUtil.getCurrentUser().getId();
String[] ops = {op};
List<SubjectAccess> accessList = null;
if (CollectionUtils.isEmpty(siteNames)) {
accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops);
} else {
accessList = daoFactory.getSubjectDao().getAccessList(userId, resource, ops, siteNames.toArray(new String[0]));
}
Set<Long> cpIds = new HashSet<Long>();
Set<Long> cpOfSites = new HashSet<Long>();
for (SubjectAccess access : accessList) {
if (access.getSite() != null && access.getCollectionProtocol() != null) {
cpIds.add(access.getCollectionProtocol().getId());
} else if (access.getSite() != null) {
cpOfSites.add(access.getSite().getId());
} else {
Collection<Site> sites = getUserInstituteSites(userId);
for (Site site : sites) {
if (CollectionUtils.isEmpty(siteNames) || siteNames.contains(site.getName())) {
cpOfSites.add(site.getId());
}
}
}
}
if (!cpOfSites.isEmpty()) {
cpIds.addAll(daoFactory.getCollectionProtocolDao().getCpIdsBySiteIds(cpOfSites));
}
return cpIds;
}
private Set<Site> getUserInstituteSites(Long userId) {
return getUserInstitute(userId).getSites();
}
private Institute getUserInstitute(Long userId) {
User user = userDao.getById(userId);
return user.getInstitute();
}
private boolean canUserPerformOp(Long userId, Resource resource, Operation[] operations) {
List<String> ops = new ArrayList<String>();
for (Operation operation : operations) {
ops.add(operation.getName());
}
return daoFactory.getSubjectDao().canUserPerformOps(
userId,
resource.getName(),
ops.toArray(new String[0]));
}
}
| |
/**
* Copyright 2011-2014 Asakusa Framework Team.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.asakusafw.dmdl.directio.tsv.driver;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.math.BigDecimal;
import org.apache.hadoop.io.Text;
import org.junit.Before;
import org.junit.Test;
import com.asakusafw.dmdl.java.emitter.driver.ObjectDriver;
import com.asakusafw.runtime.directio.BinaryStreamFormat;
import com.asakusafw.runtime.io.ModelInput;
import com.asakusafw.runtime.io.ModelOutput;
import com.asakusafw.runtime.value.Date;
import com.asakusafw.runtime.value.DateTime;
import com.asakusafw.runtime.value.StringOption;
/**
* Test for {@link TsvFormatEmitter}.
*/
public class TsvFormatEmitterTest extends GeneratorTesterRoot {
/**
* Initializes the test.
* @throws Exception if some errors were occurred
*/
@Before
public void setUp() throws Exception {
emitDrivers.add(new TsvFormatEmitter());
emitDrivers.add(new ObjectDriver());
}
/**
* simple testing.
* @throws Exception if failed
*/
@Test
public void simple() throws Exception {
ModelLoader loaded = generateJava("simple");
ModelWrapper model = loaded.newModel("Simple");
BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("tsv", "SimpleTsvFormat");
assertThat(support.getSupportedType(), is((Object) model.unwrap().getClass()));
BinaryStreamFormat<Object> unsafe = unsafe(support);
model.set("value", new Text("Hello, world!"));
ByteArrayOutputStream output = new ByteArrayOutputStream();
ModelOutput<Object> writer = unsafe.createOutput(model.unwrap().getClass(), "hello", output);
writer.write(model.unwrap());
writer.close();
Object buffer = loaded.newModel("Simple").unwrap();
ModelInput<Object> reader = unsafe.createInput(model.unwrap().getClass(), "hello", in(output),
0, size(output));
assertThat(reader.readTo(buffer), is(true));
assertThat(buffer, is(model.unwrap()));
assertThat(reader.readTo(buffer), is(false));
}
/**
* All types.
* @throws Exception if failed
*/
@Test
public void types() throws Exception {
ModelLoader loaded = generateJava("types");
ModelWrapper model = loaded.newModel("Types");
BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("tsv", "TypesTsvFormat");
assertThat(support.getSupportedType(), is((Object) model.unwrap().getClass()));
ModelWrapper empty = loaded.newModel("Types");
ModelWrapper all = loaded.newModel("Types");
all.set("c_int", 100);
all.set("c_text", new Text("Hello, DMDL world!"));
all.set("c_boolean", true);
all.set("c_byte", (byte) 64);
all.set("c_short", (short) 1023);
all.set("c_long", 100000L);
all.set("c_float", 1.5f);
all.set("c_double", 2.5f);
all.set("c_decimal", new BigDecimal("3.1415"));
all.set("c_date", new Date(2011, 9, 1));
all.set("c_datetime", new DateTime(2011, 12, 31, 23, 59, 59));
BinaryStreamFormat<Object> unsafe = unsafe(support);
ByteArrayOutputStream output = new ByteArrayOutputStream();
ModelOutput<Object> writer = unsafe.createOutput(model.unwrap().getClass(), "hello", output);
writer.write(empty.unwrap());
writer.write(all.unwrap());
writer.close();
Object buffer = loaded.newModel("Types").unwrap();
ModelInput<Object> reader = unsafe.createInput(model.unwrap().getClass(), "hello", in(output),
0, size(output));
assertThat(reader.readTo(buffer), is(true));
assertThat(buffer, is(empty.unwrap()));
assertThat(reader.readTo(buffer), is(true));
assertThat(buffer, is(all.unwrap()));
assertThat(reader.readTo(buffer), is(false));
}
/**
* With compression.
* @throws Exception if failed
*/
@Test
public void compression() throws Exception {
ModelLoader loaded = generateJava("compression");
ModelWrapper model = loaded.newModel("Compression");
BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("tsv", "CompressionTsvFormat");
assertThat(support.getSupportedType(), is((Object) model.unwrap().getClass()));
BinaryStreamFormat<Object> unsafe = unsafe(support);
model.set("value", new Text("Hello, world!"));
ByteArrayOutputStream output = new ByteArrayOutputStream();
ModelOutput<Object> writer = unsafe.createOutput(model.unwrap().getClass(), "hello", output);
writer.write(model.unwrap());
writer.close();
Object buffer = loaded.newModel("Compression").unwrap();
ModelInput<Object> reader = unsafe.createInput(model.unwrap().getClass(), "hello", in(output),
0, size(output));
assertThat(reader.readTo(buffer), is(true));
assertThat(buffer, is(model.unwrap()));
assertThat(reader.readTo(buffer), is(false));
}
/**
* simple testing.
* @throws Exception if failed
*/
@Test
public void header() throws Exception {
ModelLoader loaded = generateJava("header");
ModelWrapper model = loaded.newModel("Header");
BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("tsv", "HeaderTsvFormat");
assertThat(support.getSupportedType(), is((Object) model.unwrap().getClass()));
BinaryStreamFormat<Object> unsafe = unsafe(support);
model.set("key", 100);
model.set("value", new Text("Hello, world!"));
ByteArrayOutputStream output = new ByteArrayOutputStream();
ModelOutput<Object> writer = unsafe.createOutput(model.unwrap().getClass(), "hello", output);
writer.write(model.unwrap());
writer.close();
Object buffer = loaded.newModel("Header").unwrap();
ModelInput<Object> reader = unsafe.createInput(model.unwrap().getClass(), "hello", in(output), 0, size(output));
assertThat(reader.readTo(buffer), is(true));
assertThat(buffer, is(model.unwrap()));
assertThat(reader.readTo(buffer), is(false));
}
/**
* With ignoring field.
* @throws Exception if failed
*/
@Test
public void ignore() throws Exception {
ModelLoader loaded = generateJava("ignore");
ModelWrapper model = loaded.newModel("Ignore");
BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("tsv", "IgnoreTsvFormat");
assertThat(support.getSupportedType(), is((Object) model.unwrap().getClass()));
BinaryStreamFormat<Object> unsafe = unsafe(support);
model.set("value", new Text("Hello, world!"));
ByteArrayOutputStream output = new ByteArrayOutputStream();
ModelOutput<Object> writer = unsafe.createOutput(model.unwrap().getClass(), "hello", output);
writer.write(model.unwrap());
writer.close();
Object buffer = loaded.newModel("Ignore").unwrap();
ModelInput<Object> reader = unsafe.createInput(model.unwrap().getClass(), "hello", in(output),
0, size(output));
assertThat(reader.readTo(buffer), is(true));
assertThat(buffer, is(model.unwrap()));
assertThat(reader.readTo(buffer), is(false));
}
/**
* With file name.
* @throws Exception if failed
*/
@Test
public void file_name() throws Exception {
ModelLoader loaded = generateJava("file_name");
ModelWrapper model = loaded.newModel("FileName");
BinaryStreamFormat<?> support = (BinaryStreamFormat<?>) loaded.newObject("tsv", "FileNameTsvFormat");
assertThat(support.getSupportedType(), is((Object) model.unwrap().getClass()));
BinaryStreamFormat<Object> unsafe = unsafe(support);
model.set("value", new Text("Hello, world!"));
ByteArrayOutputStream output = new ByteArrayOutputStream();
ModelOutput<Object> writer = unsafe.createOutput(model.unwrap().getClass(), "hello.tsv", output);
writer.write(model.unwrap());
writer.close();
ModelWrapper buffer = loaded.newModel("FileName");
ModelInput<Object> reader = unsafe.createInput(model.unwrap().getClass(), "hello.tsv", in(output),
0, size(output));
assertThat(reader.readTo(buffer.unwrap()), is(true));
assertThat(buffer.getOption("value"), is((Object) new StringOption("Hello, world!")));
assertThat(buffer.getOption("path"), is((Object) new StringOption("hello.tsv")));
assertThat(reader.readTo(buffer.unwrap()), is(false));
}
@SuppressWarnings("unchecked")
private BinaryStreamFormat<Object> unsafe(Object support) {
return (BinaryStreamFormat<Object>) support;
}
private ByteArrayInputStream in(ByteArrayOutputStream output) {
return new ByteArrayInputStream(output.toByteArray());
}
private long size(ByteArrayOutputStream output) {
return output.size();
}
}
| |
/*
* Copyright [2017] [Andy Moncsek]
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jacpfx.circuitbreaker;
import com.google.gson.Gson;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Vertx;
import io.vertx.core.http.HttpClient;
import io.vertx.core.http.HttpClientOptions;
import io.vertx.core.http.HttpClientRequest;
import io.vertx.core.json.JsonObject;
import io.vertx.core.spi.cluster.ClusterManager;
import io.vertx.test.core.VertxTestBase;
import io.vertx.test.fakecluster.FakeClusterManager;
import java.io.IOException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import org.jacpfx.entity.Payload;
import org.jacpfx.entity.encoder.ExampleStringEncoder;
import org.jacpfx.vxms.common.ServiceEndpoint;
import org.jacpfx.vxms.common.util.Serializer;
import org.jacpfx.vxms.rest.base.response.RestHandler;
import org.jacpfx.vxms.services.VxmsEndpoint;
import org.junit.Before;
import org.junit.Test;
/** Created by Andy Moncsek on 23.04.15. */
public class RESTJerseyClientStatefulCircuitBrakerTests extends VertxTestBase {
public static final String SERVICE_REST_GET = "/wsService";
public static final int PORT = 9998;
private static final int MAX_RESPONSE_ELEMENTS = 4;
private static final String HOST = "127.0.0.1";
private HttpClient client;
protected int getNumNodes() {
return 1;
}
protected Vertx getVertx() {
return vertices[0];
}
@Override
protected ClusterManager getClusterManager() {
return new FakeClusterManager();
}
@Override
public void setUp() throws Exception {
super.setUp();
startNodes(getNumNodes());
}
@Before
public void startVerticles() throws InterruptedException {
CountDownLatch latch2 = new CountDownLatch(1);
DeploymentOptions options = new DeploymentOptions().setInstances(1);
options.setConfig(
new JsonObject()
.put("clustered", false)
.put("host", HOST)
.put("circuit-breaker-scope", "local"));
// Deploy the module - the System property `vertx.modulename` will contain the name of the
// module so you
// don'failure have to hardecode it in your tests
getVertx()
.deployVerticle(
new WsServiceOne(),
options,
asyncResult -> {
// Deployment is asynchronous and this this handler will be called when it's complete
// (or failed)
System.out.println("start service: " + asyncResult.succeeded());
assertTrue(asyncResult.succeeded());
assertNotNull("deploymentID should not be null", asyncResult.result());
// If deployed correctly then start the tests!
// latch2.countDown();
latch2.countDown();
});
client = getVertx().createHttpClient(new HttpClientOptions());
awaitLatch(latch2);
}
@Test
public void stringGETResponseCircuitBaseTest() throws InterruptedException {
HttpClientOptions options = new HttpClientOptions();
options.setDefaultPort(PORT);
options.setDefaultHost(HOST);
HttpClient client = vertx.createHttpClient(options);
HttpClientRequest request =
client.get(
"/wsService/stringGETResponseCircuitBaseTest/crash",
resp ->
resp.bodyHandler(
body -> {
System.out.println("Got a createResponse: " + body.toString());
assertEquals(body.toString(), "failure");
HttpClientRequest request2 =
client.get(
"/wsService/stringGETResponseCircuitBaseTest/value",
resp2 ->
resp2.bodyHandler(
body2 -> {
System.out.println(
"Got a createResponse: " + body2.toString());
assertEquals(body2.toString(), "failure");
// wait 1s, but circuit is still open
vertx.setTimer(
1205,
handler -> {
HttpClientRequest request3 =
client.get(
"/wsService/stringGETResponseCircuitBaseTest/value",
resp3 ->
resp3.bodyHandler(
body3 -> {
System.out.println(
"Got a createResponse: "
+ body3.toString());
assertEquals(
body3.toString(), "failure");
// wait another 1s, now circuit
// should be closed
vertx.setTimer(
2005,
handler2 -> {
HttpClientRequest request4 =
client.get(
"/wsService/stringGETResponseCircuitBaseTest/value",
resp4 ->
resp4.bodyHandler(
body4 -> {
System.out
.println(
"Got a createResponse: "
+ body4
.toString());
assertEquals(
body4
.toString(),
"value");
// should be
// closed
testComplete();
}));
request4.end();
});
}));
request3.end();
});
}));
request2.end();
}));
request.end();
await(80000, TimeUnit.MILLISECONDS);
}
@Test
public void objectGETResponseCircuitBaseTest() throws InterruptedException {
HttpClientOptions options = new HttpClientOptions();
options.setDefaultPort(PORT);
options.setDefaultHost(HOST);
HttpClient client = vertx.createHttpClient(options);
HttpClientRequest request =
client.get(
"/wsService/objectGETResponseCircuitBaseTest/crash",
resp ->
resp.bodyHandler(
body -> {
System.out.println("Got a createResponse: " + body.toString());
Payload<String> pp = new Gson().fromJson(body.toString(), Payload.class);
assertEquals(new Payload<String>("failure").getValue(), pp.getValue());
HttpClientRequest request2 =
client.get(
"/wsService/objectGETResponseCircuitBaseTest/value",
resp2 ->
resp2.bodyHandler(
body2 -> {
System.out.println(
"Got a createResponse: " + body2.toString());
Payload<String> pp2 =
new Gson().fromJson(body2.toString(), Payload.class);
assertEquals(
new Payload<String>("failure").getValue(),
pp2.getValue());
// wait 1s, but circuit is still open
vertx.setTimer(
1205,
handler -> {
HttpClientRequest request3 =
client.get(
"/wsService/objectGETResponseCircuitBaseTest/value",
resp3 ->
resp3.bodyHandler(
body3 -> {
System.out.println(
"Got a createResponse: "
+ body3.toString());
Payload<String> pp3 =
new Gson()
.fromJson(
body3.toString(),
Payload.class);
assertEquals(
new Payload<String>("failure")
.getValue(),
pp3.getValue());
// wait another 1s, now circuit
// should be closed
vertx.setTimer(
2005,
handler2 -> {
HttpClientRequest request4 =
client.get(
"/wsService/objectGETResponseCircuitBaseTest/value",
resp4 ->
resp4.bodyHandler(
body4 -> {
System.out
.println(
"Got a createResponse: "
+ body4
.toString());
Payload<
String>
pp4 =
new Gson()
.fromJson(
body4
.toString(),
Payload
.class);
assertEquals(
new Payload<
String>(
"value")
.getValue(),
pp4
.getValue());
// should be
// closed
testComplete();
}));
request4.end();
});
}));
request3.end();
});
}));
request2.end();
}));
request.end();
await(80000, TimeUnit.MILLISECONDS);
}
@Test
public void byteGETResponseCircuitBaseTest() throws InterruptedException {
HttpClientOptions options = new HttpClientOptions();
options.setDefaultPort(PORT);
options.setDefaultHost(HOST);
HttpClient client = vertx.createHttpClient(options);
HttpClientRequest request =
client.get(
"/wsService/byteGETResponseCircuitBaseTest/crash",
resp ->
resp.bodyHandler(
body -> {
System.out.println("Got a createResponse: " + body.toString());
Payload<String> pp = null;
try {
pp = (Payload<String>) Serializer.deserialize(body.getBytes());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
assertEquals(new Payload<String>("failure").getValue(), pp.getValue());
HttpClientRequest request2 =
client.get(
"/wsService/byteGETResponseCircuitBaseTest/value",
resp2 ->
resp2.bodyHandler(
body2 -> {
System.out.println(
"Got a createResponse: " + body2.toString());
Payload<String> pp2 = null;
try {
pp2 =
(Payload<String>)
Serializer.deserialize(body2.getBytes());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
assertEquals(
new Payload<String>("failure").getValue(),
pp2.getValue());
// wait 1s, but circuit is still open
vertx.setTimer(
1205,
handler -> {
HttpClientRequest request3 =
client.get(
"/wsService/byteGETResponseCircuitBaseTest/value",
resp3 ->
resp3.bodyHandler(
body3 -> {
System.out.println(
"Got a createResponse: "
+ body3.toString());
Payload<String> pp3 = null;
try {
pp3 =
(Payload<String>)
Serializer.deserialize(
body.getBytes());
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
assertEquals(
new Payload<String>("failure")
.getValue(),
pp3.getValue());
// wait another 1s, now circuit
// should be closed
vertx.setTimer(
2005,
handler2 -> {
HttpClientRequest request4 =
client.get(
"/wsService/byteGETResponseCircuitBaseTest/value",
resp4 ->
resp4.bodyHandler(
body4 -> {
System.out
.println(
"Got a createResponse: "
+ body4
.toString());
Payload<
String>
pp4 =
null;
try {
pp4 =
(Payload<
String>)
Serializer
.deserialize(
body4
.getBytes());
} catch (
IOException
e) {
e
.printStackTrace();
} catch (
ClassNotFoundException
e) {
e
.printStackTrace();
}
assertEquals(
new Payload<
String>(
"value")
.getValue(),
pp4
.getValue());
// should be
// closed
testComplete();
}));
request4.end();
});
}));
request3.end();
});
}));
request2.end();
}));
request.end();
await(80000, TimeUnit.MILLISECONDS);
}
public HttpClient getClient() {
return client;
}
@ServiceEndpoint(name = SERVICE_REST_GET, contextRoot = SERVICE_REST_GET, port = PORT)
public class WsServiceOne extends VxmsEndpoint {
///// ------------- sync blocking ----------------
@Path("/stringGETResponseCircuitBaseTest/:val")
@GET
public void stringGETResponseCircuitBaseTest(RestHandler reply) {
final String val = reply.request().param("val");
System.out.println("stringResponse: " + val);
reply
.response()
.stringResponse(
(future) -> {
if (val.equals("crash")) {
throw new NullPointerException("test-123");
}
future.complete(val);
})
.onError(e -> System.out.println(e.getMessage()))
.retry(3)
.closeCircuitBreaker(2000)
.onFailureRespond((error, future) -> future.complete("failure"))
.execute();
}
@Path("/objectGETResponseCircuitBaseTest/:val")
@GET
public void objectGETResponseCircuitBaseTest(RestHandler reply) {
final String val = reply.request().param("val");
System.out.println("object: " + val);
reply
.response()
.objectResponse(
(future) -> {
if (val.equals("crash")) {
throw new NullPointerException("test-123");
}
future.complete(new Payload<>(val));
},
new ExampleStringEncoder())
.onError(e -> System.out.println(e.getMessage()))
.retry(3)
.closeCircuitBreaker(2000)
.onFailureRespond(
(error, future) -> future.complete(new Payload<>("failure")),
new ExampleStringEncoder())
.execute();
}
@Path("/byteGETResponseCircuitBaseTest/:val")
@GET
public void byteGETResponseCircuitBaseTest(RestHandler reply) {
final String val = reply.request().param("val");
System.out.println("byte: " + val);
reply
.response()
.byteResponse(
(future) -> {
if (val.equals("crash")) {
throw new NullPointerException("test-123");
}
future.complete(Serializer.serialize(new Payload<>(val)));
})
.onError(e -> System.out.println(e.getMessage()))
.retry(3)
.closeCircuitBreaker(2000)
.onFailureRespond(
(error, future) -> future.complete(Serializer.serialize(new Payload<>("failure"))))
.execute();
}
}
}
| |
/*
* #%L
* %%
* Copyright (C) 2011 - 2017 BMW Car IT GmbH
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* #L%
*/
package io.joynr.messaging.routing;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.inject.Inject;
import com.google.inject.name.Named;
import io.joynr.exceptions.JoynrIllegalStateException;
import io.joynr.exceptions.JoynrRuntimeException;
import io.joynr.messaging.MessagingPropertyKeys;
import joynr.ImmutableMessage;
import joynr.Message;
import joynr.Message.MessageType;
import joynr.system.RoutingTypes.Address;
import joynr.system.RoutingTypes.MqttAddress;
public class AddressManager {
private static final Logger logger = LoggerFactory.getLogger(AddressManager.class);
public static final String multicastAddressCalculatorParticipantId = "joynr.internal.multicastAddressCalculatorParticipantId";
private final MulticastReceiverRegistry multicastReceiversRegistry;
private RoutingTable routingTable;
private MulticastAddressCalculator multicastAddressCalculator;
protected static class PrimaryGlobalTransportHolder {
@Inject(optional = true)
@Named(MessagingPropertyKeys.PROPERTY_MESSAGING_PRIMARYGLOBALTRANSPORT)
private String primaryGlobalTransport;
public PrimaryGlobalTransportHolder() {
}
// For testing only
protected PrimaryGlobalTransportHolder(String primaryGlobalTransport) {
this.primaryGlobalTransport = primaryGlobalTransport;
}
public String get() {
return primaryGlobalTransport;
}
}
@Inject
public AddressManager(RoutingTable routingTable,
PrimaryGlobalTransportHolder primaryGlobalTransport,
Set<MulticastAddressCalculator> multicastAddressCalculators,
MulticastReceiverRegistry multicastReceiverRegistry) {
logger.trace("Initialised with routingTable: {}, primaryGlobalTransport: {}, multicastAddressCalculators: {}, multicastReceiverRegistry: {}",
routingTable,
primaryGlobalTransport.get(),
multicastAddressCalculators,
multicastReceiverRegistry);
this.routingTable = routingTable;
this.multicastReceiversRegistry = multicastReceiverRegistry;
if (multicastAddressCalculators.size() > 1 && primaryGlobalTransport.get() == null) {
throw new JoynrIllegalStateException("Multiple multicast address calculators registered, but no primary global transport set.");
}
if (multicastAddressCalculators.size() == 1) {
this.multicastAddressCalculator = multicastAddressCalculators.iterator().next();
} else {
for (MulticastAddressCalculator multicastAddressCalculator : multicastAddressCalculators) {
if (multicastAddressCalculator.supports(primaryGlobalTransport.get())) {
this.multicastAddressCalculator = multicastAddressCalculator;
break;
}
}
}
}
/**
* Get the participantIds to which the passed in message should be sent to grouped by their address.
* <ul>
* <li> For multicast messages, the returned map can have multiple entries with multiple participantIds.
* <li> For non multicast messages, the returned map always has a single entry: a dummy address mapped to the
* participantId of the recipient.
* </ul>
*
* @param message the message for which we want to find the participantIds to send it to.
* @return map of participantIds to send the message to grouped by their addresses. Will not be null, because if
* a participantId can't be determined, the returned map will be empty.
*/
public Map<Address, Set<String>> getParticipantIdMap(ImmutableMessage message) {
HashMap<Address, Set<String>> result = new HashMap<>();
if (MessageType.VALUE_MESSAGE_TYPE_MULTICAST.equals(message.getType())) {
Set<String> localReceivers = getLocalMulticastReceiversFromRegistry(message);
for (String r : localReceivers) {
Address address = routingTable.get(r);
if (address == null) {
logger.error("No address found for multicast receiver {} for {}", r, message.getTrackingInfo());
continue;
}
Set<String> receiverSet = result.get(address);
if (receiverSet == null) {
receiverSet = new HashSet<String>();
result.put(address, receiverSet);
}
receiverSet.add(r);
}
if (!message.isReceivedFromGlobal() && multicastAddressCalculator != null) {
if (multicastAddressCalculator.createsGlobalTransportAddresses()) {
// only global providers should multicast to the "outside world"
if (isProviderGloballyVisible(message.getSender())) {
addReceiversFromAddressCalculator(message, result);
}
} else {
// in case the address calculator does not provide an address
// to the "outside world" it is safe to forward the message
// regardless of the provider being globally visible or not
addReceiversFromAddressCalculator(message, result);
}
}
} else {
String toParticipantId = message.getRecipient();
if (toParticipantId != null) {
result.put(new Address(), Set.of(toParticipantId));
}
}
logger.trace("Found the following recipients for {}: {}", message, result);
return result;
}
/**
* Get the address to which the passed in message should be sent to.
* This can be an address contained in the {@link RoutingTable}, or a
* multicast address calculated from the header content of the message.
* <p>
* If the message has multiple recipients (this should only happen for multicast messages), this methods expects
* that all recipients have the same address, see {@link #getParticipantIdMap(ImmutableMessage)}).
*
* @param message the message for which we want to find an address to send it to.
* @return Optional of an address to send the message to. Will not be null, because if an address
* can't be determined, the returned Optional will be empty.
*/
public Optional<Address> getAddressForDelayableImmutableMessage(DelayableImmutableMessage message) {
Map<String, String> customHeader = message.getMessage().getCustomHeaders();
final String gbidVal = customHeader.get(Message.CUSTOM_HEADER_GBID_KEY);
Address address = null;
Set<String> recipients = message.getRecipients();
for (String recipient : recipients) {
// Return the first non null address. All recipients of a message have the same address, see getAddressesMap().
if (address != null) {
break;
} else if (recipient.startsWith(multicastAddressCalculatorParticipantId)) {
address = determineAddressFromMulticastAddressCalculator(message, recipient);
} else if (gbidVal == null) {
address = routingTable.get(recipient);
} else {
address = routingTable.get(recipient, gbidVal);
}
}
return address == null ? Optional.empty() : Optional.of(address);
}
private Address determineAddressFromMulticastAddressCalculator(DelayableImmutableMessage message,
String recipient) {
Address address = null;
Set<Address> addressSet = multicastAddressCalculator.calculate(message.getMessage());
if (addressSet.size() <= 1) {
for (Address calculatedAddress : addressSet) {
address = calculatedAddress;
}
} else {
// This case can only happen if we have multiple backends, which can only happen in case of MQTT
for (Address calculatedAddress : addressSet) {
MqttAddress mqttAddress = (MqttAddress) calculatedAddress;
String brokerUri = mqttAddress.getBrokerUri();
if (recipient.equals(multicastAddressCalculatorParticipantId + "_" + brokerUri)) {
address = calculatedAddress;
break;
}
}
}
return address;
}
private boolean isProviderGloballyVisible(String participantId) {
boolean isGloballyVisible = false;
try {
isGloballyVisible = routingTable.getIsGloballyVisible(participantId);
} catch (JoynrRuntimeException e) {
// This should never happen
logger.error("No routing entry found for Multicast Provider {}. The message will not be published globally.",
participantId);
}
return isGloballyVisible;
}
private void addReceiversFromAddressCalculator(ImmutableMessage message, HashMap<Address, Set<String>> result) {
Set<Address> calculatedAddresses = multicastAddressCalculator.calculate(message);
if (calculatedAddresses.size() == 1) {
result.put(calculatedAddresses.iterator().next(), Set.of(multicastAddressCalculatorParticipantId));
} else {
// This case can only happen if we have multiple backends, which can only happen in case of MQTT
for (Address address : calculatedAddresses) {
MqttAddress mqttAddress = (MqttAddress) address;
result.put(address, Set.of(multicastAddressCalculatorParticipantId + "_" + mqttAddress.getBrokerUri()));
}
}
}
private Set<String> getLocalMulticastReceiversFromRegistry(ImmutableMessage message) {
return multicastReceiversRegistry.getReceivers(message.getRecipient());
}
}
| |
/*
* Copyright 2003-2014 Dave Griffith, Bas Leijdekkers
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.siyeh.ig;
import com.intellij.codeInspection.ProblemHighlightType;
import com.intellij.codeInspection.ProblemsHolder;
import com.intellij.openapi.util.TextRange;
import com.intellij.psi.*;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
public abstract class BaseInspectionVisitor extends JavaElementVisitor {
private BaseInspection inspection = null;
private boolean onTheFly = false;
private ProblemsHolder holder = null;
final void setInspection(BaseInspection inspection) {
this.inspection = inspection;
}
final void setOnTheFly(boolean onTheFly) {
this.onTheFly = onTheFly;
}
public final boolean isOnTheFly() {
return onTheFly;
}
protected final void registerNewExpressionError(
@NotNull PsiNewExpression expression, Object... infos) {
final PsiJavaCodeReferenceElement classReference =
expression.getClassOrAnonymousClassReference();
if (classReference == null) {
registerError(expression, infos);
}
else {
registerError(classReference, infos);
}
}
protected final void registerMethodCallError(
@NotNull PsiMethodCallExpression expression,
@NonNls Object... infos) {
final PsiReferenceExpression methodExpression =
expression.getMethodExpression();
final PsiElement nameToken = methodExpression.getReferenceNameElement();
if (nameToken == null) {
registerError(expression, infos);
}
else {
registerError(nameToken, infos);
}
}
protected final void registerStatementError(@NotNull PsiStatement statement,
Object... infos) {
final PsiElement statementToken = statement.getFirstChild();
if (statementToken == null) {
registerError(statement, infos);
}
else {
registerError(statementToken, infos);
}
}
protected final void registerClassError(@NotNull PsiClass aClass,
Object... infos) {
PsiElement nameIdentifier;
if (aClass instanceof PsiEnumConstantInitializer) {
final PsiEnumConstantInitializer enumConstantInitializer =
(PsiEnumConstantInitializer)aClass;
final PsiEnumConstant enumConstant =
enumConstantInitializer.getEnumConstant();
nameIdentifier = enumConstant.getNameIdentifier();
}
else if (aClass instanceof PsiAnonymousClass) {
final PsiAnonymousClass anonymousClass = (PsiAnonymousClass)aClass;
nameIdentifier = anonymousClass.getBaseClassReference();
}
else {
nameIdentifier = aClass.getNameIdentifier();
}
if (nameIdentifier != null && !nameIdentifier.isPhysical()) {
nameIdentifier = nameIdentifier.getNavigationElement();
}
if (nameIdentifier == null || !nameIdentifier.isPhysical()) {
registerError(aClass.getContainingFile(), infos);
}
else {
registerError(nameIdentifier, infos);
}
}
protected final void registerMethodError(@NotNull PsiMethod method,
Object... infos) {
final PsiElement nameIdentifier = method.getNameIdentifier();
if (nameIdentifier == null) {
registerError(method.getContainingFile(), infos);
}
else {
registerError(nameIdentifier, infos);
}
}
protected final void registerVariableError(@NotNull PsiVariable variable,
Object... infos) {
final PsiElement nameIdentifier = variable.getNameIdentifier();
if (nameIdentifier == null) {
registerError(variable, infos);
}
else {
registerError(nameIdentifier, infos);
}
}
protected final void registerTypeParameterError(
@NotNull PsiTypeParameter typeParameter, Object... infos) {
final PsiElement nameIdentifier = typeParameter.getNameIdentifier();
if (nameIdentifier == null) {
registerError(typeParameter, infos);
}
else {
registerError(nameIdentifier, infos);
}
}
protected final void registerFieldError(@NotNull PsiField field,
Object... infos) {
final PsiElement nameIdentifier = field.getNameIdentifier();
registerError(nameIdentifier, infos);
}
protected final void registerModifierError(
@NotNull String modifier, @NotNull PsiModifierListOwner parameter,
Object... infos) {
final PsiModifierList modifiers = parameter.getModifierList();
if (modifiers == null) {
return;
}
final PsiElement[] children = modifiers.getChildren();
for (final PsiElement child : children) {
final String text = child.getText();
if (modifier.equals(text)) {
registerError(child, infos);
}
}
}
protected final void registerClassInitializerError(
@NotNull PsiClassInitializer initializer, Object... infos) {
final PsiCodeBlock body = initializer.getBody();
final PsiJavaToken lBrace = body.getLBrace();
if (lBrace == null) {
registerError(initializer, infos);
}
else {
registerError(lBrace, infos);
}
}
protected final void registerError(@NotNull PsiElement location,
Object... infos) {
registerError(location, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, infos);
}
protected final void registerError(@NotNull PsiElement location,
final ProblemHighlightType highlightType,
Object... infos) {
if (location.getTextLength() == 0 && !(location instanceof PsiFile)) {
return;
}
final InspectionGadgetsFix[] fixes = createFixes(infos);
for (InspectionGadgetsFix fix : fixes) {
fix.setOnTheFly(onTheFly);
}
final String description = inspection.buildErrorString(infos);
holder.registerProblem(location, description, highlightType, fixes);
}
protected final void registerErrorAtOffset(@NotNull PsiElement location, int offset, int length, Object... infos) {
registerErrorAtOffset(location, offset, length, ProblemHighlightType.GENERIC_ERROR_OR_WARNING, infos);
}
protected final void registerErrorAtOffset(@NotNull PsiElement location, int offset, int length,
ProblemHighlightType highlightType,
Object... infos) {
if (location.getTextLength() == 0 || length == 0) {
return;
}
final InspectionGadgetsFix[] fixes = createFixes(infos);
for (InspectionGadgetsFix fix : fixes) {
fix.setOnTheFly(onTheFly);
}
final String description = inspection.buildErrorString(infos);
final TextRange range = new TextRange(offset, offset + length);
holder.registerProblem(location, description, highlightType, range, fixes);
}
@NotNull
private InspectionGadgetsFix[] createFixes(Object... infos) {
if (!onTheFly && inspection.buildQuickFixesOnlyForOnTheFlyErrors()) {
return InspectionGadgetsFix.EMPTY_ARRAY;
}
final InspectionGadgetsFix[] fixes = inspection.buildFixes(infos);
if (fixes.length > 0) {
return fixes;
}
final InspectionGadgetsFix fix = inspection.buildFix(infos);
if (fix == null) {
return InspectionGadgetsFix.EMPTY_ARRAY;
}
return new InspectionGadgetsFix[]{fix};
}
@Override
public void visitReferenceExpression(PsiReferenceExpression expression) {
visitExpression(expression);
}
public final void setProblemsHolder(ProblemsHolder holder) {
this.holder = holder;
}
}
| |
/**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
package fixtures.azurespecials.implementation;
import retrofit2.Retrofit;
import com.google.common.reflect.TypeToken;
import com.microsoft.rest.ServiceCallback;
import com.microsoft.rest.ServiceFuture;
import com.microsoft.rest.ServiceResponseWithHeaders;
import com.microsoft.rest.Validator;
import fixtures.azurespecials.ErrorException;
import fixtures.azurespecials.HeaderCustomNamedRequestIdHeaders;
import fixtures.azurespecials.HeaderCustomNamedRequestIdHeadHeaders;
import fixtures.azurespecials.HeaderCustomNamedRequestIdParamGroupingHeaders;
import fixtures.azurespecials.HeaderCustomNamedRequestIdParamGroupingParameters;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.http.HEAD;
import retrofit2.http.Header;
import retrofit2.http.Headers;
import retrofit2.http.POST;
import retrofit2.Response;
import rx.functions.Func1;
import rx.Observable;
/**
* An instance of this class provides access to all the operations defined
* in Headers.
*/
public class HeadersInner {
/** The Retrofit service to perform REST calls. */
private HeadersService service;
/** The service client containing this operation class. */
private AutoRestAzureSpecialParametersTestClientImpl client;
/**
* Initializes an instance of HeadersInner.
*
* @param retrofit the Retrofit instance built from a Retrofit Builder.
* @param client the instance of the service client containing this operation class.
*/
public HeadersInner(Retrofit retrofit, AutoRestAzureSpecialParametersTestClientImpl client) {
this.service = retrofit.create(HeadersService.class);
this.client = client;
}
/**
* The interface defining all the services for Headers to be
* used by Retrofit to perform actually REST calls.
*/
interface HeadersService {
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: fixtures.azurespecials.Headers customNamedRequestId" })
@POST("azurespecials/customNamedRequestId")
Observable<Response<ResponseBody>> customNamedRequestId(@Header("foo-client-request-id") String fooClientRequestId, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: fixtures.azurespecials.Headers customNamedRequestIdParamGrouping" })
@POST("azurespecials/customNamedRequestIdParamGrouping")
Observable<Response<ResponseBody>> customNamedRequestIdParamGrouping(@Header("accept-language") String acceptLanguage, @Header("foo-client-request-id") String fooClientRequestId, @Header("User-Agent") String userAgent);
@Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: fixtures.azurespecials.Headers customNamedRequestIdHead" })
@HEAD("azurespecials/customNamedRequestIdHead")
Observable<Response<Void>> customNamedRequestIdHead(@Header("foo-client-request-id") String fooClientRequestId, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent);
}
/**
* Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request.
*
* @param fooClientRequestId The fooRequestId
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
*/
public void customNamedRequestId(String fooClientRequestId) {
customNamedRequestIdWithServiceResponseAsync(fooClientRequestId).toBlocking().single().body();
}
/**
* Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request.
*
* @param fooClientRequestId The fooRequestId
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Void> customNamedRequestIdAsync(String fooClientRequestId, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromHeaderResponse(customNamedRequestIdWithServiceResponseAsync(fooClientRequestId), serviceCallback);
}
/**
* Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request.
*
* @param fooClientRequestId The fooRequestId
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponseWithHeaders} object if successful.
*/
public Observable<Void> customNamedRequestIdAsync(String fooClientRequestId) {
return customNamedRequestIdWithServiceResponseAsync(fooClientRequestId).map(new Func1<ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdHeaders>, Void>() {
@Override
public Void call(ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdHeaders> response) {
return response.body();
}
});
}
/**
* Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request.
*
* @param fooClientRequestId The fooRequestId
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponseWithHeaders} object if successful.
*/
public Observable<ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdHeaders>> customNamedRequestIdWithServiceResponseAsync(String fooClientRequestId) {
if (fooClientRequestId == null) {
throw new IllegalArgumentException("Parameter fooClientRequestId is required and cannot be null.");
}
return service.customNamedRequestId(fooClientRequestId, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdHeaders>> call(Response<ResponseBody> response) {
try {
ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdHeaders> clientResponse = customNamedRequestIdDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdHeaders> customNamedRequestIdDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<Void, ErrorException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<Void>() { }.getType())
.registerError(ErrorException.class)
.buildWithHeaders(response, HeaderCustomNamedRequestIdHeaders.class);
}
/**
* Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request, via a parameter group.
*
* @param headerCustomNamedRequestIdParamGroupingParameters Additional parameters for the operation
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
*/
public void customNamedRequestIdParamGrouping(HeaderCustomNamedRequestIdParamGroupingParameters headerCustomNamedRequestIdParamGroupingParameters) {
customNamedRequestIdParamGroupingWithServiceResponseAsync(headerCustomNamedRequestIdParamGroupingParameters).toBlocking().single().body();
}
/**
* Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request, via a parameter group.
*
* @param headerCustomNamedRequestIdParamGroupingParameters Additional parameters for the operation
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Void> customNamedRequestIdParamGroupingAsync(HeaderCustomNamedRequestIdParamGroupingParameters headerCustomNamedRequestIdParamGroupingParameters, final ServiceCallback<Void> serviceCallback) {
return ServiceFuture.fromHeaderResponse(customNamedRequestIdParamGroupingWithServiceResponseAsync(headerCustomNamedRequestIdParamGroupingParameters), serviceCallback);
}
/**
* Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request, via a parameter group.
*
* @param headerCustomNamedRequestIdParamGroupingParameters Additional parameters for the operation
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponseWithHeaders} object if successful.
*/
public Observable<Void> customNamedRequestIdParamGroupingAsync(HeaderCustomNamedRequestIdParamGroupingParameters headerCustomNamedRequestIdParamGroupingParameters) {
return customNamedRequestIdParamGroupingWithServiceResponseAsync(headerCustomNamedRequestIdParamGroupingParameters).map(new Func1<ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdParamGroupingHeaders>, Void>() {
@Override
public Void call(ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdParamGroupingHeaders> response) {
return response.body();
}
});
}
/**
* Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request, via a parameter group.
*
* @param headerCustomNamedRequestIdParamGroupingParameters Additional parameters for the operation
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceResponseWithHeaders} object if successful.
*/
public Observable<ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdParamGroupingHeaders>> customNamedRequestIdParamGroupingWithServiceResponseAsync(HeaderCustomNamedRequestIdParamGroupingParameters headerCustomNamedRequestIdParamGroupingParameters) {
if (headerCustomNamedRequestIdParamGroupingParameters == null) {
throw new IllegalArgumentException("Parameter headerCustomNamedRequestIdParamGroupingParameters is required and cannot be null.");
}
Validator.validate(headerCustomNamedRequestIdParamGroupingParameters);
String fooClientRequestId = headerCustomNamedRequestIdParamGroupingParameters.fooClientRequestId();
return service.customNamedRequestIdParamGrouping(this.client.acceptLanguage(), fooClientRequestId, this.client.userAgent())
.flatMap(new Func1<Response<ResponseBody>, Observable<ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdParamGroupingHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdParamGroupingHeaders>> call(Response<ResponseBody> response) {
try {
ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdParamGroupingHeaders> clientResponse = customNamedRequestIdParamGroupingDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponseWithHeaders<Void, HeaderCustomNamedRequestIdParamGroupingHeaders> customNamedRequestIdParamGroupingDelegate(Response<ResponseBody> response) throws ErrorException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<Void, ErrorException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<Void>() { }.getType())
.registerError(ErrorException.class)
.buildWithHeaders(response, HeaderCustomNamedRequestIdParamGroupingHeaders.class);
}
/**
* Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request.
*
* @param fooClientRequestId The fooRequestId
* @throws IllegalArgumentException thrown if parameters fail the validation
* @throws ErrorException thrown if the request is rejected by server
* @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent
* @return the boolean object if successful.
*/
public boolean customNamedRequestIdHead(String fooClientRequestId) {
return customNamedRequestIdHeadWithServiceResponseAsync(fooClientRequestId).toBlocking().single().body();
}
/**
* Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request.
*
* @param fooClientRequestId The fooRequestId
* @param serviceCallback the async ServiceCallback to handle successful and failed responses.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the {@link ServiceFuture} object
*/
public ServiceFuture<Boolean> customNamedRequestIdHeadAsync(String fooClientRequestId, final ServiceCallback<Boolean> serviceCallback) {
return ServiceFuture.fromHeaderResponse(customNamedRequestIdHeadWithServiceResponseAsync(fooClientRequestId), serviceCallback);
}
/**
* Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request.
*
* @param fooClientRequestId The fooRequestId
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the Boolean object
*/
public Observable<Boolean> customNamedRequestIdHeadAsync(String fooClientRequestId) {
return customNamedRequestIdHeadWithServiceResponseAsync(fooClientRequestId).map(new Func1<ServiceResponseWithHeaders<Boolean, HeaderCustomNamedRequestIdHeadHeaders>, Boolean>() {
@Override
public Boolean call(ServiceResponseWithHeaders<Boolean, HeaderCustomNamedRequestIdHeadHeaders> response) {
return response.body();
}
});
}
/**
* Send foo-client-request-id = 9C4D50EE-2D56-4CD3-8152-34347DC9F2B0 in the header of the request.
*
* @param fooClientRequestId The fooRequestId
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable to the Boolean object
*/
public Observable<ServiceResponseWithHeaders<Boolean, HeaderCustomNamedRequestIdHeadHeaders>> customNamedRequestIdHeadWithServiceResponseAsync(String fooClientRequestId) {
if (fooClientRequestId == null) {
throw new IllegalArgumentException("Parameter fooClientRequestId is required and cannot be null.");
}
return service.customNamedRequestIdHead(fooClientRequestId, this.client.acceptLanguage(), this.client.userAgent())
.flatMap(new Func1<Response<Void>, Observable<ServiceResponseWithHeaders<Boolean, HeaderCustomNamedRequestIdHeadHeaders>>>() {
@Override
public Observable<ServiceResponseWithHeaders<Boolean, HeaderCustomNamedRequestIdHeadHeaders>> call(Response<Void> response) {
try {
ServiceResponseWithHeaders<Boolean, HeaderCustomNamedRequestIdHeadHeaders> clientResponse = customNamedRequestIdHeadDelegate(response);
return Observable.just(clientResponse);
} catch (Throwable t) {
return Observable.error(t);
}
}
});
}
private ServiceResponseWithHeaders<Boolean, HeaderCustomNamedRequestIdHeadHeaders> customNamedRequestIdHeadDelegate(Response<Void> response) throws ErrorException, IOException, IllegalArgumentException {
return this.client.restClient().responseBuilderFactory().<Boolean, ErrorException>newInstance(this.client.serializerAdapter())
.register(200, new TypeToken<Void>() { }.getType())
.register(404, new TypeToken<Void>() { }.getType())
.registerError(ErrorException.class)
.buildEmptyWithHeaders(response, HeaderCustomNamedRequestIdHeadHeaders.class);
}
}
| |
package net.minecraft.server;
import java.util.List;
public class TileEntityHopper extends TileEntityContainer implements IHopper, IUpdatePlayerListBox {
private ItemStack[] items = new ItemStack[5];
private String f;
private int g = -1;
public TileEntityHopper() {}
public void a(NBTTagCompound nbttagcompound) {
super.a(nbttagcompound);
NBTTagList nbttaglist = nbttagcompound.getList("Items", 10);
this.items = new ItemStack[this.getSize()];
if (nbttagcompound.hasKeyOfType("CustomName", 8)) {
this.f = nbttagcompound.getString("CustomName");
}
this.g = nbttagcompound.getInt("TransferCooldown");
for (int i = 0; i < nbttaglist.size(); ++i) {
NBTTagCompound nbttagcompound1 = nbttaglist.get(i);
byte b0 = nbttagcompound1.getByte("Slot");
if (b0 >= 0 && b0 < this.items.length) {
this.items[b0] = ItemStack.createStack(nbttagcompound1);
}
}
}
public void b(NBTTagCompound nbttagcompound) {
super.b(nbttagcompound);
NBTTagList nbttaglist = new NBTTagList();
for (int i = 0; i < this.items.length; ++i) {
if (this.items[i] != null) {
NBTTagCompound nbttagcompound1 = new NBTTagCompound();
nbttagcompound1.setByte("Slot", (byte) i);
this.items[i].save(nbttagcompound1);
nbttaglist.add(nbttagcompound1);
}
}
nbttagcompound.set("Items", nbttaglist);
nbttagcompound.setInt("TransferCooldown", this.g);
if (this.hasCustomName()) {
nbttagcompound.setString("CustomName", this.f);
}
}
public void update() {
super.update();
}
public int getSize() {
return this.items.length;
}
public ItemStack getItem(int i) {
return this.items[i];
}
public ItemStack splitStack(int i, int j) {
if (this.items[i] != null) {
ItemStack itemstack;
if (this.items[i].count <= j) {
itemstack = this.items[i];
this.items[i] = null;
return itemstack;
} else {
itemstack = this.items[i].a(j);
if (this.items[i].count == 0) {
this.items[i] = null;
}
return itemstack;
}
} else {
return null;
}
}
public ItemStack splitWithoutUpdate(int i) {
if (this.items[i] != null) {
ItemStack itemstack = this.items[i];
this.items[i] = null;
return itemstack;
} else {
return null;
}
}
public void setItem(int i, ItemStack itemstack) {
this.items[i] = itemstack;
if (itemstack != null && itemstack.count > this.getMaxStackSize()) {
itemstack.count = this.getMaxStackSize();
}
}
public String getName() {
return this.hasCustomName() ? this.f : "container.hopper";
}
public boolean hasCustomName() {
return this.f != null && this.f.length() > 0;
}
public void a(String s) {
this.f = s;
}
public int getMaxStackSize() {
return 64;
}
public boolean a(EntityHuman entityhuman) {
return this.world.getTileEntity(this.position) != this ? false : entityhuman.e((double) this.position.getX() + 0.5D, (double) this.position.getY() + 0.5D, (double) this.position.getZ() + 0.5D) <= 64.0D;
}
public void startOpen(EntityHuman entityhuman) {}
public void closeContainer(EntityHuman entityhuman) {}
public boolean b(int i, ItemStack itemstack) {
return true;
}
public void c() {
if (this.world != null && !this.world.isStatic) {
--this.g;
if (!this.n()) {
this.d(0);
this.m();
}
}
}
public boolean m() {
if (this.world != null && !this.world.isStatic) {
if (!this.n() && BlockHopper.f(this.u())) {
boolean flag = false;
if (!this.p()) {
flag = this.r();
}
if (!this.q()) {
flag = a((IHopper) this) || flag;
}
if (flag) {
this.d(8);
this.update();
return true;
}
}
return false;
} else {
return false;
}
}
private boolean p() {
ItemStack[] aitemstack = this.items;
int i = aitemstack.length;
for (int j = 0; j < i; ++j) {
ItemStack itemstack = aitemstack[j];
if (itemstack != null) {
return false;
}
}
return true;
}
private boolean q() {
ItemStack[] aitemstack = this.items;
int i = aitemstack.length;
for (int j = 0; j < i; ++j) {
ItemStack itemstack = aitemstack[j];
if (itemstack == null || itemstack.count != itemstack.getMaxStackSize()) {
return false;
}
}
return true;
}
private boolean r() {
IInventory iinventory = this.G();
if (iinventory == null) {
return false;
} else {
EnumDirection enumdirection = BlockHopper.b(this.u()).opposite();
if (this.a(iinventory, enumdirection)) {
return false;
} else {
for (int i = 0; i < this.getSize(); ++i) {
if (this.getItem(i) != null) {
ItemStack itemstack = this.getItem(i).cloneItemStack();
ItemStack itemstack1 = addItem(iinventory, this.splitStack(i, 1), enumdirection);
if (itemstack1 == null || itemstack1.count == 0) {
iinventory.update();
return true;
}
this.setItem(i, itemstack);
}
}
return false;
}
}
}
private boolean a(IInventory iinventory, EnumDirection enumdirection) {
if (iinventory instanceof IWorldInventory) {
IWorldInventory iworldinventory = (IWorldInventory) iinventory;
int[] aint = iworldinventory.getSlotsForFace(enumdirection);
for (int i = 0; i < aint.length; ++i) {
ItemStack itemstack = iworldinventory.getItem(aint[i]);
if (itemstack == null || itemstack.count != itemstack.getMaxStackSize()) {
return false;
}
}
} else {
int j = iinventory.getSize();
for (int k = 0; k < j; ++k) {
ItemStack itemstack1 = iinventory.getItem(k);
if (itemstack1 == null || itemstack1.count != itemstack1.getMaxStackSize()) {
return false;
}
}
}
return true;
}
private static boolean b(IInventory iinventory, EnumDirection enumdirection) {
if (iinventory instanceof IWorldInventory) {
IWorldInventory iworldinventory = (IWorldInventory) iinventory;
int[] aint = iworldinventory.getSlotsForFace(enumdirection);
for (int i = 0; i < aint.length; ++i) {
if (iworldinventory.getItem(aint[i]) != null) {
return false;
}
}
} else {
int j = iinventory.getSize();
for (int k = 0; k < j; ++k) {
if (iinventory.getItem(k) != null) {
return false;
}
}
}
return true;
}
public static boolean a(IHopper ihopper) {
IInventory iinventory = b(ihopper);
if (iinventory != null) {
EnumDirection enumdirection = EnumDirection.DOWN;
if (b(iinventory, enumdirection)) {
return false;
}
if (iinventory instanceof IWorldInventory) {
IWorldInventory iworldinventory = (IWorldInventory) iinventory;
int[] aint = iworldinventory.getSlotsForFace(enumdirection);
for (int i = 0; i < aint.length; ++i) {
if (a(ihopper, iinventory, aint[i], enumdirection)) {
return true;
}
}
} else {
int j = iinventory.getSize();
for (int k = 0; k < j; ++k) {
if (a(ihopper, iinventory, k, enumdirection)) {
return true;
}
}
}
} else {
EntityItem entityitem = a(ihopper.getWorld(), ihopper.A(), ihopper.B() + 1.0D, ihopper.C());
if (entityitem != null) {
return a((IInventory) ihopper, entityitem);
}
}
return false;
}
private static boolean a(IHopper ihopper, IInventory iinventory, int i, EnumDirection enumdirection) {
ItemStack itemstack = iinventory.getItem(i);
if (itemstack != null && b(iinventory, itemstack, i, enumdirection)) {
ItemStack itemstack1 = itemstack.cloneItemStack();
ItemStack itemstack2 = addItem(ihopper, iinventory.splitStack(i, 1), (EnumDirection) null);
if (itemstack2 == null || itemstack2.count == 0) {
iinventory.update();
return true;
}
iinventory.setItem(i, itemstack1);
}
return false;
}
public static boolean a(IInventory iinventory, EntityItem entityitem) {
boolean flag = false;
if (entityitem == null) {
return false;
} else {
ItemStack itemstack = entityitem.getItemStack().cloneItemStack();
ItemStack itemstack1 = addItem(iinventory, itemstack, (EnumDirection) null);
if (itemstack1 != null && itemstack1.count != 0) {
entityitem.setItemStack(itemstack1);
} else {
flag = true;
entityitem.die();
}
return flag;
}
}
public static ItemStack addItem(IInventory iinventory, ItemStack itemstack, EnumDirection enumdirection) {
if (iinventory instanceof IWorldInventory && enumdirection != null) {
IWorldInventory iworldinventory = (IWorldInventory) iinventory;
int[] aint = iworldinventory.getSlotsForFace(enumdirection);
for (int i = 0; i < aint.length && itemstack != null && itemstack.count > 0; ++i) {
itemstack = c(iinventory, itemstack, aint[i], enumdirection);
}
} else {
int j = iinventory.getSize();
for (int k = 0; k < j && itemstack != null && itemstack.count > 0; ++k) {
itemstack = c(iinventory, itemstack, k, enumdirection);
}
}
if (itemstack != null && itemstack.count == 0) {
itemstack = null;
}
return itemstack;
}
private static boolean a(IInventory iinventory, ItemStack itemstack, int i, EnumDirection enumdirection) {
return !iinventory.b(i, itemstack) ? false : !(iinventory instanceof IWorldInventory) || ((IWorldInventory) iinventory).canPlaceItemThroughFace(i, itemstack, enumdirection);
}
private static boolean b(IInventory iinventory, ItemStack itemstack, int i, EnumDirection enumdirection) {
return !(iinventory instanceof IWorldInventory) || ((IWorldInventory) iinventory).canTakeItemThroughFace(i, itemstack, enumdirection);
}
private static ItemStack c(IInventory iinventory, ItemStack itemstack, int i, EnumDirection enumdirection) {
ItemStack itemstack1 = iinventory.getItem(i);
if (a(iinventory, itemstack, i, enumdirection)) {
boolean flag = false;
if (itemstack1 == null) {
iinventory.setItem(i, itemstack);
itemstack = null;
flag = true;
} else if (a(itemstack1, itemstack)) {
int j = itemstack.getMaxStackSize() - itemstack1.count;
int k = Math.min(itemstack.count, j);
itemstack.count -= k;
itemstack1.count += k;
flag = k > 0;
}
if (flag) {
if (iinventory instanceof TileEntityHopper) {
TileEntityHopper tileentityhopper = (TileEntityHopper) iinventory;
if (tileentityhopper.o()) {
tileentityhopper.d(8);
}
iinventory.update();
}
iinventory.update();
}
}
return itemstack;
}
private IInventory G() {
EnumDirection enumdirection = BlockHopper.b(this.u());
return b(this.getWorld(), (double) (this.position.getX() + enumdirection.getAdjacentX()), (double) (this.position.getY() + enumdirection.getAdjacentY()), (double) (this.position.getZ() + enumdirection.getAdjacentZ()));
}
public static IInventory b(IHopper ihopper) {
return b(ihopper.getWorld(), ihopper.A(), ihopper.B() + 1.0D, ihopper.C());
}
public static EntityItem a(World world, double d0, double d1, double d2) {
List list = world.a(EntityItem.class, new AxisAlignedBB(d0, d1, d2, d0 + 1.0D, d1 + 1.0D, d2 + 1.0D), IEntitySelector.a);
return list.size() > 0 ? (EntityItem) list.get(0) : null;
}
public static IInventory b(World world, double d0, double d1, double d2) {
Object object = null;
int i = MathHelper.floor(d0);
int j = MathHelper.floor(d1);
int k = MathHelper.floor(d2);
BlockPosition blockposition = new BlockPosition(i, j, k);
TileEntity tileentity = world.getTileEntity(new BlockPosition(i, j, k));
if (tileentity instanceof IInventory) {
object = (IInventory) tileentity;
if (object instanceof TileEntityChest) {
Block block = world.getType(new BlockPosition(i, j, k)).getBlock();
if (block instanceof BlockChest) {
object = ((BlockChest) block).d(world, blockposition);
}
}
}
if (object == null) {
List list = world.a((Entity) null, new AxisAlignedBB(d0, d1, d2, d0 + 1.0D, d1 + 1.0D, d2 + 1.0D), IEntitySelector.c);
if (list.size() > 0) {
object = (IInventory) list.get(world.random.nextInt(list.size()));
}
}
return (IInventory) object;
}
private static boolean a(ItemStack itemstack, ItemStack itemstack1) {
return itemstack.getItem() != itemstack1.getItem() ? false : (itemstack.getData() != itemstack1.getData() ? false : (itemstack.count > itemstack.getMaxStackSize() ? false : ItemStack.equals(itemstack, itemstack1)));
}
public double A() {
return (double) this.position.getX();
}
public double B() {
return (double) this.position.getY();
}
public double C() {
return (double) this.position.getZ();
}
public void d(int i) {
this.g = i;
}
public boolean n() {
return this.g > 0;
}
public boolean o() {
return this.g <= 1;
}
public String getContainerName() {
return "minecraft:hopper";
}
public Container createContainer(PlayerInventory playerinventory, EntityHuman entityhuman) {
return new ContainerHopper(playerinventory, this, entityhuman);
}
public int getProperty(int i) {
return 0;
}
public void b(int i, int j) {}
public int g() {
return 0;
}
public void l() {
for (int i = 0; i < this.items.length; ++i) {
this.items[i] = null;
}
}
}
| |
/*******************************************************************************
* Copyright (c) 2015-2018 Skymind, Inc.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
******************************************************************************/
package org.nd4j.linalg.io;
import java.util.*;
public abstract class StringUtils {
private static final String FOLDER_SEPARATOR = "/";
private static final String WINDOWS_FOLDER_SEPARATOR = "\\";
private static final String TOP_PATH = "..";
private static final String CURRENT_PATH = ".";
private static final char EXTENSION_SEPARATOR = '.';
public StringUtils() {}
public static boolean isEmpty(Object str) {
return str == null || "".equals(str);
}
public static boolean hasLength(CharSequence str) {
return str != null && str.length() > 0;
}
public static boolean hasLength(String str) {
return hasLength((CharSequence) str);
}
public static boolean hasText(CharSequence str) {
if (!hasLength(str)) {
return false;
} else {
int strLen = str.length();
for (int i = 0; i < strLen; ++i) {
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}
}
public static boolean hasText(String str) {
return hasText((CharSequence) str);
}
public static boolean containsWhitespace(CharSequence str) {
if (!hasLength(str)) {
return false;
} else {
int strLen = str.length();
for (int i = 0; i < strLen; ++i) {
if (Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}
}
public static boolean containsWhitespace(String str) {
return containsWhitespace((CharSequence) str);
}
public static String trimWhitespace(String str) {
if (!hasLength(str)) {
return str;
} else {
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
sb.deleteCharAt(0);
}
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
}
public static String trimAllWhitespace(String str) {
if (!hasLength(str)) {
return str;
} else {
StringBuilder sb = new StringBuilder(str);
int index = 0;
while (sb.length() > index) {
if (Character.isWhitespace(sb.charAt(index))) {
sb.deleteCharAt(index);
} else {
++index;
}
}
return sb.toString();
}
}
public static String trimLeadingWhitespace(String str) {
if (!hasLength(str)) {
return str;
} else {
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(0))) {
sb.deleteCharAt(0);
}
return sb.toString();
}
}
public static String trimTrailingWhitespace(String str) {
if (!hasLength(str)) {
return str;
} else {
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && Character.isWhitespace(sb.charAt(sb.length() - 1))) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
}
public static String trimLeadingCharacter(String str, char leadingCharacter) {
if (!hasLength(str)) {
return str;
} else {
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && sb.charAt(0) == leadingCharacter) {
sb.deleteCharAt(0);
}
return sb.toString();
}
}
public static String trimTrailingCharacter(String str, char trailingCharacter) {
if (!hasLength(str)) {
return str;
} else {
StringBuilder sb = new StringBuilder(str);
while (sb.length() > 0 && sb.charAt(sb.length() - 1) == trailingCharacter) {
sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
}
public static boolean startsWithIgnoreCase(String str, String prefix) {
if (str != null && prefix != null) {
if (str.startsWith(prefix)) {
return true;
} else if (str.length() < prefix.length()) {
return false;
} else {
String lcStr = str.substring(0, prefix.length()).toLowerCase();
String lcPrefix = prefix.toLowerCase();
return lcStr.equals(lcPrefix);
}
} else {
return false;
}
}
public static boolean endsWithIgnoreCase(String str, String suffix) {
if (str != null && suffix != null) {
if (str.endsWith(suffix)) {
return true;
} else if (str.length() < suffix.length()) {
return false;
} else {
String lcStr = str.substring(str.length() - suffix.length()).toLowerCase();
String lcSuffix = suffix.toLowerCase();
return lcStr.equals(lcSuffix);
}
} else {
return false;
}
}
public static boolean substringMatch(CharSequence str, int index, CharSequence substring) {
for (int j = 0; j < substring.length(); ++j) {
int i = index + j;
if (i >= str.length() || str.charAt(i) != substring.charAt(j)) {
return false;
}
}
return true;
}
public static int countOccurrencesOf(String str, String sub) {
if (str != null && sub != null && str.length() != 0 && sub.length() != 0) {
int count = 0;
int idx;
for (int pos = 0; (idx = str.indexOf(sub, pos)) != -1; pos = idx + sub.length()) {
++count;
}
return count;
} else {
return 0;
}
}
public static String replace(String inString, String oldPattern, String newPattern) {
if (hasLength(inString) && hasLength(oldPattern) && newPattern != null) {
StringBuilder sb = new StringBuilder();
int pos = 0;
int index = inString.indexOf(oldPattern);
for (int patLen = oldPattern.length(); index >= 0; index = inString.indexOf(oldPattern, pos)) {
sb.append(inString.substring(pos, index));
sb.append(newPattern);
pos = index + patLen;
}
sb.append(inString.substring(pos));
return sb.toString();
} else {
return inString;
}
}
public static String delete(String inString, String pattern) {
return replace(inString, pattern, "");
}
public static String deleteAny(String inString, String charsToDelete) {
if (hasLength(inString) && hasLength(charsToDelete)) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < inString.length(); ++i) {
char c = inString.charAt(i);
if (charsToDelete.indexOf(c) == -1) {
sb.append(c);
}
}
return sb.toString();
} else {
return inString;
}
}
public static String quote(String str) {
return str != null ? "\'" + str + "\'" : null;
}
public static Object quoteIfString(Object obj) {
return obj instanceof String ? quote((String) obj) : obj;
}
public static String unqualify(String qualifiedName) {
return unqualify(qualifiedName, '.');
}
public static String unqualify(String qualifiedName, char separator) {
return qualifiedName.substring(qualifiedName.lastIndexOf(separator) + 1);
}
public static String capitalize(String str) {
return changeFirstCharacterCase(str, true);
}
public static String uncapitalize(String str) {
return changeFirstCharacterCase(str, false);
}
private static String changeFirstCharacterCase(String str, boolean capitalize) {
if (str != null && str.length() != 0) {
StringBuilder sb = new StringBuilder(str.length());
if (capitalize) {
sb.append(Character.toUpperCase(str.charAt(0)));
} else {
sb.append(Character.toLowerCase(str.charAt(0)));
}
sb.append(str.substring(1));
return sb.toString();
} else {
return str;
}
}
public static String getFilename(String path) {
if (path == null) {
return null;
} else {
int separatorIndex = path.lastIndexOf("/");
return separatorIndex != -1 ? path.substring(separatorIndex + 1) : path;
}
}
public static String getFilenameExtension(String path) {
if (path == null) {
return null;
} else {
int extIndex = path.lastIndexOf(46);
if (extIndex == -1) {
return null;
} else {
int folderIndex = path.lastIndexOf("/");
return folderIndex > extIndex ? null : path.substring(extIndex + 1);
}
}
}
public static String stripFilenameExtension(String path) {
if (path == null) {
return null;
} else {
int extIndex = path.lastIndexOf(46);
if (extIndex == -1) {
return path;
} else {
int folderIndex = path.lastIndexOf("/");
return folderIndex > extIndex ? path : path.substring(0, extIndex);
}
}
}
public static String applyRelativePath(String path, String relativePath) {
int separatorIndex = path.lastIndexOf("/");
if (separatorIndex != -1) {
String newPath = path.substring(0, separatorIndex);
if (!relativePath.startsWith("/")) {
newPath = newPath + "/";
}
return newPath + relativePath;
} else {
return relativePath;
}
}
public static String cleanPath(String path) {
if (path == null) {
return null;
} else {
String pathToUse = replace(path, "\\", "/");
int prefixIndex = pathToUse.indexOf(":");
String prefix = "";
if (prefixIndex != -1) {
prefix = pathToUse.substring(0, prefixIndex + 1);
pathToUse = pathToUse.substring(prefixIndex + 1);
}
if (pathToUse.startsWith("/")) {
prefix = prefix + "/";
pathToUse = pathToUse.substring(1);
}
String[] pathArray = delimitedListToStringArray(pathToUse, "/");
LinkedList pathElements = new LinkedList();
int tops = 0;
int i;
for (i = pathArray.length - 1; i >= 0; --i) {
String element = pathArray[i];
if (!".".equals(element)) {
if ("..".equals(element)) {
++tops;
} else if (tops > 0) {
--tops;
} else {
pathElements.add(0, element);
}
}
}
for (i = 0; i < tops; ++i) {
pathElements.add(0, "..");
}
return prefix + collectionToDelimitedString(pathElements, "/");
}
}
public static boolean pathEquals(String path1, String path2) {
return cleanPath(path1).equals(cleanPath(path2));
}
public static Locale parseLocaleString(String localeString) {
String[] parts = tokenizeToStringArray(localeString, "_ ", false, false);
String language = parts.length > 0 ? parts[0] : "";
String country = parts.length > 1 ? parts[1] : "";
validateLocalePart(language);
validateLocalePart(country);
String variant = "";
if (parts.length >= 2) {
int endIndexOfCountryCode = localeString.lastIndexOf(country) + country.length();
variant = trimLeadingWhitespace(localeString.substring(endIndexOfCountryCode));
if (variant.startsWith("_")) {
variant = trimLeadingCharacter(variant, '_');
}
}
return language.length() > 0 ? new Locale(language, country, variant) : null;
}
private static void validateLocalePart(String localePart) {
for (int i = 0; i < localePart.length(); ++i) {
char ch = localePart.charAt(i);
if (ch != 95 && ch != 32 && !Character.isLetterOrDigit(ch)) {
throw new IllegalArgumentException("Locale part \"" + localePart + "\" contains invalid characters");
}
}
}
public static String toLanguageTag(Locale locale) {
return locale.getLanguage() + (hasText(locale.getCountry()) ? "-" + locale.getCountry() : "");
}
public static String[] addStringToArray(String[] array, String str) {
if (ObjectUtils.isEmpty(array)) {
return new String[] {str};
} else {
String[] newArr = new String[array.length + 1];
System.arraycopy(array, 0, newArr, 0, array.length);
newArr[array.length] = str;
return newArr;
}
}
public static String[] concatenateStringArrays(String[] array1, String[] array2) {
if (ObjectUtils.isEmpty(array1)) {
return array2;
} else if (ObjectUtils.isEmpty(array2)) {
return array1;
} else {
String[] newArr = new String[array1.length + array2.length];
System.arraycopy(array1, 0, newArr, 0, array1.length);
System.arraycopy(array2, 0, newArr, array1.length, array2.length);
return newArr;
}
}
public static String[] mergeStringArrays(String[] array1, String[] array2) {
if (ObjectUtils.isEmpty(array1)) {
return array2;
} else if (ObjectUtils.isEmpty(array2)) {
return array1;
} else {
ArrayList result = new ArrayList();
result.addAll(Arrays.asList(array1));
String[] arr$ = array2;
int len$ = array2.length;
for (int i$ = 0; i$ < len$; ++i$) {
String str = arr$[i$];
if (!result.contains(str)) {
result.add(str);
}
}
return toStringArray(result);
}
}
public static String[] sortStringArray(String[] array) {
if (ObjectUtils.isEmpty(array)) {
return new String[0];
} else {
Arrays.sort(array);
return array;
}
}
public static String[] toStringArray(Collection<String> collection) {
return collection == null ? null : collection.toArray(new String[collection.size()]);
}
public static String[] toStringArray(Enumeration<String> enumeration) {
if (enumeration == null) {
return null;
} else {
ArrayList list = Collections.list(enumeration);
return (String[]) list.toArray(new String[list.size()]);
}
}
public static String[] trimArrayElements(String[] array) {
if (ObjectUtils.isEmpty(array)) {
return new String[0];
} else {
String[] result = new String[array.length];
for (int i = 0; i < array.length; ++i) {
String element = array[i];
result[i] = element != null ? element.trim() : null;
}
return result;
}
}
public static String[] removeDuplicateStrings(String[] array) {
if (ObjectUtils.isEmpty(array)) {
return array;
} else {
TreeSet set = new TreeSet();
String[] arr$ = array;
int len$ = array.length;
for (int i$ = 0; i$ < len$; ++i$) {
String element = arr$[i$];
set.add(element);
}
return toStringArray(set);
}
}
public static String[] split(String toSplit, String delimiter) {
if (hasLength(toSplit) && hasLength(delimiter)) {
int offset = toSplit.indexOf(delimiter);
if (offset < 0) {
return null;
} else {
String beforeDelimiter = toSplit.substring(0, offset);
String afterDelimiter = toSplit.substring(offset + delimiter.length());
return new String[] {beforeDelimiter, afterDelimiter};
}
} else {
return null;
}
}
public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter) {
return splitArrayElementsIntoProperties(array, delimiter, null);
}
public static Properties splitArrayElementsIntoProperties(String[] array, String delimiter, String charsToDelete) {
if (ObjectUtils.isEmpty(array)) {
return null;
} else {
Properties result = new Properties();
String[] arr$ = array;
int len$ = array.length;
for (int i$ = 0; i$ < len$; ++i$) {
String element = arr$[i$];
if (charsToDelete != null) {
element = deleteAny(element, charsToDelete);
}
String[] splittedElement = split(element, delimiter);
if (splittedElement != null) {
result.setProperty(splittedElement[0].trim(), splittedElement[1].trim());
}
}
return result;
}
}
public static String[] tokenizeToStringArray(String str, String delimiters) {
return tokenizeToStringArray(str, delimiters, true, true);
}
public static String[] tokenizeToStringArray(String str, String delimiters, boolean trimTokens,
boolean ignoreEmptyTokens) {
if (str == null) {
return null;
} else {
StringTokenizer st = new StringTokenizer(str, delimiters);
ArrayList tokens = new ArrayList();
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (trimTokens) {
token = token.trim();
}
if (!ignoreEmptyTokens || token.length() > 0) {
tokens.add(token);
}
}
return toStringArray(tokens);
}
}
public static String[] delimitedListToStringArray(String str, String delimiter) {
return delimitedListToStringArray(str, delimiter, null);
}
public static String[] delimitedListToStringArray(String str, String delimiter, String charsToDelete) {
if (str == null) {
return new String[0];
} else if (delimiter == null) {
return new String[] {str};
} else {
ArrayList result = new ArrayList();
int pos;
if ("".equals(delimiter)) {
for (pos = 0; pos < str.length(); ++pos) {
result.add(deleteAny(str.substring(pos, pos + 1), charsToDelete));
}
} else {
int delPos;
for (pos = 0; (delPos = str.indexOf(delimiter, pos)) != -1; pos = delPos + delimiter.length()) {
result.add(deleteAny(str.substring(pos, delPos), charsToDelete));
}
if (str.length() > 0 && pos <= str.length()) {
result.add(deleteAny(str.substring(pos), charsToDelete));
}
}
return toStringArray(result);
}
}
public static String[] commaDelimitedListToStringArray(String str) {
return delimitedListToStringArray(str, ",");
}
public static Set<String> commaDelimitedListToSet(String str) {
TreeSet set = new TreeSet();
String[] tokens = commaDelimitedListToStringArray(str);
String[] arr$ = tokens;
int len$ = tokens.length;
for (int i$ = 0; i$ < len$; ++i$) {
String token = arr$[i$];
set.add(token);
}
return set;
}
public static String collectionToDelimitedString(Collection<?> coll, String delim, String prefix, String suffix) {
if (CollectionUtils.isEmpty(coll)) {
return "";
} else {
StringBuilder sb = new StringBuilder();
Iterator it = coll.iterator();
while (it.hasNext()) {
sb.append(prefix).append(it.next()).append(suffix);
if (it.hasNext()) {
sb.append(delim);
}
}
return sb.toString();
}
}
public static String collectionToDelimitedString(Collection<?> coll, String delim) {
return collectionToDelimitedString(coll, delim, "", "");
}
public static String collectionToCommaDelimitedString(Collection<?> coll) {
return collectionToDelimitedString(coll, ",");
}
public static String arrayToDelimitedString(Object[] arr, String delim) {
if (ObjectUtils.isEmpty(arr)) {
return "";
} else if (arr.length == 1) {
return ObjectUtils.nullSafeToString(arr[0]);
} else {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < arr.length; ++i) {
if (i > 0) {
sb.append(delim);
}
sb.append(arr[i]);
}
return sb.toString();
}
}
public static String arrayToCommaDelimitedString(Object[] arr) {
return arrayToDelimitedString(arr, ",");
}
}
| |
/*
* Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
// SunJSSE does not support dynamic system properties, no way to re-use
// system properties in samevm/agentvm mode.
/*
* @test
* @bug 1234567
* @summary Use this template to help speed your client/server tests.
* @run main/othervm SSLSocketTemplate
* @author Brad Wetmore
*/
import java.io.*;
import java.net.*;
import javax.net.ssl.*;
public class SSLSocketTemplate {
/*
* =============================================================
* Set the various variables needed for the tests, then
* specify what tests to run on each side.
*/
/*
* Should we run the client or server in a separate thread?
* Both sides can throw exceptions, but do you have a preference
* as to which side should be the main thread.
*/
static boolean separateServerThread = false;
/*
* Where do we find the keystores?
*/
static String pathToStores = "../etc";
static String keyStoreFile = "keystore";
static String trustStoreFile = "truststore";
static String passwd = "passphrase";
/*
* Is the server ready to serve?
*/
volatile static boolean serverReady = false;
/*
* Turn on SSL debugging?
*/
static boolean debug = false;
/*
* If the client or server is doing some kind of object creation
* that the other side depends on, and that thread prematurely
* exits, you may experience a hang. The test harness will
* terminate all hung threads after its timeout has expired,
* currently 3 minutes by default, but you might try to be
* smart about it....
*/
/*
* Define the server side of the test.
*
* If the server prematurely exits, serverReady will be set to true
* to avoid infinite hangs.
*/
void doServerSide() throws Exception {
SSLServerSocketFactory sslssf =
(SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
SSLServerSocket sslServerSocket =
(SSLServerSocket) sslssf.createServerSocket(serverPort);
serverPort = sslServerSocket.getLocalPort();
/*
* Signal Client, we're ready for his connect.
*/
serverReady = true;
SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
InputStream sslIS = sslSocket.getInputStream();
OutputStream sslOS = sslSocket.getOutputStream();
sslIS.read();
sslOS.write(85);
sslOS.flush();
sslSocket.close();
}
/*
* Define the client side of the test.
*
* If the server prematurely exits, serverReady will be set to true
* to avoid infinite hangs.
*/
void doClientSide() throws Exception {
/*
* Wait for server to get started.
*/
while (!serverReady) {
Thread.sleep(50);
}
SSLSocketFactory sslsf =
(SSLSocketFactory) SSLSocketFactory.getDefault();
SSLSocket sslSocket = (SSLSocket)
sslsf.createSocket("localhost", serverPort);
InputStream sslIS = sslSocket.getInputStream();
OutputStream sslOS = sslSocket.getOutputStream();
sslOS.write(280);
sslOS.flush();
sslIS.read();
sslSocket.close();
}
/*
* =============================================================
* The remainder is just support stuff
*/
// use any free port by default
volatile int serverPort = 0;
volatile Exception serverException = null;
volatile Exception clientException = null;
public static void main(String[] args) throws Exception {
String keyFilename =
System.getProperty("test.src", ".") + "/" + pathToStores +
"/" + keyStoreFile;
String trustFilename =
System.getProperty("test.src", ".") + "/" + pathToStores +
"/" + trustStoreFile;
System.setProperty("javax.net.ssl.keyStore", keyFilename);
System.setProperty("javax.net.ssl.keyStorePassword", passwd);
System.setProperty("javax.net.ssl.trustStore", trustFilename);
System.setProperty("javax.net.ssl.trustStorePassword", passwd);
if (debug)
System.setProperty("javax.net.debug", "all");
/*
* Start the tests.
*/
new SSLSocketTemplate();
}
Thread clientThread = null;
Thread serverThread = null;
/*
* Primary constructor, used to drive remainder of the test.
*
* Fork off the other side, then do your work.
*/
SSLSocketTemplate() throws Exception {
Exception startException = null;
try {
if (separateServerThread) {
startServer(true);
startClient(false);
} else {
startClient(true);
startServer(false);
}
} catch (Exception e) {
startException = e;
}
/*
* Wait for other side to close down.
*/
if (separateServerThread) {
if (serverThread != null) {
serverThread.join();
}
} else {
if (clientThread != null) {
clientThread.join();
}
}
/*
* When we get here, the test is pretty much over.
* Which side threw the error?
*/
Exception local;
Exception remote;
if (separateServerThread) {
remote = serverException;
local = clientException;
} else {
remote = clientException;
local = serverException;
}
Exception exception = null;
/*
* Check various exception conditions.
*/
if ((local != null) && (remote != null)) {
// If both failed, return the curthread's exception.
local.initCause(remote);
exception = local;
} else if (local != null) {
exception = local;
} else if (remote != null) {
exception = remote;
} else if (startException != null) {
exception = startException;
}
/*
* If there was an exception *AND* a startException,
* output it.
*/
if (exception != null) {
if (exception != startException && startException != null) {
exception.addSuppressed(startException);
}
throw exception;
}
// Fall-through: no exception to throw!
}
void startServer(boolean newThread) throws Exception {
if (newThread) {
serverThread = new Thread() {
public void run() {
try {
doServerSide();
} catch (Exception e) {
/*
* Our server thread just died.
*
* Release the client, if not active already...
*/
System.err.println("Server died...");
serverReady = true;
serverException = e;
}
}
};
serverThread.start();
} else {
try {
doServerSide();
} catch (Exception e) {
serverException = e;
} finally {
serverReady = true;
}
}
}
void startClient(boolean newThread) throws Exception {
if (newThread) {
clientThread = new Thread() {
public void run() {
try {
doClientSide();
} catch (Exception e) {
/*
* Our client thread just died.
*/
System.err.println("Client died...");
clientException = e;
}
}
};
clientThread.start();
} else {
try {
doClientSide();
} catch (Exception e) {
clientException = e;
}
}
}
}
| |
// Copyright 2000-2017 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.inspections;
import com.jetbrains.python.fixtures.PyInspectionTestCase;
import com.jetbrains.python.psi.LanguageLevel;
import org.jetbrains.annotations.NotNull;
/**
* @author yole
*/
public class PyArgumentListInspectionTest extends PyInspectionTestCase {
public void testBadarglist() {
doTest();
}
public void testKwargsMapToNothing() {
doTest();
}
public void testDecorators() {
doTest();
}
public void testDecoratorsPy3K() {
runWithLanguageLevel(LanguageLevel.PYTHON34, this::doTest);
}
// PY-19130
public void testClassDecoratedThroughDecorator() {
doTest();
}
// PY-19130
public void testClassDecoratedThroughCall() {
doTest();
}
public void testTupleVsLiteralList() {
doTest();
}
// PY-312
public void testInheritedInit() {
doTest();
}
// PY-428
public void testBadDecorator() {
doTest();
}
public void testImplicitResolveResult() {
doTest();
}
public void testCallingClassDefinition() {
doTest();
}
public void testPy1133() {
doTest();
}
public void testPy2005() {
doTest();
}
public void testPy1268() {
runWithLanguageLevel(LanguageLevel.PYTHON34, this::doTest);
}
public void testInstanceMethodAsLambda() {
doTest();
}
public void testClassMethodMultipleDecorators() {
doTest();
}
// PY-19412
public void testReassignedViaClassMethod() {
doTest();
}
// PY-19412
public void testReassignedViaClassMethodInAnotherModule() {
doMultiFileTest("b.py");
}
// PY-2294
public void testTuples() {
doTest();
}
// PY-2460
public void testNestedClass() {
doTest();
}
// PY-2622
public void testReassignedMethod() {
doTest();
}
public void testConstructorQualifiedByModule() {
doTest();
}
// PY-3623
public void testFunctionStoredInInstance() {
doTest();
}
// PY-4419
public void testUnresolvedSuperclass() {
doTest();
}
// PY-4897
public void testMultipleInheritedConstructors() {
doTest();
}
public void testArgs() {
doTest();
}
// PY-9080
public void testMultipleInheritedConstructorsMRO() {
doTest();
}
// PY-9978
public void testXRange() {
doTest();
}
// PY-9978
public void testSlice() {
doTest();
}
public void testPy3k() {
runWithLanguageLevel(LanguageLevel.PYTHON34, this::doTest);
}
@NotNull
@Override
protected Class<? extends PyInspection> getInspectionClass() {
return PyArgumentListInspection.class;
}
// PY-9664
public void testFloatConstructor() {
doTest();
}
// PY-10601
public void testDecoratedChangedParameters() {
doTest();
}
// PY-9605
public void testPropertyReturnsCallable() {
doTest();
}
// PY-11162
public void testUnicodeConstructor() {
doTest();
}
// PY-11169
public void testDictFromKeys() {
doTest();
}
// PY-9934
public void testParameterWithDefaultAfterKeywordContainer() {
doTest();
}
// PY-10351
public void testParameterWithDefaultAfterKeywordContainer2() {
doTest();
}
// PY-18275
public void testStrFormat() {
doTest();
}
// PY-19716
public void testMethodsForLoggingExceptions() {
doMultiFileTest("b.py");
}
// PY-19522
public void testCsvRegisterDialect() {
doMultiFileTest("b.py");
}
// PY-21083
public void testFloatFromhex() {
doTest();
}
public void testMultiResolveWhenOneResultIsDecoratedFunction() {
doTest();
}
public void testMultiResolveWhenOneResultIsDunderInitInDecoratedClass() {
// Implement after fixing PY-20057
}
public void testMultiResolveWhenOneResultDoesNotHaveUnmappedArguments() {
doTest();
}
public void testMultiResolveWhenOneResultDoesNotHaveUnmappedParameters() {
doTest();
}
public void testMultiResolveWhenAllResultsHaveUnmappedArguments() {
doTest();
}
public void testMultiResolveWhenAllResultsHaveUnmappedParameters() {
doTest();
}
public void testUnfilledSentinelInBuiltinIter() {
doTest();
}
public void testUnfilledDefaultInBuiltinNext() {
doTest();
}
public void testUnfilledIter4InBuiltinZip() {
doTest();
}
public void testUnfilledIter2InBuiltinMap() {
doTest();
}
// PY-22507
public void testTimetupleOnAssertedDate() {
doMultiFileTest("b.py");
}
// PY-23069
public void testDunderNewCallInDictInheritor() {
doTest();
}
// PY-22767
public void testBuiltinZip() {
doTest();
}
// PY-19293, PY-22102
public void testInitializingTypingNamedTuple() {
runWithLanguageLevel(LanguageLevel.PYTHON36, this::doTest);
}
// PY-24099
public void testInitializingTypingNamedTupleWithDefaultValues() {
runWithLanguageLevel(LanguageLevel.PYTHON36, this::doTest);
}
// PY-4344, PY-8422, PY-22269, PY-22740
public void testInitializingCollectionsNamedTuple() {
doTest();
}
// PY-22971
public void testOverloadsAndImplementationInClass() {
runWithLanguageLevel(LanguageLevel.PYTHON35, this::doTest);
}
// PY-22971
public void testTopLevelOverloadsAndImplementation() {
runWithLanguageLevel(LanguageLevel.PYTHON35, this::doTest);
}
// PY-22971
public void testOverloadsAndImplementationInImportedClass() {
runWithLanguageLevel(LanguageLevel.PYTHON35, () -> doMultiFileTest("b.py"));
}
// PY-22971
public void testOverloadsAndImplementationInImportedModule() {
runWithLanguageLevel(LanguageLevel.PYTHON35, () -> doMultiFileTest("b.py"));
}
public void testTypingCallableCall() {
runWithLanguageLevel(LanguageLevel.PYTHON35, this::doTest);
}
// PY-24286
public void testBuiltinLong() {
doTest();
}
// PY-24930
public void testCallOperator() {
runWithLanguageLevel(LanguageLevel.PYTHON35, this::doTest);
}
// PY-16968
public void testKwargsAgainstKeywordOnly() {
runWithLanguageLevel(LanguageLevel.PYTHON36, this::doTest);
}
// PY-26023
public void testAbstractMethod() {
runWithLanguageLevel(LanguageLevel.PYTHON34, this::doTest);
}
// PY-27148
public void testCollectionsNamedTupleReplace() {
doTest();
}
// PY-27148
public void testTypingNamedTupleReplace() {
runWithLanguageLevel(LanguageLevel.PYTHON36, this::doTest);
}
// PY-27398
public void testInitializingDataclass() {
runWithLanguageLevel(LanguageLevel.PYTHON37, this::doMultiFileTest);
}
public void testInitializingImportedTypingNamedTupleInheritor() {
runWithLanguageLevel(LanguageLevel.PYTHON37, this::doMultiFileTest);
}
}
| |
/*
* Copyright 2019 Mark Adamcin
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.adamcin.oakpal.webster;
import net.adamcin.oakpal.api.Rules;
import net.adamcin.oakpal.core.Checklist;
import net.adamcin.oakpal.core.ForcedRoot;
import net.adamcin.oakpal.api.Fun;
import net.adamcin.oakpal.api.JavaxJson;
import net.adamcin.oakpal.core.JcrNs;
import net.adamcin.oakpal.core.JsonCnd;
import net.adamcin.oakpal.core.NamespaceMappingRequest;
import net.adamcin.oakpal.api.Result;
import net.adamcin.oakpal.api.Rule;
import org.apache.jackrabbit.spi.Name;
import org.apache.jackrabbit.spi.PrivilegeDefinition;
import org.apache.jackrabbit.spi.QNodeTypeDefinition;
import org.apache.jackrabbit.spi.commons.conversion.DefaultNamePathResolver;
import org.apache.jackrabbit.spi.commons.conversion.NamePathResolver;
import org.apache.jackrabbit.spi.commons.namespace.NamespaceMapping;
import org.apache.jackrabbit.spi.commons.namespace.SessionNamespaceResolver;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jcr.NamespaceRegistry;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.nodetype.NodeType;
import javax.jcr.nodetype.NodeTypeDefinition;
import javax.jcr.nodetype.NodeTypeManager;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.json.Json;
import javax.json.JsonArray;
import javax.json.JsonObject;
import javax.json.JsonObjectBuilder;
import javax.json.JsonWriter;
import javax.json.stream.JsonCollectors;
import javax.json.stream.JsonGenerator;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.BiPredicate;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static net.adamcin.oakpal.api.Fun.compose1;
import static net.adamcin.oakpal.api.Fun.mapValue;
import static net.adamcin.oakpal.api.Fun.testKey;
import static net.adamcin.oakpal.api.Fun.uncheck1;
import static net.adamcin.oakpal.api.Fun.uncheckVoid1;
/**
* Exports namespaces, node types, and {@link ForcedRoot}s from a JCR session to assist with project checklist management.
*/
public final class ChecklistExporter {
private static final Logger LOGGER = LoggerFactory.getLogger(ChecklistExporter.class);
/**
* Builder for a {@link ChecklistExporter}, which is otherwise immutable.
*/
public static final class Builder {
private List<Op> operations = new ArrayList<>();
private List<String> exportTypeDefs = new ArrayList<>();
private List<Rule> pathScopes = new ArrayList<>();
private List<Rule> nodeTypeFilters = new ArrayList<>();
private List<JcrNs> nsMapping = new ArrayList<>();
/**
* Add an operation to export a set of roots by individual paths. If a specified path does not exist in the
* repository, a root will not be exported for it.
*
* @param paths the list of paths to export as forced roots
* @return this builder
*/
public Builder byPath(final String... paths) {
LOGGER.debug("[byPath] paths={}", Arrays.toString(paths));
this.operations.add(new Op(SelectorType.PATH, paths));
return this;
}
/**
* Add an operation to export a set of roots returned by the specified JCR query. This query can be in either
* JCR-SQL2 or XPath language.
*
* @param statement the JCR query statement
* @return this builder
*/
public Builder byQuery(final String statement) {
LOGGER.debug("[byQuery] statement={}", statement);
this.operations.add(new Op(SelectorType.QUERY, statement));
return this;
}
/**
* Add an operation to export a set of roots returned by a nodetype query. By default, only nodes which are
* _explicitly_ typed with one of the specified node types are returned. If you also want to include nodes which
* are either _explicitly_ or _implicitly_ typed with a particular node type or one of its subtypes, you must
* prefix the type name with a "+", e.g. "+sling:Folder" instead of "sling:Folder".
*
* @param nodeTypes the list of JCR node types to query for
* @return this builder
*/
public Builder byNodeType(final String... nodeTypes) {
LOGGER.debug("[byNodeType] nodeTypes={}", Arrays.toString(nodeTypes));
this.operations.add(new Op(SelectorType.NODETYPE, nodeTypes));
this.exportTypeDefs.addAll(Arrays.asList(nodeTypes));
return this;
}
/**
* Limit the scope of exported forced root paths using a list of {@link Rule} patterns. Paths which last-match
* an "INCLUDE" pattern are considered to be "in scope", which means they can be returned by the specified
* operations and/or replaced in existing checklists. Use EXCLUDE patterns to protect existing forced roots from
* being overwritten by a particular instance of {@link ChecklistExporter}.
*
* @param scopePaths the list of include/exclude patterns
* @return this builder
* @see Rules#lastMatch(List, String)
*/
public Builder withScopePaths(final List<Rule> scopePaths) {
this.pathScopes = Optional.ofNullable(scopePaths).orElse(Collections.emptyList());
return this;
}
/**
* In situations where a checklist is only concerned with a subset of node types, use this method to
* exclude irrelevant types from the output. This is useful when trying to avoid introducing a dependency on an
* JCR namespace or CND that exists in a template repository for other purposes. For example, an EXCLUDE rule
* for "cq:.*" would exclude any types in the cq namespace.
*
* @param nodeTypeFilters the list of include/exclude patterns
* @return this builder
* @see Rules#lastMatch(List, String)
*/
public Builder withNodeTypeFilters(final List<Rule> nodeTypeFilters) {
this.nodeTypeFilters = Optional.ofNullable(nodeTypeFilters).orElse(Collections.emptyList());
return this;
}
/**
* Provide a list of JCR namespace prefix mappings to register or remap before performing the operations.
*
* @param jcrNamespaces the list of jcr namespace mappings
* @return this builder
*/
public Builder withJcrNamespaces(final List<JcrNs> jcrNamespaces) {
this.nsMapping = jcrNamespaces;
return this;
}
/**
* To export node types that aren't necessarily referenced in exported forced roots or in a node type selector,
* list them here in the same format as you would in a node type selector. These are also filtered by
* {@link #nodeTypeFilters}, which makes sense if you select a broad supertype for export, but want to restrict the
* resulting exported subtypes to a particular namespace, or to exclude an enumerated list of subtypes.
*
* @param exportNodeTypes the list of JCR node types to export
* @return this builder
* @see #byNodeType(String...)
*/
public Builder withExportNodeTypes(final List<String> exportNodeTypes) {
Optional.ofNullable(exportNodeTypes).ifPresent(exportTypeDefs::addAll);
return this;
}
/**
* Create the new exporter instance.
*
* @return the new {@link ChecklistExporter} instance
*/
public ChecklistExporter build() {
return new ChecklistExporter(this.operations, this.exportTypeDefs, this.pathScopes, this.nodeTypeFilters,
this.nsMapping);
}
}
public enum SelectorType {
QUERY, PATH, NODETYPE;
public static SelectorType byName(final String name) {
for (SelectorType value : values()) {
if (value.name().equalsIgnoreCase(name)) {
return value;
}
}
throw new IllegalArgumentException("Unknown selector type: " + name);
}
}
/**
* Represents an atomic export operation.
*/
static final class Op {
private final SelectorType selectorType;
private final List<String> args;
Op(final @NotNull SelectorType selectorType, final @NotNull String... args) {
this.selectorType = selectorType;
this.args = Arrays.asList(args);
}
@Override
public String toString() {
return String.format("%s: %s", selectorType.name(), args);
}
}
private final List<Op> operations;
private final List<String> exportTypeDefs;
private final List<Rule> pathScopes;
private final List<Rule> nodeTypeFilters;
private final List<JcrNs> jcrNamespaces;
private ChecklistExporter(final List<Op> operations,
final List<String> exportTypeDefs,
final List<Rule> pathScopes,
final List<Rule> nodeTypeFilters,
final List<JcrNs> jcrNamespaces) {
this.operations = operations;
this.exportTypeDefs = exportTypeDefs;
this.pathScopes = pathScopes;
this.nodeTypeFilters = nodeTypeFilters;
this.jcrNamespaces = jcrNamespaces;
}
public enum ForcedRootUpdatePolicy {
/**
* Remove all existing forced roots from the checklist before exporting new ones.
*/
TRUNCATE,
/**
* Remove existing forced roots that are included by the pathScopes before exporting new ones.
*/
REPLACE,
/**
* Existing forced roots will not be removed. If exported root paths match existing root paths, the existing
* entries will be overwritten, such that the primaryType and mixinTypes may be changed by the export.
*/
MERGE;
public static ForcedRootUpdatePolicy byName(final String name) {
for (ForcedRootUpdatePolicy value : values()) {
if (value.name().equalsIgnoreCase(name)) {
return value;
}
}
throw new IllegalArgumentException("Unknown policy name: " + name);
}
}
public static final ForcedRootUpdatePolicy DEFAULT_UPDATE_POLICY = ForcedRootUpdatePolicy.REPLACE;
public static final String COVARIANT_PREFIX = "+";
static final Predicate<String> COVARIANT_FILTER = name -> name.startsWith(COVARIANT_PREFIX);
static final Function<String, String> COVARIANT_FORMAT = name -> name.substring(COVARIANT_PREFIX.length());
static void ensureNamespaces(final @NotNull Session session,
final @NotNull NamespaceMapping namespaces) throws RepositoryException {
NamespaceRegistry registry = session.getWorkspace().getNamespaceRegistry();
List<String> registered = Arrays.asList(registry.getURIs());
namespaces.getURIToPrefixMapping().entrySet().stream()
.filter(entry -> !entry.getKey().isEmpty() && !entry.getValue().isEmpty())
.forEachOrdered(uncheckVoid1(entry -> {
if (registered.contains(entry.getKey())) {
session.setNamespacePrefix(entry.getValue(), entry.getKey());
} else {
registry.registerNamespace(entry.getValue(), entry.getKey());
}
}));
}
static Set<String> findJcrPrefixesInForcedRoot(final @NotNull Set<String> acc, final @NotNull ForcedRoot forcedRoot) {
acc.addAll(Arrays.asList(forcedRoot.getNamespacePrefixes()));
return acc;
}
static Set<String> findNodeTypesInForcedRoot(final Set<String> acc, final ForcedRoot forcedRoot) {
Optional.ofNullable(forcedRoot.getPrimaryType()).ifPresent(acc::add);
Optional.ofNullable(forcedRoot.getMixinTypes()).ifPresent(acc::addAll);
return acc;
}
static <U> BinaryOperator<U> preferDifferent(final @NotNull U value) {
return (left, right) -> left.equals(value) ? right : left;
}
static Function<String, String> nsRemapName(final NamespaceMapping fromMapping, final NamespaceMapping toMapping) {
Map<String, String> fromUris = fromMapping.getURIToPrefixMapping();
Map<String, String> toUris = toMapping.getURIToPrefixMapping();
Set<String> allUris = new HashSet<>(fromUris.keySet());
allUris.addAll(toUris.keySet());
final Map<String, Pattern> prefixToPrefix = new HashMap<>();
for (String uri : allUris) {
final String fromPrefix = fromUris.getOrDefault(uri, toUris.get(uri));
final String toPrefix = toUris.getOrDefault(uri, fromUris.get(uri));
if (!fromPrefix.equals(toPrefix)) {
prefixToPrefix.put(toPrefix, Pattern.compile("(?<=^|/)" + Pattern.quote(fromPrefix) + "(?=:)"));
}
}
return value -> prefixToPrefix.entrySet().stream()
.reduce(
value,
(input, entry) -> entry.getValue().matcher(input).replaceAll(entry.getKey()),
preferDifferent(value));
}
static Function<ForcedRoot, ForcedRoot> nsRemapForcedRoot(final NamespaceMapping fromMapping, final NamespaceMapping toMapping) {
final Function<String, String> replacer = nsRemapName(fromMapping, toMapping);
return orig -> {
ForcedRoot root = new ForcedRoot();
Optional.ofNullable(orig.getPath()).map(replacer).ifPresent(root::setPath);
Optional.ofNullable(orig.getPrimaryType()).map(replacer).ifPresent(root::setPrimaryType);
Optional.ofNullable(orig.getMixinTypes())
.map(mixins -> mixins.stream().map(replacer).collect(Collectors.toList()))
.ifPresent(root::setMixinTypes);
return root;
};
}
/**
* Function type that provides a Writer.
*/
@FunctionalInterface
public interface WriterOpener {
@NotNull Writer open() throws IOException;
}
Predicate<ForcedRoot> getRetainFilter(final ForcedRootUpdatePolicy updatePolicy) {
switch (updatePolicy != null ? updatePolicy : DEFAULT_UPDATE_POLICY) {
case TRUNCATE:
// retain nothing
return root -> false;
case REPLACE:
// only retain roots excluded by the path filter
return root -> Rules.lastMatch(pathScopes, root.getPath()).isExclude();
case MERGE:
default:
// retain everything
return root -> true;
}
}
BiPredicate<NamePathResolver, NodeType> exportTypeDefSelector() {
final Set<String> singleTypes = exportTypeDefs.stream()
.filter(COVARIANT_FILTER.negate())
.collect(Collectors.toSet());
final Set<String> superTypes = exportTypeDefs.stream()
.filter(COVARIANT_FILTER)
.map(COVARIANT_FORMAT)
.collect(Collectors.toSet());
return (resolver, type) -> {
final String name = type.getName();
return Rules.lastMatch(nodeTypeFilters, name).isInclude()
&& (singleTypes.contains(name) || Stream.of(type.getSupertypes())
.map(NodeType::getName).anyMatch(superTypes::contains));
};
}
/**
* Update a checklist (or start a new one) with the forced roots exported from the provided session. Tidied JSON
* output will be written to the provided writer.
*
* @param writerOpener an opener that provides the writer to write the JSON output to
* @param session the JCR session to export roots from
* @param checklist the checklist to update, or null to start from scratch
* @param updatePolicy specify behavior for retaining existing forced roots
* @throws IOException if an error occurs when writing the checklist
* @throws RepositoryException if an error occurs when exporting the new forced roots
*/
public void updateChecklist(final WriterOpener writerOpener,
final Session session,
final Checklist checklist,
final ForcedRootUpdatePolicy updatePolicy)
throws IOException, RepositoryException {
final List<JcrNs> chkNs = new ArrayList<>();
// first attempt to remap JCR namespaces in the session, if necessary.
if (checklist != null && checklist.getJcrNamespaces() != null) {
chkNs.addAll(checklist.getJcrNamespaces());
}
final NamespaceMapping origMapping = JsonCnd.toNamespaceMapping(chkNs);
final NamespaceMapping remapping = JsonCnd.toNamespaceMapping(jcrNamespaces);
ensureNamespaces(session, origMapping);
ensureNamespaces(session, remapping);
// try to find the roots. If any error occurs there, we want to fail fast before committing to other
// potentially expensive, destructive, or error-prone logic.
final List<ForcedRoot> newRoots = findRoots(session);
// construct a stream filter for retaining existing forced roots
Predicate<ForcedRoot> retainFilter = getRetainFilter(updatePolicy);
final JsonObjectBuilder builder = Json.createObjectBuilder();
final Map<String, ForcedRoot> existing = new LinkedHashMap<>();
final List<PrivilegeDefinition> privileges = new ArrayList<>();
// remap the names of existing jcr definitions to match the new jcr namespaces
if (checklist != null) {
checklist.toJson().forEach(builder::add);
privileges.addAll(checklist.getJcrPrivileges());
checklist.getForcedRoots().stream()
.map(nsRemapForcedRoot(origMapping, remapping))
.filter(retainFilter)
.forEachOrdered(root -> existing.put(root.getPath(), root));
}
//final Set<String> finalPrefixes = new HashSet<>();
final NamespaceMappingRequest.Builder request = new NamespaceMappingRequest.Builder();
if (!privileges.isEmpty()) {
builder.add(Checklist.keys().jcrPrivileges(), JsonCnd.privilegesToJson(privileges, origMapping));
privileges.stream().flatMap(JsonCnd::namedBy).forEach(request::withQName);
}
newRoots.forEach(root -> existing.put(root.getPath(), root));
final List<ForcedRoot> forcedRoots = new ArrayList<>(existing.values());
Collections.sort(forcedRoots);
final JsonArray forcedRootsJson = forcedRoots.stream()
.map(ForcedRoot::toJson)
.collect(JsonCollectors.toJsonArray());
builder.add(Checklist.keys().forcedRoots(), forcedRootsJson);
// begin nodetype handling
final NamePathResolver resolver = new DefaultNamePathResolver(session);
final Set<Name> builtinNodetypes = CndExporter.BUILTIN_NODETYPES.stream()
.map(uncheck1(resolver::getQName))
.filter(Objects::nonNull)
.collect(Collectors.toSet());
final List<Name> foundNodeTypes = forcedRoots.stream()
.reduce(new HashSet<>(),
ChecklistExporter::findNodeTypesInForcedRoot,
addToLeft()).stream()
.map(uncheck1(resolver::getQName))
.collect(Collectors.toList());
final Map<Name, NodeTypeDefinition> exportedNodeTypes =
CndExporter.retrieveNodeTypes(session, foundNodeTypes, exportTypeDefSelector());
final List<QNodeTypeDefinition> qNodeTypes = exportedNodeTypes.entrySet().stream()
.map(mapValue(JsonCnd.adaptToQ(session)))
.filter(testKey(((Predicate<Name>) builtinNodetypes::contains).negate()))
.map(Map.Entry::getValue)
.collect(Collectors.toList());
final NamespaceMapping spm = new NamespaceMapping(new SessionNamespaceResolver(session));
if (!qNodeTypes.isEmpty()) {
final Set<String> nsUris = qNodeTypes.stream()
.flatMap(JsonCnd::namedBy)
.map(Name::getNamespaceURI)
.collect(Collectors.toSet());
final Map<String, String> uriMapping = remapping.getURIToPrefixMapping();
nsUris.forEach(Fun.uncheckVoid1(uri -> {
final String prefix = uriMapping.containsKey(uri) ? uriMapping.get(uri) : spm.getPrefix(uri);
request.withRetainPrefix(prefix);
spm.setMapping(prefix, uri);
}));
final JsonObject jcrNodetypes =
JsonCnd.toJson(qNodeTypes, new NamespaceMapping(new SessionNamespaceResolver(session)));
builder.add(Checklist.keys().jcrNodetypes(), jcrNodetypes);
}
// begin namespace handling
final Set<String> forcedRootPrefixes = forcedRoots.stream()
.reduce(new HashSet<>(),
ChecklistExporter::findJcrPrefixesInForcedRoot,
addToLeft());
forcedRootPrefixes.forEach(request::withRetainPrefix);
final List<JcrNs> exportNamespaces = request.build()
.resolveToJcrNs(spm).stream()
.flatMap(Result::stream)
.collect(Collectors.toList());
if (!exportNamespaces.isEmpty()) {
builder.add(Checklist.keys().jcrNamespaces(), JavaxJson.wrap(exportNamespaces));
}
final JsonObject sorted = builder.build().entrySet().stream()
.sorted(Checklist.comparingJsonKeys(Map.Entry::getKey))
.collect(JsonCollectors.toJsonObject());
try (Writer writer = writerOpener.open();
JsonWriter jsonWriter = Json
.createWriterFactory(Collections.singletonMap(JsonGenerator.PRETTY_PRINTING, true))
.createWriter(writer)) {
jsonWriter.writeObject(sorted);
}
}
static <E, U extends Collection<E>> BinaryOperator<U> addToLeft() {
return (left, right) -> {
left.addAll(right);
return left;
};
}
/**
* Perform all retrieval operations against the provided session.
*
* @param session the session to retrieve nodes from
* @return the result list of {@link ForcedRoot}s
* @throws RepositoryException if an error occurs
*/
public List<ForcedRoot> findRoots(final Session session) throws RepositoryException {
List<ForcedRoot> roots = new ArrayList<>();
for (Op op : this.operations) {
switch (op.selectorType) {
case PATH:
roots.addAll(traverse(session, op.args));
break;
case NODETYPE:
roots.addAll(query(session, ntStatement(session, op.args)));
break;
case QUERY:
default:
roots.addAll(query(session, op.args.get(0)));
break;
}
}
return roots;
}
/**
* Construct a union SQL2 statement to find nodes of specified types. Prefix a node type name with a '+' to treat
* that type as a supertype and find nodes which are of that type or any of its subtypes.
*
* @param session the session which will be queried
* @param nodeTypeNames the list of node type names to query from
* @return the generated JCR-SQL2 query statement
* @throws RepositoryException if an error occurs
*/
String ntStatement(final Session session, final List<String> nodeTypeNames) throws RepositoryException {
final List<String> subqueries = new ArrayList<>();
final NodeTypeManager ntManager = session.getWorkspace().getNodeTypeManager();
// covariants (find nodes of specified types or their subtypes)
nodeTypeNames.stream()
.filter(COVARIANT_FILTER)
.map(COVARIANT_FORMAT)
// TODO this can quietly suppress ALL nodetypes and lead to a JCR query parse exception
.filter(Fun.testOrDefault1(ntManager::hasNodeType, false))
.map(name -> String.format("SELECT [jcr:path] FROM [%s] AS a", name))
.forEachOrdered(subqueries::add);
// invariants (find only nodes which are of specified types)
nodeTypeNames.stream()
.filter(COVARIANT_FILTER.negate())
.filter(Fun.testOrDefault1(ntManager::hasNodeType, false))
.map(name -> String.format("SELECT [jcr:path] FROM [nt:base] AS a WHERE [a].[jcr:primaryType] = '%s' UNION SELECT [jcr:path] FROM [nt:base] AS a WHERE [a].[jcr:mixinTypes] = '%s'", name, name))
.forEachOrdered(subqueries::add);
return String.join(" UNION ", subqueries) + " OPTION(TRAVERSAL OK, INDEX NAME nodetype)";
}
/**
* Retrieve a list of {@link ForcedRoot}s by JCR query.
*
* @param session the session to retrieve nodes from
* @param statement the query statement
* @return the result list of ForcedRoots
* @throws RepositoryException when an error occurs
*/
List<ForcedRoot> query(final Session session, final String statement) throws RepositoryException {
final QueryManager qm = session.getWorkspace().getQueryManager();
final NamespaceMapping mapping = new NamespaceMapping(new SessionNamespaceResolver(session));
final String language =
statement.toUpperCase().replaceFirst("^\\s*((MEASURE|EXPLAIN)\\s*)*", "")
.startsWith("SELECT") ? Query.JCR_SQL2 : Query.XPATH;
final Query query = qm.createQuery(statement, language);
final QueryResult result = query.execute();
final Map<String, ForcedRoot> roots = new LinkedHashMap<>();
for (NodeIterator nodes = result.getNodes(); nodes.hasNext(); ) {
nodeToRoot(nodes.nextNode(), mapping).ifPresent(root -> roots.put(root.getPath(), root));
}
return new ArrayList<>(roots.values());
}
/**
* Gets each node from the session, then adapts to a {@link ForcedRoot} within the current path and node type scopes.
*
* @param session the session to retrieve nodes from
* @param paths the list of node paths to retrieve
* @return the result list of ForcedRoots
* @throws RepositoryException when an error occurs
*/
List<ForcedRoot> traverse(final Session session, final List<String> paths) throws RepositoryException {
final List<ForcedRoot> roots = new ArrayList<>();
final NamespaceMapping mapping = new NamespaceMapping(new SessionNamespaceResolver(session));
for (String path : paths) {
if (session.nodeExists(path)) {
nodeToRoot(session.getNode(path), mapping).ifPresent(roots::add);
}
}
return roots;
}
/**
* Construct a forced root object for the given node, within the context of path and type scopes.
*
* @param node the node to convert to a {@link ForcedRoot}
* @return empty when the node is not within path scope
* @throws RepositoryException when an error occurs
*/
Optional<ForcedRoot> nodeToRoot(final Node node, final NamespaceMapping mapping) throws RepositoryException {
if (Rules.lastMatch(pathScopes, node.getPath()).isExclude()) {
return Optional.empty();
}
ForcedRoot forcedRoot = new ForcedRoot();
forcedRoot.setPath(node.getPath());
final String primaryType = node.getPrimaryNodeType().getName();
if (Rules.lastMatch(nodeTypeFilters, QName.parseQName(mapping, QName.Type.NODETYPE, primaryType).toString()).isInclude()) {
forcedRoot.setPrimaryType(primaryType);
}
final List<String> mixinTypes = Stream.of(node.getMixinNodeTypes())
.map(compose1(NodeType::getName,
qName -> QName.parseQName(mapping, QName.Type.NODETYPE, qName).toString()))
.filter(name -> Rules.lastMatch(nodeTypeFilters, name).isInclude())
.collect(Collectors.toList());
forcedRoot.setMixinTypes(mixinTypes);
return Optional.of(forcedRoot);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.camel.dataformat.beanio;
import java.io.File;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.util.Properties;
import org.apache.camel.CamelContext;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.Message;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.WrappedFile;
import org.apache.camel.support.ResourceHelper;
import org.apache.camel.util.IOHelper;
import org.apache.camel.util.ObjectHelper;
import org.beanio.BeanReader;
import org.beanio.BeanReaderErrorHandler;
import org.beanio.StreamFactory;
import static org.apache.camel.dataformat.beanio.BeanIOHelper.getOrCreateBeanReaderErrorHandler;
/**
* You can use {@link BeanIOSplitter} with the Camel Splitter EIP to split big payloads
* using a stream mode to avoid reading the entire content into memory.
*/
public class BeanIOSplitter implements Expression {
private BeanIOConfiguration configuration = new BeanIOConfiguration();
private StreamFactory factory;
public BeanIOSplitter() throws Exception {
}
public BeanIOSplitter(BeanIOConfiguration configuration) {
this.configuration = configuration;
}
public BeanIOSplitter(String mapping, String streamName) {
setMapping(mapping);
setStreamName(streamName);
}
protected StreamFactory createStreamFactory(CamelContext camelContext) throws Exception {
ObjectHelper.notNull(getStreamName(), "Stream name not configured.");
// Create the stream factory that will be used to read/write objects.
StreamFactory answer = StreamFactory.newInstance();
// Load the mapping file using the resource helper to ensure it can be loaded in OSGi and other environments
InputStream is = ResourceHelper.resolveMandatoryResourceAsInputStream(camelContext, getMapping());
try {
if (getProperties() != null) {
answer.load(is, getProperties());
} else {
answer.load(is);
}
} finally {
IOHelper.close(is);
}
return answer;
}
public Object evaluate(Exchange exchange) throws Exception {
Message msg = exchange.getIn();
Object body = msg.getBody();
if (factory == null) {
factory = createStreamFactory(exchange.getContext());
}
BeanReader beanReader = null;
if (body instanceof WrappedFile) {
body = ((WrappedFile) body).getFile();
}
if (body instanceof File) {
File file = (File) body;
beanReader = factory.createReader(getStreamName(), file);
}
if (beanReader == null) {
Reader reader = msg.getMandatoryBody(Reader.class);
beanReader = factory.createReader(getStreamName(), reader);
}
BeanIOIterator iterator = new BeanIOIterator(beanReader);
BeanReaderErrorHandler errorHandler = getOrCreateBeanReaderErrorHandler(configuration, exchange, null, iterator);
beanReader.setErrorHandler(errorHandler);
return iterator;
}
@Override
public <T> T evaluate(Exchange exchange, Class<T> type) {
try {
Object result = evaluate(exchange);
return exchange.getContext().getTypeConverter().convertTo(type, exchange, result);
} catch (Exception e) {
throw RuntimeCamelException.wrapRuntimeCamelException(e);
}
}
public BeanIOConfiguration getConfiguration() {
return configuration;
}
public void setConfiguration(BeanIOConfiguration configuration) {
this.configuration = configuration;
}
public StreamFactory getFactory() {
return factory;
}
public void setFactory(StreamFactory factory) {
this.factory = factory;
}
public String getMapping() {
return configuration.getMapping();
}
public void setIgnoreUnexpectedRecords(boolean ignoreUnexpectedRecords) {
configuration.setIgnoreUnexpectedRecords(ignoreUnexpectedRecords);
}
public void setProperties(Properties properties) {
configuration.setProperties(properties);
}
public void setStreamName(String streamName) {
configuration.setStreamName(streamName);
}
public boolean isIgnoreUnidentifiedRecords() {
return configuration.isIgnoreUnidentifiedRecords();
}
public boolean isIgnoreInvalidRecords() {
return configuration.isIgnoreInvalidRecords();
}
public void setIgnoreInvalidRecords(boolean ignoreInvalidRecords) {
configuration.setIgnoreInvalidRecords(ignoreInvalidRecords);
}
public void setEncoding(Charset encoding) {
configuration.setEncoding(encoding);
}
public boolean isIgnoreUnexpectedRecords() {
return configuration.isIgnoreUnexpectedRecords();
}
public Properties getProperties() {
return configuration.getProperties();
}
public String getStreamName() {
return configuration.getStreamName();
}
public void setMapping(String mapping) {
configuration.setMapping(mapping);
}
public void setIgnoreUnidentifiedRecords(boolean ignoreUnidentifiedRecords) {
configuration.setIgnoreUnidentifiedRecords(ignoreUnidentifiedRecords);
}
public Charset getEncoding() {
return configuration.getEncoding();
}
public BeanReaderErrorHandler getBeanReaderErrorHandler() {
return configuration.getBeanReaderErrorHandler();
}
public void setBeanReaderErrorHandler(BeanReaderErrorHandler beanReaderErrorHandler) {
configuration.setBeanReaderErrorHandler(beanReaderErrorHandler);
}
public String getBeanReaderErrorHandlerType() {
return configuration.getBeanReaderErrorHandlerType();
}
public void setBeanReaderErrorHandlerType(String beanReaderErrorHandlerType) {
configuration.setBeanReaderErrorHandlerType(beanReaderErrorHandlerType);
}
public void setBeanReaderErrorHandlerType(Class<?> beanReaderErrorHandlerType) {
configuration.setBeanReaderErrorHandlerType(beanReaderErrorHandlerType);
}
}
| |
/*
* Copyright 2002-2013 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.mcxiaoke.next.bus.support;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
/**
* Helper for resolving synthetic {@link Method#isBridge bridge Methods} to the
* {@link Method} being bridged.
*
* <p>Given a synthetic {@link Method#isBridge bridge Method} returns the {@link Method}
* being bridged. A bridge method may be created by the compiler when extending a
* parameterized type whose methods have parameterized arguments. During runtime
* invocation the bridge {@link Method} may be invoked and/or used via reflection.
* When attempting to locate annotations on {@link Method Methods}, it is wise to check
* for bridge {@link Method Methods} as appropriate and find the bridged {@link Method}.
*
* <p>See <a href="http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#15.12.4.5">
* The Java Language Specification</a> for more details on the use of bridge methods.
*
* @author Rob Harrop
* @author Juergen Hoeller
* @since 2.0
*/
public abstract class BridgeMethodResolver {
/**
* Find the original method for the supplied {@link Method bridge Method}.
* <p>It is safe to call this method passing in a non-bridge {@link Method} instance.
* In such a case, the supplied {@link Method} instance is returned directly to the caller.
* Callers are <strong>not</strong> required to check for bridging before calling this method.
*
* @param bridgeMethod the method to introspect
* @return the original method (either the bridged method or the passed-in method
* if no more specific one could be found)
*/
public static Method findBridgedMethod(Method bridgeMethod) {
if (bridgeMethod == null || !bridgeMethod.isBridge()) {
return bridgeMethod;
}
// Gather all methods with matching name and parameter size.
List<Method> candidateMethods = new ArrayList<Method>();
Method[] methods = ReflectionUtils.getAllDeclaredMethods(bridgeMethod.getDeclaringClass());
for (Method candidateMethod : methods) {
if (isBridgedCandidateFor(candidateMethod, bridgeMethod)) {
candidateMethods.add(candidateMethod);
}
}
// Now perform simple quick check.
if (candidateMethods.size() == 1) {
return candidateMethods.get(0);
}
// Search for candidate match.
Method bridgedMethod = searchCandidates(candidateMethods, bridgeMethod);
if (bridgedMethod != null) {
// Bridged method found...
return bridgedMethod;
} else {
// A bridge method was passed in but we couldn't find the bridged method.
// Let's proceed with the passed-in method and hope for the best...
return bridgeMethod;
}
}
/**
* Searches for the bridged method in the given candidates.
*
* @param candidateMethods the List of candidate Methods
* @param bridgeMethod the bridge method
* @return the bridged method, or {@code null} if none found
*/
private static Method searchCandidates(List<Method> candidateMethods, Method bridgeMethod) {
if (candidateMethods.isEmpty()) {
return null;
}
Map<TypeVariable, Type> typeParameterMap = GenericTypeResolver.getTypeVariableMap(bridgeMethod.getDeclaringClass());
Method previousMethod = null;
boolean sameSig = true;
for (Method candidateMethod : candidateMethods) {
if (isBridgeMethodFor(bridgeMethod, candidateMethod, typeParameterMap)) {
return candidateMethod;
} else if (previousMethod != null) {
sameSig = sameSig &&
Arrays.equals(candidateMethod.getGenericParameterTypes(), previousMethod.getGenericParameterTypes());
}
previousMethod = candidateMethod;
}
return (sameSig ? candidateMethods.get(0) : null);
}
/**
* Returns {@code true} if the supplied '{@code candidateMethod}' can be
* consider a validate candidate for the {@link Method} that is {@link Method#isBridge() bridged}
* by the supplied {@link Method bridge Method}. This method performs inexpensive
* checks and can be used quickly filter for a set of possible matches.
*/
private static boolean isBridgedCandidateFor(Method candidateMethod, Method bridgeMethod) {
return (!candidateMethod.isBridge() && !candidateMethod.equals(bridgeMethod) &&
candidateMethod.getName().equals(bridgeMethod.getName()) &&
candidateMethod.getParameterTypes().length == bridgeMethod.getParameterTypes().length);
}
/**
* Determines whether or not the bridge {@link Method} is the bridge for the
* supplied candidate {@link Method}.
*/
static boolean isBridgeMethodFor(Method bridgeMethod, Method candidateMethod, Map<TypeVariable, Type> typeVariableMap) {
if (isResolvedTypeMatch(candidateMethod, bridgeMethod, typeVariableMap)) {
return true;
}
Method method = findGenericDeclaration(bridgeMethod);
return (method != null && isResolvedTypeMatch(method, candidateMethod, typeVariableMap));
}
/**
* Searches for the generic {@link Method} declaration whose erased signature
* matches that of the supplied bridge method.
*
* @throws IllegalStateException if the generic declaration cannot be found
*/
private static Method findGenericDeclaration(Method bridgeMethod) {
// Search parent types for method that has same signature as bridge.
Class superclass = bridgeMethod.getDeclaringClass().getSuperclass();
while (superclass != null && !Object.class.equals(superclass)) {
Method method = searchForMatch(superclass, bridgeMethod);
if (method != null && !method.isBridge()) {
return method;
}
superclass = superclass.getSuperclass();
}
// Search interfaces.
Class[] interfaces = ClassUtils.getAllInterfacesForClass(bridgeMethod.getDeclaringClass());
for (Class ifc : interfaces) {
Method method = searchForMatch(ifc, bridgeMethod);
if (method != null && !method.isBridge()) {
return method;
}
}
return null;
}
/**
* Returns {@code true} if the {@link Type} signature of both the supplied
* {@link Method#getGenericParameterTypes() generic Method} and concrete {@link Method}
* are equal after resolving all {@link TypeVariable TypeVariables} using the supplied
* TypeVariable Map, otherwise returns {@code false}.
*/
private static boolean isResolvedTypeMatch(
Method genericMethod, Method candidateMethod, Map<TypeVariable, Type> typeVariableMap) {
Type[] genericParameters = genericMethod.getGenericParameterTypes();
Class[] candidateParameters = candidateMethod.getParameterTypes();
if (genericParameters.length != candidateParameters.length) {
return false;
}
for (int i = 0; i < genericParameters.length; i++) {
Type genericParameter = genericParameters[i];
Class candidateParameter = candidateParameters[i];
if (candidateParameter.isArray()) {
// An array type: compare the component type.
Type rawType = GenericTypeResolver.getRawType(genericParameter, typeVariableMap);
if (rawType instanceof GenericArrayType) {
if (!candidateParameter.getComponentType().equals(
GenericTypeResolver.resolveType(((GenericArrayType) rawType).getGenericComponentType(), typeVariableMap))) {
return false;
}
break;
}
}
// A non-array type: compare the type itself.
Class resolvedParameter = GenericTypeResolver.resolveType(genericParameter, typeVariableMap);
if (!candidateParameter.equals(resolvedParameter)) {
return false;
}
}
return true;
}
/**
* If the supplied {@link Class} has a declared {@link Method} whose signature matches
* that of the supplied {@link Method}, then this matching {@link Method} is returned,
* otherwise {@code null} is returned.
*/
private static Method searchForMatch(Class type, Method bridgeMethod) {
return ReflectionUtils.findMethod(type, bridgeMethod.getName(), bridgeMethod.getParameterTypes());
}
/**
* Compare the signatures of the bridge method and the method which it bridges. If
* the parameter and return types are the same, it is a 'visibility' bridge method
* introduced in Java 6 to fix http://bugs.sun.com/view_bug.do?bug_id=6342411.
* See also http://stas-blogspot.blogspot.com/2010/03/java-bridge-methods-explained.html
*
* @return whether signatures match as described
*/
public static boolean isVisibilityBridgeMethodPair(Method bridgeMethod, Method bridgedMethod) {
if (bridgeMethod == bridgedMethod) {
return true;
}
return Arrays.equals(bridgeMethod.getParameterTypes(), bridgedMethod.getParameterTypes()) &&
bridgeMethod.getReturnType().equals(bridgedMethod.getReturnType());
}
}
| |
package com.mbh.mbutils.thread;
/**
* Implementation of Exponential Backoff thread, which will increase the sleep delay if not needed
* CreatedBy MBH on 2016-06-04.
*/
public class MBExpoBackoffThread {
private Thread expoThread;
private volatile boolean running = false;
private int maxRefreshDelay = 10 * 60 * 1000; // Milliseconds 10 minutes
private int firstDelay = 5 * 1000;
private int startAfter = 0; // start Immediately
private boolean isStartAfterUsed = false;
private int currentDelay = 0;
private int tempDelay = 0;
private boolean stopOnError = false;
private boolean resetDelayOnError = true;
private OnExpoFailure onExpoFailure;
private OnExpoDoWork mOnExpoDoWork;
public MBExpoBackoffThread(int startAfter,
int firstDelay,
int maxRefreshDelay,
boolean stopOnError,
boolean resetDelayOnError,
OnExpoDoWork onExpoDoWork,
OnExpoFailure onExpoFailure) {
this.startAfter = startAfter;
this.firstDelay = firstDelay;
this.maxRefreshDelay = maxRefreshDelay;
this.stopOnError = stopOnError;
this.resetDelayOnError = resetDelayOnError;
mOnExpoDoWork = onExpoDoWork;
this.onExpoFailure = onExpoFailure;
}
public void start() {
if (expoThread != null && expoThread.isAlive()) {
return;
}
running = true;
initializeThread();
expoThread.start();
}
public boolean isAlive() {
return expoThread != null && expoThread.isAlive() && running;
}
private void initializeThread() {
expoThread = new Thread() {
@Override
public void run() {
while (true) {
if (!running) {
break;
}
if(!isStartAfterUsed){
isStartAfterUsed = true;
if(startAfter != 0){
if(startAfter > 100){
MBThreadUtils.TryToSleepFor(startAfter);
}
}
}
try {
if (mOnExpoDoWork != null) {
if (mOnExpoDoWork.ExpoDoWork()) {
currentDelay = tempDelay;
tempDelay = 0;
} else {
currentDelay = 0;
}
}
} catch (Exception exception) {
if (resetDelayOnError) {
currentDelay = 0;
}
if (stopOnError) {
throw new RuntimeException(exception);
}
if (onExpoFailure != null) onExpoFailure.OnExpoFailed(exception);
}
MBThreadUtils.TryToSleepFor(getNextDelay());
if (!running) {
break;
}
}
}
};
}
private int getNextDelay() {
tempDelay = currentDelay;
if (tempDelay == 0) {
tempDelay = firstDelay;
} else {
tempDelay *= 2;
if (tempDelay > maxRefreshDelay)
tempDelay = maxRefreshDelay;
}
return tempDelay;
}
public void stop() {
running = false;
if (expoThread != null) {
if (expoThread.isAlive()) {
running = false;
expoThread = null;
} else {
running = false;
expoThread = null;
}
}
}
public interface OnExpoFailure {
void OnExpoFailed(Exception exception);
}
public interface OnExpoDoWork {
/**
* Implementation of Work will be done on exponential time delay
*
* @return true if work went successfully
*/
boolean ExpoDoWork() throws Exception;
}
public static class Builder {
private int maxRefreshDelay = 10 * 60 * 1000; // Milliseconds 10 minutes
private int firstDelay = 10 * 1000;
private int startAfter = 0;
private boolean isStopOnError = false;
private boolean isResetDelayOnError = true;
private OnExpoFailure onExpFailure;
private OnExpoDoWork onExpWork;
public Builder() {
}
/**
* Set the maximum delay that will thread sleep it after a while
* @param milliseconds: how many seconds should sleep at max in milliseconds
* @return builder
*/
// region builder functions
public Builder setMaxDelay(int milliseconds) {
this.maxRefreshDelay = milliseconds;
return this;
}
/**
* Set the first delay that will the thread sleep it before start multiplying the sleep time
* @param milliseconds: time in milliseconds
* @return builder
*/
public Builder setFirstDelay(int milliseconds) {
this.firstDelay = milliseconds;
return this;
}
/**
* Set the time that will the thread wait before it start first time.
* @param milliseconds: time in milliseconds
* @return builder
*/
public Builder setStartAfter(int milliseconds) {
this.startAfter = milliseconds;
return this;
}
/**
* Set whether the thread should stop if any error happened
* @param stopOnError: true to stop on error, false to continue
* @return builder
*/
public Builder setStopOnError(boolean stopOnError) {
this.isStopOnError = stopOnError;
return this;
}
/**
* Set whether the delay should reset on error
* @param isResetDelayOnError: true to reset delay to first delay on error, false to not
* @return builder
*/
public Builder setResetDelayOnError(boolean isResetDelayOnError) {
this.isResetDelayOnError = isResetDelayOnError;
return this;
}
/**
* Set work that should be done on any failure happened
* @param onExpFailure: work to be done on failure
* @return builder
*/
public Builder setOnExpoFailure(OnExpoFailure onExpFailure) {
this.onExpFailure = onExpFailure;
return this;
}
/**
* Set work that should be done on
* @param onExpoDoWord: work to be done on
* @return builder
*/
public Builder setOnExpoDoWord(OnExpoDoWork onExpoDoWord) {
this.onExpWork = onExpoDoWord;
return this;
}
// endregion
/**
* This function will build the Exponential thread and return it
* @return MBExpoBackoffThread: Exponential Thread that will do the work
*/
public MBExpoBackoffThread build() {
return new MBExpoBackoffThread(
startAfter,
firstDelay,
maxRefreshDelay,
isStopOnError,
isResetDelayOnError,
onExpWork,
onExpFailure);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.imaging.internal;
import java.awt.color.ICC_Profile;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Internal-only debug class. Used for collecting extra information when parsing or
* modifying images or metadata. These methods are useful for troubleshooting and
* issue analysis, but this should not be used directly by end-users, nor extended
* in any way. This may change or be removed at any time.
*/
public final class Debug {
private static final Logger LOGGER = Logger.getLogger(Debug.class.getName());
// public static String newline = System.getProperty("line.separator");
private static final String NEWLINE = "\r\n";
private static long counter;
public static void debug(final String message) {
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest(message);
}
}
public static void debug() {
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest(NEWLINE);
}
}
private static String getDebug(final String message, final int[] v) {
final StringBuilder result = new StringBuilder();
if (v == null) {
result.append(message + " (" + null + ")" + NEWLINE);
} else {
result.append(message + " (" + v.length + ")" + NEWLINE);
for (final int element : v) {
result.append("\t" + element + NEWLINE);
}
result.append(NEWLINE);
}
return result.toString();
}
private static String getDebug(final String message, final byte[] v) {
final int max = 250;
return getDebug(message, v, max);
}
private static String getDebug(final String message, final byte[] v, final int max) {
final StringBuilder result = new StringBuilder();
if (v == null) {
result.append(message + " (" + null + ")" + NEWLINE);
} else {
result.append(message + " (" + v.length + ")" + NEWLINE);
for (int i = 0; i < max && i < v.length; i++) {
final int b = 0xff & v[i];
char c;
if (b == 0 || b == 10 || b == 11 || b == 13) {
c = ' ';
} else {
c = (char) b;
}
result.append("\t" + i + ": " + b + " (" + c + ", 0x"
+ Integer.toHexString(b) + ")" + NEWLINE);
}
if (v.length > max) {
result.append("\t..." + NEWLINE);
}
result.append(NEWLINE);
}
return result.toString();
}
private static String getDebug(final String message, final char[] v) {
final StringBuilder result = new StringBuilder();
if (v == null) {
result.append(message + " (" + null + ")" + NEWLINE);
} else {
result.append(message + " (" + v.length + ")" + NEWLINE);
for (final char element : v) {
result.append("\t" + element + " (" + (0xff & element) + ")" + NEWLINE);
}
result.append(NEWLINE);
}
return result.toString();
}
private static void debug(final String message, final Map<?, ?> map) {
debug(getDebug(message, map));
}
private static String getDebug(final String message, final Map<?, ?> map) {
final StringBuilder result = new StringBuilder();
if (map == null) {
return message + " map: " + null;
}
final List<Object> keys = new ArrayList<>(map.keySet());
result.append(message + " map: " + keys.size() + NEWLINE);
for (int i = 0; i < keys.size(); i++) {
final Object key = keys.get(i);
final Object value = map.get(key);
result.append("\t" + i + ": '" + key + "' -> '" + value + "'" + NEWLINE);
}
result.append(NEWLINE);
return result.toString();
}
private static String byteQuadToString(final int byteQuad) {
final byte b1 = (byte) ((byteQuad >> 24) & 0xff);
final byte b2 = (byte) ((byteQuad >> 16) & 0xff);
final byte b3 = (byte) ((byteQuad >> 8) & 0xff);
final byte b4 = (byte) ((byteQuad >> 0) & 0xff);
final char c1 = (char) b1;
final char c2 = (char) b2;
final char c3 = (char) b3;
final char c4 = (char) b4;
// return new String(new char[] { c1, c2, c3, c4 });
final StringBuilder buffer = new StringBuilder(31);
buffer.append(new String(new char[]{c1, c2, c3, c4}));
buffer.append(" byteQuad: ");
buffer.append(byteQuad);
buffer.append(" b1: ");
buffer.append(b1);
buffer.append(" b2: ");
buffer.append(b2);
buffer.append(" b3: ");
buffer.append(b3);
buffer.append(" b4: ");
buffer.append(b4);
return buffer.toString();
}
public static void debug(final String message, final Object value) {
if (value == null) {
debug(message, "null");
} else if (value instanceof char[]) {
debug(message, (char[]) value);
} else if (value instanceof byte[]) {
debug(message, (byte[]) value);
} else if (value instanceof int[]) {
debug(message, (int[]) value);
} else if (value instanceof String) {
debug(message, (String) value);
} else if (value instanceof List) {
debug(message, (List<?>) value);
} else if (value instanceof Map) {
debug(message, (Map<?, ?>) value);
} else if (value instanceof ICC_Profile) {
debug(message, (ICC_Profile) value);
} else if (value instanceof File) {
debug(message, (File) value);
} else if (value instanceof Date) {
debug(message, (Date) value);
} else if (value instanceof Calendar) {
debug(message, (Calendar) value);
} else {
debug(message, value.toString());
}
}
private static void debug(final String message, final byte[] v) {
debug(getDebug(message, v));
}
private static void debug(final String message, final char[] v) {
debug(getDebug(message, v));
}
private static void debug(final String message, final Calendar value) {
final DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH);
debug(message, (value == null) ? "null" : df.format(value.getTime()));
}
private static void debug(final String message, final Date value) {
final DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss", Locale.ENGLISH);
debug(message, (value == null) ? "null" : df.format(value));
}
private static void debug(final String message, final File file) {
debug(message + ": " + ((file == null) ? "null" : file.getPath()));
}
private static void debug(final String message, final ICC_Profile value) {
debug("ICC_Profile " + message + ": " + ((value == null) ? "null" : value.toString()));
if (value != null) {
debug("\t getProfileClass: " + byteQuadToString(value.getProfileClass()));
debug("\t getPCSType: " + byteQuadToString(value.getPCSType()));
debug("\t getColorSpaceType() : " + byteQuadToString(value.getColorSpaceType()));
}
}
private static void debug(final String message, final int[] v) {
debug(getDebug(message, v));
}
private static void debug(final String message, final List<?> v) {
final String suffix = " [" + counter++ + "]";
debug(message + " (" + v.size() + ")" + suffix);
for (final Object aV : v) {
debug("\t" + aV.toString() + suffix);
}
debug();
}
private static void debug(final String message, final String value) {
debug(message + " " + value);
}
public static void debug(final Throwable e) {
debug(getDebug(e));
}
public static void debug(final Throwable e, final int value) {
debug(getDebug(e, value));
}
private static String getDebug(final Throwable e) {
return getDebug(e, -1);
}
private static String getDebug(final Throwable e, final int max) {
final StringBuilder result = new StringBuilder(35);
final SimpleDateFormat timestamp = new SimpleDateFormat(
"yyyy-MM-dd kk:mm:ss:SSS", Locale.ENGLISH);
final String datetime = timestamp.format(new Date()).toLowerCase();
result.append(NEWLINE);
result.append("Throwable: "
+ ((e == null) ? "" : ("(" + e.getClass().getName() + ")"))
+ ":" + datetime + NEWLINE);
result.append("Throwable: " + ((e == null) ? "null" : e.getLocalizedMessage()) + NEWLINE);
result.append(NEWLINE);
result.append(getStackTrace(e, max));
result.append("Caught here:" + NEWLINE);
result.append(getStackTrace(new Exception(), max, 1));
// Debug.dumpStack();
result.append(NEWLINE);
return result.toString();
}
private static String getStackTrace(final Throwable e, final int limit) {
return getStackTrace(e, limit, 0);
}
private static String getStackTrace(final Throwable e, final int limit, final int skip) {
final StringBuilder result = new StringBuilder();
if (e != null) {
final StackTraceElement[] stes = e.getStackTrace();
if (stes != null) {
for (int i = skip; i < stes.length && (limit < 0 || i < limit); i++) {
final StackTraceElement ste = stes[i];
result.append("\tat " + ste.getClassName() + "."
+ ste.getMethodName() + "(" + ste.getFileName()
+ ":" + ste.getLineNumber() + ")" + NEWLINE);
}
if (limit >= 0 && stes.length > limit) {
result.append("\t..." + NEWLINE);
}
}
// e.printStackTrace(System.out);
result.append(NEWLINE);
}
return result.toString();
}
private Debug() {
}
}
| |
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch licenses this
* file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.elasticsearch.common.io.stream;
import org.apache.lucene.util.BytesRef;
import org.elasticsearch.Version;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.bytes.BytesReference;
import org.elasticsearch.common.io.UTF8StreamWriter;
import org.elasticsearch.common.text.Text;
import org.joda.time.ReadableInstant;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
*
*/
public abstract class StreamOutput extends OutputStream {
private Version version = Version.CURRENT;
public Version getVersion() {
return this.version;
}
public StreamOutput setVersion(Version version) {
this.version = version;
return this;
}
public boolean seekPositionSupported() {
return false;
}
public long position() throws IOException {
throw new UnsupportedOperationException();
}
public void seek(long position) throws IOException {
throw new UnsupportedOperationException();
}
/**
* Writes a single byte.
*/
public abstract void writeByte(byte b) throws IOException;
/**
* Writes an array of bytes.
*
* @param b the bytes to write
*/
public void writeBytes(byte[] b) throws IOException {
writeBytes(b, 0, b.length);
}
/**
* Writes an array of bytes.
*
* @param b the bytes to write
* @param length the number of bytes to write
*/
public void writeBytes(byte[] b, int length) throws IOException {
writeBytes(b, 0, length);
}
/**
* Writes an array of bytes.
*
* @param b the bytes to write
* @param offset the offset in the byte array
* @param length the number of bytes to write
*/
public abstract void writeBytes(byte[] b, int offset, int length) throws IOException;
/**
* Writes the bytes reference, including a length header.
*/
public void writeBytesReference(@Nullable BytesReference bytes) throws IOException {
if (bytes == null) {
writeVInt(0);
return;
}
writeVInt(bytes.length());
bytes.writeTo(this);
}
public void writeBytesRef(BytesRef bytes) throws IOException {
if (bytes == null) {
writeVInt(0);
return;
}
writeVInt(bytes.length);
write(bytes.bytes, bytes.offset, bytes.length);
}
public final void writeShort(short v) throws IOException {
writeByte((byte) (v >> 8));
writeByte((byte) v);
}
/**
* Writes an int as four bytes.
*/
public void writeInt(int i) throws IOException {
writeByte((byte) (i >> 24));
writeByte((byte) (i >> 16));
writeByte((byte) (i >> 8));
writeByte((byte) i);
}
/**
* Writes an int in a variable-length format. Writes between one and
* five bytes. Smaller values take fewer bytes. Negative numbers are not
* supported.
*/
public void writeVInt(int i) throws IOException {
while ((i & ~0x7F) != 0) {
writeByte((byte) ((i & 0x7f) | 0x80));
i >>>= 7;
}
writeByte((byte) i);
}
/**
* Writes a long as eight bytes.
*/
public void writeLong(long i) throws IOException {
writeInt((int) (i >> 32));
writeInt((int) i);
}
/**
* Writes an long in a variable-length format. Writes between one and five
* bytes. Smaller values take fewer bytes. Negative numbers are not
* supported.
*/
public void writeVLong(long i) throws IOException {
while ((i & ~0x7F) != 0) {
writeByte((byte) ((i & 0x7f) | 0x80));
i >>>= 7;
}
writeByte((byte) i);
}
public void writeOptionalString(@Nullable String str) throws IOException {
if (str == null) {
writeBoolean(false);
} else {
writeBoolean(true);
writeString(str);
}
}
public void writeOptionalText(@Nullable Text text) throws IOException {
if (text == null) {
writeInt(-1);
} else {
writeText(text);
}
}
public void writeText(Text text) throws IOException {
if (!text.hasBytes() && seekPositionSupported()) {
long pos1 = position();
// make room for the size
seek(pos1 + 4);
UTF8StreamWriter utf8StreamWriter = CachedStreamOutput.utf8StreamWriter();
utf8StreamWriter.setOutput(this);
utf8StreamWriter.write(text.string());
utf8StreamWriter.close();
long pos2 = position();
seek(pos1);
writeInt((int) (pos2 - pos1 - 4));
seek(pos2);
} else {
BytesReference bytes = text.bytes();
writeInt(bytes.length());
bytes.writeTo(this);
}
}
public void writeSharedText(Text text) throws IOException {
writeText(text);
}
public void writeString(String str) throws IOException {
int charCount = str.length();
writeVInt(charCount);
int c;
for (int i = 0; i < charCount; i++) {
c = str.charAt(i);
if (c <= 0x007F) {
writeByte((byte) c);
} else if (c > 0x07FF) {
writeByte((byte) (0xE0 | c >> 12 & 0x0F));
writeByte((byte) (0x80 | c >> 6 & 0x3F));
writeByte((byte) (0x80 | c >> 0 & 0x3F));
} else {
writeByte((byte) (0xC0 | c >> 6 & 0x1F));
writeByte((byte) (0x80 | c >> 0 & 0x3F));
}
}
}
public void writeFloat(float v) throws IOException {
writeInt(Float.floatToIntBits(v));
}
public void writeDouble(double v) throws IOException {
writeLong(Double.doubleToLongBits(v));
}
private static byte ZERO = 0;
private static byte ONE = 1;
/**
* Writes a boolean.
*/
public void writeBoolean(boolean b) throws IOException {
writeByte(b ? ONE : ZERO);
}
/**
* Forces any buffered output to be written.
*/
public abstract void flush() throws IOException;
/**
* Closes this stream to further operations.
*/
public abstract void close() throws IOException;
public abstract void reset() throws IOException;
@Override
public void write(int b) throws IOException {
writeByte((byte) b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
writeBytes(b, off, len);
}
public void writeStringArray(String[] array) throws IOException {
writeVInt(array.length);
for (String s : array) {
writeString(s);
}
}
/**
* Writes a string array, for nullable string, writes it as 0 (empty string).
*/
public void writeStringArrayNullable(@Nullable String[] array) throws IOException {
if (array == null) {
writeVInt(0);
} else {
writeVInt(array.length);
for (String s : array) {
writeString(s);
}
}
}
public void writeMap(@Nullable Map<String, Object> map) throws IOException {
writeGenericValue(map);
}
public void writeGenericValue(@Nullable Object value) throws IOException {
if (value == null) {
writeByte((byte) -1);
return;
}
Class type = value.getClass();
if (type == String.class) {
writeByte((byte) 0);
writeString((String) value);
} else if (type == Integer.class) {
writeByte((byte) 1);
writeInt((Integer) value);
} else if (type == Long.class) {
writeByte((byte) 2);
writeLong((Long) value);
} else if (type == Float.class) {
writeByte((byte) 3);
writeFloat((Float) value);
} else if (type == Double.class) {
writeByte((byte) 4);
writeDouble((Double) value);
} else if (type == Boolean.class) {
writeByte((byte) 5);
writeBoolean((Boolean) value);
} else if (type == byte[].class) {
writeByte((byte) 6);
writeVInt(((byte[]) value).length);
writeBytes(((byte[]) value));
} else if (value instanceof List) {
writeByte((byte) 7);
List list = (List) value;
writeVInt(list.size());
for (Object o : list) {
writeGenericValue(o);
}
} else if (value instanceof Object[]) {
writeByte((byte) 8);
Object[] list = (Object[]) value;
writeVInt(list.length);
for (Object o : list) {
writeGenericValue(o);
}
} else if (value instanceof Map) {
if (value instanceof LinkedHashMap) {
writeByte((byte) 9);
} else {
writeByte((byte) 10);
}
Map<String, Object> map = (Map<String, Object>) value;
writeVInt(map.size());
for (Map.Entry<String, Object> entry : map.entrySet()) {
writeString(entry.getKey());
writeGenericValue(entry.getValue());
}
} else if (type == Byte.class) {
writeByte((byte) 11);
writeByte((Byte) value);
} else if (type == Date.class) {
writeByte((byte) 12);
writeLong(((Date) value).getTime());
} else if (value instanceof ReadableInstant) {
writeByte((byte) 13);
writeLong(((ReadableInstant) value).getMillis());
} else if (value instanceof BytesReference) {
writeByte((byte) 14);
writeBytesReference((BytesReference) value);
} else if (value instanceof Text) {
writeByte((byte) 15);
writeText((Text) value);
} else if (type == Short.class) {
writeByte((byte) 16);
writeShort((Short) value);
} else {
throw new IOException("Can't write type [" + type + "]");
}
}
}
| |
package com.vaadin.data.util.filter;
import java.math.BigDecimal;
import java.util.Date;
import org.junit.Assert;
import com.vaadin.data.Container.Filter;
import com.vaadin.data.Item;
import com.vaadin.data.util.ObjectProperty;
import com.vaadin.data.util.PropertysetItem;
import com.vaadin.data.util.filter.Compare.Equal;
import com.vaadin.data.util.filter.Compare.Greater;
import com.vaadin.data.util.filter.Compare.GreaterOrEqual;
import com.vaadin.data.util.filter.Compare.Less;
import com.vaadin.data.util.filter.Compare.LessOrEqual;
public class CompareFilterTest extends AbstractFilterTestBase<Compare> {
protected Item itemNull;
protected Item itemEmpty;
protected Item itemA;
protected Item itemB;
protected Item itemC;
protected final Filter equalB = new Equal(PROPERTY1, "b");
protected final Filter greaterB = new Greater(PROPERTY1, "b");
protected final Filter lessB = new Less(PROPERTY1, "b");
protected final Filter greaterEqualB = new GreaterOrEqual(PROPERTY1, "b");
protected final Filter lessEqualB = new LessOrEqual(PROPERTY1, "b");
protected final Filter equalNull = new Equal(PROPERTY1, null);
protected final Filter greaterNull = new Greater(PROPERTY1, null);
protected final Filter lessNull = new Less(PROPERTY1, null);
protected final Filter greaterEqualNull = new GreaterOrEqual(PROPERTY1,
null);
protected final Filter lessEqualNull = new LessOrEqual(PROPERTY1, null);
@Override
protected void setUp() throws Exception {
super.setUp();
itemNull = new PropertysetItem();
itemNull.addItemProperty(PROPERTY1, new ObjectProperty<String>(null,
String.class));
itemEmpty = new PropertysetItem();
itemEmpty.addItemProperty(PROPERTY1, new ObjectProperty<String>("",
String.class));
itemA = new PropertysetItem();
itemA.addItemProperty(PROPERTY1, new ObjectProperty<String>("a",
String.class));
itemB = new PropertysetItem();
itemB.addItemProperty(PROPERTY1, new ObjectProperty<String>("b",
String.class));
itemC = new PropertysetItem();
itemC.addItemProperty(PROPERTY1, new ObjectProperty<String>("c",
String.class));
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
itemNull = null;
itemEmpty = null;
itemA = null;
itemB = null;
}
public void testCompareString() {
Assert.assertFalse(equalB.passesFilter(null, itemEmpty));
Assert.assertFalse(equalB.passesFilter(null, itemA));
Assert.assertTrue(equalB.passesFilter(null, itemB));
Assert.assertFalse(equalB.passesFilter(null, itemC));
Assert.assertFalse(greaterB.passesFilter(null, itemEmpty));
Assert.assertFalse(greaterB.passesFilter(null, itemA));
Assert.assertFalse(greaterB.passesFilter(null, itemB));
Assert.assertTrue(greaterB.passesFilter(null, itemC));
Assert.assertTrue(lessB.passesFilter(null, itemEmpty));
Assert.assertTrue(lessB.passesFilter(null, itemA));
Assert.assertFalse(lessB.passesFilter(null, itemB));
Assert.assertFalse(lessB.passesFilter(null, itemC));
Assert.assertFalse(greaterEqualB.passesFilter(null, itemEmpty));
Assert.assertFalse(greaterEqualB.passesFilter(null, itemA));
Assert.assertTrue(greaterEqualB.passesFilter(null, itemB));
Assert.assertTrue(greaterEqualB.passesFilter(null, itemC));
Assert.assertTrue(lessEqualB.passesFilter(null, itemEmpty));
Assert.assertTrue(lessEqualB.passesFilter(null, itemA));
Assert.assertTrue(lessEqualB.passesFilter(null, itemB));
Assert.assertFalse(lessEqualB.passesFilter(null, itemC));
}
public void testCompareWithNull() {
// null comparisons: null is less than any other value
Assert.assertFalse(equalB.passesFilter(null, itemNull));
Assert.assertTrue(greaterB.passesFilter(null, itemNull));
Assert.assertFalse(lessB.passesFilter(null, itemNull));
Assert.assertTrue(greaterEqualB.passesFilter(null, itemNull));
Assert.assertFalse(lessEqualB.passesFilter(null, itemNull));
Assert.assertTrue(equalNull.passesFilter(null, itemNull));
Assert.assertFalse(greaterNull.passesFilter(null, itemNull));
Assert.assertFalse(lessNull.passesFilter(null, itemNull));
Assert.assertTrue(greaterEqualNull.passesFilter(null, itemNull));
Assert.assertTrue(lessEqualNull.passesFilter(null, itemNull));
Assert.assertFalse(equalNull.passesFilter(null, itemA));
Assert.assertFalse(greaterNull.passesFilter(null, itemA));
Assert.assertTrue(lessNull.passesFilter(null, itemA));
Assert.assertFalse(greaterEqualNull.passesFilter(null, itemA));
Assert.assertTrue(lessEqualNull.passesFilter(null, itemA));
}
public void testCompareInteger() {
int negative = -1;
int zero = 0;
int positive = 1;
Item itemNegative = new PropertysetItem();
itemNegative.addItemProperty(PROPERTY1, new ObjectProperty<Integer>(
negative, Integer.class));
Item itemZero = new PropertysetItem();
itemZero.addItemProperty(PROPERTY1, new ObjectProperty<Integer>(zero,
Integer.class));
Item itemPositive = new PropertysetItem();
itemPositive.addItemProperty(PROPERTY1, new ObjectProperty<Integer>(
positive, Integer.class));
Filter equalZero = new Equal(PROPERTY1, zero);
Assert.assertFalse(equalZero.passesFilter(null, itemNegative));
Assert.assertTrue(equalZero.passesFilter(null, itemZero));
Assert.assertFalse(equalZero.passesFilter(null, itemPositive));
Filter isPositive = new Greater(PROPERTY1, zero);
Assert.assertFalse(isPositive.passesFilter(null, itemNegative));
Assert.assertFalse(isPositive.passesFilter(null, itemZero));
Assert.assertTrue(isPositive.passesFilter(null, itemPositive));
Filter isNegative = new Less(PROPERTY1, zero);
Assert.assertTrue(isNegative.passesFilter(null, itemNegative));
Assert.assertFalse(isNegative.passesFilter(null, itemZero));
Assert.assertFalse(isNegative.passesFilter(null, itemPositive));
Filter isNonNegative = new GreaterOrEqual(PROPERTY1, zero);
Assert.assertFalse(isNonNegative.passesFilter(null, itemNegative));
Assert.assertTrue(isNonNegative.passesFilter(null, itemZero));
Assert.assertTrue(isNonNegative.passesFilter(null, itemPositive));
Filter isNonPositive = new LessOrEqual(PROPERTY1, zero);
Assert.assertTrue(isNonPositive.passesFilter(null, itemNegative));
Assert.assertTrue(isNonPositive.passesFilter(null, itemZero));
Assert.assertFalse(isNonPositive.passesFilter(null, itemPositive));
}
public void testCompareBigDecimal() {
BigDecimal negative = new BigDecimal(-1);
BigDecimal zero = new BigDecimal(0);
BigDecimal positive = new BigDecimal(1);
positive.setScale(1);
BigDecimal positiveScaleTwo = new BigDecimal(1).setScale(2);
Item itemNegative = new PropertysetItem();
itemNegative.addItemProperty(PROPERTY1, new ObjectProperty<BigDecimal>(
negative, BigDecimal.class));
Item itemZero = new PropertysetItem();
itemZero.addItemProperty(PROPERTY1, new ObjectProperty<BigDecimal>(
zero, BigDecimal.class));
Item itemPositive = new PropertysetItem();
itemPositive.addItemProperty(PROPERTY1, new ObjectProperty<BigDecimal>(
positive, BigDecimal.class));
Item itemPositiveScaleTwo = new PropertysetItem();
itemPositiveScaleTwo.addItemProperty(PROPERTY1,
new ObjectProperty<BigDecimal>(positiveScaleTwo,
BigDecimal.class));
Filter equalZero = new Equal(PROPERTY1, zero);
Assert.assertFalse(equalZero.passesFilter(null, itemNegative));
Assert.assertTrue(equalZero.passesFilter(null, itemZero));
Assert.assertFalse(equalZero.passesFilter(null, itemPositive));
Filter isPositive = new Greater(PROPERTY1, zero);
Assert.assertFalse(isPositive.passesFilter(null, itemNegative));
Assert.assertFalse(isPositive.passesFilter(null, itemZero));
Assert.assertTrue(isPositive.passesFilter(null, itemPositive));
Filter isNegative = new Less(PROPERTY1, zero);
Assert.assertTrue(isNegative.passesFilter(null, itemNegative));
Assert.assertFalse(isNegative.passesFilter(null, itemZero));
Assert.assertFalse(isNegative.passesFilter(null, itemPositive));
Filter isNonNegative = new GreaterOrEqual(PROPERTY1, zero);
Assert.assertFalse(isNonNegative.passesFilter(null, itemNegative));
Assert.assertTrue(isNonNegative.passesFilter(null, itemZero));
Assert.assertTrue(isNonNegative.passesFilter(null, itemPositive));
Filter isNonPositive = new LessOrEqual(PROPERTY1, zero);
Assert.assertTrue(isNonPositive.passesFilter(null, itemNegative));
Assert.assertTrue(isNonPositive.passesFilter(null, itemZero));
Assert.assertFalse(isNonPositive.passesFilter(null, itemPositive));
Filter isPositiveScaleTwo = new Equal(PROPERTY1, positiveScaleTwo);
Assert.assertTrue(isPositiveScaleTwo.passesFilter(null,
itemPositiveScaleTwo));
Assert.assertTrue(isPositiveScaleTwo.passesFilter(null, itemPositive));
}
public void testCompareDate() {
Date now = new Date();
// new Date() is only accurate to the millisecond, so repeating it gives
// the same date
Date earlier = new Date(now.getTime() - 1);
Date later = new Date(now.getTime() + 1);
Item itemEarlier = new PropertysetItem();
itemEarlier.addItemProperty(PROPERTY1, new ObjectProperty<Date>(
earlier, Date.class));
Item itemNow = new PropertysetItem();
itemNow.addItemProperty(PROPERTY1, new ObjectProperty<Date>(now,
Date.class));
Item itemLater = new PropertysetItem();
itemLater.addItemProperty(PROPERTY1, new ObjectProperty<Date>(later,
Date.class));
Filter equalNow = new Equal(PROPERTY1, now);
Assert.assertFalse(equalNow.passesFilter(null, itemEarlier));
Assert.assertTrue(equalNow.passesFilter(null, itemNow));
Assert.assertFalse(equalNow.passesFilter(null, itemLater));
Filter after = new Greater(PROPERTY1, now);
Assert.assertFalse(after.passesFilter(null, itemEarlier));
Assert.assertFalse(after.passesFilter(null, itemNow));
Assert.assertTrue(after.passesFilter(null, itemLater));
Filter before = new Less(PROPERTY1, now);
Assert.assertTrue(before.passesFilter(null, itemEarlier));
Assert.assertFalse(before.passesFilter(null, itemNow));
Assert.assertFalse(before.passesFilter(null, itemLater));
Filter afterOrNow = new GreaterOrEqual(PROPERTY1, now);
Assert.assertFalse(afterOrNow.passesFilter(null, itemEarlier));
Assert.assertTrue(afterOrNow.passesFilter(null, itemNow));
Assert.assertTrue(afterOrNow.passesFilter(null, itemLater));
Filter beforeOrNow = new LessOrEqual(PROPERTY1, now);
Assert.assertTrue(beforeOrNow.passesFilter(null, itemEarlier));
Assert.assertTrue(beforeOrNow.passesFilter(null, itemNow));
Assert.assertFalse(beforeOrNow.passesFilter(null, itemLater));
}
public void testCompareAppliesToProperty() {
Filter filterA = new Equal("a", 1);
Filter filterB = new Equal("b", 1);
Assert.assertTrue(filterA.appliesToProperty("a"));
Assert.assertFalse(filterA.appliesToProperty("b"));
Assert.assertFalse(filterB.appliesToProperty("a"));
Assert.assertTrue(filterB.appliesToProperty("b"));
}
public void testCompareEqualsHashCode() {
// most checks with Equal filter, then only some with others
Filter equalNull2 = new Equal(PROPERTY1, null);
Filter equalNullProperty2 = new Equal(PROPERTY2, null);
Filter equalEmpty = new Equal(PROPERTY1, "");
Filter equalEmpty2 = new Equal(PROPERTY1, "");
Filter equalEmptyProperty2 = new Equal(PROPERTY2, "");
Filter equalA = new Equal(PROPERTY1, "a");
Filter equalB2 = new Equal(PROPERTY1, "b");
Filter equalBProperty2 = new Equal(PROPERTY2, "b");
Filter greaterEmpty = new Greater(PROPERTY1, "");
// equals()
Assert.assertEquals(equalNull, equalNull);
Assert.assertEquals(equalNull, equalNull2);
Assert.assertFalse(equalNull.equals(equalNullProperty2));
Assert.assertFalse(equalNull.equals(equalEmpty));
Assert.assertFalse(equalNull.equals(equalB));
Assert.assertEquals(equalEmpty, equalEmpty);
Assert.assertFalse(equalEmpty.equals(equalNull));
Assert.assertEquals(equalEmpty, equalEmpty2);
Assert.assertFalse(equalEmpty.equals(equalEmptyProperty2));
Assert.assertFalse(equalEmpty.equals(equalB));
Assert.assertEquals(equalB, equalB);
Assert.assertFalse(equalB.equals(equalNull));
Assert.assertFalse(equalB.equals(equalEmpty));
Assert.assertEquals(equalB, equalB2);
Assert.assertFalse(equalB.equals(equalBProperty2));
Assert.assertFalse(equalB.equals(equalA));
Assert.assertEquals(greaterB, greaterB);
Assert.assertFalse(greaterB.equals(lessB));
Assert.assertFalse(greaterB.equals(greaterEqualB));
Assert.assertFalse(greaterB.equals(lessEqualB));
Assert.assertFalse(greaterNull.equals(greaterEmpty));
Assert.assertFalse(greaterNull.equals(greaterB));
Assert.assertFalse(greaterEmpty.equals(greaterNull));
Assert.assertFalse(greaterEmpty.equals(greaterB));
Assert.assertFalse(greaterB.equals(greaterNull));
Assert.assertFalse(greaterB.equals(greaterEmpty));
// hashCode()
Assert.assertEquals(equalNull.hashCode(), equalNull2.hashCode());
Assert.assertEquals(equalEmpty.hashCode(), equalEmpty2.hashCode());
Assert.assertEquals(equalB.hashCode(), equalB2.hashCode());
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.ignite.cache;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.Map;
import org.apache.ignite.cache.store.jdbc.CacheJdbcPojoStore;
import org.apache.ignite.internal.util.tostring.GridToStringInclude;
import org.apache.ignite.internal.util.typedef.internal.S;
import org.apache.ignite.lang.IgniteBiTuple;
/**
* Cache type metadata need for configuration of indexes or automatic persistence.
*/
public class CacheTypeMetadata implements Serializable {
/** */
private static final long serialVersionUID = 0L;
/** Schema name in database. */
private String dbSchema;
/** Table name in database. */
private String dbTbl;
/** Key class used to store key in cache. */
private String keyType;
/** Value class used to store value in cache. */
private String valType;
/** Optional persistent key fields (needed only if {@link CacheJdbcPojoStore} is used). */
@GridToStringInclude
private Collection<CacheTypeFieldMetadata> keyFields;
/** Optional persistent value fields (needed only if {@link CacheJdbcPojoStore} is used). */
@GridToStringInclude
private Collection<CacheTypeFieldMetadata> valFields;
/** Field name-to-type map to be queried, in addition to indexed fields. */
@GridToStringInclude
private Map<String, Class<?>> qryFlds;
/** Field name-to-type map to index in ascending order. */
@GridToStringInclude
private Map<String, Class<?>> ascFlds;
/** Field name-to-type map to index in descending order. */
@GridToStringInclude
private Map<String, Class<?>> descFlds;
/** Fields to index as text. */
@GridToStringInclude
private Collection<String> txtFlds;
/** Fields to create group indexes for. */
@GridToStringInclude
private Map<String, LinkedHashMap<String, IgniteBiTuple<Class<?>, Boolean>>> grps;
/**
* Default constructor.
*/
public CacheTypeMetadata() {
keyFields = new ArrayList<>();
valFields = new ArrayList<>();
qryFlds = new LinkedHashMap<>();
ascFlds = new LinkedHashMap<>();
descFlds = new LinkedHashMap<>();
txtFlds = new LinkedHashSet<>();
grps = new LinkedHashMap<>();
}
/**
* Copy constructor.
*/
public CacheTypeMetadata(CacheTypeMetadata src) {
dbSchema = src.getDatabaseSchema();
dbTbl = src.getDatabaseTable();
keyType = src.getKeyType();
valType = src.getValueType();
keyFields = new ArrayList<>(src.getKeyFields());
valFields = new ArrayList<>(src.getValueFields());
qryFlds = new LinkedHashMap<>(src.getQueryFields());
ascFlds = new LinkedHashMap<>(src.getAscendingFields());
descFlds = new LinkedHashMap<>(src.getDescendingFields());
txtFlds = new LinkedHashSet<>(src.getTextFields());
grps = new LinkedHashMap<>(src.getGroups());
}
/**
* Gets database schema name.
*
* @return Schema name.
*/
public String getDatabaseSchema() {
return dbSchema;
}
/**
* Sets database schema name.
*
* @param dbSchema Schema name.
*/
public void setDatabaseSchema(String dbSchema) {
this.dbSchema = dbSchema;
}
/**
* Gets table name in database.
*
* @return Table name in database.
*/
public String getDatabaseTable() {
return dbTbl;
}
/**
* Table name in database.
*
* @param dbTbl Table name in database.
*/
public void setDatabaseTable(String dbTbl) {
this.dbTbl = dbTbl;
}
/**
* Gets key type.
*
* @return Key type.
*/
public String getKeyType() {
return keyType;
}
/**
* Sets key type.
*
* @param keyType Key type.
*/
public void setKeyType(String keyType) {
this.keyType = keyType;
}
/**
* Sets key type.
*
* @param cls Key type class.
*/
public void setKeyType(Class<?> cls) {
setKeyType(cls.getName());
}
/**
* Gets value type.
*
* @return Key type.
*/
public String getValueType() {
return valType;
}
/**
* Sets value type.
*
* @param valType Value type.
*/
public void setValueType(String valType) {
this.valType = valType;
}
/**
* Sets value type.
*
* @param cls Value type class.
*/
public void setValueType(Class<?> cls) {
setValueType(cls.getName());
}
/**
* Gets optional persistent key fields (needed only if {@link CacheJdbcPojoStore} is used).
*
* @return Persistent key fields.
*/
public Collection<CacheTypeFieldMetadata> getKeyFields() {
return keyFields;
}
/**
* Sets optional persistent key fields (needed only if {@link CacheJdbcPojoStore} is used).
*
* @param keyFields Persistent key fields.
*/
public void setKeyFields(Collection<CacheTypeFieldMetadata> keyFields) {
this.keyFields = keyFields;
}
/**
* Gets optional persistent value fields (needed only if {@link CacheJdbcPojoStore} is used).
*
* @return Persistent value fields.
*/
public Collection<CacheTypeFieldMetadata> getValueFields() {
return valFields;
}
/**
* Sets optional persistent value fields (needed only if {@link CacheJdbcPojoStore} is used).
*
* @param valFields Persistent value fields.
*/
public void setValueFields(Collection<CacheTypeFieldMetadata> valFields) {
this.valFields = valFields;
}
/**
* Gets name-to-type map for query-enabled fields.
*
* @return Name-to-type map for query-enabled fields.
*/
public Map<String, Class<?>> getQueryFields() {
return qryFlds;
}
/**
* Sets name-to-type map for query-enabled fields.
*
* @param qryFlds Name-to-type map for query-enabled fields.
*/
public void setQueryFields(Map<String, Class<?>> qryFlds) {
this.qryFlds = qryFlds;
}
/**
* Gets name-to-type map for ascending-indexed fields.
*
* @return Name-to-type map for ascending-indexed fields.
*/
public Map<String, Class<?>> getAscendingFields() {
return ascFlds;
}
/**
* Sets name-to-type map for ascending-indexed fields.
*
* @param ascFlds Name-to-type map for ascending-indexed fields.
*/
public void setAscendingFields(Map<String, Class<?>> ascFlds) {
this.ascFlds = ascFlds;
}
/**
* Gets name-to-type map for descending-indexed fields.
*
* @return Name-to-type map of descending-indexed fields.
*/
public Map<String, Class<?>> getDescendingFields() {
return descFlds;
}
/**
* Sets name-to-type map for descending-indexed fields.
*
* @param descFlds Name-to-type map of descending-indexed fields.
*/
public void setDescendingFields(Map<String, Class<?>> descFlds) {
this.descFlds = descFlds;
}
/**
* Gets text-indexed fields.
*
* @return Collection of text indexed fields.
*/
public Collection<String> getTextFields() {
return txtFlds;
}
/**
* Sets text-indexed fields.
*
* @param txtFlds Text-indexed fields.
*/
public void setTextFields(Collection<String> txtFlds) {
this.txtFlds = txtFlds;
}
/**
* Gets group-indexed fields.
*
* @return Map of group-indexed fields.
*/
public Map<String, LinkedHashMap<String, IgniteBiTuple<Class<?>, Boolean>>> getGroups() {
return grps;
}
/**
* Sets group-indexed fields.
*
* @param grps Map of group-indexed fields from index name to index fields.
*/
public void setGroups(Map<String, LinkedHashMap<String, IgniteBiTuple<Class<?>, Boolean>>> grps) {
this.grps = grps;
}
/** {@inheritDoc} */
@Override public String toString() {
return S.toString(CacheTypeMetadata.class, this);
}
}
| |
// Copyright (c) 2003-present, Jodd Team (jodd.org). All Rights Reserved.
package jodd.jerry;
import jodd.lagarto.dom.DOMBuilder;
import jodd.lagarto.dom.Document;
import jodd.lagarto.dom.LagartoDOMBuilder;
import jodd.lagarto.dom.Node;
import jodd.lagarto.dom.NodeSelector;
import jodd.lagarto.dom.Text;
import jodd.util.ArraysUtil;
import jodd.util.StringUtil;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Jerry is JQuery in Java.
*/
@SuppressWarnings("MethodNamesDifferingOnlyByCase")
public class Jerry implements Iterable<Jerry> {
@SuppressWarnings("CloneableClassWithoutClone")
private static class NodeList extends ArrayList<Node> {
private NodeList(int initialCapacity) {
super(initialCapacity);
}
private NodeList() {
}
@Override
public boolean add(Node o) {
for (Node node : this) {
if (node == o) {
return false;
}
}
return super.add(o);
}
}
// ---------------------------------------------------------------- create
/**
* Parses input sequence and creates new <code>Jerry</code>.
*/
public static Jerry jerry(char[] content) {
return jerry().parse(content);
}
/**
* Parses input content and creates new <code>Jerry</code>.
*/
public static Jerry jerry(String content) {
return jerry().parse(content);
}
// ---------------------------------------------------------------- 2-steps init
/**
* Content parser and Jerry factory.
*/
public static class JerryParser {
protected final DOMBuilder domBuilder;
public JerryParser() {
this.domBuilder = new LagartoDOMBuilder();
}
public JerryParser(DOMBuilder domBuilder) {
this.domBuilder = domBuilder;
}
/**
* Returns {@link DOMBuilder} for additional configuration.
*/
public DOMBuilder getDOMBuilder() {
return domBuilder;
}
/**
* Invokes parsing on {@link DOMBuilder}.
*/
public Jerry parse(char[] content) {
Document doc = domBuilder.parse(content);
return new Jerry(domBuilder, doc);
}
/**
* Invokes parsing on {@link DOMBuilder}.
*/
public Jerry parse(String content) {
Document doc = domBuilder.parse(content);
return new Jerry(domBuilder, doc);
}
}
/**
* Just creates new {@link jodd.jerry.Jerry.JerryParser Jerry runner} to separate
* parser creation and creation of new Jerry instances.
*/
public static JerryParser jerry() {
return new JerryParser();
}
/**
* Creates new {@link jodd.jerry.Jerry.JerryParser Jerry runner} with
* provided implementation of {@link jodd.lagarto.dom.DOMBuilder}.
*/
public static JerryParser jerry(DOMBuilder domBuilder) {
return new JerryParser(domBuilder);
}
// ---------------------------------------------------------------- ctor
protected final Jerry parent;
protected final Node[] nodes;
protected final DOMBuilder builder;
/**
* Creates root Jerry.
*/
protected Jerry(DOMBuilder builder, Node... nodes) {
this.parent = null;
this.nodes = nodes;
this.builder = builder;
}
/**
* Creates child Jerry.
*/
protected Jerry(Jerry parent, Node... nodes) {
this.parent = parent;
this.nodes = nodes;
this.builder = parent.builder;
}
/**
* Creates child Jerry.
*/
protected Jerry(Jerry parent, Node[] nodes1, Node[] nodes2) {
this.parent = parent;
this.nodes = ArraysUtil.join(nodes1, nodes2);
this.builder = parent.builder;
}
/**
* Creates child Jerry.
*/
protected Jerry(Jerry parent, List<Node> nodeList) {
this(parent, nodeList.toArray(new Node[nodeList.size()]));
}
// ---------------------------------------------------------------- this
/**
* Returns number of nodes in this Jerry.
*/
public int length() {
return nodes.length;
}
/**
* Returns number of nodes in this Jerry.
*/
public int size() {
return nodes.length;
}
/**
* Returns node at given index. Returns <code>null</code>
* if index is out of bounds.
*/
public Node get(int index) {
if ((index < 0) || (index >= nodes.length)) {
return null;
}
return nodes[index];
}
/**
* Retrieve all DOM elements matched by this set.
* Warning: returned array is not a clone!
*/
public Node[] get() {
return nodes;
}
/**
* Searches for a given <code>Node</code> from among the matched elements.
*/
public int index(Node element) {
int index = 0;
for (Node node : nodes) {
if (node == element) {
return index;
}
index++;
}
return -1;
}
// ---------------------------------------------------------------- Traversing
/**
* Gets the immediate children of each element in the set of matched elements.
*/
public Jerry children() {
List<Node> result = new NodeList(nodes.length);
for (Node node : nodes) {
Node[] children = node.getChildElements();
Collections.addAll(result, children);
}
return new Jerry(this, result);
}
/**
* Gets the parent of each element in the current set of matched elements.
*/
public Jerry parent() {
List<Node> result = new NodeList(nodes.length);
for (Node node : nodes) {
result.add(node.getParentNode());
}
return new Jerry(this, result);
}
/**
* Gets the siblings of each element in the set of matched elements.
*/
public Jerry siblings() {
List<Node> result = new NodeList(nodes.length);
for (Node node : nodes) {
Node[] allElements = node.getParentNode().getChildElements();
for (Node sibling : allElements) {
if (sibling != node) {
result.add(sibling);
}
}
}
return new Jerry(this, result);
}
/**
* Gets the immediately following sibling of each element in the
* set of matched elements.
*/
public Jerry next() {
List<Node> result = new NodeList(nodes.length);
for (Node node : nodes) {
result.add(node.getNextSiblingElement());
}
return new Jerry(this, result);
}
/**
* Gets the immediately preceding sibling of each element in the
* set of matched elements.
*/
public Jerry prev() {
List<Node> result = new NodeList(nodes.length);
for (Node node : nodes) {
result.add(node.getPreviousSiblingElement());
}
return new Jerry(this, result);
}
/**
* Gets the descendants of each element in the current set of matched elements,
* filtered by a selector.
*/
public Jerry find(String cssSelector) {
final List<Node> result = new NodeList();
for (Node node : nodes) {
NodeSelector nodeSelector = createNodeSelector(node);
List<Node> filteredNodes = nodeSelector.select(cssSelector);
result.addAll(filteredNodes);
}
return new Jerry(this, result);
}
/**
* @see #find(String)
*/
public Jerry $(String cssSelector) {
return find(cssSelector);
}
/**
* Shortcut for <code>context.find(css)</code>.
*/
public static Jerry $(String cssSelector, Jerry context) {
return context.find(cssSelector);
}
/**
* Creates node selector.
*/
protected NodeSelector createNodeSelector(Node node) {
return new NodeSelector(node);
}
/**
* Iterates over a jQuery object, executing a function for
* each matched element.
*/
public Jerry each(JerryFunction function) {
for (int i = 0; i < nodes.length; i++) {
Node node = nodes[i];
Jerry $this = new Jerry(this, node);
if (function.onNode($this, i) == false) {
break;
}
}
return this;
}
/**
* Iterates over a jQuery object, executing a function for
* each matched element.
*/
public Jerry each(JerryNodeFunction function) {
for (int i = 0; i < nodes.length; i++) {
Node node = nodes[i];
if (function.onNode(node, i) == false) {
break;
}
}
return this;
}
// ---------------------------------------------------------------- Miscellaneous Traversing
/**
* Adds elements to the set of matched elements.
*/
public Jerry add(String selector) {
return new Jerry(this, nodes, root().find(selector).nodes);
}
/**
* Ends the most recent filtering operation in the current chain
* and returns the set of matched elements to its previous state.
*/
public Jerry end() {
return parent;
}
/**
* Removes elements from the set of matched elements.
*/
public Jerry not(String cssSelector) {
Node[] notNodes = root().find(cssSelector).nodes;
List<Node> result = new NodeList(nodes.length);
for (Node node : nodes) {
if (ArraysUtil.contains(notNodes, node) == false) {
result.add(node);
}
}
return new Jerry(this, result);
}
/**
* Returns root Jerry.
*/
public Jerry root() {
Jerry jerry = this.parent;
if (jerry == null) {
return this;
}
while (jerry.parent != null) {
jerry = jerry.parent;
}
return jerry;
}
// ---------------------------------------------------------------- Filtering
/**
* Reduces the set of matched elements to the first in the set.
*/
public Jerry first() {
List<Node> result = new NodeList(nodes.length);
if (nodes.length > 0) {
result.add(nodes[0]);
}
return new Jerry(this, result);
}
/**
* Reduces the set of matched elements to the last in the set.
*/
public Jerry last() {
List<Node> result = new NodeList(nodes.length);
if (nodes.length > 0) {
result.add(nodes[nodes.length - 1]);
}
return new Jerry(this, result);
}
/**
* Reduces the set of matched elements to the one at the specified index.
*/
public Jerry eq(int value) {
List<Node> result = new NodeList(1);
int index = 0;
int matchingIndex = value >= 0 ? value : nodes.length + value;
for (Node node : nodes) {
if (index == matchingIndex) {
result.add(node);
break;
}
index++;
}
return new Jerry(this, result);
}
/**
* Reduces the set of matched elements to the one at an index greater
* than specified index.
*/
public Jerry gt(int value) {
List<Node> result = new NodeList(nodes.length);
int index = 0;
for (Node node : nodes) {
if (index > value) {
result.add(node);
}
index++;
}
return new Jerry(this, result);
}
/**
* Reduces the set of matched elements to the one at an index less
* than specified index.
*/
public Jerry lt(int value) {
List<Node> result = new NodeList(nodes.length);
int index = 0;
for (Node node : nodes) {
if (index < value) {
result.add(node);
}
index++;
}
return new Jerry(this, result);
}
/**
* Checks the current matched set of elements against a selector and
* return <code>true</code> if at least one of these elements matches
* the given arguments.
*/
public boolean is(String cssSelectors) {
for (Node node : nodes) {
Node parentNode = node.getParentNode();
if (parentNode == null) {
continue;
}
NodeSelector nodeSelector = createNodeSelector(parentNode);
List<Node> selectedNodes = nodeSelector.select(cssSelectors);
for (Node selected : selectedNodes) {
if (node == selected) {
return true;
}
}
}
return false;
}
/**
* Reduces the set of matched elements to those that match the selector.
*/
public Jerry filter(String cssSelectors) {
List<Node> result = new NodeList(nodes.length);
for (Node node : nodes) {
Node parentNode = node.getParentNode();
if (parentNode == null) {
continue;
}
NodeSelector nodeSelector = createNodeSelector(parentNode);
List<Node> selectedNodes = nodeSelector.select(cssSelectors);
for (Node selected : selectedNodes) {
if (node == selected) {
result.add(node);
}
}
}
return new Jerry(this, result);
}
/**
* Reduces the set of matched elements to those that pass the
* {@link JerryFunction function's} test.
*/
public Jerry filter(JerryFunction jerryFunction) {
List<Node> result = new NodeList(nodes.length);
for (int i = 0; i < nodes.length; i++) {
Node node = nodes[i];
Node parentNode = node.getParentNode();
if (parentNode == null) {
continue;
}
Jerry $this = new Jerry(this, node);
boolean accept = jerryFunction.onNode($this, i);
if (accept) {
result.add(node);
}
}
return new Jerry(this, result);
}
// ---------------------------------------------------------------- Attributes
/**
* Gets the value of an attribute for the first element in the set of matched elements.
* Returns <code>null</code> if set is empty.
*/
public String attr(String name) {
if (nodes.length == 0) {
return null;
}
return nodes[0].getAttribute(name);
}
/**
* Sets one or more attributes for the set of matched elements.
*/
public Jerry attr(String name, String value) {
for (Node node : nodes) {
node.setAttribute(name, value);
}
return this;
}
/**
* Removes an attribute from each element in the set of matched elements.
*/
public Jerry removeAttr(String name) {
for (Node node : nodes) {
node.removeAttribute(name);
}
return this;
}
/**
* Gets the value of a style property for the first element
* in the set of matched elements. Returns <code>null</code>
* if set is empty.
*/
public String css(String propertyName) {
if (nodes.length == 0) {
return null;
}
propertyName = StringUtil.fromCamelCase(propertyName, '-');
String styleAttrValue = nodes[0].getAttribute("style");
if (styleAttrValue == null) {
return null;
}
Map<String, String> styles = createPropertiesMap(styleAttrValue, ';', ':');
return styles.get(propertyName);
}
/**
* Sets one or more CSS properties for the set of matched elements.
* By passing an empty value, that property will be removed.
* Note that this is different from jQuery, where this means
* that property will be reset to previous value if existed.
*/
public Jerry css(String propertyName, String value) {
propertyName = StringUtil.fromCamelCase(propertyName, '-');
for (Node node : nodes) {
String styleAttrValue = node.getAttribute("style");
Map<String, String> styles = createPropertiesMap(styleAttrValue, ';', ':');
if (value.length() == 0) {
styles.remove(propertyName);
} else {
styles.put(propertyName, value);
}
styleAttrValue = generateAttributeValue(styles, ';', ':');
node.setAttribute("style", styleAttrValue);
}
return this;
}
/**
* Sets one or more CSS properties for the set of matched elements.
*/
public Jerry css(String... css) {
for (Node node : nodes) {
String styleAttrValue = node.getAttribute("style");
Map<String, String> styles = createPropertiesMap(styleAttrValue, ';', ':');
for (int i = 0; i < css.length; i += 2) {
String propertyName = css[i];
propertyName = StringUtil.fromCamelCase(propertyName, '-');
String value = css[i + 1];
if (value.length() == 0) {
styles.remove(propertyName);
} else {
styles.put(propertyName, value);
}
}
styleAttrValue = generateAttributeValue(styles, ';', ':');
node.setAttribute("style", styleAttrValue);
}
return this;
}
/**
* Adds the specified class(es) to each of the set of matched elements.
*/
public Jerry addClass(String... classNames) {
for (Node node : nodes) {
String attrClass = node.getAttribute("class");
Set<String> classes = createPropertiesSet(attrClass, ' ');
boolean wasChange = false;
for (String className : classNames) {
if (classes.add(className) == true) {
wasChange = true;
}
}
if (wasChange) {
String attrValue = generateAttributeValue(classes, ' ');
node.setAttribute("class", attrValue);
}
}
return this;
}
/**
* Determines whether any of the matched elements are assigned the given class.
*/
public boolean hasClass(String... classNames) {
for (Node node : nodes) {
String attrClass = node.getAttribute("class");
Set<String> classes = createPropertiesSet(attrClass, ' ');
for (String className : classNames) {
if (classes.contains(className)) {
return true;
}
}
}
return false;
}
/**
* Removes a single class, multiple classes, or all classes
* from each element in the set of matched elements.
*/
public Jerry removeClass(String... classNames) {
for (Node node : nodes) {
String attrClass = node.getAttribute("class");
Set<String> classes = createPropertiesSet(attrClass, ' ');
boolean wasChange = false;
for (String className : classNames) {
if (classes.remove(className) == true) {
wasChange = true;
}
}
if (wasChange) {
String attrValue = generateAttributeValue(classes, ' ');
node.setAttribute("class", attrValue);
}
}
return this;
}
/**
* Adds or remove one or more classes from each element in the set of
* matched elements, depending on either the class's presence or
* the value of the switch argument.
*/
public Jerry toggleClass(String... classNames) {
for (Node node : nodes) {
String attrClass = node.getAttribute("class");
Set<String> classes = createPropertiesSet(attrClass, ' ');
for (String className : classNames) {
if (classes.contains(className) == true) {
classes.remove(className);
} else {
classes.add(className);
}
}
String attrValue = generateAttributeValue(classes, ' ');
node.setAttribute("class", attrValue);
}
return this;
}
// ---------------------------------------------------------------- content
/**
* Gets the combined text contents of each element in the set of
* matched elements, including their descendants.
* Text is HTML decoded for text nodes.
*/
public String text() {
StringBuilder sb = new StringBuilder();
for (Node node : nodes) {
sb.append(node.getTextContent());
}
return sb.toString();
}
/**
* Sets the content of each element in the set of matched elements to the specified text.
*/
public Jerry text(String text) {
for (Node node : nodes) {
node.removeAllChilds();
Text textNode = new Text(node.getOwnerDocument(), text);
node.addChild(textNode);
}
return this;
}
/**
* Gets the HTML contents of the first element in the set of matched elements.
* Content is raw, not HTML decoded.
* @see #htmlAll(boolean)
*/
public String html() {
if (nodes.length == 0) {
return null;
}
return nodes[0].getInnerHtml();
}
/**
* Gets the combined HTML contents of each element in the set of
* matched elements, including their descendants.
* @see #html()
* @param setIncluded if <code>true</code> than sets node are included in the output
*/
public String htmlAll(boolean setIncluded) {
StringBuilder sb = new StringBuilder();
for (Node node : nodes) {
sb.append(setIncluded ? node.getHtml() : node.getInnerHtml());
}
return sb.toString();
}
/**
* Sets the HTML contents of each element in the set of matched elements.
*/
public Jerry html(String html) {
final Document doc = builder.parse(html);
for (Node node : nodes) {
node.removeAllChilds();
// clone to preserve for next iteration
// as nodes will be detached from parent
Document workingDoc = doc.clone();
node.addChild(workingDoc.getChildNodes());
}
return this;
}
// ---------------------------------------------------------------- DOM
/**
* Inserts content, specified by the parameter, to the end of each
* element in the set of matched elements.
*/
public Jerry append(String html) {
final Document doc = builder.parse(html);
for (Node node : nodes) {
Document workingDoc = doc.clone();
node.addChild(workingDoc.getChildNodes());
}
return this;
}
/**
* Inserts content, specified by the parameter, before each
* element in the set of matched elements.
*/
public Jerry before(String html) {
final Document doc = builder.parse(html);
for (Node node : nodes) {
Document workingDoc = doc.clone();
node.insertBefore(workingDoc.getChildNodes(), node);
}
return this;
}
/**
* Removes the set of matched elements from the DOM.
*/
public Jerry remove() {
for (Node node : nodes) {
node.detachFromParent();
}
return this;
}
/**
* Removes the set of matched elements from the DOM.
* Identical to {@link #remove()}.
*/
public Jerry detach() {
for (Node node : nodes) {
node.detachFromParent();
}
return this;
}
/**
* Removes all child nodes of the set of matched elements from the DOM.
*/
public Jerry empty() {
for (Node node : nodes) {
node.removeAllChilds();
}
return this;
}
// ---------------------------------------------------------------- wrap
/**
* Wraps an HTML structure around each element in the set of matched elements.
* Returns the original set of elements for chaining purposes.
*/
public Jerry wrap(String html) {
final Document doc = builder.parse(html);
for (Node node : nodes) {
Document workingDoc = doc.clone();
Node inmostNode = workingDoc;
while (inmostNode.hasChildNodes()) {
inmostNode = inmostNode.getFirstChild();
}
// replace
Node parent = node.getParentNode();
int index = node.getSiblingIndex();
inmostNode.addChild(node);
parent.insertChild(workingDoc.getFirstChild(), index);
}
return this;
}
// ---------------------------------------------------------------- iterator
/**
* Returns iterator over nodes contained in the Jerry object.
* Each node is wrapped. Similar to {@link #each(JerryFunction)}.
*/
public Iterator<Jerry> iterator() {
final Jerry jerry = this;
return new Iterator<Jerry>() {
private int index = 0;
public boolean hasNext() {
return index < jerry.nodes.length;
}
public Jerry next() {
Jerry nextJerry = new Jerry(jerry, jerry.get(index));
index++;
return nextJerry;
}
public void remove() {
throw new UnsupportedOperationException();
}
};
}
// ---------------------------------------------------------------- form
/**
* Processes all forms, collects all form parameters and calls back the
* {@link JerryFormHandler}.
*/
public Jerry form(String formCssSelector, JerryFormHandler jerryFormHandler) {
Jerry form = find(formCssSelector);
// process each form
for (Node node : form.nodes) {
Jerry singleForm = new Jerry(this, node);
final Map<String, String[]> parameters = new HashMap<String, String[]>();
// process all input elements
singleForm.$("input").each(new JerryFunction() {
public boolean onNode(Jerry $inputTag, int index) {
String type = $inputTag.attr("type");
boolean isCheckbox = type.equals("checkbox");
boolean isRadio = type.equals("radio");
if (isRadio || isCheckbox) {
if ($inputTag.nodes[0].hasAttribute("checked") == false) {
return true;
}
}
String name = $inputTag.attr("name");
if (name == null) {
return true;
}
String tagValue = $inputTag.attr("value");
if (tagValue == null) {
if (isCheckbox) {
tagValue = "on";
}
}
// add tag value
String[] value = parameters.get(name);
if (value == null) {
value = new String[] {tagValue};
} else {
value = ArraysUtil.append(value, tagValue);
}
parameters.put(name, value);
return true;
}
});
// process all select elements
singleForm.$("select").each(new JerryFunction() {
public boolean onNode(Jerry $selectTag, int index) {
final String name = $selectTag.attr("name");
$selectTag.$("option").each(new JerryFunction() {
public boolean onNode(Jerry $optionTag, int index) {
if ($optionTag.nodes[0].hasAttribute("selected")) {
String tagValue = $optionTag.attr("value");
// add tag value
String[] value = parameters.get(name);
if (value == null) {
value = new String[] {tagValue};
} else {
value = ArraysUtil.append(value, tagValue);
}
parameters.put(name, value);
}
return true;
}
});
return true;
}
});
// process all text areas
singleForm.$("textarea").each(new JerryFunction() {
public boolean onNode(Jerry $textarea, int index) {
String name = $textarea.attr("name");
String value = $textarea.text();
parameters.put(name, new String[] {value});
return true;
}
});
// done
jerryFormHandler.onForm(singleForm, parameters);
}
return this;
}
// ---------------------------------------------------------------- internal
protected Set<String> createPropertiesSet(String attrValue, char propertiesDelimiter) {
if (attrValue == null) {
return new LinkedHashSet<String>();
}
String[] properties = StringUtil.splitc(attrValue, propertiesDelimiter);
LinkedHashSet<String> set = new LinkedHashSet<String>(properties.length);
Collections.addAll(set, properties);
return set;
}
protected String generateAttributeValue(Set<String> set, char propertiesDelimiter) {
StringBuilder sb = new StringBuilder(set.size() * 16);
boolean first = true;
for (String entry : set) {
if (first == false) {
sb.append(propertiesDelimiter);
} else {
first = false;
}
sb.append(entry);
}
return sb.toString();
}
protected Map<String, String> createPropertiesMap(String attrValue, char propertiesDelimiter, char valueDelimiter) {
if (attrValue == null) {
return new LinkedHashMap<String, String>();
}
String[] properties = StringUtil.splitc(attrValue, propertiesDelimiter);
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>(properties.length);
for (String property : properties) {
int valueDelimiterIndex = property.indexOf(valueDelimiter);
if (valueDelimiterIndex != -1) {
String propertyName = property.substring(0, valueDelimiterIndex).trim();
String propertyValue = property.substring(valueDelimiterIndex + 1).trim();
map.put(propertyName, propertyValue);
}
}
return map;
}
protected String generateAttributeValue(Map<String, String> map, char propertiesDelimiter, char valueDelimiter) {
StringBuilder sb = new StringBuilder(map.size() * 32);
for (Map.Entry<String, String> entry : map.entrySet()) {
sb.append(entry.getKey());
sb.append(valueDelimiter);
sb.append(entry.getValue());
sb.append(propertiesDelimiter);
}
return sb.toString();
}
}
| |
/*
* Copyright 2016 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.j2cl.tools.minifier;
import static com.google.common.base.Preconditions.checkState;
import static com.google.common.collect.Iterables.getLast;
import static java.nio.charset.StandardCharsets.UTF_8;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multiset;
import com.google.j2cl.tools.rta.CodeRemovalInfo;
import com.google.j2cl.tools.rta.LineRange;
import com.google.j2cl.tools.rta.UnusedLines;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* A thread-safe, fast and pretty minifier/comment stripper for J2CL generated code.
*
* <p>Converts mangled J2CL names to minified (but still pretty and unique) versions and strips
* block comments (doing both these things while doing no AST construction and respecting the
* sanctity of strings).
*
* <p>The imagined use case for this minifier is to be part of fast concatenating uncompiled JS
* servers used as part of the development cycle. There is an expectation that because uncompiled
* and non-@JsType J2CL output is mangled that it might be large enough to slow down the browser as
* well as be difficult to directly read and this minifier addresses that problem. Callers should
* reuse the same minifier instance across multiple files to get consistent minification.
*
* <p>It is expected that minification opportunities will only be found in J2CL generated files
* (files ending in .java.js) since only such files should contain references to mangled J2CL names.
* So if some caller wants to optimize their minifier usage they might consider invoking it only on
* .java.js files.
*/
public class J2clMinifier {
private interface TransitionFunction {
void transition(Buffer buffer, char c);
}
private static class Buffer {
private final StringBuilder contentBuffer = new StringBuilder();
private int identifierStartIndex = -1;
private int whitespaceStartIndex = 0;
// We essentially want the ability to see if the last meaningful character we saw is something
// that is clearly a statement start semi-colon so we know that is not inside an expression.
// We could easily achive that by tracing back the characters but that is inefficient vs. our
// tracking here via append.
private int statementStartIndex = 0;
private boolean nextIsStatementStart = true;
void append(char c) {
int nextIndex = contentBuffer.length();
if (nextIsStatementStart) {
statementStartIndex = nextIndex;
nextIsStatementStart = false;
}
if (c == ' ') {
contentBuffer.append(c);
return; // Exit early since we don't want to increment the whiteSpaceStartIndex.
}
if (c == '\n') {
// Trim the trailing whitespace since it doesn't break sourcemaps.
nextIndex = trimTrailingWhitespace(nextIndex);
// Also move the statetementStartIndex to point new line if it was looking at the
// whitespace. This also simplifies the statement matches.
if (statementStartIndex == nextIndex) {
statementStartIndex = nextIndex + 1;
}
} else if (c == ';' || c == '{' || c == '}') {
// There are other ways to start statements but this is enough in the context of minifier.
nextIsStatementStart = true;
}
contentBuffer.append(c);
// The character that is placed in the buffer is not a whitespace, update whitespace index.
whitespaceStartIndex = nextIndex + 1;
}
private int trimTrailingWhitespace(int nextIndex) {
if (whitespaceStartIndex != nextIndex) {
// There are trailing whitespace characters, trim them.
nextIndex = whitespaceStartIndex;
contentBuffer.setLength(nextIndex);
}
return nextIndex;
}
void recordStartOfNewIdentifier() {
identifierStartIndex = contentBuffer.length();
}
String getIdentifier() {
return contentBuffer.substring(identifierStartIndex);
}
void replaceIdentifier(String newIdentifier) {
contentBuffer.replace(identifierStartIndex, contentBuffer.length(), newIdentifier);
identifierStartIndex = -1;
whitespaceStartIndex = contentBuffer.length();
}
boolean endOfStatement() {
return nextIsStatementStart;
}
int lastStatementIndexOf(String name) {
int index = contentBuffer.indexOf(name, statementStartIndex);
return index == -1 ? -1 : index - statementStartIndex;
}
Matcher matchLastStatement(Pattern pattern) {
return pattern.matcher(contentBuffer).region(statementStartIndex, contentBuffer.length());
}
void replaceStatement(String replacement) {
contentBuffer.replace(statementStartIndex, contentBuffer.length(), replacement);
statementStartIndex = contentBuffer.length();
whitespaceStartIndex = statementStartIndex;
}
@Override
public String toString() {
return contentBuffer.toString();
}
}
private static final String MINIFICATION_SEPARATOR = "_$";
// TODO(b/149248404): Remove zip handling.
private static final String ZIP_FILE_SEPARATOR = "!/";
private static final String JS_DIR_SEPARATOR = ".js/";
private static final int[][] nextState;
private static int numberOfStates = 0;
private static final int S_BLOCK_COMMENT = numberOfStates++;
private static final int S_DOUBLE_QUOTED_STRING = numberOfStates++;
private static final int S_DOUBLE_QUOTED_STRING_ESCAPE = numberOfStates++;
private static final int S_IDENTIFIER = numberOfStates++;
private static final int S_LINE_COMMENT = numberOfStates++;
private static final int S_SOURCE_MAP = numberOfStates++;
private static final int S_MAYBE_BLOCK_COMMENT_END = numberOfStates++;
private static final int S_MAYBE_COMMENT_START = numberOfStates++;
private static final int S_NON_IDENTIFIER = numberOfStates++;
private static final int S_SINGLE_QUOTED_STRING = numberOfStates++;
private static final int S_SINGLE_QUOTED_STRING_ESCAPE = numberOfStates++;
private static final int S_END_STATE = numberOfStates++;
static {
// Create and initialize state transitions table.
{
nextState = new int[numberOfStates][256];
setDefaultTransitions(S_NON_IDENTIFIER, S_NON_IDENTIFIER);
setIdentifierStartTransitions(S_NON_IDENTIFIER);
setCommentOrStringStartTransitions(S_NON_IDENTIFIER);
setDefaultTransitions(S_IDENTIFIER, S_NON_IDENTIFIER);
setIdentifierCharTransitions(S_IDENTIFIER, S_IDENTIFIER);
setCommentOrStringStartTransitions(S_IDENTIFIER);
setDefaultTransitions(S_MAYBE_COMMENT_START, S_NON_IDENTIFIER);
setIdentifierStartTransitions(S_MAYBE_COMMENT_START);
nextState[S_MAYBE_COMMENT_START]['/'] = S_LINE_COMMENT;
nextState[S_MAYBE_COMMENT_START]['*'] = S_BLOCK_COMMENT;
nextState[S_MAYBE_COMMENT_START]['\''] = S_SINGLE_QUOTED_STRING;
nextState[S_MAYBE_COMMENT_START]['"'] = S_DOUBLE_QUOTED_STRING;
setDefaultTransitions(S_LINE_COMMENT, S_LINE_COMMENT);
nextState[S_LINE_COMMENT]['\n'] = S_NON_IDENTIFIER;
// This is conservative since any # will preserve the line comment but it is safe and simple.
nextState[S_LINE_COMMENT]['#'] = S_SOURCE_MAP;
setDefaultTransitions(S_SOURCE_MAP, S_SOURCE_MAP);
nextState[S_SOURCE_MAP]['\n'] = S_NON_IDENTIFIER;
setDefaultTransitions(S_BLOCK_COMMENT, S_BLOCK_COMMENT);
nextState[S_BLOCK_COMMENT]['*'] = S_MAYBE_BLOCK_COMMENT_END;
setDefaultTransitions(S_MAYBE_BLOCK_COMMENT_END, S_BLOCK_COMMENT);
nextState[S_MAYBE_BLOCK_COMMENT_END]['/'] = S_NON_IDENTIFIER;
nextState[S_MAYBE_BLOCK_COMMENT_END]['*'] = S_MAYBE_BLOCK_COMMENT_END;
setDefaultTransitions(S_SINGLE_QUOTED_STRING, S_SINGLE_QUOTED_STRING);
nextState[S_SINGLE_QUOTED_STRING]['\\'] = S_SINGLE_QUOTED_STRING_ESCAPE;
nextState[S_SINGLE_QUOTED_STRING]['\''] = S_NON_IDENTIFIER;
setDefaultTransitions(S_DOUBLE_QUOTED_STRING, S_DOUBLE_QUOTED_STRING);
nextState[S_DOUBLE_QUOTED_STRING]['\\'] = S_DOUBLE_QUOTED_STRING_ESCAPE;
nextState[S_DOUBLE_QUOTED_STRING]['"'] = S_NON_IDENTIFIER;
setDefaultTransitions(S_SINGLE_QUOTED_STRING_ESCAPE, S_SINGLE_QUOTED_STRING);
setDefaultTransitions(S_DOUBLE_QUOTED_STRING_ESCAPE, S_DOUBLE_QUOTED_STRING);
}
}
public static boolean isJ2clFile(String filePath) {
return filePath.endsWith(".java.js");
}
private static String computePrettyIdentifier(String identifier) {
// Extract a simplified name to the form of <name> or static_<name> or _<name>
String simplifiedName = identifier.substring(1, identifier.indexOf("__"));
// Remove before underscore in the simplified name (if it exists).
return simplifiedName.substring(simplifiedName.indexOf('_') + 1);
}
private static boolean isIdentifierChar(char c) {
return c == '_'
|| c == '$'
|| (c >= '0' && c <= '9')
|| (c >= 'a' && c <= 'z')
|| (c >= 'A' && c <= 'Z');
}
// Note that the regular member form is the current shortest identifier style. (Please see the
// identifier forms described in #startsLikeJavaMangledName).
private static final int MIN_JAVA_IDENTIFIER_SIZE = "f_x__".length();
private static boolean isMinifiableIdentifier(String identifier) {
if (identifier.length() < MIN_JAVA_IDENTIFIER_SIZE) {
return false;
}
return startsLikeJavaMangledName(identifier) && identifier.contains("__");
}
private static boolean startsLikeJavaMangledName(String identifier) {
char firstChar = identifier.charAt(0);
char secondChar = identifier.charAt(1);
// Form of m_ or f_ (i.e. regular members).
if ((firstChar == 'm' || firstChar == 'f') && secondChar == '_') {
return true;
}
// Form of $create, $implements $static etc. (i.e. synthetic members)
if (firstChar == '$' && secondChar > 'a' && secondChar < 'z') {
return true;
}
return false;
}
private static void setDefaultTransitions(int currentState, int nextState) {
for (char c = 0; c < 256; c++) {
J2clMinifier.nextState[currentState][c] = nextState;
}
}
private static void setIdentifierStartTransitions(int currentState) {
setIdentifierCharTransitions(currentState, S_IDENTIFIER);
}
private static void setIdentifierCharTransitions(int currentState, int nextState) {
for (char c = 0; c < 256; c++) {
if (isIdentifierChar(c)) {
J2clMinifier.nextState[currentState][c] = nextState;
}
}
}
private static void setCommentOrStringStartTransitions(int currentState) {
nextState[currentState]['/'] = S_MAYBE_COMMENT_START;
nextState[currentState]['\''] = S_SINGLE_QUOTED_STRING;
nextState[currentState]['"'] = S_DOUBLE_QUOTED_STRING;
}
@SuppressWarnings("unused")
private static void skipChar(Buffer buffer, char c) {}
private static void skipCharUnlessNewLine(Buffer buffer, char c) {
if (c == '\n') {
writeChar(buffer, c);
}
}
private static void startNewIdentifier(Buffer buffer, char c) {
buffer.recordStartOfNewIdentifier();
writeChar(buffer, c);
}
private static void writeNonIdentifierCharOrReplace(Buffer buffer, char c) {
if (c != 0) {
writeChar(buffer, c);
}
if (buffer.endOfStatement()) {
maybeReplaceStatement(buffer);
}
}
private static final Pattern FIELD_STATEMENT = Pattern.compile(" *[\\w_$]+(\\.[\\w_$]+)+;");
private static final String MODULE_NAME = "['\"][\\w\\.$]+['\"]";
private static final Pattern GOOG_FORWARD_DECLARE =
Pattern.compile("((?:let|var) [\\w$]+) = goog.forwardDeclare\\(" + MODULE_NAME + "\\);");
private static final Pattern GOOG_REQUIRE =
Pattern.compile("goog.require\\(" + MODULE_NAME + "\\);");
private static void maybeReplaceStatement(Buffer buffer) {
// Unassigned field access is only useful for compiler.
Matcher m = buffer.matchLastStatement(FIELD_STATEMENT);
if (m.matches()) {
buffer.replaceStatement("");
return;
}
int index = buffer.lastStatementIndexOf("goog.");
if (index == -1) {
return;
}
if (index == 0) {
// Unassigned goog.require is only useful for compiler and bundling.
m = buffer.matchLastStatement(GOOG_REQUIRE);
if (m.matches()) {
buffer.replaceStatement("");
}
} else {
// goog.forwardDeclare is only useful for compiler except the variable declaration.
m = buffer.matchLastStatement(GOOG_FORWARD_DECLARE);
if (m.matches()) {
buffer.replaceStatement(m.group(1) + ";");
}
}
}
private static void writeChar(Buffer buffer, char c) {
buffer.append(c);
}
private static void writeSlash(Buffer buffer, @SuppressWarnings("unused") char c) {
writeChar(buffer, '/');
}
private static void writeSlashAndChar(Buffer buffer, char c) {
writeChar(buffer, '/');
writeChar(buffer, c);
}
private static void writeDoubleSlashAndChar(Buffer buffer, char c) {
writeChar(buffer, '/');
writeSlashAndChar(buffer, c);
}
private static void writeSlashAndStartNewIdentifier(Buffer buffer, char c) {
writeChar(buffer, '/');
startNewIdentifier(buffer, c);
}
private static void writeQuoteAndStartNewIdentifier(Buffer buffer, char c) {
writeChar(buffer, '\'');
buffer.recordStartOfNewIdentifier();
}
private static String extractFileKey(String fullPath) {
if (fullPath == null) {
return null;
}
// Because the mapping is done during transpilation and j2cl doesn't know the final path of
// the zip file, the key used is the path of the file inside the zip file.
String key = fullPath;
int keyStartIndex = fullPath.indexOf(ZIP_FILE_SEPARATOR);
if (keyStartIndex > 0) {
key = key.substring(keyStartIndex + ZIP_FILE_SEPARATOR.length());
} else {
keyStartIndex = fullPath.indexOf(JS_DIR_SEPARATOR);
if (keyStartIndex > 0) {
key = key.substring(keyStartIndex + JS_DIR_SEPARATOR.length());
}
}
return key;
}
/**
* These fields contain the persistent state that allows for name collision dodging and consistent
* renaming within and across multiple files.
*/
private final Multiset<String> countsByIdentifier = HashMultiset.create();
private final boolean minifierDisabled = Boolean.getBoolean("j2cl_minifier_disabled");
/** Set of file paths that are not used by the application. */
private ImmutableSet<String> unusedFiles;
/**
* Gives per file key the array of line indexes that can be stripped. If the index of the line
* being scanned is out of bounds of the array, it means the line is used. Otherwise the boolean
* stored at the index in the array indicates if the line is used or not.
*/
// We choose to use a boolean[] instead of the usual recommended Map<> or Set<> data structure for
// performance purpose. Please do not change that instead you measure your change doesn't impact
// the performance.
private Map<String, boolean[]> unusedLinesPerFile;
/**
* This is a cache of previously minified content (presumably whole files). This makes reloads in
* fast concatenating uncompiled JS servers extra-extra fast.
*/
private final Map<String, String> minifiedContentByContent = new Hashtable<>();
private final TransitionFunction[][] transFn;
@VisibleForTesting Map<String, String> minifiedIdentifiersByIdentifier = new HashMap<>();
public J2clMinifier() {
this(null);
}
public J2clMinifier(String codeRemovalFilePath) {
// TODO(goktug): Rename to j2cl_rta_pruning_manifest
codeRemovalFilePath =
System.getProperty("j2cl_rta_removal_code_info_file", codeRemovalFilePath);
setupRtaCodeRemoval(readCodeRemovalInfoFile(codeRemovalFilePath));
transFn = new TransitionFunction[numberOfStates][numberOfStates];
transFn[S_NON_IDENTIFIER][S_IDENTIFIER] = J2clMinifier::startNewIdentifier;
transFn[S_NON_IDENTIFIER][S_NON_IDENTIFIER] = J2clMinifier::writeNonIdentifierCharOrReplace;
transFn[S_NON_IDENTIFIER][S_MAYBE_COMMENT_START] = J2clMinifier::skipChar;
transFn[S_NON_IDENTIFIER][S_SINGLE_QUOTED_STRING] =
J2clMinifier::writeQuoteAndStartNewIdentifier;
transFn[S_NON_IDENTIFIER][S_DOUBLE_QUOTED_STRING] = J2clMinifier::writeChar;
transFn[S_NON_IDENTIFIER][S_END_STATE] = J2clMinifier::writeNonIdentifierCharOrReplace;
transFn[S_IDENTIFIER][S_IDENTIFIER] = J2clMinifier::writeChar;
transFn[S_IDENTIFIER][S_NON_IDENTIFIER] = this::maybeReplaceIdentifierAndWriteNonIdentifier;
transFn[S_IDENTIFIER][S_MAYBE_COMMENT_START] = this::maybeReplaceIdentifier;
transFn[S_IDENTIFIER][S_SINGLE_QUOTED_STRING] = this::maybeReplaceIdentifierAndWriteChar;
transFn[S_IDENTIFIER][S_DOUBLE_QUOTED_STRING] = this::maybeReplaceIdentifierAndWriteChar;
transFn[S_IDENTIFIER][S_END_STATE] = this::maybeReplaceIdentifier;
transFn[S_MAYBE_COMMENT_START][S_IDENTIFIER] = J2clMinifier::writeSlashAndStartNewIdentifier;
transFn[S_MAYBE_COMMENT_START][S_MAYBE_COMMENT_START] = J2clMinifier::writeChar;
transFn[S_MAYBE_COMMENT_START][S_LINE_COMMENT] = J2clMinifier::skipChar;
transFn[S_MAYBE_COMMENT_START][S_BLOCK_COMMENT] = J2clMinifier::skipChar;
transFn[S_MAYBE_COMMENT_START][S_NON_IDENTIFIER] = J2clMinifier::writeSlashAndChar;
// Note that this is potential String start and we might choose to handle identifiers here.
// However it is not worthwhile and keeping String identifier replacement conservative is good
// idea for our very limited use cases.
transFn[S_MAYBE_COMMENT_START][S_SINGLE_QUOTED_STRING] = J2clMinifier::writeSlashAndChar;
transFn[S_MAYBE_COMMENT_START][S_DOUBLE_QUOTED_STRING] = J2clMinifier::writeSlashAndChar;
transFn[S_MAYBE_COMMENT_START][S_END_STATE] = J2clMinifier::writeSlash;
transFn[S_LINE_COMMENT][S_LINE_COMMENT] = J2clMinifier::skipChar;
transFn[S_LINE_COMMENT][S_SOURCE_MAP] = J2clMinifier::writeDoubleSlashAndChar;
transFn[S_LINE_COMMENT][S_NON_IDENTIFIER] = J2clMinifier::writeChar;
transFn[S_LINE_COMMENT][S_END_STATE] = J2clMinifier::skipChar;
transFn[S_SOURCE_MAP][S_SOURCE_MAP] = J2clMinifier::writeChar;
transFn[S_SOURCE_MAP][S_NON_IDENTIFIER] = J2clMinifier::writeChar;
transFn[S_SOURCE_MAP][S_END_STATE] = J2clMinifier::skipChar;
transFn[S_BLOCK_COMMENT][S_BLOCK_COMMENT] = J2clMinifier::skipCharUnlessNewLine;
transFn[S_BLOCK_COMMENT][S_MAYBE_BLOCK_COMMENT_END] = J2clMinifier::skipCharUnlessNewLine;
transFn[S_BLOCK_COMMENT][S_END_STATE] = J2clMinifier::skipChar;
transFn[S_MAYBE_BLOCK_COMMENT_END][S_BLOCK_COMMENT] = J2clMinifier::skipCharUnlessNewLine;
transFn[S_MAYBE_BLOCK_COMMENT_END][S_NON_IDENTIFIER] = J2clMinifier::skipChar;
transFn[S_MAYBE_BLOCK_COMMENT_END][S_MAYBE_BLOCK_COMMENT_END] = J2clMinifier::skipChar;
transFn[S_MAYBE_BLOCK_COMMENT_END][S_END_STATE] = J2clMinifier::skipChar;
transFn[S_SINGLE_QUOTED_STRING][S_SINGLE_QUOTED_STRING] = J2clMinifier::writeChar;
transFn[S_SINGLE_QUOTED_STRING][S_SINGLE_QUOTED_STRING_ESCAPE] = J2clMinifier::writeChar;
transFn[S_SINGLE_QUOTED_STRING][S_NON_IDENTIFIER] =
this::maybeReplaceIdentifierAndWriteNonIdentifier;
transFn[S_SINGLE_QUOTED_STRING][S_END_STATE] = J2clMinifier::skipChar;
transFn[S_DOUBLE_QUOTED_STRING][S_DOUBLE_QUOTED_STRING] = J2clMinifier::writeChar;
transFn[S_DOUBLE_QUOTED_STRING][S_DOUBLE_QUOTED_STRING_ESCAPE] = J2clMinifier::writeChar;
transFn[S_DOUBLE_QUOTED_STRING][S_NON_IDENTIFIER] = J2clMinifier::writeChar;
transFn[S_DOUBLE_QUOTED_STRING][S_END_STATE] = J2clMinifier::skipChar;
transFn[S_SINGLE_QUOTED_STRING_ESCAPE][S_SINGLE_QUOTED_STRING] = J2clMinifier::writeChar;
transFn[S_SINGLE_QUOTED_STRING_ESCAPE][S_END_STATE] = J2clMinifier::skipChar;
transFn[S_DOUBLE_QUOTED_STRING_ESCAPE][S_DOUBLE_QUOTED_STRING] = J2clMinifier::writeChar;
transFn[S_DOUBLE_QUOTED_STRING_ESCAPE][S_END_STATE] = J2clMinifier::skipChar;
}
/**
* Process the content of a file for converting mangled J2CL names to minified (but still pretty
* and unique) versions and strips block comments.
*/
public String minify(String content) {
return minify(/* filePath= */ null, content);
}
/**
* Process the content of a file for converting mangled J2CL names to minified (but still pretty
* and unique) versions and strips block comments.
*/
public String minify(String filePath, String content) {
if (minifierDisabled) {
return content;
}
String fileKey = extractFileKey(filePath);
// early exit if the file need to be removed entirely
if (unusedFiles.contains(fileKey)) {
// TODO(dramaix): please document that minifier can completely remove the content of a file
// when RTA is not experimental anymore.
return "";
}
// Return a previously cached version of minified output, if possible.
String minifiedContent = minifiedContentByContent.get(content);
if (minifiedContent != null) {
return minifiedContent;
}
boolean[] unusedLines = unusedLinesPerFile.get(fileKey);
Buffer buffer = new Buffer();
int lastParseState = S_NON_IDENTIFIER;
int lineNumber = 0;
boolean skippingLine = unusedLines != null && unusedLines[lineNumber];
/**
* Loop over the chars in the content, keeping track of in/not-in identifier state, copying
* non-identifier chars immediately and accumulating identifiers chars for minifying and copying
* when the identifier ends.
*/
for (int i = 0; i < content.length(); i++) {
char c = content.charAt(i);
// Skip unused lines if necessary. Any unused line should not effect the state machine.
if (unusedLines != null) {
if (c == '\n') {
lineNumber++;
skippingLine = unusedLines.length > lineNumber && unusedLines[lineNumber];
} else if (skippingLine) {
continue;
}
}
int parseState = nextState[lastParseState][c < 256 ? c : 0];
transFn[lastParseState][parseState].transition(buffer, c);
lastParseState = parseState;
}
// if we used RTA to remove lines, ensure that we removed everything expected by RTA.
checkState(unusedLines == null || lineNumber >= unusedLines.length - 1);
// Transition to the end state
transFn[lastParseState][S_END_STATE].transition(buffer, (char) 0);
minifiedContent = buffer.toString();
// Update the minified content cache for next time.
minifiedContentByContent.put(content, minifiedContent);
return minifiedContent;
}
/**
* The minifier might be used from multiple threads so make sure that this function (which along
* with the makeUnique function, which is also only called from here, is the only place that
* mutates class state) is synchronized.
*/
private synchronized String getMinifiedIdentifier(String identifier) {
if (minifiedIdentifiersByIdentifier.containsKey(identifier)) {
return minifiedIdentifiersByIdentifier.get(identifier);
}
String prettyIdentifier = computePrettyIdentifier(identifier);
if (prettyIdentifier.isEmpty()) {
// The identifier must contain something strange like triple _'s. Leave the whole thing alone
// just to be safe.
minifiedIdentifiersByIdentifier.put(identifier, identifier);
return identifier;
}
String uniquePrettyIdentifier = makeUnique(prettyIdentifier);
minifiedIdentifiersByIdentifier.put(identifier, uniquePrettyIdentifier);
return uniquePrettyIdentifier;
}
private String makeUnique(String identifier) {
int count = countsByIdentifier.add(identifier, 1) + 1;
return identifier + MINIFICATION_SEPARATOR + count;
}
private void maybeReplaceIdentifier(Buffer buffer, @SuppressWarnings("unused") char c) {
String identifier = buffer.getIdentifier();
if (isMinifiableIdentifier(identifier)) {
buffer.replaceIdentifier(getMinifiedIdentifier(identifier));
}
}
private void maybeReplaceIdentifierAndWriteChar(Buffer buffer, char c) {
maybeReplaceIdentifier(buffer, c);
writeChar(buffer, c);
}
private void maybeReplaceIdentifierAndWriteNonIdentifier(Buffer buffer, char c) {
maybeReplaceIdentifier(buffer, c);
writeNonIdentifierCharOrReplace(buffer, c);
}
private static CodeRemovalInfo readCodeRemovalInfoFile(String codeRemovalInfoFilePath) {
if (codeRemovalInfoFilePath == null) {
return null;
}
try (InputStream inputStream = new FileInputStream(codeRemovalInfoFilePath)) {
return CodeRemovalInfo.parseFrom(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@VisibleForTesting
void setupRtaCodeRemoval(CodeRemovalInfo codeRemovalInfo) {
if (codeRemovalInfo != null) {
unusedFiles = ImmutableSet.copyOf(codeRemovalInfo.getUnusedFilesList());
unusedLinesPerFile = createUnusedLinesPerFileMap(codeRemovalInfo);
} else {
unusedFiles = ImmutableSet.of();
unusedLinesPerFile = ImmutableMap.of();
}
}
private static Map<String, boolean[]> createUnusedLinesPerFileMap(
CodeRemovalInfo codeRemovalInfo) {
Map<String, boolean[]> unusedLinesPerFile = new HashMap<>();
for (UnusedLines unusedLines : codeRemovalInfo.getUnusedLinesList()) {
checkState(!unusedLines.getUnusedRangesList().isEmpty());
// UnusedRangesList is sorted and the last item is the highest line index to remove.
// Note that getLineEnd returns an exclusive index and can be used as length of the array.
int lastUnusedLine = getLast(unusedLines.getUnusedRangesList()).getLineEnd();
boolean[] unusedLinesArray = new boolean[lastUnusedLine];
for (LineRange lineRange : unusedLines.getUnusedRangesList()) {
Arrays.fill(unusedLinesArray, lineRange.getLineStart(), lineRange.getLineEnd(), true);
}
unusedLinesPerFile.put(unusedLines.getFileKey(), unusedLinesArray);
}
return unusedLinesPerFile;
}
/**
* Entry point to the minifier standalone binary.
*
* <p>Usage: minifier file-to-minifiy.js
*
* <p>Outputs results to stdout.
*/
public static void main(String... args) throws IOException {
checkState(args.length == 1, "Provide a input file to minify");
String file = args[0];
String contents = new String(Files.readAllBytes(Paths.get(file)), UTF_8);
System.out.println(new J2clMinifier().minify(file, contents));
}
}
| |
/* Copyright 2017 Telstra Open Source
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.openkilda.atdd;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import cucumber.api.PendingException;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.openkilda.LinksUtils;
import org.openkilda.SwitchesUtils;
import org.openkilda.messaging.info.event.IslChangeType;
import org.openkilda.messaging.info.event.IslInfoData;
import org.openkilda.messaging.info.event.PathNode;
import org.openkilda.messaging.info.event.SwitchInfoData;
import org.openkilda.messaging.info.event.SwitchState;
import org.openkilda.topo.builders.TestTopologyBuilder;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
/**
* Created by carmine on 5/1/17.
*/
public class TopologyEventsBasicTest {
@When("^multiple links exist between all switches$")
public void multiple_links_exist_between_all_switches() throws Exception {
List<String> switchIds = IntStream.range(1, 6)
.mapToObj(TestTopologyBuilder::intToSwitchId)
.collect(Collectors.toList());
assertTrue("Switches should have multiple links",
getSwitchesWithoutMultipleLinks(switchIds).isEmpty());
}
private List<String> getSwitchesWithoutMultipleLinks(List<String> switches) throws Exception {
List<IslInfoData> links = LinksUtils.dumpLinks();
return switches.stream()
.filter(sw -> isSwitchHasLessThanTwoLinks(sw, links))
.collect(Collectors.toList());
}
@When("^a link is dropped in the middle$")
public void a_link_is_dropped_in_the_middle() throws Exception {
List<IslInfoData> links = LinksUtils.dumpLinks();
IslInfoData middleLink = getMiddleLink(links);
PathNode node = middleLink.getPath().get(0);
assertTrue(LinksUtils.islFail(getSwitchName(node.getSwitchId()), String.valueOf(node.getPortNo())));
}
@Then("^the link will have no health checks$")
public void the_link_will_have_no_health_checks() throws Exception {
List<IslInfoData> links = LinksUtils.dumpLinks();
List<IslInfoData> cutLinks = links.stream()
.filter(isl -> isl.getState() != IslChangeType.DISCOVERED)
.collect(Collectors.toList());
assertFalse("Link should be cut", cutLinks.isEmpty());
assertThat("Only one link should be cut", cutLinks.size(), is(1));
}
@Then("^the link disappears from the topology engine\\.$")
public void the_link_disappears_from_the_topology_engine() throws Exception {
List<IslInfoData> links = LinksUtils.dumpLinks();
}
@When("^a link is added in the middle$")
public void a_link_is_added_in_the_middle() throws Exception {
List<IslInfoData> links = LinksUtils.dumpLinks();
IslInfoData middleLink = getMiddleLink(links);
String srcSwitch = getSwitchName(middleLink.getPath().get(0).getSwitchId());
String dstSwitch = getSwitchName(middleLink.getPath().get(1).getSwitchId());
assertTrue("Link is not added", LinksUtils.addLink(srcSwitch, dstSwitch));
TimeUnit.SECONDS.sleep(2);
}
@Then("^the link will have health checks$")
public void the_link_will_have_health_checks() throws Exception {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Then("^the link appears in the topology engine\\.$")
public void the_link_appears_in_the_topology_engine() throws Exception {
List<IslInfoData> links = LinksUtils.dumpLinks();
assertThat("Amount of links should be 18 (initial 16 and 2 newly created)", links.size(), is(18));
}
@When("^a switch is dropped in the middle$")
public void a_switch_is_dropped_in_the_middle() throws Exception {
List<SwitchInfoData> switches = SwitchesUtils.dumpSwitches();
SwitchInfoData middleSwitch = getMiddleSwitch(switches);
assertTrue("Should successfully knockout switch",
SwitchesUtils.knockoutSwitch(getSwitchName(middleSwitch.getSwitchId())));
TimeUnit.SECONDS.sleep(1);
List<SwitchInfoData> updatedSwitches = SwitchesUtils.dumpSwitches();
SwitchInfoData deactivatedSwitch = updatedSwitches.stream()
.filter(sw -> sw.getSwitchId().equalsIgnoreCase(middleSwitch.getSwitchId()))
.findFirst().orElseThrow(() -> new IllegalStateException("Switch should exist"));
assertThat(deactivatedSwitch.getState(), is(SwitchState.DEACTIVATED));
}
@Then("^all links through the dropped switch will have no health checks$")
public void all_links_through_the_dropped_switch_will_have_no_health_checks() throws Exception {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Then("^the links disappear from the topology engine\\.$")
public void the_links_disappear_from_the_topology_engine() throws Exception {
//todo check whether we need to wait until links will disappear or we might delete them instantly when switch goes down
TimeUnit.SECONDS.sleep(15);
final SwitchInfoData middleSwitch = getMiddleSwitch(SwitchesUtils.dumpSwitches());
final List<IslInfoData> links = LinksUtils.dumpLinks();
List<IslInfoData> switchLinks = links.stream()
.filter(isl -> isLinkBelongToSwitch(middleSwitch.getSwitchId(), isl))
.filter(isl -> isl.getState() == IslChangeType.DISCOVERED)
.collect(Collectors.toList());
assertTrue("Switch shouldn't have any active links", switchLinks.isEmpty());
}
@Then("^the switch disappears from the topology engine\\.$")
public void the_switch_disappears_from_the_topology_engine() throws Exception {
List<SwitchInfoData> switches = SwitchesUtils.dumpSwitches();
SwitchInfoData middleSwitch = getMiddleSwitch(switches);
//right now switch doesn't disappear in neo4j - we just update status
assertThat(middleSwitch.getState(), is(SwitchState.DEACTIVATED));
}
@When("^a switch is added at the edge$")
public void a_switch_is_added_at_the_edge() throws Exception {
assertTrue("Should add switch to mininet topology",
SwitchesUtils.addSwitch("01010001", "DEADBEEF01010001"));
TimeUnit.SECONDS.sleep(1);
}
@When("^links are added between the new switch and its neighbor$")
public void links_are_added_between_the_new_switch_and_its_neighbor() throws Exception {
List<IslInfoData> links = LinksUtils.dumpLinks();
List<SwitchInfoData> switches = SwitchesUtils.dumpSwitches();
SwitchInfoData switchWithoutLinks = switches.stream()
.filter(sw -> links.stream()
.anyMatch(isl -> isLinkBelongToSwitch(sw.getSwitchId(), isl)))
.findAny()
.orElseThrow(() -> new IllegalStateException("At least one switch should exist"));
SwitchInfoData latestConnectedSwitch = switches.stream()
.sorted(Comparator.comparing(SwitchInfoData::getSwitchId).reversed())
.findFirst().get();
assertTrue(LinksUtils.addLink(getSwitchName(switchWithoutLinks.getSwitchId()),
getSwitchName(latestConnectedSwitch.getSwitchId())));
assertTrue(LinksUtils.addLink(getSwitchName(switchWithoutLinks.getSwitchId()),
getSwitchName(latestConnectedSwitch.getSwitchId())));
TimeUnit.SECONDS.sleep(1);
}
@Then("^all links through the added switch will have health checks$")
public void all_links_through_the_added_switch_will_have_health_checks() throws Exception {
// Write code here that turns the phrase above into concrete actions
throw new PendingException();
}
@Then("^now amount of switches is (\\d+)\\.$")
public void the_switch_appears_in_the_topology_engine(int switches) throws Exception {
List<SwitchInfoData> switchList = SwitchesUtils.dumpSwitches();
List<SwitchInfoData> activeSwitches = switchList.stream()
.filter(sw -> sw.getState() == SwitchState.ACTIVATED)
.collect(Collectors.toList());
assertThat("Switch should disappear from neo4j", activeSwitches.size(), is(switches));
}
private boolean isSwitchHasLessThanTwoLinks(String switchId, List<IslInfoData> links) {
int inputsAmount = 0;
int outputsAmount = 0;
for (IslInfoData isl : links) {
for (PathNode node : isl.getPath()) {
if (switchId.equalsIgnoreCase(node.getSwitchId())) {
if (node.getSeqId() == 0) {
outputsAmount++;
} else if (node.getSeqId() == 1) {
inputsAmount++;
}
}
}
}
//check whether switch has more than one link in both direction (sequence id 0 and 1)
return inputsAmount <= NumberUtils.INTEGER_ONE && outputsAmount <= NumberUtils.INTEGER_ONE;
}
private IslInfoData getMiddleLink(List<IslInfoData> links) {
return links.stream()
.sorted(Comparator.comparing((isl) -> isl.getPath().get(0).getSwitchId()))
.collect(Collectors.toList())
.get((links.size() / 2) + 1);
}
private SwitchInfoData getMiddleSwitch(List<SwitchInfoData> switches) {
return switches.stream()
.sorted(Comparator.comparing(SwitchInfoData::getSwitchId))
.collect(Collectors.toList())
.get(switches.size() / 2);
}
private String getSwitchName(String switchId) {
return switchId.replaceAll("[^\\d]", StringUtils.EMPTY);
}
private boolean isLinkBelongToSwitch(String switchId, IslInfoData isl) {
return switchId.equalsIgnoreCase(isl.getPath().get(0).getSwitchId())
|| switchId.equalsIgnoreCase(isl.getPath().get(1).getSwitchId());
}
}
| |
package carbon.widget;
import android.content.Context;
import android.content.res.ColorStateList;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewParent;
import com.nineoldandroids.animation.Animator;
import com.nineoldandroids.animation.AnimatorListenerAdapter;
import com.nineoldandroids.animation.ValueAnimator;
import java.util.ArrayList;
import java.util.List;
import carbon.Carbon;
import carbon.R;
import carbon.animation.AnimUtils;
import carbon.animation.AnimatedView;
import carbon.animation.StateAnimator;
import carbon.drawable.ControlFocusedColorStateList;
import carbon.drawable.EmptyDrawable;
import carbon.drawable.RippleDrawable;
import carbon.drawable.RippleView;
/**
* Created by Marcin on 2015-06-25.
*/
public class SeekBar extends View implements RippleView, carbon.animation.StateAnimatorView, AnimatedView, TintedView {
float value = 1.0f;
float min, max, step;
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
private int colorControl;
public SeekBar(Context context) {
this(context, null);
}
public SeekBar(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.seekBarStyle);
}
public SeekBar(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(attrs, defStyle);
}
private void init(AttributeSet attrs, int defStyleAttr) {
if (isInEditMode())
return;
Resources.Theme theme = getContext().getTheme();
TypedValue typedvalueattr = new TypedValue();
theme.resolveAttribute(R.attr.colorControlNormal, typedvalueattr, true);
colorControl = typedvalueattr.resourceId != 0 ? getContext().getResources().getColor(typedvalueattr.resourceId) : typedvalueattr.data;
Carbon.initAnimations(this, attrs, defStyleAttr);
Carbon.initTint(this, attrs, defStyleAttr);
Carbon.initRippleDrawable(this, attrs, defStyleAttr);
setFocusableInTouchMode(false); // TODO: from theme
}
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (!changed)
return;
if (getWidth() == 0 || getHeight() == 0)
return;
if (rippleDrawable != null)
rippleDrawable.setBounds(0, 0, getWidth(), getHeight());
}
@Override
public void draw(@NonNull Canvas canvas) {
super.draw(canvas);
float thumbRadius = Carbon.getDip(getContext()) * 12;
int thumbX = (int) (value * (getWidth() - getPaddingLeft() - getPaddingRight() - thumbRadius * 2) + getPaddingLeft() + thumbRadius);
int thumbY = getHeight() / 2;
paint.setStrokeWidth(Carbon.getDip(getContext()) * 2);
if (!isInEditMode())
paint.setColor(tint.getColorForState(getDrawableState(), tint.getDefaultColor()));
canvas.drawCircle(thumbX, thumbY, thumbRadius, paint);
if (getPaddingLeft() + thumbRadius < thumbX - thumbRadius)
canvas.drawLine(getPaddingLeft() + thumbRadius, thumbY, thumbX - thumbRadius, thumbY, paint);
paint.setColor(colorControl);
if (thumbX + thumbRadius < getWidth() - getPaddingLeft() - thumbRadius)
canvas.drawLine(thumbX + thumbRadius, thumbY, getWidth() - getPaddingLeft() - thumbRadius, thumbY, paint);
canvas.save(Canvas.MATRIX_SAVE_FLAG);
canvas.translate(thumbX - thumbRadius * 1.5f, thumbY - thumbRadius * 1.5f);
if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Over)
rippleDrawable.draw(canvas);
canvas.restore();
}
// -------------------------------
// ripple
// -------------------------------
private RippleDrawable rippleDrawable;
private EmptyDrawable emptyBackground = new EmptyDrawable();
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
ViewParent parent = getParent();
if(parent!=null)
parent.requestDisallowInterceptTouchEvent(true);
} else if (event.getAction() == MotionEvent.ACTION_CANCEL || event.getAction() == MotionEvent.ACTION_UP) {
ViewParent parent = getParent();
if(parent!=null)
parent.requestDisallowInterceptTouchEvent(false);
}
float thumbRadius = Carbon.getDip(getContext()) * 12;
value = (event.getX() - getPaddingLeft() - thumbRadius) / (getWidth() - getPaddingLeft() - getPaddingRight() - thumbRadius * 2);
value = Math.max(0, Math.min(value, 1));
postInvalidate();
if (rippleDrawable != null) {
int thumbX = (int) (value * (getWidth() - getPaddingLeft() - getPaddingRight() - thumbRadius * 2) + getPaddingLeft() + thumbRadius);
int thumbY = getHeight() / 2;
float rippleRadius = Carbon.getDip(getContext()) * 15;
rippleDrawable.setBounds((int) (thumbX - rippleRadius), (int) (thumbY - rippleRadius), (int) (thumbX + rippleRadius), (int) (thumbY + rippleRadius));
}
if (rippleDrawable != null)
rippleDrawable.setHotspot(event.getX(), event.getY());
return true;
}
@Override
public RippleDrawable getRippleDrawable() {
return rippleDrawable;
}
public void setRippleDrawable(RippleDrawable newRipple) {
if (rippleDrawable != null) {
rippleDrawable.setCallback(null);
if (rippleDrawable.getStyle() == RippleDrawable.Style.Background)
super.setBackgroundDrawable(rippleDrawable.getBackground() == null ? emptyBackground : rippleDrawable.getBackground());
}
if (newRipple != null) {
newRipple.setCallback(this);
if (newRipple.getStyle() == RippleDrawable.Style.Background) {
super.setBackgroundDrawable((Drawable) newRipple);
}
}
rippleDrawable = newRipple;
}
@Override
protected boolean verifyDrawable(Drawable who) {
return super.verifyDrawable(who) || rippleDrawable == who;
}
@Override
public void invalidateDrawable(@NonNull Drawable drawable) {
super.invalidateDrawable(drawable);
if (getParent() == null || !(getParent() instanceof View))
return;
if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Borderless)
((View) getParent()).invalidate();
}
@Override
public void invalidate(@NonNull Rect dirty) {
super.invalidate(dirty);
if (getParent() == null || !(getParent() instanceof View))
return;
if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Borderless)
((View) getParent()).invalidate(dirty);
}
@Override
public void invalidate(int l, int t, int r, int b) {
super.invalidate(l, t, r, b);
if (getParent() == null || !(getParent() instanceof View))
return;
if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Borderless)
((View) getParent()).invalidate(l, t, r, b);
}
@Override
public void invalidate() {
super.invalidate();
if (getParent() == null || !(getParent() instanceof View))
return;
if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Borderless)
((View) getParent()).invalidate();
}
@Override
public void postInvalidateDelayed(long delayMilliseconds) {
super.postInvalidateDelayed(delayMilliseconds);
if (getParent() == null || !(getParent() instanceof View))
return;
if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Borderless)
((View) getParent()).postInvalidateDelayed(delayMilliseconds);
}
@Override
public void postInvalidateDelayed(long delayMilliseconds, int left, int top, int right, int bottom) {
super.postInvalidateDelayed(delayMilliseconds, left, top, right, bottom);
if (getParent() == null || !(getParent() instanceof View))
return;
if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Borderless)
((View) getParent()).postInvalidateDelayed(delayMilliseconds, left, top, right, bottom);
}
@Override
public void postInvalidate() {
super.postInvalidate();
if (getParent() == null || !(getParent() instanceof View))
return;
if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Borderless)
((View) getParent()).postInvalidate();
}
@Override
public void postInvalidate(int left, int top, int right, int bottom) {
super.postInvalidate(left, top, right, bottom);
if (getParent() == null || !(getParent() instanceof View))
return;
if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Borderless)
((View) getParent()).postInvalidate(left, top, right, bottom);
}
@Override
public void setBackground(Drawable background) {
setBackgroundDrawable(background);
}
@Override
public void setBackgroundDrawable(Drawable background) {
if (background instanceof RippleDrawable) {
setRippleDrawable((RippleDrawable) background);
return;
}
if (rippleDrawable != null && rippleDrawable.getStyle() == RippleDrawable.Style.Background) {
rippleDrawable.setCallback(null);
rippleDrawable = null;
}
super.setBackgroundDrawable(background == null ? emptyBackground : background);
}
// -------------------------------
// state animators
// -------------------------------
private List<StateAnimator> stateAnimators = new ArrayList<>();
public void removeStateAnimator(StateAnimator animator) {
stateAnimators.remove(animator);
}
public void addStateAnimator(StateAnimator animator) {
this.stateAnimators.add(animator);
}
@Override
protected void drawableStateChanged() {
super.drawableStateChanged();
if (rippleDrawable != null && rippleDrawable.getStyle() != RippleDrawable.Style.Background)
rippleDrawable.setState(getDrawableState());
if (stateAnimators != null)
for (StateAnimator animator : stateAnimators)
animator.stateChanged(getDrawableState());
}
// -------------------------------
// animations
// -------------------------------
private AnimUtils.Style inAnim, outAnim;
private Animator animator;
public void setVisibility(final int visibility) {
if (visibility == View.VISIBLE && (getVisibility() != View.VISIBLE || animator != null)) {
if (animator != null)
animator.cancel();
if (inAnim != AnimUtils.Style.None) {
animator = AnimUtils.animateIn(this, inAnim, new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator a) {
animator = null;
}
});
}
super.setVisibility(visibility);
} else if (visibility != View.VISIBLE && (getVisibility() == View.VISIBLE || animator != null)) {
if (animator != null)
animator.cancel();
if (outAnim == AnimUtils.Style.None) {
super.setVisibility(visibility);
return;
}
animator = AnimUtils.animateOut(this, outAnim, new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator a) {
if (((ValueAnimator) a).getAnimatedFraction() == 1)
SeekBar.super.setVisibility(visibility);
animator = null;
}
});
}
}
public void setVisibilityImmediate(final int visibility) {
super.setVisibility(visibility);
}
public Animator getAnimator() {
return animator;
}
public AnimUtils.Style getOutAnimation() {
return outAnim;
}
public void setOutAnimation(AnimUtils.Style outAnim) {
this.outAnim = outAnim;
}
public AnimUtils.Style getInAnimation() {
return inAnim;
}
public void setInAnimation(AnimUtils.Style inAnim) {
this.inAnim = inAnim;
}
// -------------------------------
// tint
// -------------------------------
ColorStateList tint;
@Override
public void setTint(ColorStateList list) {
this.tint = list != null ? list : new ControlFocusedColorStateList(getContext());
}
@Override
public void setTint(int color) {
setTint(ColorStateList.valueOf(color));
}
@Override
public ColorStateList getTint() {
return tint;
}
}
| |
/*
* Copyright (c) 2010-2015 Evolveum
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.evolveum.polygon.connector.liferay;
import com.evolveum.polygon.connector.liferay.contact.ContactServiceSoap;
import com.evolveum.polygon.connector.liferay.contact.ContactServiceSoapServiceLocator;
import com.evolveum.polygon.connector.liferay.contact.ContactSoap;
import com.evolveum.polygon.connector.liferay.expandovalue.ExpandoValueServiceSoap;
import com.evolveum.polygon.connector.liferay.expandovalue.ExpandoValueServiceSoapServiceLocator;
import com.evolveum.polygon.connector.liferay.group.GroupServiceSoap;
import com.evolveum.polygon.connector.liferay.group.GroupServiceSoapServiceLocator;
import com.evolveum.polygon.connector.liferay.group.GroupSoap;
import com.evolveum.polygon.connector.liferay.organization.OrganizationServiceSoap;
import com.evolveum.polygon.connector.liferay.organization.OrganizationServiceSoapServiceLocator;
import com.evolveum.polygon.connector.liferay.organization.OrganizationSoap;
import com.evolveum.polygon.connector.liferay.role.RoleServiceSoap;
import com.evolveum.polygon.connector.liferay.role.RoleServiceSoapServiceLocator;
import com.evolveum.polygon.connector.liferay.role.RoleSoap;
import com.evolveum.polygon.connector.liferay.user.*;
import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;
import org.apache.axis.client.Stub;
import org.identityconnectors.common.logging.Log;
import org.identityconnectors.common.security.GuardedString;
import org.identityconnectors.framework.common.objects.*;
import org.junit.BeforeClass;
import org.junit.Test;
import org.w3c.dom.Element;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import java.rmi.RemoteException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
public class TestClient {
private static final Log LOG = Log.getLog(TestClient.class);
public static final long COMPANY_ID = 20155L; // id in my instance
//public static final String HOST = "http://test:test@localhost:8080/api/axis/";
// public static final String HOST = "http://midpoint%40liferay.sk:heslo123@localhost:4480/api/axis/";
// public static final String HOST = "http://midpoint@liferay.sk:heslo123@localhost:4480/api/axis/";
public static final String HOST = "http://localhost:4480/api/axis/";
private static String URL_USER_SERVICE = HOST + LiferayConnector.SERVICE_USERSERVICE;
private static String URL_CONTACT_SERVICE = HOST + LiferayConnector.SERVICE_CONTACTSERVICE;
private static String URL_EXPANDOVALUE_SERVICE = HOST + LiferayConnector.SERVICE_EXPANDOVALUESERVICE;
private static String URL_ROLE_SERVICE = HOST + LiferayConnector.SERVICE_ROLESERVICE;
private static String URL_ORGANIZATION_SERVICE = HOST + LiferayConnector.SERVICE_ORGANIZATIONSERVICE;
private static String URL_GROUP_SERVICE = HOST + LiferayConnector.SERVICE_GROUPSERVICE;
private static UserServiceSoap userSoap;
private static ContactServiceSoap contactSoap;
private static RoleServiceSoap roleSoap;
private static ExpandoValueServiceSoap expandoValueSoap;
private static OrganizationServiceSoap organizationSoap;
private static GroupServiceSoap groupSoap;
@BeforeClass
public static void setUp() throws Exception {
// Locate the User service
UserServiceSoapServiceLocator locatorUser = new UserServiceSoapServiceLocator();
userSoap = locatorUser.getPortal_UserService(new URL(URL_USER_SERVICE));
ContactServiceSoapServiceLocator locatorContact = new ContactServiceSoapServiceLocator();
contactSoap = locatorContact.getPortal_ContactService(new URL(URL_CONTACT_SERVICE));
ExpandoValueServiceSoapServiceLocator locatorExpandoValuue = new ExpandoValueServiceSoapServiceLocator();
expandoValueSoap = locatorExpandoValuue.getPortlet_Expando_ExpandoValueService(new URL(URL_EXPANDOVALUE_SERVICE));
RoleServiceSoapServiceLocator locatorRole = new RoleServiceSoapServiceLocator();
roleSoap = locatorRole.getPortal_RoleService(new URL(URL_ROLE_SERVICE));
OrganizationServiceSoapServiceLocator locatorOrganization = new OrganizationServiceSoapServiceLocator();
organizationSoap = locatorOrganization.getPortal_OrganizationService(new URL(URL_ORGANIZATION_SERVICE));
GroupServiceSoapServiceLocator locatorGroup = new GroupServiceSoapServiceLocator();
groupSoap = locatorGroup.getPortal_GroupService(new URL(URL_GROUP_SERVICE));
}
@Test
public void testOrganizationRoles() throws Exception {
String user = "midpoint@liferay.sk";
String password = "XXX";
((Stub)userSoap)._setProperty(Call.USERNAME_PROPERTY, user);
((Stub)userSoap)._setProperty(Call.PASSWORD_PROPERTY, password);
((Stub)organizationSoap)._setProperty(Call.USERNAME_PROPERTY, user);
((Stub)organizationSoap)._setProperty(Call.PASSWORD_PROPERTY, password);
((Stub)roleSoap)._setProperty(Call.USERNAME_PROPERTY, user);
((Stub)roleSoap)._setProperty(Call.PASSWORD_PROPERTY, password);
((Stub)groupSoap)._setProperty(Call.USERNAME_PROPERTY, user);
((Stub)groupSoap)._setProperty(Call.PASSWORD_PROPERTY, password);
UserSoap u = userSoap.getUserByEmailAddress(COMPANY_ID, "midpoint@liferay.sk");
System.out.println("User: " + u);
int userCount = userSoap.getCompanyUsersCount(COMPANY_ID);
System.out.println("User count: " + userCount);
long userId = 23644; //mspRedaktorId = 23701; mspadmin=23644
GroupSoap orgGroup = groupSoap.getGroup(COMPANY_ID, "MSP LFR_ORGANIZATION");
System.out.println("orgGroup.getPrimaryKey() = " + orgGroup.getPrimaryKey());
System.out.println("orgGroup.getName() = " + orgGroup.getName());
GroupSoap[] orgGroups = groupSoap.getUserOrganizationsGroups(userId, 0, -1);
for (GroupSoap og : orgGroups) {
System.out.println("og.getName() = " + og.getName());
System.out.println("og.getType() = " + og.getType());
System.out.println("og.getPrimaryKey() = " + og.getPrimaryKey());
RoleSoap[] orgRoles = roleSoap.getUserGroupRoles(userId, og.getGroupId());
for (RoleSoap roleSoap : orgRoles) {
System.out.println(" roleSoap.getName() = " + roleSoap.getName());
System.out.println(" roleSoap.getRoleId() = " + roleSoap.getRoleId());
System.out.println(" roleSoap.getType() = " + roleSoap.getType());
}
}
OrganizationSoap[] orgs = organizationSoap.getOrganizations(COMPANY_ID, 0/*root*/);
for (OrganizationSoap org : orgs) {
System.out.println("org.getType() = " + org.getType());
System.out.println("org.getName() = " + org.getName());
System.out.println("org.getOrganizationId() = " + org.getOrganizationId());
RoleSoap[] orgRoles = roleSoap.getUserGroupRoles(userId, org.getOrganizationId());
for (RoleSoap role : orgRoles) {
System.out.println(" role.getRoleId() = " + role.getRoleId());
System.out.println(" role.getName() = " + role.getName());
}
}
//long[] ogrs = new long[] {23738}; // MSP
long[] ogrs = new long[] {}; // MSP
long[] roleIds = new long[] {};// bez regular role
long siteId = 23739;//MSP LFR_ORGANIZATION
long[] groupIds = new long[] {siteId};
long[] userGroupIds = null;
UserGroupRoleSoap[] userGroupRoles = new UserGroupRoleSoap[1];
UserGroupRoleSoap ugr = new UserGroupRoleSoap();
long userID = 24700;
ugr.setUserId(userID);
ugr.setGroupId(siteId);
ugr.setRoleId(20167); // Organization Administrator
userGroupRoles[0] = ugr;
userSoap.updateUser(userID, null, null, null, false, "", "", "mspadminevo",
"mspadmin@evolveum.com", 1l, "", "", "", "", "",
"msp", "", "Admin evolveum", 0, 0, true, 3, 22, 1981,
"", "", "", "", "", "", "", "", "", "",
"", groupIds, ogrs, roleIds, userGroupRoles, userGroupIds, new ServiceContext());
// LiferayConfiguration config = new LiferayConfiguration();
// config.setCompanyId(TestClient.COMPANY_ID);
// config.setEndpoint(TestClient.HOST);
// config.setUsername(user);
// config.setPlainPassword(password);
//
// LiferayConnector lc = new LiferayConnector();
// lc.init(config);
// lc.test();
// ObjectClass objectClass = new ObjectClass(ObjectClass.ACCOUNT_NAME);
// Set<Attribute> attributesUpdate = new HashSet<Attribute>();
// attributesUpdate.add(AttributeBuilder.build("roles", "Organization Administrator,3,MSP LFR_ORGANIZATION"));
//
// Uid userUid = new Uid("24700");
// lc.update(objectClass, userUid, attributesUpdate, null);
}
@Test
public void testCRUDOperations() throws Exception {
// list of users
int userCount = userSoap.getCompanyUsersCount(COMPANY_ID);
System.out.println("User count: " + userCount);
UserSoap[] users = userSoap.getCompanyUsers(COMPANY_ID, 0, userCount);
for (UserSoap user : users)
System.out.println("\t" + user.getPrimaryKey() + ": " + user.getScreenName());
// create user
int rand = new Random().nextInt();
String screenName = "randomScreenName." + rand;
long groupIds[] = null;
long organizationIds[] = null; // root
long roleIds[] = null; //{20162};// admin
long userGroupIds[] = null;
ServiceContext serviceContext = new ServiceContext();
UserSoap newUser = userSoap.addUser(COMPANY_ID, false, "password", "password",
false, screenName, screenName + "@liferay.com", 0L, "", null,
"firstName_" + rand, "middleName_" + rand, "lastName_" + rand, 0, 0, true, 3, 22, 1981,
"Identity Engineer", groupIds, organizationIds, roleIds, userGroupIds, false,
serviceContext);
LOG.ok("new user created: " + newUser.getPrimaryKey() + ": " + newUser.getScreenName());
//update user
UserGroupRoleSoap[] userGroupRoles = null;
userSoap.updateUser(newUser.getPrimaryKey(), "password", null, null, false, "", "", newUser.getScreenName(),
newUser.getEmailAddress(), 1l, "", "", "", "", "",
newUser.getFirstName(), newUser.getMiddleName(), newUser.getLastName(), 0, 0, true, 3, 22, 1981,
"", "", "", "", "", "", "", "", "", "",
newUser.getJobTitle(), groupIds, organizationIds, roleIds, userGroupRoles, userGroupIds, serviceContext);
LOG.ok("new user updated: " + newUser.getPrimaryKey() + ": " + newUser.getScreenName());
// activate user
int enabledStatus = 0;
userSoap.updateStatus(newUser.getPrimaryKey(), enabledStatus, serviceContext);
LOG.ok("user activated: " + newUser.getPrimaryKey() + ": " + newUser.getScreenName());
// delete new user
userSoap.deleteUser(newUser.getPrimaryKey());
LOG.ok("user deleted: " + newUser.getPrimaryKey() + ": " + newUser.getScreenName());
}
@Test
public void testConnectorCRUDOperations() throws Exception {
LiferayConfiguration config = new LiferayConfiguration();
config.setCompanyId(TestClient.COMPANY_ID);
config.setEndpoint(TestClient.HOST);
LiferayConnector lc = new LiferayConnector();
lc.init(config);
//test
lc.test();
//create
ObjectClass objectClass = new ObjectClass(ObjectClass.ACCOUNT_NAME);
/*
Set<Attribute> attributes = new HashSet<Attribute>();
String randName = "random-22201"; //"random"+(new Random()).nextInt();
attributes.add(AttributeBuilder.build("emailAddress", randName + "@evolveom.com"));
attributes.add(AttributeBuilder.build(Name.NAME, randName));
attributes.add(AttributeBuilder.build("firstName", randName));
GuardedString gs = new GuardedString("test".toCharArray());
// attributes.add(AttributeBuilder.build(OperationalAttributeInfos.PASSWORD.getName(), gs));
attributes.add(AttributeBuilder.build("locale", "hu_HU"));
attributes.add(AttributeBuilder.build("passwordReset", false));
Uid userUid = lc.create(objectClass, attributes, null);
// LOG.ok("New user Uid is: {0}, name: {1}", userUid.getUidValue(), randName);
GuardedString gsNew = new GuardedString("test2".toCharArray());
// attributes.add(AttributeBuilder.build(OperationalAttributeInfos.PASSWORD.getName(), gsNew));
attributes.add(AttributeBuilder.build("locale", "en_US"));
//update without password ??
// Set<Attribute> attributesUpdate = new HashSet<Attribute>();
// Uid userUid = new Uid("22201");
// lc.update(objectClass, userUid, attributesUpdate, null);
// delete
//lc.delete(objectClass, userUid, null);
*/
}
@Test
public void testConnectorQueryOperation() throws Exception {
LiferayConfiguration config = new LiferayConfiguration();
config.setCompanyId(TestClient.COMPANY_ID);
config.setEndpoint(TestClient.HOST);
LiferayConnector lc = new LiferayConnector();
lc.init(config);
//create
ObjectClass objectClass = new ObjectClass(ObjectClass.ACCOUNT_NAME);
ResultsHandler rh = new ResultsHandler() {
@Override
public boolean handle(ConnectorObject connectorObject) {
System.out.println(connectorObject);
return true;
}
};
// searchByUId
LiferayFilter searchByUid = new LiferayFilter();
searchByUid.byUid = 20199l;
lc.executeQuery(objectClass, searchByUid, rh, null);
// searchByScreenName
LiferayFilter searchByName = new LiferayFilter();
searchByName.byName = "test";
lc.executeQuery(objectClass, searchByName, rh, null);
// searchByEMail
LiferayFilter searchByEmail = new LiferayFilter();
searchByEmail.byEmailAddress = "test@liferay.com";
lc.executeQuery(objectClass, searchByEmail, rh, null);
// searchAll
lc.executeQuery(objectClass, null, rh, null);
}
@Test
public void testgetAllContacts() throws Exception {
UserSoap user = userSoap.getUserById(20199l);
long contactId = user.getContactId();
System.out.println("contactId = " + contactId);
ContactSoap contact = contactSoap.getContact(contactId);
long classNameId = contact.getClassNameId();
long classPK = contact.getClassPK();
long primaryKey = contact.getPrimaryKey();
long userPK = user.getPrimaryKey();
System.out.println("contact.getCompanyId() = " + contact.getCompanyId());
System.out.println("TestClient.COMPANY_ID = " + TestClient.COMPANY_ID);
System.out.println("userPK = " + userPK);
System.out.println("primaryKey = " + primaryKey);
System.out.println("classNameId = " + classNameId);
System.out.println("classPK = " + classPK);
//
//
// user = userSoap.getUserById(22515l);
// contactId = user.getContactId();
// System.out.println("contactId = " + contactId);
// contact = contactSoap.getContact(contactId);
//
// classNameId = contact.getClassNameId();
// classPK = contact.getClassPK();
// userPK = user.getPrimaryKey();
// System.out.println("userPK = " + userPK);
// System.out.println("primaryKey = " + primaryKey);
// System.out.println("classNameId = " + classNameId);
// System.out.println("classPK = " + classPK);
ContactSoap[] contacts = contactSoap.getContacts(classNameId, classPK, -1, -1, null);
System.out.println("contacts.length = " + contacts.length);
}
@Test
public void testPrintUserDetails() throws Exception {
UserSoap u = userSoap.getUserById(22828l);
if (u != null)
System.out.println("UserSoap{" +
"agreedToTermsOfUse=" + u.isAgreedToTermsOfUse() +
", comments='" + u.getComments() + '\'' +
", companyId=" + u.getCompanyId() +
", contactId=" + u.getContactId() +
", createDate=" + u.getCreateDate() +
", defaultUser=" + u.isDefaultUser() +
", digest='" + u.getDigest() + '\'' +
", emailAddress='" + u.getEmailAddress() + '\'' +
", emailAddressVerified=" + u.isEmailAddressVerified() +
", facebookId=" + u.getFacebookId() +
", failedLoginAttempts=" + u.getFailedLoginAttempts() +
", firstName='" + u.getFirstName() + '\'' +
", graceLoginCount=" + u.getGraceLoginCount() +
", greeting='" + u.getGreeting() + '\'' +
", jobTitle='" + u.getJobTitle() + '\'' +
", languageId='" + u.getLanguageId() + '\'' +
", lastFailedLoginDate=" + u.getLastFailedLoginDate() +
", lastLoginDate=" + u.getLastLoginDate() +
", lastLoginIP='" + u.getLastLoginIP() + '\'' +
", lastName='" + u.getLastName() + '\'' +
", ldapServerId=" + u.getLdapServerId() +
", lockout=" + u.isLockout() +
", lockoutDate=" + u.getLockoutDate() +
", loginDate=" + u.getLoginDate() +
", loginIP='" + u.getLoginIP() + '\'' +
", middleName='" + u.getMiddleName() + '\'' +
", modifiedDate=" + u.getModifiedDate() +
", openId='" + u.getOpenId() + '\'' +
", password='" + u.getPassword() + '\'' +
", passwordEncrypted=" + u.isPasswordEncrypted() +
", passwordModifiedDate=" + u.getPasswordModifiedDate() +
", passwordReset=" + u.isPasswordReset() +
", portraitId=" + u.getPortraitId() +
", primaryKey=" + u.getPrimaryKey() +
", reminderQueryAnswer='" + u.getReminderQueryAnswer() + '\'' +
", reminderQueryQuestion='" + u.getReminderQueryQuestion() + '\'' +
", screenName='" + u.getScreenName() + '\'' +
", status=" + u.getStatus() +
", timeZoneId='" + u.getTimeZoneId() + '\'' +
", userId=" + u.getUserId() +
", uuid='" + u.getUuid() + '\'' +
'}');
}
@Test
public void testConnectorSyncOperations() throws Exception {
LiferayConfiguration config = new LiferayConfiguration();
config.setCompanyId(TestClient.COMPANY_ID);
config.setEndpoint(TestClient.HOST);
LiferayConnector lc = new LiferayConnector();
lc.init(config);
ObjectClass objectClass = new ObjectClass(ObjectClass.ACCOUNT_NAME);
SyncToken token = lc.getLatestSyncToken(objectClass);
SyncResultsHandler handler = new SyncResultsHandler() {
@Override
public boolean handle(SyncDelta delta) {
return false;
}
};
lc.sync(objectClass, token, handler, null);
Calendar cal = GregorianCalendar.getInstance();
cal.set(2015, 4, 4);
token = new SyncToken(cal.getTime().getTime());
lc.sync(objectClass, token, handler, null);
token = null;
lc.sync(objectClass, token, handler, null);
}
@Test
public void testExpandoValue() throws Exception {
expandoValueSoap.addValue(COMPANY_ID, "com.liferay.portal.model.User", "CUSTOM_FIELDS", "CustomBoolean", 20542, Boolean.FALSE);
String dataBool = expandoValueSoap.getJSONData(COMPANY_ID, "com.liferay.portal.model.User", "CUSTOM_FIELDS", "CustomBoolean", 20542);
System.out.println("dataBool = " + dataBool);
expandoValueSoap.addValue(COMPANY_ID, "com.liferay.portal.model.User", "CUSTOM_FIELDS", "CustomDate", 20542, new Date());
String dataDate = expandoValueSoap.getJSONData(COMPANY_ID, "com.liferay.portal.model.User", "CUSTOM_FIELDS", "CustomDate", 20542);
System.out.println("dataDate = " + dataDate);
}
@Test
public void testConnectorCreateUser() {
LiferayConfiguration config = new LiferayConfiguration();
config.setCompanyId(TestClient.COMPANY_ID);
config.setUsername("test");
config.setPlainPassword("test");
config.setEndpoint("http://localhost:8080/api/axis/");
LiferayConnector lc = new LiferayConnector();
lc.init(config);
//create
ObjectClass objectClass = new ObjectClass(ObjectClass.ACCOUNT_NAME);
Set<Attribute> attributes = new HashSet<Attribute>();
String randName = "random" + (new Random()).nextInt();
attributes.add(AttributeBuilder.build("emailAddress", randName + "@evolveom.com"));
attributes.add(AttributeBuilder.build(Name.NAME, randName));
attributes.add(AttributeBuilder.build("firstName", randName));
attributes.add(AttributeBuilder.build("facebookId", 12345l));
attributes.add(AttributeBuilder.build("facebookSn", "facebookSn"));
GuardedString gs = new GuardedString("test".toCharArray());
attributes.add(AttributeBuilder.build(OperationalAttributeInfos.PASSWORD.getName(), gs));
attributes.add(AttributeBuilder.build(OperationalAttributeInfos.ENABLE.getName(), true));
Uid userUid = lc.create(objectClass, attributes, null);
LOG.ok("New user Uid is: {0}, name: {1}", userUid.getUidValue(), randName);
}
@Test
public void testGetRoles() throws RemoteException {
RoleSoap testRole = roleSoap.getRole(TestClient.COMPANY_ID, "testRole");
System.out.println("testRole.getRoleId() = " + testRole.getRoleId());
RoleSoap powerUserRole = roleSoap.getRole(TestClient.COMPANY_ID, "Power User");
System.out.println("powerUserRole.getRoleId() = " + powerUserRole.getRoleId());
RoleSoap[] roles = roleSoap.getUserRoles(23511l);
for (RoleSoap role : roles) {
System.out.println("roles = " + role.getRoleId() + ": " + role.getName());
}
}
@Test
public void testuserGroupRoleUpdate() throws RemoteException {
long[] ogrs = new long[] {23983};
long[] roleIds = new long[] {20166};
long siteId = 23906;
long[] groupIds = new long[] {siteId};
long[] userGroupIds = null;
UserGroupRoleSoap[] userGroupRoles = new UserGroupRoleSoap[1];
UserGroupRoleSoap ugr = new UserGroupRoleSoap();
// long userID = 24221l;
long userID = 23406;
ugr.setUserId(userID);
ugr.setGroupId(siteId);
ugr.setRoleId(23905);
userGroupRoles[0] = ugr;
userSoap.updateUser(userID, null, null, null, false, "", "", "userrole01",
"userrole01@evolveum.com", 1l, "", "", "", "", "",
"userrole01", "", "userrole01", 0, 0, true, 3, 22, 1981,
"", "", "", "", "", "", "", "", "", "",
"", groupIds, ogrs, roleIds, userGroupRoles, userGroupIds, new ServiceContext());
}
@Test
public void testCreateOrg(){
String orgName = "test root org 2";
ObjectClass objectClass = new ObjectClass(LiferayConnector.ORGANIZATION_NAME);
Set<Attribute> attributes = new HashSet<Attribute>();
attributes.add(AttributeBuilder.build(Name.NAME, orgName));
long parent = 0;
attributes.add(AttributeBuilder.build("parentOrganizationId", parent));
LiferayConfiguration config = new LiferayConfiguration();
config.setCompanyId(TestClient.COMPANY_ID);
config.setEndpoint("http://localhost:8080/api/axis/");
config.setUsername("test");
config.setPlainPassword("test");
LiferayConnector lc = new LiferayConnector();
lc.init(config);
lc.create(objectClass, attributes, null);
}
@Test
public void testOrganization() throws Exception {
Long test2Org = 24200l;
OrganizationSoap org = organizationSoap.getOrganization(23983l);
System.out.println("org.getName() = " + org.getName());
System.out.println("org.getType() = " + org.getType());
System.out.println("org.getTreePath() = " + org.getTreePath());
System.out.println("org.getParentOrganizationId() = " + org.getParentOrganizationId());
System.out.println("org.getRegionId() = " + org.getRegionId());
System.out.println("org.getCountryId() = " + org.getCountryId());
System.out.println("org.getStatusId() = " + org.getStatusId());
System.out.println("org.getComments() = " + org.getComments());
System.out.println("org.isRecursable() = " + org.isRecursable()); // whether the permissions of the organization are to be inherited by its sub-organizations
long rootOrganizationId =0;
long regionId = 0;
long countryId = 0;
int statusId = 12017; // ListTypeConstants.ORGANIZATION_STATUS_DEFAULT
String comments = null;
boolean site = false; // create site
String type = "regular-organization";
// OrganizationSoap ret = organizationSoap.addOrganization(rootOrganizationId, "testOrg", type, regionId, countryId, statusId, comments, site, null);
// System.out.println("ret.getOrganizationId() = " + ret.getOrganizationId());
//
//
// updateOrganization(long organizationId, long parentOrganizationId, String name, String type, long regionId, long countryId, int statusId, String comments, boolean site, ServiceContext serviceContext)
//
// getOrganizationId(long companyId, String name)
LiferayConfiguration config = new LiferayConfiguration();
config.setCompanyId(TestClient.COMPANY_ID);
config.setEndpoint("http://localhost:8080/api/axis/");
config.setUsername("test");
config.setPlainPassword("test");
LiferayConnector lc = new LiferayConnector();
lc.init(config);
//create
ObjectClass objectClass = new ObjectClass(LiferayConnector.ORGANIZATION_NAME);
Set<Attribute> attributes = new HashSet<Attribute>();
String randName = "test"; //"random"+(new Random()).nextInt();
attributes.add(AttributeBuilder.build(Name.NAME, randName));
try {
// Uid userUid = lc.create(objectClass, attributes, null);
// LOG.ok("New org Uid is: {0}, name: {1}", userUid.getUidValue(), randName);
OrganizationSoap ret = organizationSoap.addOrganization(rootOrganizationId, "testOrg", type, regionId, countryId, statusId, comments, site, null);
}
catch (Exception e) {
System.out.println("e = " + e);
System.out.println("e.getMessage() = " + e.getMessage());
System.out.println("e.getLocalizedMessage() = " + e.getLocalizedMessage());
System.out.println("e.getCause() = " + e.getCause());
System.out.println("e.fillInStackTrace() = " + e.fillInStackTrace());
System.out.println("e.getStackTrace() = " + e.getStackTrace());
AxisFault af = (AxisFault) e;
HandleAxisFault(af);
System.out.println("af.getFaultDetails() = " + af.getFaultDetails());
System.out.println("af.getFaultString() = " + af.getFaultString());
System.out.println("af.getFaultCode() = " + af.getFaultCode());
System.out.println("af.getFaultActor() = " + af.getFaultActor());
System.out.println("af.dumpToString() = " + af.dumpToString());
// e = java.rmi.RemoteException: There is another organization named testOrg
// e.getMessage() = java.rmi.RemoteException: There is another organization named testOrg
// e.getLocalizedMessage() = java.rmi.RemoteException: There is another organization named testOrg
// e.getCause() = null
// e.fillInStackTrace() = java.rmi.RemoteException: There is another organization named testOrg
// e.getStackTrace() = [Ljava.lang.StackTraceElement;@59d69ffc
// sResult = Error: [0] AxisFault
// faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
// faultSubcode:
// faultString: java.rmi.RemoteException: There is another organization named testOrg
// faultActor:
// faultNode:
// faultDetail:
// {http://xml.apache.org/axis/}hostname:RUKBIBUFNTB
//
//
// Stack Trace: null
// af.getFaultDetails() = [Lorg.w3c.dom.Element;@1171fa02
// af.getFaultString() = java.rmi.RemoteException: There is another organization named testOrg
// af.getFaultCode() = {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
// af.getFaultActor() = null
// af.dumpToString() = AxisFault
// faultCode: {http://schemas.xmlsoap.org/soap/envelope/}Server.userException
// faultSubcode:
// faultString: java.rmi.RemoteException: There is another organization named testOrg
// faultActor:
// faultNode:
// faultDetail:
// {http://xml.apache.org/axis/}hostname:RUKBIBUFNTB
}
}
private static String HandleAxisFault(AxisFault af)
{
String sResult = null;
//defaults
String sErrorString = af.dumpToString();
String sErrorCode = "0";
String sStackTrace = null;
Element[] details = af.getFaultDetails();
if(details != null)
{
for(int i = 0; i < details.length; i++)
{
String elementName = details[i].getTagName();
if(elementName.equals("MWSErrorString"))
{
sErrorString = details[i].getAttribute("mws:String");
}
else if (elementName.equals("MWSErrorCode"))
{
sErrorCode = details[i].getAttribute("mws:Code");
}
else if (elementName.equals("StackTrace"))
{
sStackTrace = details[i].getAttribute("mws:String");
}
}
}
sResult = "Error: [" + sErrorCode + "] " + sErrorString + "\n";
sResult += "\n" + "Stack Trace: " + sStackTrace;
System.out.println("sResult = " + sResult);
return sResult;
} // end HandleAxisFault
@Test
public void testTraverse() throws RemoteException {
List<OrganizationSoap> allOrgs = new LinkedList<OrganizationSoap>();
getChild(0l, allOrgs);
for (OrganizationSoap org : allOrgs) {
System.out.println("org = " + org);
}
// System.out.println("allOrgs = " + allOrgs);
}
private void getChild(long parentOrgId, List<OrganizationSoap> ret) throws RemoteException {
OrganizationSoap[] orgs = organizationSoap.getOrganizations(COMPANY_ID, parentOrgId);
for (OrganizationSoap org : orgs) {
ret.add(org);
}
for (OrganizationSoap org : orgs) {
getChild(org.getOrganizationId(), ret);
}
}
@Test
public void testParseDate() throws RemoteException, ParseException {
String target = "04.06.1975";
DateFormat df = new SimpleDateFormat("dd.MM.yyyy");
Date result = df.parse(target);
System.out.println("result = " + result);
}
@Test
public void testSplit() throws RemoteException, ParseException {
String uid = "ROF_EXP_CAT|1|2015-01-07 00:00:00|UP_IT9";
// uid = "ROF_EXP_CAT;1;2015-01-07 00:00:00;UP_IT9";
List<String> pks = Arrays.asList(uid.split("\\|"));
System.out.println("pks = " + pks);
System.out.println("pks(0) = " + pks.get(0));
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more contributor license
* agreements. See the NOTICE file distributed with this work for additional information regarding
* copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the License. You may obtain a
* copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/
package org.apache.geode.internal.cache.tier.sockets;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.assertj.core.api.Assertions.catchThrowable;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.quality.Strictness.STRICT_STUBS;
import java.io.IOException;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Properties;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Future;
import java.util.concurrent.atomic.AtomicReference;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.mockito.junit.MockitoJUnit;
import org.mockito.junit.MockitoRule;
import org.apache.geode.CancelCriterion;
import org.apache.geode.InternalGemFireError;
import org.apache.geode.Statistics;
import org.apache.geode.cache.Operation;
import org.apache.geode.cache.query.internal.cq.ServerCQ;
import org.apache.geode.distributed.DistributedMember;
import org.apache.geode.distributed.internal.InternalDistributedSystem;
import org.apache.geode.internal.SystemTimer;
import org.apache.geode.internal.cache.EntryEventImpl;
import org.apache.geode.internal.cache.EnumListenerEvent;
import org.apache.geode.internal.cache.FilterProfile;
import org.apache.geode.internal.cache.FilterRoutingInfo;
import org.apache.geode.internal.cache.FilterRoutingInfo.FilterInfo;
import org.apache.geode.internal.cache.InternalCache;
import org.apache.geode.internal.cache.InternalCacheEvent;
import org.apache.geode.internal.cache.InternalRegion;
import org.apache.geode.internal.cache.RegionQueueException;
import org.apache.geode.internal.cache.tier.sockets.ClientRegistrationEventQueueManager.ClientRegistrationEventQueue;
import org.apache.geode.internal.statistics.StatisticsClock;
import org.apache.geode.internal.statistics.StatisticsManager;
import org.apache.geode.test.junit.rules.ExecutorServiceRule;
public class CacheClientNotifierTest {
private static final String CQ_NAME = "testCQ";
private static final long CQ_ID = 0;
private final AtomicReference<CountDownLatch> afterLatch =
new AtomicReference<>(new CountDownLatch(0));
private final AtomicReference<CountDownLatch> beforeLatch =
new AtomicReference<>(new CountDownLatch(0));
private CacheClientProxy cacheClientProxy;
private ClientProxyMembershipID clientProxyMembershipId;
private ClientRegistrationEventQueueManager clientRegistrationEventQueueManager;
private ClientRegistrationMetadata clientRegistrationMetadata;
private InternalCache internalCache;
private InternalDistributedSystem internalDistributedSystem;
private Socket socket;
private Statistics statistics;
private StatisticsManager statisticsManager;
private InternalRegion region;
private CacheClientNotifier cacheClientNotifier;
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule().strictness(STRICT_STUBS);
@Rule
public ExecutorServiceRule executorServiceRule = new ExecutorServiceRule();
@BeforeClass
public static void clearStatics() {
// Perform cleanup on any singletons received from previous test runs, since the
// CacheClientNotifier is a static and previous tests may not have cleaned up properly.
CacheClientNotifier cacheClientNotifier = CacheClientNotifier.getInstance();
if (cacheClientNotifier != null) {
cacheClientNotifier.shutdown(0);
}
}
@Before
public void setUp() {
cacheClientProxy = mock(CacheClientProxy.class);
clientProxyMembershipId = mock(ClientProxyMembershipID.class);
clientRegistrationEventQueueManager = mock(ClientRegistrationEventQueueManager.class);
clientRegistrationMetadata = mock(ClientRegistrationMetadata.class);
internalCache = mock(InternalCache.class);
internalDistributedSystem = mock(InternalDistributedSystem.class);
region = mock(InternalRegion.class);
socket = mock(Socket.class);
statistics = mock(Statistics.class);
statisticsManager = mock(StatisticsManager.class);
}
@After
public void tearDown() {
beforeLatch.get().countDown();
afterLatch.get().countDown();
clearStatics();
}
@Test
public void eventsInClientRegistrationQueueAreSentToClientAfterRegistrationIsComplete()
throws Exception {
// this test requires real impl instance of ClientRegistrationEventQueueManager
clientRegistrationEventQueueManager = new ClientRegistrationEventQueueManager();
when(cacheClientProxy.getProxyID())
.thenReturn(clientProxyMembershipId);
when(clientRegistrationMetadata.getClientProxyMembershipID())
.thenReturn(clientProxyMembershipId);
when(internalCache.getCancelCriterion())
.thenReturn(mock(CancelCriterion.class));
when(internalCache.getCCPTimer())
.thenReturn(mock(SystemTimer.class));
when(internalCache.getInternalDistributedSystem())
.thenReturn(internalDistributedSystem);
when(internalDistributedSystem.getStatisticsManager())
.thenReturn(statisticsManager);
when(statisticsManager.createAtomicStatistics(any(), any()))
.thenReturn(statistics);
cacheClientNotifier = spy(CacheClientNotifier.getInstance(internalCache,
clientRegistrationEventQueueManager, mock(StatisticsClock.class),
mock(CacheServerStats.class), 0, 0, mock(ConnectionListener.class), null, false));
beforeLatch.set(new CountDownLatch(1));
afterLatch.set(new CountDownLatch(1));
// We stub out the CacheClientNotifier.registerClientInternal() to do some "work" until
// a new event is received and queued, as triggered by the afterLatch
doAnswer(invocation -> {
cacheClientNotifier.addClientProxy(cacheClientProxy);
beforeLatch.get().countDown();
afterLatch.get().await();
return null;
})
.when(cacheClientNotifier)
.registerClientInternal(clientRegistrationMetadata, socket, false, 0, true);
Collection<Callable<Void>> tasks = new ArrayList<>();
// In one thread, we register the new client which should create the temporary client
// registration event queue. Events will be passed to that queue while registration is
// underway. Once registration is complete, the queue is drained and the event is processed
// as normal.
tasks.add(() -> {
cacheClientNotifier.registerClient(clientRegistrationMetadata, socket, false, 0, true);
return null;
});
// In a second thread, we mock the arrival of a new event. We want to ensure this event
// goes into the temporary client registration event queue. To do that, we wait on the
// beforeLatch until registration is underway and the temp queue is
// created. Once it is, we process the event and notify clients, which should add the event
// to the temp queue. Finally, we resume registration and after it is complete, we verify
// that the event was drained, processed, and "delivered" (note message delivery is mocked
// and results in a no-op).
tasks.add(() -> {
beforeLatch.get().await();
InternalCacheEvent internalCacheEvent = internalCacheEvent(clientProxyMembershipId);
ClientUpdateMessageImpl clientUpdateMessageImpl = mock(ClientUpdateMessageImpl.class);
CacheClientNotifier.notifyClients(internalCacheEvent, clientUpdateMessageImpl);
afterLatch.get().countDown();
return null;
});
for (Future future : executorServiceRule.getExecutorService().invokeAll(tasks)) {
future.get();
}
verify(cacheClientProxy).deliverMessage(any());
}
@Test
public void initializingMessageDoesNotSerializeValuePrematurely() {
// this test requires mock of EntryEventImpl instead of InternalCacheEvent
EntryEventImpl entryEventImpl = mock(EntryEventImpl.class);
when(entryEventImpl.getEventType())
.thenReturn(EnumListenerEvent.AFTER_CREATE);
when(entryEventImpl.getOperation())
.thenReturn(Operation.CREATE);
when(entryEventImpl.getRegion())
.thenReturn(region);
when(internalCache.getCCPTimer())
.thenReturn(mock(SystemTimer.class));
when(internalCache.getInternalDistributedSystem())
.thenReturn(internalDistributedSystem);
when(internalDistributedSystem.getStatisticsManager())
.thenReturn(statisticsManager);
when(statisticsManager.createAtomicStatistics(any(), any()))
.thenReturn(statistics);
cacheClientNotifier = CacheClientNotifier.getInstance(internalCache,
mock(ClientRegistrationEventQueueManager.class), mock(StatisticsClock.class),
mock(CacheServerStats.class), 0, 0, mock(ConnectionListener.class), null, false);
cacheClientNotifier.constructClientMessage(entryEventImpl);
verify(entryEventImpl, never()).exportNewValue(any());
}
@Test
public void clientRegistrationFailsQueueStillDrained() throws Exception {
ClientRegistrationEventQueue clientRegistrationEventQueue =
mock(ClientRegistrationEventQueue.class);
when(clientRegistrationEventQueueManager.create(eq(clientProxyMembershipId), any(), any()))
.thenReturn(clientRegistrationEventQueue);
when(clientRegistrationMetadata.getClientProxyMembershipID())
.thenReturn(clientProxyMembershipId);
when(internalCache.getCCPTimer())
.thenReturn(mock(SystemTimer.class));
when(internalCache.getInternalDistributedSystem())
.thenReturn(internalDistributedSystem);
when(internalDistributedSystem.getStatisticsManager())
.thenReturn(statisticsManager);
when(statisticsManager.createAtomicStatistics(any(), any()))
.thenReturn(statistics);
cacheClientNotifier = spy(CacheClientNotifier.getInstance(internalCache,
clientRegistrationEventQueueManager, mock(StatisticsClock.class),
mock(CacheServerStats.class), 0, 0, mock(ConnectionListener.class), null, false));
doThrow(new RegionQueueException("thrown during client registration"))
.when(cacheClientNotifier)
.registerClientInternal(clientRegistrationMetadata, socket, false, 0, true);
Throwable thrown = catchThrowable(() -> {
cacheClientNotifier.registerClient(clientRegistrationMetadata, socket, false, 0, true);
});
assertThat(thrown).isInstanceOf(IOException.class);
verify(clientRegistrationEventQueueManager)
.create(eq(clientProxyMembershipId), any(), any());
verify(clientRegistrationEventQueueManager)
.drain(eq(clientRegistrationEventQueue), eq(cacheClientNotifier));
}
@Test
public void testSingletonHasClientProxiesFalseNoCCN() {
assertThat(CacheClientNotifier.singletonHasClientProxies()).isFalse();
}
@Test
public void testSingletonHasClientProxiesFalseNoProxy() {
when(internalCache.getCCPTimer())
.thenReturn(mock(SystemTimer.class));
cacheClientNotifier = CacheClientNotifier.getInstance(internalCache,
mock(ClientRegistrationEventQueueManager.class), mock(StatisticsClock.class),
mock(CacheServerStats.class), 10, 10, mock(ConnectionListener.class), null, true);
assertThat(CacheClientNotifier.singletonHasClientProxies()).isFalse();
}
@Test
public void testSingletonHasClientProxiesTrue() {
when(cacheClientProxy.getAcceptorId())
.thenReturn(111L);
when(cacheClientProxy.getProxyID())
.thenReturn(mock(ClientProxyMembershipID.class));
when(internalCache.getCCPTimer())
.thenReturn(mock(SystemTimer.class));
cacheClientNotifier = CacheClientNotifier.getInstance(internalCache,
mock(ClientRegistrationEventQueueManager.class), mock(StatisticsClock.class),
mock(CacheServerStats.class), 10, 10, mock(ConnectionListener.class), null, true);
cacheClientNotifier.addClientProxy(cacheClientProxy);
// check ClientProxy Map is not empty
assertThat(CacheClientNotifier.singletonHasClientProxies()).isTrue();
}
@Test
public void testSingletonHasInitClientProxiesTrue() {
when(cacheClientProxy.getAcceptorId())
.thenReturn(111L);
when(cacheClientProxy.getProxyID())
.thenReturn(mock(ClientProxyMembershipID.class));
when(internalCache.getCCPTimer())
.thenReturn(mock(SystemTimer.class));
cacheClientNotifier = CacheClientNotifier.getInstance(internalCache,
mock(ClientRegistrationEventQueueManager.class), mock(StatisticsClock.class),
mock(CacheServerStats.class), 10, 10, mock(ConnectionListener.class), null, true);
cacheClientNotifier.addClientInitProxy(cacheClientProxy);
// check InitClientProxy Map is not empty
assertThat(CacheClientNotifier.singletonHasClientProxies()).isTrue();
cacheClientNotifier.addClientProxy(cacheClientProxy);
// check ClientProxy Map is not empty
assertThat(CacheClientNotifier.singletonHasClientProxies()).isTrue();
}
private InternalCacheEvent internalCacheEvent(ClientProxyMembershipID clientProxyMembershipID) {
FilterInfo filterInfo = mock(FilterInfo.class);
FilterProfile filterProfile = mock(FilterProfile.class);
FilterRoutingInfo filterRoutingInfo = mock(FilterRoutingInfo.class);
InternalCacheEvent internalCacheEvent = mock(InternalCacheEvent.class);
ServerCQ serverCQ = mock(ServerCQ.class);
HashMap<Long, Integer> cqs = new HashMap<>();
cqs.put(CQ_ID, 123);
when(filterInfo.getCQs())
.thenReturn(cqs);
when(filterProfile.getCq(CQ_NAME))
.thenReturn(serverCQ);
when(filterProfile.getRealCqID(CQ_ID))
.thenReturn(CQ_NAME);
when(filterProfile.getFilterRoutingInfoPart2(null, internalCacheEvent))
.thenReturn(filterRoutingInfo);
when(filterRoutingInfo.getLocalFilterInfo())
.thenReturn(filterInfo);
when(internalCacheEvent.getRegion())
.thenReturn(region);
when(internalCacheEvent.getLocalFilterInfo())
.thenReturn(filterInfo);
when(internalCacheEvent.getOperation())
.thenReturn(mock(Operation.class));
when(region.getFilterProfile())
.thenReturn(filterProfile);
when(serverCQ.getClientProxyId())
.thenReturn(clientProxyMembershipID);
return internalCacheEvent;
}
@Test
public void registerClientInternalWithDuplicateDurableClientClosesSocket() throws Exception {
when(internalCache.getCCPTimer())
.thenReturn(mock(SystemTimer.class));
when(internalCache.getInternalDistributedSystem())
.thenReturn(internalDistributedSystem);
when(internalCache.getDistributedSystem()).thenReturn(internalDistributedSystem);
when(internalDistributedSystem.getProperties()).thenReturn(mock(Properties.class));
when(internalDistributedSystem.getStatisticsManager())
.thenReturn(statisticsManager);
when(statisticsManager.createAtomicStatistics(any(), any()))
.thenReturn(statistics);
cacheClientNotifier = CacheClientNotifier.getInstance(internalCache,
mock(ClientRegistrationEventQueueManager.class), mock(StatisticsClock.class),
mock(CacheServerStats.class), 10, 10, mock(ConnectionListener.class), null, false,
mock(SocketMessageWriter.class));
ClientRegistrationMetadata metadata = mock(ClientRegistrationMetadata.class);
ClientProxyMembershipID id = mock(ClientProxyMembershipID.class);
CacheClientProxy proxy = mock(CacheClientProxy.class);
when(proxy.getProxyID()).thenReturn(id);
when(metadata.getClientProxyMembershipID()).thenReturn(id);
when(id.getDistributedMember()).thenReturn(mock(DistributedMember.class));
when(id.getDurableId()).thenReturn("durable");
when(id.isDurable()).thenReturn(true);
cacheClientNotifier.addClientProxy(proxy);
cacheClientNotifier.registerClientInternal(metadata, socket, true, 0, false);
verify(socket).close();
}
@Test
public void makePrimaryWouldThrowIfNoSuchProxy() {
setUpSpyNotifier();
doReturn(null).when(cacheClientNotifier).getClientProxy(clientProxyMembershipId);
assertThatThrownBy(() -> cacheClientNotifier.makePrimary(clientProxyMembershipId, true))
.isInstanceOf(InternalGemFireError.class);
assertThatThrownBy(() -> cacheClientNotifier.makePrimary(clientProxyMembershipId, false))
.isInstanceOf(InternalGemFireError.class);
}
@Test
public void makePrimary_durableClient_ready() {
setUpSpyNotifier();
doReturn(cacheClientProxy).when(cacheClientNotifier).getClientProxy(clientProxyMembershipId);
when(cacheClientProxy.isDurable()).thenReturn(true);
cacheClientNotifier.makePrimary(clientProxyMembershipId, true);
verify(cacheClientProxy).startOrResumeMessageDispatcher(true);
}
@Test
public void makePrimary_durableClient_notReady() {
setUpSpyNotifier();
doReturn(cacheClientProxy).when(cacheClientNotifier).getClientProxy(clientProxyMembershipId);
when(cacheClientProxy.isDurable()).thenReturn(true);
cacheClientNotifier.makePrimary(clientProxyMembershipId, false);
verify(cacheClientProxy, never()).startOrResumeMessageDispatcher(anyBoolean());
}
@Test
public void makePrimary_nonDurableClient_ready() {
setUpSpyNotifier();
doReturn(cacheClientProxy).when(cacheClientNotifier).getClientProxy(clientProxyMembershipId);
when(cacheClientProxy.isDurable()).thenReturn(false);
cacheClientNotifier.makePrimary(clientProxyMembershipId, true);
verify(cacheClientProxy).startOrResumeMessageDispatcher(false);
}
@Test
public void makePrimary_nonDurableClient_notReady() {
setUpSpyNotifier();
doReturn(cacheClientProxy).when(cacheClientNotifier).getClientProxy(clientProxyMembershipId);
when(cacheClientProxy.isDurable()).thenReturn(false);
cacheClientNotifier.makePrimary(clientProxyMembershipId, false);
verify(cacheClientProxy).startOrResumeMessageDispatcher(false);
}
private void setUpSpyNotifier() {
when(internalCache.getCCPTimer())
.thenReturn(mock(SystemTimer.class));
when(internalCache.getInternalDistributedSystem())
.thenReturn(internalDistributedSystem);
when(internalDistributedSystem.getStatisticsManager())
.thenReturn(statisticsManager);
when(statisticsManager.createAtomicStatistics(any(), any()))
.thenReturn(statistics);
cacheClientNotifier = spy(CacheClientNotifier.getInstance(internalCache,
clientRegistrationEventQueueManager, mock(StatisticsClock.class),
mock(CacheServerStats.class), 0, 0, mock(ConnectionListener.class), null, false));
}
}
| |
package ravtrix.backpackerbuddy.activities.discussion.discussioncomments;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import ravtrix.backpackerbuddy.R;
import ravtrix.backpackerbuddy.helpers.Helpers;
import ravtrix.backpackerbuddy.models.UserLocalStore;
import ravtrix.backpackerbuddy.recyclerviewfeed.commentdiscussionrecyclerview.CommentDiscussionAdapter;
import ravtrix.backpackerbuddy.recyclerviewfeed.commentdiscussionrecyclerview.CommentModel;
import ravtrix.backpackerbuddy.recyclerviewfeed.travelpostsrecyclerview.decorator.DividerDecoration;
public class DiscussionComments extends AppCompatActivity implements View.OnClickListener, IDiscussionCommentsView {
@BindView(R.id.toolbar) protected Toolbar toolbar;
@BindView(R.id.submitButton) protected Button submitButton;
@BindView(R.id.etComment) protected EditText etComment;
@BindView(R.id.recyclerView_comment) protected RecyclerView recyclerView;
@BindView(R.id.linearRecycler) protected LinearLayout linearLayout;
@BindView(R.id.linearProgressbar) protected LinearLayout linearProg;
private int discussionID, ownerID;
private DiscussionCommentsPresenter discussionCommentsPresenter;
private UserLocalStore userLocalStore;
private CommentDiscussionAdapter commentDiscussionAdapter;
private List<CommentModel> commentModels;
private long mLastClickTime = 0;
private int backPressExit = 1;
private ProgressDialog progressDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_discussion_comments);
ButterKnife.bind(this);
Helpers.setToolbar(this, toolbar);
setTitle("Comments");
Helpers.overrideFonts(this, etComment);
hideProgressbar();
hideRecyclerView();
RecyclerView.ItemDecoration dividerDecorator = new DividerDecoration(this, R.drawable.line_divider_inbox);
recyclerView.addItemDecoration(dividerDecorator);
getDiscussionBundle();
userLocalStore = new UserLocalStore(this);
discussionCommentsPresenter = new DiscussionCommentsPresenter(this);
submitButton.setOnClickListener(this);
discussionCommentsPresenter.fetchDiscussionComments(ownerID, discussionID);
}
@Override
public void onClick(View view) {
// Prevents double clicking
if (SystemClock.elapsedRealtime() - mLastClickTime < 1000){
return;
}
mLastClickTime = SystemClock.elapsedRealtime();
switch(view.getId()) {
case R.id.submitButton:
if (userLocalStore.getLoggedInUser().getUserID() != 0) {
if (etComment.getText().toString().trim().isEmpty()) {
Helpers.displayToast(this, "Empty comment...");
} else if (etComment.getText().toString().trim().length() >= 500) {
Helpers.displayToast(this, "Exceeded max character count (500)");
} else {
// Submit comment
discussionCommentsPresenter.insertComment(getDiscussionHash(),
userLocalStore.getLoggedInUser().getUserID(), discussionID, ownerID);
etComment.getText().clear();
}
} else {
Helpers.displayToast(this, "Become a member to comment");
}
break;
default:
break;
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == 1) { // refresh from edit comment
discussionCommentsPresenter.fetchDiscussionCommentsRefresh(ownerID, discussionID);
}
}
}
private void getDiscussionBundle() {
Bundle discussionBundle = getIntent().getExtras();
if (discussionBundle != null) {
discussionID = discussionBundle.getInt("discussionID");
ownerID = discussionBundle.getInt("ownerID");
}
}
@Override
public void showProgressDialog() {
progressDialog = Helpers.showProgressDialog(this, "Posting...");
}
@Override
public void hideProgressDialog() {
if (progressDialog != null) Helpers.hideProgressDialog(progressDialog);
}
@Override
public void onBackPressed() {
super.onBackPressed();
}
@Override
public void hideKeyboard() {
// Hide keyboard
View view = getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
@Override
public void displayErrorToast() {
Helpers.displayErrorToast(this);
}
@Override
public void setModelsEmpty() {
this.commentModels = new ArrayList<>(); // empty list
}
@Override
public void setModels(List<CommentModel> commentModels) {
this.commentModels = commentModels;
}
@Override
public void setRecyclerView() {
commentDiscussionAdapter = new CommentDiscussionAdapter(DiscussionComments.this,
commentModels, userLocalStore);
recyclerView.setAdapter(commentDiscussionAdapter);
// Bring recycler view to end of its scroll to see new comment
final LinearLayoutManager linearLayoutManager = new LinearLayoutManager(DiscussionComments.this);
linearLayoutManager.scrollToPosition(commentModels.size() - 1);
recyclerView.setLayoutManager(linearLayoutManager);
}
@Override
public void showDisplayAfterLoading() {
linearProg.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
@Override
public void hideProgressbar() {
linearProg.setVisibility(View.GONE);
}
@Override
public void showProgressbar() {
linearProg.setVisibility(View.VISIBLE);
}
@Override
public void swapModels(List<CommentModel> commentModels) {
commentDiscussionAdapter.swap(commentModels);
}
@Override
public void clearEditText() {
etComment.getText().clear();
}
@Override
public void clearData() {
if (commentDiscussionAdapter != null) {
commentDiscussionAdapter.clearData();
}
}
@Override
public void hideRecyclerView() {
recyclerView.setVisibility(View.INVISIBLE);
}
private HashMap<String, String> getDiscussionHash() {
final HashMap<String, String> discussionHash = new HashMap<>();
discussionHash.put("userID", Integer.toString(userLocalStore.getLoggedInUser().getUserID()));
discussionHash.put("discussionID", Integer.toString(discussionID));
discussionHash.put("comment", etComment.getText().toString().trim());
discussionHash.put("time", Long.toString(System.currentTimeMillis()));
return discussionHash;
}
public void fetchDiscussionCommentsRefresh() {
discussionCommentsPresenter.fetchDiscussionCommentsRefresh(ownerID, discussionID);
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.nifi.encrypt;
import java.nio.charset.StandardCharsets;
import java.security.Provider;
import java.security.SecureRandom;
import java.security.Security;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.crypto.Cipher;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringUtils;
import org.apache.nifi.security.kms.CryptoUtils;
import org.apache.nifi.security.util.EncryptionMethod;
import org.apache.nifi.security.util.KeyDerivationFunction;
import org.apache.nifi.security.util.crypto.CipherProvider;
import org.apache.nifi.security.util.crypto.CipherProviderFactory;
import org.apache.nifi.security.util.crypto.CipherUtility;
import org.apache.nifi.security.util.crypto.KeyedCipherProvider;
import org.apache.nifi.security.util.crypto.NiFiLegacyCipherProvider;
import org.apache.nifi.security.util.crypto.PBECipherProvider;
import org.apache.nifi.util.NiFiProperties;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.util.encoders.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <p>
* An application specific string encryptor that collects configuration from the
* application properties, system properties, and/or system environment.
* </p>
* <p>
* <p>
* Instance of this class are thread-safe</p>
* <p>
* <p>
* The encryption provider and algorithm is configured using the application
* properties:
* <ul>
* <li>nifi.sensitive.props.provider</li>
* <li>nifi.sensitive.props.algorithm</li>
* </ul>
* </p>
* <p>
* <p>
* The encryptor's password may be set by configuring the below property:
* <ul>
* <li>nifi.sensitive.props.key</li>
* </ul>
* </p>
*/
public class StringEncryptor {
private static final Logger logger = LoggerFactory.getLogger(StringEncryptor.class);
private static final List<String> SUPPORTED_ALGORITHMS = new ArrayList<>();
private static final List<String> SUPPORTED_PROVIDERS = new ArrayList<>();
private final String algorithm;
private final String provider;
private final PBEKeySpec password;
private final SecretKeySpec key;
private String encoding = "HEX";
private CipherProvider cipherProvider;
static {
Security.addProvider(new BouncyCastleProvider());
for (EncryptionMethod em : EncryptionMethod.values()) {
SUPPORTED_ALGORITHMS.add(em.getAlgorithm());
}
logger.debug("Supported encryption algorithms: " + StringUtils.join(SUPPORTED_ALGORITHMS, "\n"));
for (Provider provider : Security.getProviders()) {
SUPPORTED_PROVIDERS.add(provider.getName());
}
logger.debug("Supported providers: " + StringUtils.join(SUPPORTED_PROVIDERS, "\n"));
}
public static final String NF_SENSITIVE_PROPS_KEY = "nifi.sensitive.props.key";
public static final String NF_SENSITIVE_PROPS_ALGORITHM = "nifi.sensitive.props.algorithm";
public static final String NF_SENSITIVE_PROPS_PROVIDER = "nifi.sensitive.props.provider";
private static final String DEFAULT_SENSITIVE_PROPS_KEY = "nififtw!";
/**
* This constructor creates an encryptor using <em>Password-Based Encryption</em> (PBE). The <em>key</em> value is the direct value provided in <code>nifi.sensitive.props.key</code> in
* <code>nifi.properties</code>, which is a <em>PASSWORD</em> rather than a <em>KEY</em>, but is named such for backward/legacy logical compatibility throughout the rest of the codebase.
* <p>
* For actual raw key provision, see {@link #StringEncryptor(String, String, byte[])}.
*
* @param algorithm the PBE cipher algorithm ({@link EncryptionMethod#algorithm})
* @param provider the JCA Security provider ({@link EncryptionMethod#provider})
* @param key the UTF-8 characters from nifi.properties -- nifi.sensitive.props.key
*/
public StringEncryptor(final String algorithm, final String provider, final String key) {
this.algorithm = algorithm;
this.provider = provider;
this.key = null;
this.password = new PBEKeySpec(key == null
? DEFAULT_SENSITIVE_PROPS_KEY.toCharArray()
: key.toCharArray());
initialize();
}
/**
* This constructor creates an encryptor using <em>Keyed Encryption</em>. The <em>key</em> value is the raw byte value of a symmetric encryption key
* (usually expressed for human-readability/transmission in hexadecimal or Base64 encoded format).
*
* @param algorithm the PBE cipher algorithm ({@link EncryptionMethod#algorithm})
* @param provider the JCA Security provider ({@link EncryptionMethod#provider})
* @param key a raw encryption key in bytes
*/
public StringEncryptor(final String algorithm, final String provider, final byte[] key) {
this.algorithm = algorithm;
this.provider = provider;
this.key = new SecretKeySpec(key, extractKeyTypeFromAlgorithm(algorithm));
this.password = null;
initialize();
}
/**
* A default constructor for mocking during testing.
*/
protected StringEncryptor() {
this.algorithm = null;
this.provider = null;
this.key = null;
this.password = null;
}
/**
* Extracts the cipher "family" (i.e. "AES", "DES", "RC4") from the full algorithm name.
*
* @param algorithm the algorithm ({@link EncryptionMethod#algorithm})
* @return the cipher family
* @throws EncryptionException if the algorithm is null/empty or not supported
*/
private String extractKeyTypeFromAlgorithm(String algorithm) throws EncryptionException {
if (StringUtils.isBlank(algorithm)) {
throw new EncryptionException("The algorithm cannot be null or empty");
}
String parsedCipher = CipherUtility.parseCipherFromAlgorithm(algorithm);
if (parsedCipher.equals(algorithm)) {
throw new EncryptionException("No supported algorithm detected");
} else {
return parsedCipher;
}
}
/**
* Creates an instance of the NiFi sensitive property encryptor.
*
* @param niFiProperties properties
* @return encryptor
* @throws EncryptionException if any issues arise initializing or
* validating the encryptor
* @see #createEncryptor(String, String, String)
* @deprecated as of NiFi 1.4.0 because the entire {@link NiFiProperties} object is not necessary to generate the encryptor.
*/
@Deprecated
public static StringEncryptor createEncryptor(final NiFiProperties niFiProperties) throws EncryptionException {
// Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
final String sensitivePropAlgorithmVal = niFiProperties.getProperty(NF_SENSITIVE_PROPS_ALGORITHM);
final String sensitivePropProviderVal = niFiProperties.getProperty(NF_SENSITIVE_PROPS_PROVIDER);
final String sensitivePropValueNifiPropVar = niFiProperties.getProperty(NF_SENSITIVE_PROPS_KEY, DEFAULT_SENSITIVE_PROPS_KEY);
return createEncryptor(sensitivePropAlgorithmVal, sensitivePropProviderVal, sensitivePropValueNifiPropVar);
}
/**
* Creates an instance of the NiFi sensitive property encryptor.
*
* @param algorithm the encryption (and key derivation) algorithm ({@link EncryptionMethod#algorithm})
* @param provider the JCA Security provider ({@link EncryptionMethod#provider})
* @param password the UTF-8 characters from nifi.properties -- nifi.sensitive.props.key
* @return the initialized encryptor
*/
public static StringEncryptor createEncryptor(String algorithm, String provider, String password) {
if (StringUtils.isBlank(algorithm)) {
throw new EncryptionException(NF_SENSITIVE_PROPS_ALGORITHM + " must be set");
}
if (StringUtils.isBlank(provider)) {
throw new EncryptionException(NF_SENSITIVE_PROPS_PROVIDER + " must be set");
}
if (StringUtils.isBlank(password)) {
throw new EncryptionException(NF_SENSITIVE_PROPS_KEY + " must be set");
}
return new StringEncryptor(algorithm, provider, password);
}
protected void initialize() {
if (isInitialized()) {
logger.debug("Attempted to initialize an already-initialized StringEncryptor");
return;
}
if (paramsAreValid()) {
if (CipherUtility.isPBECipher(algorithm)) {
cipherProvider = CipherProviderFactory.getCipherProvider(KeyDerivationFunction.NIFI_LEGACY);
} else {
cipherProvider = CipherProviderFactory.getCipherProvider(KeyDerivationFunction.NONE);
}
} else {
throw new EncryptionException("Cannot initialize the StringEncryptor because some configuration values are invalid");
}
}
private boolean paramsAreValid() {
boolean algorithmAndProviderValid = algorithmIsValid(algorithm) && providerIsValid(provider);
boolean secretIsValid = false;
if (CipherUtility.isPBECipher(algorithm)) {
secretIsValid = passwordIsValid(password);
} else if (CipherUtility.isKeyedCipher(algorithm)) {
secretIsValid = keyIsValid(key, algorithm);
}
return algorithmAndProviderValid && secretIsValid;
}
private boolean keyIsValid(SecretKeySpec key, String algorithm) {
return key != null && CipherUtility.getValidKeyLengthsForAlgorithm(algorithm).contains(key.getEncoded().length * 8);
}
private boolean passwordIsValid(PBEKeySpec password) {
try {
return password.getPassword() != null;
} catch (IllegalStateException | NullPointerException e) {
return false;
}
}
public void setEncoding(String base) {
if ("HEX".equalsIgnoreCase(base)) {
this.encoding = "HEX";
} else if ("BASE64".equalsIgnoreCase(base)) {
this.encoding = "BASE64";
} else {
throw new IllegalArgumentException("The encoding base must be 'HEX' or 'BASE64'");
}
}
/**
* Encrypts the given clear text.
*
* @param clearText the message to encrypt
* @return the cipher text
* @throws EncryptionException if the encrypt fails
*/
public String encrypt(String clearText) throws EncryptionException {
try {
if (isInitialized()) {
byte[] rawBytes;
if (CipherUtility.isPBECipher(algorithm)) {
rawBytes = encryptPBE(clearText);
} else {
rawBytes = encryptKeyed(clearText);
}
return encode(rawBytes);
} else {
throw new EncryptionException("The encryptor is not initialized");
}
} catch (final Exception e) {
throw new EncryptionException(e);
}
}
private byte[] encryptPBE(String plaintext) {
PBECipherProvider pbecp = (PBECipherProvider) cipherProvider;
final EncryptionMethod encryptionMethod = EncryptionMethod.forAlgorithm(algorithm);
// Generate salt
byte[] salt;
// NiFi legacy code determined the salt length based on the cipher block size
if (pbecp instanceof NiFiLegacyCipherProvider) {
salt = ((NiFiLegacyCipherProvider) pbecp).generateSalt(encryptionMethod);
} else {
salt = pbecp.generateSalt();
}
// Determine necessary key length
int keyLength = CipherUtility.parseKeyLengthFromAlgorithm(algorithm);
// Generate cipher
try {
Cipher cipher = pbecp.getCipher(encryptionMethod, new String(password.getPassword()), salt, keyLength, true);
// Write IV if necessary (allows for future use of PBKDF2, Bcrypt, or Scrypt)
// byte[] iv = new byte[0];
// if (cipherProvider instanceof RandomIVPBECipherProvider) {
// iv = cipher.getIV();
// }
// Encrypt the plaintext
byte[] cipherBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
// Combine the output
// byte[] rawBytes = CryptoUtils.concatByteArrays(salt, iv, cipherBytes);
return CryptoUtils.concatByteArrays(salt, cipherBytes);
} catch (Exception e) {
throw new EncryptionException("Could not encrypt sensitive value", e);
}
}
private byte[] encryptKeyed(String plaintext) {
KeyedCipherProvider keyedcp = (KeyedCipherProvider) cipherProvider;
// Generate cipher
try {
SecureRandom sr = new SecureRandom();
byte[] iv = new byte[16];
sr.nextBytes(iv);
Cipher cipher = keyedcp.getCipher(EncryptionMethod.forAlgorithm(algorithm), key, iv, true);
// Encrypt the plaintext
byte[] cipherBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
// Combine the output
return CryptoUtils.concatByteArrays(iv, cipherBytes);
} catch (Exception e) {
throw new EncryptionException("Could not encrypt sensitive value", e);
}
}
private String encode(byte[] rawBytes) {
if (this.encoding.equalsIgnoreCase("HEX")) {
return Hex.encodeHexString(rawBytes);
} else {
return Base64.toBase64String(rawBytes);
}
}
/**
* Decrypts the given cipher text.
*
* @param cipherText the message to decrypt
* @return the clear text
* @throws EncryptionException if the decrypt fails
*/
public String decrypt(String cipherText) throws EncryptionException {
try {
if (isInitialized()) {
byte[] plainBytes;
byte[] cipherBytes = decode(cipherText);
if (CipherUtility.isPBECipher(algorithm)) {
plainBytes = decryptPBE(cipherBytes);
} else {
plainBytes = decryptKeyed(cipherBytes);
}
return new String(plainBytes, StandardCharsets.UTF_8);
} else {
throw new EncryptionException("The encryptor is not initialized");
}
} catch (final Exception e) {
throw new EncryptionException(e);
}
}
private byte[] decryptPBE(byte[] cipherBytes) throws DecoderException {
PBECipherProvider pbecp = (PBECipherProvider) cipherProvider;
final EncryptionMethod encryptionMethod = EncryptionMethod.forAlgorithm(algorithm);
// Extract salt
int saltLength = CipherUtility.getSaltLengthForAlgorithm(algorithm);
byte[] salt = new byte[saltLength];
System.arraycopy(cipherBytes, 0, salt, 0, saltLength);
byte[] actualCipherBytes = Arrays.copyOfRange(cipherBytes, saltLength, cipherBytes.length);
// Determine necessary key length
int keyLength = CipherUtility.parseKeyLengthFromAlgorithm(algorithm);
// Generate cipher
try {
Cipher cipher = pbecp.getCipher(encryptionMethod, new String(password.getPassword()), salt, keyLength, false);
// Write IV if necessary (allows for future use of PBKDF2, Bcrypt, or Scrypt)
// byte[] iv = new byte[0];
// if (cipherProvider instanceof RandomIVPBECipherProvider) {
// iv = cipher.getIV();
// }
// Decrypt the plaintext
return cipher.doFinal(actualCipherBytes);
} catch (Exception e) {
throw new EncryptionException("Could not decrypt sensitive value", e);
}
}
private byte[] decryptKeyed(byte[] cipherBytes) {
KeyedCipherProvider keyedcp = (KeyedCipherProvider) cipherProvider;
// Generate cipher
try {
int ivLength = 16;
byte[] iv = new byte[ivLength];
System.arraycopy(cipherBytes, 0, iv, 0, ivLength);
byte[] actualCipherBytes = Arrays.copyOfRange(cipherBytes, ivLength, cipherBytes.length);
Cipher cipher = keyedcp.getCipher(EncryptionMethod.forAlgorithm(algorithm), key, iv, false);
// Encrypt the plaintext
return cipher.doFinal(actualCipherBytes);
} catch (Exception e) {
throw new EncryptionException("Could not decrypt sensitive value", e);
}
}
private byte[] decode(String encoded) throws DecoderException {
if (this.encoding.equalsIgnoreCase("HEX")) {
return Hex.decodeHex(encoded.toCharArray());
} else {
return Base64.decode(encoded);
}
}
public boolean isInitialized() {
return this.cipherProvider != null;
}
protected static boolean algorithmIsValid(String algorithm) {
return SUPPORTED_ALGORITHMS.contains(algorithm);
}
protected static boolean providerIsValid(String provider) {
return SUPPORTED_PROVIDERS.contains(provider);
}
}
| |
/**
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl2.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.kuali.rice.krms.impl.repository;
import org.apache.commons.lang.StringUtils;
import org.kuali.rice.core.api.mo.common.Versioned;
import org.kuali.rice.krad.data.jpa.PortableSequenceGenerator;
import org.kuali.rice.krms.api.repository.action.ActionDefinition;
import org.kuali.rice.krms.api.repository.action.ActionDefinitionContract;
import org.kuali.rice.krms.api.repository.type.KrmsAttributeDefinition;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* The Action Business Object is the Action mutable class.
*
* @author Kuali Rice Team (rice.collab@kuali.org)
* @see ActionDefinition
* @see ActionDefinitionContract
* @see org.kuali.rice.krms.framework.engine.Action
*/
@Entity
@Table(name = "KRMS_ACTN_T")
public class ActionBo implements ActionDefinitionContract, Versioned, Serializable {
private static final long serialVersionUID = 1l;
@PortableSequenceGenerator(name = "KRMS_ACTN_S")
@GeneratedValue(generator = "KRMS_ACTN_S")
@Id
@Column(name = "ACTN_ID")
private String id;
@Column(name = "NMSPC_CD")
private String namespace;
@Column(name = "NM")
private String name;
@Column(name = "DESC_TXT")
private String description;
@Column(name = "TYP_ID")
private String typeId;
@ManyToOne()
@JoinColumn(name = "RULE_ID")
private RuleBo rule;
@Column(name = "SEQ_NO")
private Integer sequenceNumber;
@Column(name = "VER_NBR")
@Version
private Long versionNumber;
@OneToMany(orphanRemoval = true, mappedBy = "action", fetch = FetchType.LAZY,
cascade = { CascadeType.REFRESH, CascadeType.MERGE, CascadeType.REMOVE, CascadeType.PERSIST })
@JoinColumn(name = "ACTN_ATTR_DATA_ID", referencedColumnName = "ACTN_ATTR_DATA_ID")
private List<ActionAttributeBo> attributeBos;
@Override
public Map<String, String> getAttributes() {
HashMap<String, String> attributes = new HashMap<String, String>();
if (attributeBos != null) for (ActionAttributeBo attr : attributeBos) {
if (attr.getAttributeDefinition() == null) {
attributes.put("", "");
} else {
attributes.put(attr.getAttributeDefinition().getName(), attr.getValue());
}
}
return attributes;
}
/**
* Set the Action Attributes
*
* @param attributes to add to this Action
*/
public void setAttributes(Map<String, String> attributes) {
this.attributeBos = new ArrayList<ActionAttributeBo>();
if (!StringUtils.isBlank(this.typeId)) {
List<KrmsAttributeDefinition> attributeDefinitions = KrmsRepositoryServiceLocator.getKrmsAttributeDefinitionService().findAttributeDefinitionsByType(this.getTypeId());
Map<String, KrmsAttributeDefinition> attributeDefinitionsByName = new HashMap<String, KrmsAttributeDefinition>();
if (attributeDefinitions != null) {
for (KrmsAttributeDefinition attributeDefinition : attributeDefinitions) {
attributeDefinitionsByName.put(attributeDefinition.getName(), attributeDefinition);
}
}
for (Map.Entry<String, String> attr : attributes.entrySet()) {
KrmsAttributeDefinition attributeDefinition = attributeDefinitionsByName.get(attr.getKey());
if (attributeDefinition != null) {
ActionAttributeBo attributeBo = new ActionAttributeBo();
attributeBo.setAction(this);
attributeBo.setValue(attr.getValue());
attributeBo.setAttributeDefinition(KrmsAttributeDefinitionBo.from(attributeDefinition));
attributeBos.add(attributeBo);
}
}
}
}
/**
* Converts a mutable bo to it's immutable counterpart
*
* @param bo the mutable business object
* @return the immutable object
*/
public static ActionDefinition to(ActionBo bo) {
if (bo == null) {
return null;
}
return ActionDefinition.Builder.create(bo).build();
}
/**
* Converts a immutable object to it's mutable bo counterpart
*
* @param im immutable object
* @return the mutable bo
*/
public static ActionBo from(ActionDefinition im) {
if (im == null) {
return null;
}
ActionBo bo = new ActionBo();
bo.id = im.getId();
bo.namespace = im.getNamespace();
bo.name = im.getName();
bo.typeId = im.getTypeId();
bo.description = im.getDescription();
// we don't set the rule because we only have the ruleId in the ActionDefinition. If you need the RuleBo as
// well, use RuleBo.from to convert the RuleDefinition and all it's children as well.
bo.sequenceNumber = im.getSequenceNumber();
bo.setVersionNumber(im.getVersionNumber());
// build the list of action attribute BOs
List<ActionAttributeBo> attrs = new ArrayList<ActionAttributeBo>();
// for each converted pair, build an ActionAttributeBo and add it to the set
for (Map.Entry<String, String> entry : im.getAttributes().entrySet()) {
KrmsAttributeDefinitionBo attrDefBo = KrmsRepositoryServiceLocator.getKrmsAttributeDefinitionService().getKrmsAttributeBo(entry.getKey(), im.getNamespace());
ActionAttributeBo attributeBo = new ActionAttributeBo();
attributeBo.setAction(bo);
attributeBo.setValue(entry.getValue());
attributeBo.setAttributeDefinition(attrDefBo);
attrs.add(attributeBo);
}
bo.setAttributeBos(attrs);
return bo;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTypeId() {
return typeId;
}
public void setTypeId(String typeId) {
this.typeId = typeId;
}
public String getRuleId() {
if (rule != null) {
return rule.getId();
}
return null;
}
public RuleBo getRule() {
return rule;
}
public void setRule(RuleBo rule) {
this.rule = rule;
}
public Integer getSequenceNumber() {
return sequenceNumber;
}
public void setSequenceNumber(Integer sequenceNumber) {
this.sequenceNumber = sequenceNumber;
}
public Long getVersionNumber() {
return versionNumber;
}
public void setVersionNumber(Long versionNumber) {
this.versionNumber = versionNumber;
}
public List<ActionAttributeBo> getAttributeBos() {
return attributeBos;
}
public void setAttributeBos(List<ActionAttributeBo> attributeBos) {
this.attributeBos = attributeBos;
}
}
| |
// Copyright 2016 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.remote;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.ListeningScheduledExecutorService;
import com.google.common.util.concurrent.MoreExecutors;
import com.google.devtools.build.lib.authandtls.AuthAndTLSOptions;
import com.google.devtools.build.lib.authandtls.GoogleAuthUtils;
import com.google.devtools.build.lib.buildeventstream.BuildEventArtifactUploader;
import com.google.devtools.build.lib.buildeventstream.BuildEventArtifactUploaderFactory;
import com.google.devtools.build.lib.buildtool.BuildRequest;
import com.google.devtools.build.lib.events.Event;
import com.google.devtools.build.lib.exec.ExecutorBuilder;
import com.google.devtools.build.lib.remote.Retrier.RetryException;
import com.google.devtools.build.lib.remote.logging.LoggingInterceptor;
import com.google.devtools.build.lib.remote.util.DigestUtil;
import com.google.devtools.build.lib.remote.util.TracingMetadataUtils;
import com.google.devtools.build.lib.runtime.BlazeModule;
import com.google.devtools.build.lib.runtime.Command;
import com.google.devtools.build.lib.runtime.CommandEnvironment;
import com.google.devtools.build.lib.runtime.ServerBuilder;
import com.google.devtools.build.lib.util.AbruptExitException;
import com.google.devtools.build.lib.util.ExitCode;
import com.google.devtools.build.lib.util.io.AsynchronousFileOutputStream;
import com.google.devtools.build.lib.vfs.DigestHashFunction;
import com.google.devtools.build.lib.vfs.FileSystemUtils;
import com.google.devtools.build.lib.vfs.Path;
import com.google.devtools.common.options.OptionsBase;
import com.google.devtools.common.options.OptionsProvider;
import com.google.protobuf.Any;
import com.google.protobuf.InvalidProtocolBufferException;
import com.google.rpc.PreconditionFailure;
import com.google.rpc.PreconditionFailure.Violation;
import io.grpc.CallCredentials;
import io.grpc.ClientInterceptor;
import io.grpc.Context;
import io.grpc.ManagedChannel;
import io.grpc.Status.Code;
import io.grpc.protobuf.StatusProto;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.function.Predicate;
import java.util.logging.Logger;
/** RemoteModule provides distributed cache and remote execution for Bazel. */
public final class RemoteModule extends BlazeModule {
private static final Logger logger = Logger.getLogger(RemoteModule.class.getName());
private AsynchronousFileOutputStream rpcLogFile;
private final ListeningScheduledExecutorService retryScheduler =
MoreExecutors.listeningDecorator(Executors.newScheduledThreadPool(1));
private RemoteActionContextProvider actionContextProvider;
private final BuildEventArtifactUploaderFactoryDelegate
buildEventArtifactUploaderFactoryDelegate = new BuildEventArtifactUploaderFactoryDelegate();
@Override
public void serverInit(OptionsProvider startupOptions, ServerBuilder builder) {
builder.addBuildEventArtifactUploaderFactory(buildEventArtifactUploaderFactoryDelegate, "remote");
}
private static final String VIOLATION_TYPE_MISSING = "MISSING";
private static final Predicate<? super Exception> RETRIABLE_EXEC_ERRORS =
e -> {
if (e instanceof CacheNotFoundException || e.getCause() instanceof CacheNotFoundException) {
return true;
}
if (!(e instanceof RetryException)
|| !RemoteRetrierUtils.causedByStatus((RetryException) e, Code.FAILED_PRECONDITION)) {
return false;
}
com.google.rpc.Status status = StatusProto.fromThrowable(e);
if (status == null || status.getDetailsCount() == 0) {
return false;
}
for (Any details : status.getDetailsList()) {
PreconditionFailure f;
try {
f = details.unpack(PreconditionFailure.class);
} catch (InvalidProtocolBufferException protoEx) {
return false;
}
if (f.getViolationsCount() == 0) {
return false; // Generally shouldn't happen
}
for (Violation v : f.getViolationsList()) {
if (!v.getType().equals(VIOLATION_TYPE_MISSING)) {
return false;
}
}
}
return true; // if *all* > 0 violations have type MISSING
};
@Override
public void beforeCommand(CommandEnvironment env) throws AbruptExitException {
env.getEventBus().register(this);
String buildRequestId = env.getBuildRequestId().toString();
String commandId = env.getCommandId().toString();
logger.info("Command: buildRequestId = " + buildRequestId + ", commandId = " + commandId);
Path logDir =
env.getOutputBase().getRelative(env.getRuntime().getProductName() + "-remote-logs");
try {
// Clean out old logs files.
if (logDir.exists()) {
FileSystemUtils.deleteTree(logDir);
}
logDir.createDirectory();
} catch (IOException e) {
env.getReporter()
.handle(Event.error("Could not create base directory for remote logs: " + logDir));
throw new AbruptExitException(ExitCode.LOCAL_ENVIRONMENTAL_ERROR, e);
}
RemoteOptions remoteOptions = env.getOptions().getOptions(RemoteOptions.class);
AuthAndTLSOptions authAndTlsOptions = env.getOptions().getOptions(AuthAndTLSOptions.class);
DigestHashFunction hashFn = env.getRuntime().getFileSystem().getDigestFunction();
DigestUtil digestUtil = new DigestUtil(hashFn);
// Quit if no remote options specified.
if (remoteOptions == null) {
return;
}
boolean enableRestCache = SimpleBlobStoreFactory.isRestUrlOptions(remoteOptions);
boolean enableDiskCache = SimpleBlobStoreFactory.isDiskCache(remoteOptions);
if (enableRestCache && enableDiskCache) {
throw new AbruptExitException(
"Cannot enable HTTP-based and local disk cache simultaneously",
ExitCode.COMMAND_LINE_ERROR);
}
boolean enableBlobStoreCache = enableRestCache || enableDiskCache;
boolean enableGrpcCache = GrpcRemoteCache.isRemoteCacheOptions(remoteOptions);
if (enableBlobStoreCache && remoteOptions.remoteExecutor != null) {
throw new AbruptExitException(
"Cannot combine gRPC based remote execution with local disk or HTTP-based caching",
ExitCode.COMMAND_LINE_ERROR);
}
try {
List<ClientInterceptor> interceptors = new ArrayList<>();
if (!remoteOptions.experimentalRemoteGrpcLog.isEmpty()) {
rpcLogFile = new AsynchronousFileOutputStream(remoteOptions.experimentalRemoteGrpcLog);
interceptors.add(new LoggingInterceptor(rpcLogFile, env.getRuntime().getClock()));
}
final RemoteRetrier executeRetrier;
final AbstractRemoteActionCache cache;
if (enableBlobStoreCache) {
Retrier retrier =
new Retrier(
() -> Retrier.RETRIES_DISABLED,
(e) -> false,
retryScheduler,
Retrier.ALLOW_ALL_CALLS);
executeRetrier = null;
cache =
new SimpleBlobStoreActionCache(
remoteOptions,
SimpleBlobStoreFactory.create(
remoteOptions,
GoogleAuthUtils.newCredentials(authAndTlsOptions),
env.getWorkingDirectory()),
retrier,
digestUtil);
} else if (enableGrpcCache || remoteOptions.remoteExecutor != null) {
// If a remote executor but no remote cache is specified, assume both at the same target.
String target = enableGrpcCache ? remoteOptions.remoteCache : remoteOptions.remoteExecutor;
ReferenceCountedChannel channel =
new ReferenceCountedChannel(
GoogleAuthUtils.newChannel(
target,
authAndTlsOptions,
interceptors.toArray(new ClientInterceptor[0])));
RemoteRetrier rpcRetrier =
new RemoteRetrier(
remoteOptions,
RemoteRetrier.RETRIABLE_GRPC_ERRORS,
retryScheduler,
Retrier.ALLOW_ALL_CALLS);
executeRetrier = createExecuteRetrier(remoteOptions, retryScheduler);
CallCredentials credentials = GoogleAuthUtils.newCallCredentials(authAndTlsOptions);
ByteStreamUploader uploader =
new ByteStreamUploader(
remoteOptions.remoteInstanceName,
channel.retain(),
credentials,
remoteOptions.remoteTimeout,
rpcRetrier);
cache =
new GrpcRemoteCache(
channel.retain(),
credentials,
remoteOptions,
rpcRetrier,
digestUtil,
uploader.retain());
Context requestContext =
TracingMetadataUtils.contextWithMetadata(buildRequestId, commandId, "bes-upload");
buildEventArtifactUploaderFactoryDelegate.init(
new ByteStreamBuildEventArtifactUploaderFactory(
uploader, target, requestContext, remoteOptions.remoteInstanceName));
uploader.release();
channel.release();
} else {
executeRetrier = null;
cache = null;
}
final GrpcRemoteExecutor executor;
if (remoteOptions.remoteExecutor != null) {
ManagedChannel channel =
GoogleAuthUtils.newChannel(
remoteOptions.remoteExecutor,
authAndTlsOptions,
interceptors.toArray(new ClientInterceptor[0]));
RemoteRetrier retrier =
new RemoteRetrier(
remoteOptions,
RemoteRetrier.RETRIABLE_GRPC_ERRORS,
retryScheduler,
Retrier.ALLOW_ALL_CALLS);
executor =
new GrpcRemoteExecutor(
channel,
GoogleAuthUtils.newCallCredentials(authAndTlsOptions),
remoteOptions.remoteTimeout,
retrier);
} else {
executor = null;
}
actionContextProvider =
new RemoteActionContextProvider(env, cache, executor, executeRetrier, digestUtil, logDir);
} catch (IOException e) {
env.getReporter().handle(Event.error(e.getMessage()));
env.getBlazeModuleEnvironment()
.exit(
new AbruptExitException(
"Error initializing RemoteModule", ExitCode.COMMAND_LINE_ERROR));
}
}
@Override
public void afterCommand() {
if (rpcLogFile != null) {
try {
rpcLogFile.close();
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
rpcLogFile = null;
}
}
buildEventArtifactUploaderFactoryDelegate.reset();
}
@Override
public void executorInit(CommandEnvironment env, BuildRequest request, ExecutorBuilder builder) {
if (actionContextProvider != null) {
builder.addActionContextProvider(actionContextProvider);
}
}
@Override
public Iterable<Class<? extends OptionsBase>> getCommandOptions(Command command) {
return "build".equals(command.name())
? ImmutableList.of(RemoteOptions.class, AuthAndTLSOptions.class)
: ImmutableList.of();
}
static RemoteRetrier createExecuteRetrier(
RemoteOptions options, ListeningScheduledExecutorService retryService) {
return new RemoteRetrier(
options.experimentalRemoteRetry
? () -> new Retrier.ZeroBackoff(options.experimentalRemoteRetryMaxAttempts)
: () -> Retrier.RETRIES_DISABLED,
RemoteModule.RETRIABLE_EXEC_ERRORS,
retryService,
Retrier.ALLOW_ALL_CALLS);
}
private static class BuildEventArtifactUploaderFactoryDelegate
implements BuildEventArtifactUploaderFactory {
private volatile BuildEventArtifactUploaderFactory uploaderFactory;
public void init(BuildEventArtifactUploaderFactory uploaderFactory) {
Preconditions.checkState(this.uploaderFactory == null);
this.uploaderFactory = uploaderFactory;
}
public void reset() {
this.uploaderFactory = null;
}
@Override
public BuildEventArtifactUploader create(OptionsProvider options) {
BuildEventArtifactUploaderFactory uploaderFactory0 = this.uploaderFactory;
if (uploaderFactory0 == null) {
return BuildEventArtifactUploader.LOCAL_FILES_UPLOADER;
}
return uploaderFactory0.create(options);
}
}
}
| |
package org.apache.sling.extensions.webconsolesecurityprovider.internal;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import java.util.Dictionary;
import java.util.Hashtable;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.jcr.Repository;
import org.apache.felix.webconsole.WebConsoleSecurityProvider;
import org.apache.sling.api.auth.Authenticator;
import org.apache.sling.auth.core.AuthenticationSupport;
import org.apache.sling.launchpad.api.StartupListener;
import org.apache.sling.launchpad.api.StartupMode;
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.InvalidSyntaxException;
import org.osgi.framework.ServiceEvent;
import org.osgi.framework.ServiceListener;
import org.osgi.framework.ServiceReference;
import org.osgi.framework.ServiceRegistration;
import org.osgi.service.cm.ManagedService;
/**
* The <code>ServicesListener</code> listens for the required services
* and registers the security provider when required services are available
*/
public class ServicesListener implements StartupListener {
private static final String AUTH_SUPPORT_CLASS = AuthenticationSupport.class.getName();
private static final String AUTHENTICATOR_CLASS = Authenticator.class.getName();
private static final String REPO_CLASS = Repository.class.getName();
/** The bundle context. */
private final BundleContext bundleContext;
/** The listener for the repository. */
private final Listener repositoryListener;
/** The listener for the authentication support. */
private final Listener authSupportListener;
/** The listener for the authenticator. */
private final Listener authListener;
private enum State {
NONE,
PROVIDER,
PROVIDER2
};
/** State */
private volatile State registrationState = State.NONE;
/** The registration for the provider */
private ServiceRegistration providerReg;
/** The registration for the provider2 */
private ServiceRegistration provider2Reg;
/** Flag for marking if startup is finished. */
private final AtomicBoolean startupFinished = new AtomicBoolean(false);
/**
* Start listeners
*/
public ServicesListener(final BundleContext bundleContext) {
this.bundleContext = bundleContext;
this.authSupportListener = new Listener(AUTH_SUPPORT_CLASS);
this.repositoryListener = new Listener(REPO_CLASS);
this.authListener = new Listener(AUTHENTICATOR_CLASS);
this.authSupportListener.start();
this.repositoryListener.start();
this.authListener.start();
}
/**
* @see org.apache.sling.launchpad.api.StartupListener#inform(org.apache.sling.launchpad.api.StartupMode, boolean)
*/
public void inform(final StartupMode mode, final boolean finished) {
if ( finished && this.startupFinished.compareAndSet(false, true) ) {
notifyChange();
}
}
/**
* @see org.apache.sling.launchpad.api.StartupListener#startupFinished(org.apache.sling.launchpad.api.StartupMode)
*/
public void startupFinished(final StartupMode mode) {
if ( this.startupFinished.compareAndSet(false, true) ) {
notifyChange();
}
}
/**
* @see org.apache.sling.launchpad.api.StartupListener#startupProgress(float)
*/
public void startupProgress(final float progress) {
// nothing to do
}
/**
* Notify of service changes from the listeners.
*/
public synchronized void notifyChange() {
// check if all services are available
final Object authSupport = this.startupFinished.get() ? this.authSupportListener.getService() : null;
final Object authenticator = this.startupFinished.get() ? this.authListener.getService() : null;
final boolean hasAuthServices = authSupport != null && authenticator != null;
final Object repository = this.repositoryListener.getService();
if ( registrationState == State.NONE ) {
if ( hasAuthServices ) {
registerProvider2(authSupport, authenticator);
} else if ( repository != null ) {
registerProvider(repository);
}
} else if ( registrationState == State.PROVIDER ) {
if ( hasAuthServices ) {
registerProvider2(authSupport, authenticator);
unregisterProvider();
} else if ( repository == null ) {
unregisterProvider();
this.registrationState = State.NONE;
}
} else {
if ( authSupport == null ) {
if ( repository != null ) {
registerProvider(repository);
} else {
this.registrationState = State.NONE;
}
unregisterProvider2();
}
}
}
private void unregisterProvider2() {
if ( this.provider2Reg != null ) {
this.provider2Reg.unregister();
this.provider2Reg = null;
}
}
private void unregisterProvider() {
if ( this.providerReg != null ) {
this.providerReg.unregister();
this.providerReg = null;
}
}
private void registerProvider2(final Object authSupport, final Object authenticator) {
final Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(Constants.SERVICE_PID, SlingWebConsoleSecurityProvider.class.getName());
props.put(Constants.SERVICE_DESCRIPTION, "Apache Sling Web Console Security Provider 2");
props.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
this.provider2Reg = this.bundleContext.registerService(
new String[] {ManagedService.class.getName(), WebConsoleSecurityProvider.class.getName()},
new SlingWebConsoleSecurityProvider2(authSupport, authenticator), props);
this.registrationState = State.PROVIDER2;
}
private void registerProvider(final Object repository) {
final Dictionary<String, Object> props = new Hashtable<String, Object>();
props.put(Constants.SERVICE_PID, SlingWebConsoleSecurityProvider.class.getName());
props.put(Constants.SERVICE_DESCRIPTION, "Apache Sling Web Console Security Provider");
props.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
this.providerReg = this.bundleContext.registerService(
new String[] {ManagedService.class.getName(), WebConsoleSecurityProvider.class.getName()}, new SlingWebConsoleSecurityProvider(repository), props);
this.registrationState = State.PROVIDER;
}
/**
* Deactivate this listener.
*/
public void deactivate() {
this.repositoryListener.deactivate();
this.authSupportListener.deactivate();
this.authListener.deactivate();
this.unregisterProvider();
this.unregisterProvider2();
}
/**
* Helper class listening for service events for a defined service.
*/
protected final class Listener implements ServiceListener {
/** The name of the service. */
private final String serviceName;
/** The service reference. */
private volatile ServiceReference reference;
/** The service. */
private volatile Object service;
/**
* Constructor
*/
public Listener(final String serviceName) {
this.serviceName = serviceName;
}
/**
* Start the listener.
* First register a service listener and then check for the service.
*/
public void start() {
try {
bundleContext.addServiceListener(this, "("
+ Constants.OBJECTCLASS + "=" + serviceName + ")");
} catch (final InvalidSyntaxException ise) {
// this should really never happen
throw new RuntimeException("Unexpected exception occured.", ise);
}
final ServiceReference ref = bundleContext.getServiceReference(serviceName);
if ( ref != null ) {
this.retainService(ref);
}
}
/**
* Unregister the listener.
*/
public void deactivate() {
bundleContext.removeServiceListener(this);
}
/**
* Return the service (if available)
*/
public synchronized Object getService() {
return this.service;
}
/**
* Try to get the service and notify the change.
*/
private synchronized void retainService(final ServiceReference ref) {
boolean hadService = this.service != null;
boolean getService = this.reference == null;
if ( !getService ) {
final int result = this.reference.compareTo(ref);
if ( result < 0 ) {
bundleContext.ungetService(this.reference);
this.service = null;
getService = true;
}
}
if ( getService ) {
this.reference = ref;
this.service = bundleContext.getService(this.reference);
if ( this.service == null ) {
this.reference = null;
} else {
notifyChange();
}
}
if ( hadService && this.service == null ) {
notifyChange();
}
}
/**
* Try to release the service and notify the change.
*/
private synchronized void releaseService(final ServiceReference ref) {
if ( this.reference != null && this.reference.compareTo(ref) == 0) {
this.service = null;
bundleContext.ungetService(this.reference);
this.reference = null;
notifyChange();
}
}
/**
* @see org.osgi.framework.ServiceListener#serviceChanged(org.osgi.framework.ServiceEvent)
*/
public void serviceChanged(final ServiceEvent event) {
if (event.getType() == ServiceEvent.REGISTERED) {
this.retainService(event.getServiceReference());
} else if ( event.getType() == ServiceEvent.UNREGISTERING ) {
this.releaseService(event.getServiceReference());
} else if ( event.getType() == ServiceEvent.MODIFIED ) {
notifyChange();
}
}
}
}
| |
package com.initianovamc.rysingdragon.landprotect.commands;
import com.initianovamc.rysingdragon.landprotect.LandProtect;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.command.args.GenericArguments;
import org.spongepowered.api.command.spec.CommandSpec;
import org.spongepowered.api.text.Text;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CommandRegistry {
private static LandProtect plugin = LandProtect.instance;
public static void registerCommands() {
CommandSpec landProtect = CommandSpec.builder()
.children(getSubCommands())
.description(Text.of("base command for all LandProtect commands"))
.executor(new LandProtectCommand())
.build();
Sponge.getGame().getCommandManager().register(plugin, landProtect, "landprotect", "lp");
}
public static Map<List<String>, CommandSpec> getSubCommands() {
Map<List<String>, CommandSpec> commands = new HashMap<>();
CommandSpec addInteractable = CommandSpec.builder()
.description(Text.of("Adds a block as interactable in protected zones"))
.permission("landprotect.addinteractable.command")
.executor(new AddInteractableCommand())
.arguments(GenericArguments.optional(GenericArguments.string(Text.of("block-id"))))
.build();
commands.put(Arrays.asList("addinteractable"), addInteractable);
CommandSpec claim = CommandSpec.builder()
.description(Text.of("Claims the chunk the player is standing in when used"))
.permission("landprotect.claim.command")
.executor(new ClaimCommand())
.build();
commands.put(Arrays.asList("claim"), claim);
CommandSpec addFriend = CommandSpec.builder()
.description(Text.of("Sends a request to a player so both of you will have access to each other's claims"))
.permission("landprotect.addfriend.command")
.executor(new AddFriendCommand())
.arguments(GenericArguments.player(Text.of("friend")))
.build();
commands.put(Arrays.asList("addfriend"), addFriend);
CommandSpec acceptFriend = CommandSpec.builder()
.description(Text.of("Accepts a player's friend request"))
.permission("landprotect.acceptrequest.command")
.executor(new AcceptFriendRequestCommand())
.build();
commands.put(Arrays.asList("acceptrequest"), acceptFriend);
CommandSpec adminclaim = CommandSpec.builder()
.description(Text.of("Claims the chunk you're standing in as an adminclaim"))
.permission("landprotect.adminclaim.command")
.executor(new AdminClaimCommand())
.build();
commands.put(Arrays.asList("adminclaim"), adminclaim);
CommandSpec trust = CommandSpec.builder()
.description(Text.of("Adds the player access to your claim you're standing in"))
.permission("landprotect.trust.command")
.executor(new TrustCommand())
.arguments(GenericArguments.user(Text.of("player")))
.build();
commands.put(Arrays.asList("trust"), trust);
CommandSpec unclaim = CommandSpec.builder()
.description(Text.of("Unclaims the chunk you're standing in and removes all trusted people access to it"))
.permission("landprotect.unclaim.command")
.executor(new UnclaimCommand())
.build();
commands.put(Arrays.asList("unclaim"), unclaim);
CommandSpec removeAdminclaim = CommandSpec.builder()
.description(Text.of("Removes this chunk as an adminclaim"))
.permission("landprotect.removeadminclaim.command")
.executor(new RemoveAdminClaimCommand())
.build();
commands.put(Arrays.asList("removeadminclaim"), removeAdminclaim);
CommandSpec help = CommandSpec.builder()
.description(Text.of("help command"))
.permission("landprotect.help.command")
.executor(new HelpCommand())
.build();
commands.put(Arrays.asList("help"), help);
CommandSpec removeClaim = CommandSpec.builder()
.description(Text.of("forcefully removes a claimed chunk"))
.permission("landprotect.removeclaim.command")
.executor(new RemoveClaimCommand())
.build();
commands.put(Arrays.asList("removeclaim"), removeClaim);
CommandSpec removeFriend = CommandSpec.builder()
.description(Text.of("removes the targeted player as a friend"))
.permission("landprotect.removefriend.command")
.executor(new RemoveFriendCommand())
.arguments(GenericArguments.user(Text.of("friend")))
.build();
commands.put(Arrays.asList("removefriend"), removeFriend);
CommandSpec untrust = CommandSpec.builder()
.description(Text.of("Remove a player as trusted from your land"))
.permission("landprotect.untrust.command")
.executor(new UntrustCommand())
.arguments(GenericArguments.user(Text.of("player")))
.build();
commands.put(Arrays.asList("untrust"), untrust);
CommandSpec interactableList = CommandSpec.builder()
.description(Text.of("List all interactable blocks"))
.permission("landprotect.listinteractables.command")
.executor(new InteractableListCommand())
.build();
commands.put(Arrays.asList("listinteractables"), interactableList);
CommandSpec removeInteractable = CommandSpec.builder()
.description(Text.of("Remove a block from being interactable"))
.permission("landprotect.removeinteractable.command")
.executor(new RemoveInteractableCommand())
.arguments(GenericArguments.optional(GenericArguments.string(Text.of("block-id"))))
.build();
commands.put(Arrays.asList("removeinteractable"), removeInteractable);
CommandSpec reloadConfig = CommandSpec.builder()
.description(Text.of("reload config"))
.permission("landprotect.reloadconfig.command")
.executor(new ReloadConfigCommand())
.build();
commands.put(Arrays.asList("reload"), reloadConfig);
CommandSpec setInspectTool = CommandSpec.builder()
.description(Text.of("sets the inspector tool to toggle claims on/off"))
.permission("landprotect.settool.command")
.executor(new SetClaimInspectToolCommand())
.arguments(GenericArguments.string(Text.of("item-id")))
.build();
commands.put(Arrays.asList("setinspecttool", "sit"), setInspectTool);
CommandSpec setBoundaryBlock = CommandSpec.builder()
.description(Text.of("sets the block to which players see claim boundaries as"))
.permission("landprotect.setboundaryblock.command")
.executor(new SetBoundaryBlockCommand())
.arguments(GenericArguments.string(Text.of("block-id")))
.build();
commands.put(Arrays.asList("setboundaryblock", "sbb"), setBoundaryBlock);
CommandSpec reloadData = CommandSpec.builder()
.description(Text.of("command that reloads the database"))
.permission("landprotect.datareload.command")
.executor(new ReloadDataCommand())
.build();
commands.put(Arrays.asList("datareload"), reloadData);
CommandSpec buyClaims = CommandSpec.builder()
.description(Text.of("buys the specified amount of claims using either economy currency if enabled or using experience points"))
.permission("landprotect.buyclaims.command")
.arguments(GenericArguments.integer(Text.of("claims")))
.executor(new BuyClaimsCommand())
.build();
commands.put(Arrays.asList("buyclaims"), buyClaims);
CommandSpec listClaims = CommandSpec.builder()
.description(Text.of("lists all of your claims in each world by chunk coordinates"))
.permission("landprotect.listclaims.command")
.executor(new ListClaimsCommand())
.build();
commands.put(Arrays.asList("listclaims"), listClaims);
CommandSpec claimBoots = CommandSpec.builder()
.description(Text.of("gives boots for adminclaiming"))
.permission("landprotect.giveclaimboots.command")
.executor(new ClaimBootsCommand())
.build();
commands.put(Arrays.asList("giveclaimboots"), claimBoots);
CommandSpec addUnallowedEntity = CommandSpec.builder()
.description(Text.of("adds the entity to list of entities not allowed to be ridden"))
.permission("landprotect.addunallowedentity.command")
.executor(new AddUnallowedEntityCommand())
.build();
commands.put(Arrays.asList("addunallowedentity"), addUnallowedEntity);
CommandSpec removeUnallowedEntity = CommandSpec.builder()
.description(Text.of("removes the entity from list of entities not allowed to be ridden"))
.permission("landprotect.removeunallowedentity.command")
.executor(new AddUnallowedEntityCommand())
.build();
commands.put(Arrays.asList("removeunallowedentity"), removeUnallowedEntity);
return commands;
}
}
| |
/*
* Copyright 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.overlord.dtgov.ui.client.local.pages;
import javax.annotation.PostConstruct;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Instance;
import javax.inject.Inject;
import org.jboss.errai.ui.nav.client.local.Page;
import org.jboss.errai.ui.nav.client.local.TransitionAnchor;
import org.jboss.errai.ui.shared.api.annotations.DataField;
import org.jboss.errai.ui.shared.api.annotations.EventHandler;
import org.jboss.errai.ui.shared.api.annotations.Templated;
import org.overlord.commons.gwt.client.local.events.TableSortEvent;
import org.overlord.commons.gwt.client.local.widgets.HtmlSnippet;
import org.overlord.commons.gwt.client.local.widgets.Pager;
import org.overlord.commons.gwt.client.local.widgets.SortableTemplatedWidgetTable.SortColumn;
import org.overlord.dtgov.ui.client.local.ClientMessages;
import org.overlord.dtgov.ui.client.local.pages.deployments.AddDeploymentDialog;
import org.overlord.dtgov.ui.client.local.pages.deployments.DeploymentFilters;
import org.overlord.dtgov.ui.client.local.pages.deployments.DeploymentTable;
import org.overlord.dtgov.ui.client.local.services.ApplicationStateKeys;
import org.overlord.dtgov.ui.client.local.services.ApplicationStateService;
import org.overlord.dtgov.ui.client.local.services.DeploymentsRpcService;
import org.overlord.dtgov.ui.client.local.services.NotificationService;
import org.overlord.dtgov.ui.client.local.services.rpc.IRpcServiceInvocationHandler;
import org.overlord.dtgov.ui.client.shared.beans.DeploymentResultSetBean;
import org.overlord.dtgov.ui.client.shared.beans.DeploymentSummaryBean;
import org.overlord.dtgov.ui.client.shared.beans.DeploymentsFilterBean;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.SpanElement;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.TextBox;
/**
* The deployment lifecycle page.
*
* @author eric.wittmann@redhat.com
*/
@Templated("/org/overlord/dtgov/ui/client/local/site/deployments.html#page")
@Page(path="deployments")
@Dependent
public class DeploymentsPage extends AbstractPage {
@Inject
protected ClientMessages i18n;
@Inject
protected DeploymentsRpcService deploymentsService;
@Inject
protected NotificationService notificationService;
@Inject
protected ApplicationStateService stateService;
// Breadcrumbs
@Inject @DataField("back-to-dashboard")
TransitionAnchor<DashboardPage> backToDashboard;
@Inject @DataField("deployments-filter-sidebar")
protected DeploymentFilters filtersPanel;
@Inject @DataField("deployment-search-box")
protected TextBox searchBox;
@Inject @DataField("btn-refresh")
protected Button refreshButton;
@Inject @DataField("btn-add")
protected Button addButton;
@Inject
protected Instance<AddDeploymentDialog> addDeploymentDialog;
@Inject @DataField("deployments-none")
protected HtmlSnippet noDataMessage;
@Inject @DataField("deployments-searching")
protected HtmlSnippet searchInProgressMessage;
@Inject @DataField("deployments-table")
protected DeploymentTable deploymentsTable;
@Inject @DataField("deployments-pager")
protected Pager pager;
@DataField("deployments-range")
protected SpanElement rangeSpan = Document.get().createSpanElement();
@DataField("deployments-total")
protected SpanElement totalSpan = Document.get().createSpanElement();
private int currentPage = 1;
/**
* Constructor.
*/
public DeploymentsPage() {
}
/**
* Called after construction.
*/
@PostConstruct
protected void postConstruct() {
filtersPanel.addValueChangeHandler(new ValueChangeHandler<DeploymentsFilterBean>() {
@Override
public void onValueChange(ValueChangeEvent<DeploymentsFilterBean> event) {
doSearch();
}
});
searchBox.addValueChangeHandler(new ValueChangeHandler<String>() {
@Override
public void onValueChange(ValueChangeEvent<String> event) {
doSearch();
}
});
pager.addValueChangeHandler(new ValueChangeHandler<Integer>() {
@Override
public void onValueChange(ValueChangeEvent<Integer> event) {
doSearch(event.getValue());
}
});
deploymentsTable.addTableSortHandler(new TableSortEvent.Handler() {
@Override
public void onTableSort(TableSortEvent event) {
doSearch(currentPage);
}
});
// Hide column 1 when in mobile mode.
deploymentsTable.setColumnClasses(1, "desktop-only"); //$NON-NLS-1$
this.rangeSpan.setInnerText("?"); //$NON-NLS-1$
this.totalSpan.setInnerText("?"); //$NON-NLS-1$
}
/**
* Event handler that fires when the user clicks the refresh button.
* @param event
*/
@EventHandler("btn-refresh")
public void onRefreshClick(ClickEvent event) {
doSearch(currentPage);
}
/**
* Event handler that fires when the user clicks the Add Deployment button.
* @param event
*/
@EventHandler("btn-add")
public void onAddClick(ClickEvent event) {
addDeploymentDialog.get().show();
}
/**
* Kick off a search at this point so that we show some data in the UI.
* @see org.overlord.dtgov.ui.client.local.pages.AbstractPage#onPageShowing()
*/
@Override
protected void onPageShowing() {
// Refresh the filters
filtersPanel.refresh();
DeploymentsFilterBean filterBean = (DeploymentsFilterBean) stateService.get(ApplicationStateKeys.DEPLOYMENTS_FILTER, new DeploymentsFilterBean());
String searchText = (String) stateService.get(ApplicationStateKeys.DEPLOYMENTS_SEARCH_TEXT, ""); //$NON-NLS-1$
Integer page = (Integer) stateService.get(ApplicationStateKeys.DEPLOYMENTS_PAGE, 1);
SortColumn sortColumn = (SortColumn) stateService.get(ApplicationStateKeys.DEPLOYMENTS_SORT_COLUMN, this.deploymentsTable.getDefaultSortColumn());
this.filtersPanel.setValue(filterBean);
this.searchBox.setValue(searchText);
this.deploymentsTable.sortBy(sortColumn.columnId, sortColumn.ascending);
// Kick off a search
doSearch(page);
}
/**
* Search for artifacts based on the current filter settings and search text.
*/
protected void doSearch() {
doSearch(1);
}
/**
* Search for deployments based on the current filter settings.
* @param page
*/
protected void doSearch(int page) {
onSearchStarting();
currentPage = page;
final DeploymentsFilterBean filterBean = filtersPanel.getValue();
final String searchText = this.searchBox.getValue();
final SortColumn currentSortColumn = this.deploymentsTable.getCurrentSortColumn();
stateService.put(ApplicationStateKeys.DEPLOYMENTS_FILTER, filterBean);
stateService.put(ApplicationStateKeys.DEPLOYMENTS_SEARCH_TEXT, searchText);
stateService.put(ApplicationStateKeys.DEPLOYMENTS_PAGE, currentPage);
stateService.put(ApplicationStateKeys.DEPLOYMENTS_SORT_COLUMN, currentSortColumn);
deploymentsService.search(filterBean, searchText, page, currentSortColumn.columnId, currentSortColumn.ascending,
new IRpcServiceInvocationHandler<DeploymentResultSetBean>() {
@Override
public void onReturn(DeploymentResultSetBean data) {
updateTable(data);
updatePager(data);
}
@Override
public void onError(Throwable error) {
notificationService.sendErrorNotification(i18n.format("deployments.error-loading"), error); //$NON-NLS-1$
noDataMessage.setVisible(true);
searchInProgressMessage.setVisible(false);
}
});
}
/**
* Called when a new search is kicked off.
*/
protected void onSearchStarting() {
this.pager.setVisible(false);
this.searchInProgressMessage.setVisible(true);
this.deploymentsTable.setVisible(false);
this.noDataMessage.setVisible(false);
this.rangeSpan.setInnerText("?"); //$NON-NLS-1$
this.totalSpan.setInnerText("?"); //$NON-NLS-1$
}
/**
* Updates the table of deployments with the given data.
* @param data
*/
protected void updateTable(DeploymentResultSetBean data) {
this.deploymentsTable.clear();
this.searchInProgressMessage.setVisible(false);
if (data.getDeployments().size() > 0) {
for (DeploymentSummaryBean deploymentSummaryBean : data.getDeployments()) {
this.deploymentsTable.addRow(deploymentSummaryBean);
}
this.deploymentsTable.setVisible(true);
} else {
this.noDataMessage.setVisible(true);
}
}
/**
* Updates the pager with the given data.
* @param data
*/
protected void updatePager(DeploymentResultSetBean data) {
int numPages = ((int) (data.getTotalResults() / data.getItemsPerPage())) + (data.getTotalResults() % data.getItemsPerPage() == 0 ? 0 : 1);
int thisPage = (data.getStartIndex() / data.getItemsPerPage()) + 1;
this.pager.setNumPages(numPages);
this.pager.setPage(thisPage);
if (numPages > 1)
this.pager.setVisible(true);
int startIndex = data.getStartIndex() + 1;
int endIndex = startIndex + data.getDeployments().size() - 1;
String rangeText = "" + startIndex + "-" + endIndex; //$NON-NLS-1$ //$NON-NLS-2$
String totalText = String.valueOf(data.getTotalResults());
this.rangeSpan.setInnerText(rangeText);
this.totalSpan.setInnerText(totalText);
}
}
| |
/**
* $RCSfile: ,v $
* $Revision: $
* $Date: $
*
* Copyright (C) 2004-2011 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.spark.ui.conferences;
import org.jivesoftware.resource.SparkRes;
import org.jivesoftware.resource.Res;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smackx.muc.MultiUserChat;
import org.jivesoftware.spark.SparkManager;
import org.jivesoftware.spark.component.TitlePanel;
import org.jivesoftware.spark.util.ModelUtil;
import org.jivesoftware.spark.util.ResourceUtils;
import org.jivesoftware.spark.util.log.Log;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
public class RoomCreationDialog extends JPanel {
private static final long serialVersionUID = -8391698290385575601L;
private JLabel nameLabel = new JLabel();
private JLabel topicLabel = new JLabel();
private JLabel passwordLabel = new JLabel();
private JLabel confirmPasswordLabel = new JLabel();
private JCheckBox permanentCheckBox = new JCheckBox();
private JCheckBox privateCheckbox = new JCheckBox();
private JTextField nameField = new JTextField();
private JTextField topicField = new JTextField();
private JPasswordField passwordField = new JPasswordField();
private JPasswordField confirmPasswordField = new JPasswordField();
private GridBagLayout gridBagLayout1 = new GridBagLayout();
private MultiUserChat groupChat = null;
public RoomCreationDialog() {
try {
jbInit();
}
catch (Exception e) {
Log.error(e);
}
}
private void jbInit() throws Exception {
this.setLayout(gridBagLayout1);
this.add(confirmPasswordField, new GridBagConstraints(1, 4, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
this.add(passwordField, new GridBagConstraints(1, 3, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
this.add(topicField, new GridBagConstraints(1, 1, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
this.add(nameField, new GridBagConstraints(1, 0, 1, 1, 1.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.HORIZONTAL, new Insets(5, 5, 5, 5), 0, 0));
this.add(privateCheckbox, new GridBagConstraints(0, 2, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
this.add(permanentCheckBox, new GridBagConstraints(0, 5, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
this.add(confirmPasswordLabel, new GridBagConstraints(0, 4, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
this.add(passwordLabel, new GridBagConstraints(0, 3, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
this.add(topicLabel, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 5, 0));
this.add(nameLabel, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(5, 5, 5, 5), 0, 0));
ResourceUtils.resLabel(nameLabel, nameField, Res.getString("label.room.name"));
ResourceUtils.resLabel(topicLabel, topicField, Res.getString("label.room.topic") + ":");
ResourceUtils.resLabel(passwordLabel, passwordField, Res.getString("label.password") + ":");
ResourceUtils.resLabel(confirmPasswordLabel, confirmPasswordField, Res.getString("label.confirm.password") + ":");
ResourceUtils.resButton(permanentCheckBox, Res.getString("checkbox.permanent"));
ResourceUtils.resButton(privateCheckbox, Res.getString("checkbox.private.room"));
}
public MultiUserChat createGroupChat(Component parent, final String serviceName) {
final JOptionPane pane;
final JDialog dlg;
TitlePanel titlePanel;
// Create the title panel for this dialog
titlePanel = new TitlePanel(Res.getString("title.create.or.join"), Res.getString("message.create.or.join.room"), SparkRes.getImageIcon(SparkRes.BLANK_24x24), true);
// Construct main panel w/ layout.
final JPanel mainPanel = new JPanel();
mainPanel.setLayout(new BorderLayout());
mainPanel.add(titlePanel, BorderLayout.NORTH);
// The user should only be able to close this dialog.
Object[] options = {Res.getString("create"), Res.getString("close")};
pane = new JOptionPane(this, JOptionPane.PLAIN_MESSAGE, JOptionPane.OK_CANCEL_OPTION, null, options, options[0]);
mainPanel.add(pane, BorderLayout.CENTER);
JOptionPane p = new JOptionPane();
dlg = p.createDialog(parent, Res.getString("title.conference.rooms"));
dlg.pack();
dlg.setSize(400, 350);
dlg.setContentPane(mainPanel);
dlg.setLocationRelativeTo(parent);
PropertyChangeListener changeListener = new PropertyChangeListener() {
public void propertyChange(PropertyChangeEvent e) {
Object o = pane.getValue();
if (o instanceof Integer) {
dlg.setVisible(false);
return;
}
String value = (String)pane.getValue();
if (Res.getString("close").equals(value)) {
dlg.setVisible(false);
}
else if (Res.getString("create").equals(value)) {
boolean isValid = validatePanel();
if (isValid) {
String room = nameField.getText().replaceAll(" ", "_") + "@" + serviceName;
try {
MultiUserChat.getRoomInfo(SparkManager.getConnection(), room);
//JOptionPane.showMessageDialog(dlg, "Room already exists. Please specify a unique room name.", "Room Exists", JOptionPane.ERROR_MESSAGE);
//pane.setValue(JOptionPane.UNINITIALIZED_VALUE);
pane.removePropertyChangeListener(this);
dlg.setVisible(false);
ConferenceUtils.joinConferenceRoom(room, room);
return;
}
catch (XMPPException e1) {
// Nothing to do
}
groupChat = createGroupChat(nameField.getText(), serviceName);
if (groupChat == null) {
showError("Could not join chat " + nameField.getText());
pane.setValue(JOptionPane.UNINITIALIZED_VALUE);
}
else {
pane.removePropertyChangeListener(this);
dlg.setVisible(false);
}
}
else {
pane.setValue(JOptionPane.UNINITIALIZED_VALUE);
}
}
}
};
pane.addPropertyChangeListener(changeListener);
nameField.requestFocusInWindow();
dlg.setVisible(true);
dlg.toFront();
dlg.requestFocus();
return groupChat;
}
private boolean validatePanel() {
String roomName = nameField.getText();
String password = new String(passwordField.getPassword());
String confirmPassword = new String(confirmPasswordField.getPassword());
boolean isPrivate = privateCheckbox.isSelected();
// Check for valid information
if (!ModelUtil.hasLength(roomName)) {
showError(Res.getString("message.specify.name.error"));
nameField.requestFocus();
return false;
}
if (isPrivate) {
if (!ModelUtil.hasLength(password)) {
showError(Res.getString("message.password.private.room.error"));
passwordField.requestFocus();
return false;
}
if (!ModelUtil.hasLength(confirmPassword)) {
showError(Res.getString("message.confirmation.password.error"));
confirmPasswordField.requestFocus();
return false;
}
if (!ModelUtil.areEqual(password, confirmPassword)) {
showError(Res.getString("message.passwords.no.match"));
passwordField.requestFocus();
return false;
}
}
return true;
}
private MultiUserChat createGroupChat(String roomName, String serviceName) {
String room = roomName.replaceAll(" ", "_") + "@" + serviceName;
// Create a group chat with valid information
return new MultiUserChat(SparkManager.getConnection(), room.toLowerCase());
}
private void showError(String errorMessage) {
JOptionPane.showMessageDialog(this, errorMessage, Res.getString("title.error"), JOptionPane.ERROR_MESSAGE);
}
public boolean isPrivate() {
return privateCheckbox.isSelected();
}
public boolean isPermanent() {
return permanentCheckBox.isSelected();
}
public boolean isPasswordProtected() {
String password = new String(passwordField.getPassword());
if (password.length() > 0) {
return true;
}
return false;
}
public String getPassword() {
return new String(confirmPasswordField.getPassword());
}
/**
* Returns the Room name of the RoomCreationDialog
*
* @return The Room name
*/
public String getRoomName() {
return nameField.getText();
}
/**
* Returns the Topic of the RoomCreationDialog
* @return The Rooms Topic
*/
public String getRoomTopic() {
return topicField.getText();
}
}
| |
package moe.banana.jsonapi2;
import com.squareup.moshi.*;
import okio.Buffer;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.*;
import static moe.banana.jsonapi2.MoshiHelper.nextNullableObject;
import static moe.banana.jsonapi2.MoshiHelper.writeNullable;
public final class ResourceAdapterFactory implements JsonAdapter.Factory {
private Map<String, Class<?>> typeMap = new HashMap<>();
private JsonNameMapping jsonNameMapping;
private ResourceAdapterFactory(List<Class<? extends Resource>> types, JsonNameMapping jsonNameMapping) {
this.jsonNameMapping = jsonNameMapping;
for (Class<? extends Resource> type : types) {
JsonApi annotation = type.getAnnotation(JsonApi.class);
String typeName = annotation.type();
if (annotation.policy() == Policy.SERIALIZATION_ONLY) {
continue;
}
if (typeMap.containsKey(typeName)) {
JsonApi annotationOld = typeMap.get(typeName).getAnnotation(JsonApi.class);
switch (annotationOld.policy()) {
case SERIALIZATION_AND_DESERIALIZATION:
if (annotation.policy() == Policy.SERIALIZATION_AND_DESERIALIZATION) {
// TODO deprecate priority here!
if (annotationOld.priority() < annotation.priority()) {
continue;
}
if (annotationOld.priority() > annotation.priority()) {
break;
}
}
case DESERIALIZATION_ONLY:
throw new IllegalArgumentException(
"@JsonApi(type = \"" + typeName + "\") declaration of [" + type.getCanonicalName() + "] conflicts with [" + typeMap.get(typeName).getCanonicalName() + "]." );
}
}
typeMap.put(typeName, type);
}
}
@Override
@SuppressWarnings("unchecked")
public JsonAdapter<?> create(Type type, Set<? extends Annotation> annotations, Moshi moshi) {
Class<?> rawType = Types.getRawType(type);
if (rawType.equals(JsonBuffer.class)) return new JsonBuffer.Adapter();
if (rawType.equals(HasMany.class)) return new HasMany.Adapter(moshi);
if (rawType.equals(HasOne.class)) return new HasOne.Adapter(moshi);
if (rawType.equals(Error.class)) return new Error.Adapter(moshi);
if (rawType.equals(ResourceIdentifier.class)) return new ResourceIdentifier.Adapter(moshi);
if (rawType.equals(Resource.class)) return new GenericAdapter(typeMap, moshi);
if (Document.class.isAssignableFrom(rawType)) {
if (type instanceof ParameterizedType) {
Type typeParameter = ((ParameterizedType) type).getActualTypeArguments()[0];
if (typeParameter instanceof Class<?>) {
return new DocumentAdapter((Class<?>) typeParameter, moshi);
}
}
return new DocumentAdapter<>(Resource.class, moshi);
}
if (Resource.class.isAssignableFrom(rawType)) return new ResourceAdapter(rawType, jsonNameMapping, moshi);
return null;
}
static class DocumentAdapter<DATA extends ResourceIdentifier> extends JsonAdapter<Document> {
JsonAdapter<JsonBuffer> jsonBufferJsonAdapter;
JsonAdapter<Error> errorJsonAdapter;
JsonAdapter<DATA> dataJsonAdapter;
JsonAdapter<Resource> resourceJsonAdapter;
public DocumentAdapter(Class<DATA> type, Moshi moshi) {
jsonBufferJsonAdapter = moshi.adapter(JsonBuffer.class);
resourceJsonAdapter = moshi.adapter(Resource.class);
errorJsonAdapter = moshi.adapter(Error.class);
dataJsonAdapter = moshi.adapter(type);
}
@Override
@SuppressWarnings("unchecked")
public Document fromJson(JsonReader reader) throws IOException {
if (reader.peek() == JsonReader.Token.NULL) {
return null;
}
Document document = new ObjectDocument<DATA>();
reader.beginObject();
while (reader.hasNext()) {
switch (reader.nextName()) {
case "data":
if (reader.peek() == JsonReader.Token.BEGIN_ARRAY) {
document = document.asArrayDocument();
reader.beginArray();
while (reader.hasNext()) {
((ArrayDocument<DATA>) document).add(dataJsonAdapter.fromJson(reader));
}
reader.endArray();
} else if (reader.peek() == JsonReader.Token.BEGIN_OBJECT) {
document = document.asObjectDocument();
((ObjectDocument<DATA>) document).set(dataJsonAdapter.fromJson(reader));
} else if (reader.peek() == JsonReader.Token.NULL) {
reader.nextNull();
document = document.asObjectDocument();
((ObjectDocument<DATA>) document).set(null);
} else {
reader.skipValue();
}
break;
case "included":
reader.beginArray();
Collection<Resource> includes = document.getIncluded();
while (reader.hasNext()) {
includes.add(resourceJsonAdapter.fromJson(reader));
}
reader.endArray();
break;
case "errors":
reader.beginArray();
List<Error> errors = document.getErrors();
while (reader.hasNext()) {
errors.add(errorJsonAdapter.fromJson(reader));
}
reader.endArray();
break;
case "links":
document.setLinks(nextNullableObject(reader, jsonBufferJsonAdapter));
break;
case "meta":
document.setMeta(nextNullableObject(reader, jsonBufferJsonAdapter));
break;
case "jsonapi":
document.setJsonApi(nextNullableObject(reader, jsonBufferJsonAdapter));
break;
default:
reader.skipValue();
break;
}
}
reader.endObject();
return document;
}
@Override
@SuppressWarnings("unchecked")
public void toJson(JsonWriter writer, Document value) throws IOException {
writer.beginObject();
if (value instanceof ArrayDocument) {
writer.name("data");
writer.beginArray();
for (DATA resource : ((ArrayDocument<DATA>) value)) {
dataJsonAdapter.toJson(writer, resource);
}
writer.endArray();
} else if (value instanceof ObjectDocument) {
writeNullable(writer, dataJsonAdapter,
"data",
((ObjectDocument<DATA>) value).get(),
((ObjectDocument<DATA>) value).hasData());
}
if (value.included.size() > 0) {
writer.name("included");
writer.beginArray();
for (Resource resource : value.included.values()) {
resourceJsonAdapter.toJson(writer, resource);
}
writer.endArray();
}
if (value.errors.size() > 0) {
writer.name("error");
writer.beginArray();
for (Error err : value.errors) {
errorJsonAdapter.toJson(writer, err);
}
writer.endArray();
}
writeNullable(writer, jsonBufferJsonAdapter, "meta", value.getMeta());
writeNullable(writer, jsonBufferJsonAdapter, "links", value.getLinks());
writeNullable(writer, jsonBufferJsonAdapter, "jsonapi", value.getJsonApi());
writer.endObject();
}
}
private static class GenericAdapter extends JsonAdapter<Resource> {
Map<String, Class<?>> typeMap;
Moshi moshi;
GenericAdapter(Map<String, Class<?>> typeMap, Moshi moshi) {
this.typeMap = typeMap;
this.moshi = moshi;
}
@Override
public Resource fromJson(JsonReader reader) throws IOException {
Buffer buffer = new Buffer();
MoshiHelper.dump(reader, buffer);
String typeName = findTypeOf(buffer);
JsonAdapter<?> adapter;
if (typeMap.containsKey(typeName)) {
adapter = moshi.adapter(typeMap.get(typeName));
} else if (typeMap.containsKey("default")) {
adapter = moshi.adapter(typeMap.get("default"));
} else {
throw new JsonDataException("Unknown type of resource: " + typeName);
}
return (Resource) adapter.fromJson(buffer);
}
@Override
@SuppressWarnings("unchecked")
public void toJson(JsonWriter writer, Resource value) throws IOException {
moshi.adapter((Class) value.getClass()).toJson(writer, value);
}
private static String findTypeOf(Buffer buffer) throws IOException {
Buffer forked = new Buffer();
buffer.copyTo(forked, 0, buffer.size());
JsonReader reader = JsonReader.of(forked);
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
switch (name) {
case "type":
return reader.nextString();
default:
reader.skipValue();
}
}
return null;
}
}
public static class Builder {
List<Class<? extends Resource>> types = new ArrayList<>();
JsonNameMapping jsonNameMapping = new MoshiJsonNameMapping();
private Builder() { }
@SafeVarargs
public final Builder add(Class<? extends Resource>... type) {
types.addAll(Arrays.asList(type));
return this;
}
public final Builder setJsonNameMapping(JsonNameMapping mapping) {
if (mapping == null) {
throw new IllegalArgumentException();
}
this.jsonNameMapping = mapping;
return this;
}
public final ResourceAdapterFactory build() {
return new ResourceAdapterFactory(types, jsonNameMapping);
}
}
public static Builder builder() {
return new Builder();
}
}
| |
/*
* Copyright 2000-2013 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.remoteServer.impl.configuration.deployment;
import com.intellij.execution.configurations.RuntimeConfigurationError;
import com.intellij.execution.configurations.RuntimeConfigurationException;
import com.intellij.execution.configurations.RuntimeConfigurationWarning;
import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SettingsEditor;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.ComboBox;
import com.intellij.openapi.util.Comparing;
import com.intellij.openapi.util.Disposer;
import com.intellij.remoteServer.ServerType;
import com.intellij.remoteServer.configuration.RemoteServer;
import com.intellij.remoteServer.configuration.RemoteServersManager;
import com.intellij.remoteServer.configuration.ServerConfiguration;
import com.intellij.remoteServer.configuration.deployment.DeploymentConfiguration;
import com.intellij.remoteServer.configuration.deployment.DeploymentConfigurator;
import com.intellij.remoteServer.configuration.deployment.DeploymentSource;
import com.intellij.remoteServer.configuration.deployment.DeploymentSourceType;
import com.intellij.remoteServer.impl.configuration.RemoteServerConnectionTester;
import com.intellij.remoteServer.util.CloudBundle;
import com.intellij.ui.SimpleColoredComponent;
import com.intellij.ui.SimpleListCellRenderer;
import com.intellij.ui.SimpleTextAttributes;
import com.intellij.ui.SortedComboBoxModel;
import com.intellij.util.ui.FormBuilder;
import com.intellij.util.ui.UIUtil;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import javax.swing.*;
import java.awt.*;
import java.util.Comparator;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicReference;
public abstract class DeployToServerSettingsEditor<S extends ServerConfiguration, D extends DeploymentConfiguration>
extends SettingsEditor<DeployToServerRunConfiguration<S, D>> {
private final DeploymentConfigurator<D, S> myDeploymentConfigurator;
private final Project myProject;
private final WithAutoDetectCombo<S> myServerCombo;
private final JPanel myDeploymentSettingsComponent;
private SettingsEditor<D> myDeploymentSettingsEditor;
private DeploymentSource myLastSelectedSource;
private RemoteServer<S> myLastSelectedServer;
public DeployToServerSettingsEditor(@NotNull ServerType<S> type,
@NotNull DeploymentConfigurator<D, S> deploymentConfigurator,
@NotNull Project project) {
myDeploymentConfigurator = deploymentConfigurator;
myProject = project;
myServerCombo = new WithAutoDetectCombo<>(type);
Disposer.register(this, myServerCombo);
myServerCombo.addChangeListener(e -> updateDeploymentSettingsEditor());
myDeploymentSettingsComponent = new JPanel(new BorderLayout());
}
protected abstract DeploymentSource getSelectedSource();
protected abstract void resetSelectedSourceFrom(@NotNull DeployToServerRunConfiguration<S, D> configuration);
protected final void updateDeploymentSettingsEditor() {
RemoteServer<S> selectedServer = myServerCombo.getSelectedServer();
DeploymentSource selectedSource = getSelectedSource();
if (Comparing.equal(selectedSource, myLastSelectedSource) && Comparing.equal(selectedServer, myLastSelectedServer)) {
return;
}
if (!Comparing.equal(selectedSource, myLastSelectedSource)) {
updateBeforeRunOptions(myLastSelectedSource, false);
updateBeforeRunOptions(selectedSource, true);
}
if (selectedSource != null && selectedServer != null) {
myDeploymentSettingsComponent.removeAll();
myDeploymentSettingsEditor = myDeploymentConfigurator.createEditor(selectedSource, selectedServer);
if (myDeploymentSettingsEditor != null) {
Disposer.register(this, myDeploymentSettingsEditor);
myDeploymentSettingsComponent.add(BorderLayout.CENTER, myDeploymentSettingsEditor.getComponent());
}
}
myLastSelectedSource = selectedSource;
myLastSelectedServer = selectedServer;
}
private void updateBeforeRunOptions(@Nullable DeploymentSource source, boolean selected) {
if (source != null) {
DeploymentSourceType type = source.getType();
type.updateBuildBeforeRunOption(myServerCombo, myProject, source, selected);
}
}
@Override
protected void resetEditorFrom(@NotNull DeployToServerRunConfiguration<S, D> configuration) {
myServerCombo.selectServerInCombo(configuration.getServerName());
resetSelectedSourceFrom(configuration);
D deploymentConfiguration = configuration.getDeploymentConfiguration();
updateDeploymentSettingsEditor();
if (deploymentConfiguration != null && myDeploymentSettingsEditor != null) {
myDeploymentSettingsEditor.resetFrom(deploymentConfiguration);
}
}
@Override
protected void applyEditorTo(@NotNull DeployToServerRunConfiguration<S, D> configuration) throws ConfigurationException {
updateDeploymentSettingsEditor();
myServerCombo.validateAutoDetectedItem();
configuration.setServerName(Optional.ofNullable(myServerCombo.getSelectedServer()).map(RemoteServer::getName).orElse(null));
DeploymentSource deploymentSource = getSelectedSource();
configuration.setDeploymentSource(deploymentSource);
if (deploymentSource != null) {
D deployment = configuration.getDeploymentConfiguration();
if (deployment == null) {
deployment = myDeploymentConfigurator.createDefaultConfiguration(deploymentSource);
configuration.setDeploymentConfiguration(deployment);
}
if (myDeploymentSettingsEditor != null) {
myDeploymentSettingsEditor.applyTo(deployment);
}
}
else {
configuration.setDeploymentConfiguration(null);
}
}
@NotNull
@Override
protected JComponent createEditor() {
FormBuilder builder = FormBuilder.createFormBuilder()
.addLabeledComponent("Server:", myServerCombo);
addDeploymentSourceUi(builder);
return builder
.addComponentFillVertically(myDeploymentSettingsComponent, UIUtil.DEFAULT_VGAP)
.getPanel();
}
protected abstract void addDeploymentSourceUi(FormBuilder formBuilder);
public static class AnySource<S extends ServerConfiguration, D extends DeploymentConfiguration>
extends DeployToServerSettingsEditor<S, D> {
private final ComboBox<DeploymentSource> mySourceComboBox;
private final SortedComboBoxModel<DeploymentSource> mySourceListModel;
public AnySource(ServerType<S> type, DeploymentConfigurator<D, S> deploymentConfigurator, Project project) {
super(type, deploymentConfigurator, project);
mySourceListModel = new SortedComboBoxModel<>(
Comparator.comparing(DeploymentSource::getPresentableName, String.CASE_INSENSITIVE_ORDER));
mySourceListModel.addAll(deploymentConfigurator.getAvailableDeploymentSources());
mySourceComboBox = new ComboBox<>(mySourceListModel);
mySourceComboBox.setRenderer(SimpleListCellRenderer.create((label, value, index) -> {
if (value == null) return;
label.setIcon(value.getIcon());
label.setText(value.getPresentableName());
}));
mySourceComboBox.addActionListener(e -> updateDeploymentSettingsEditor());
}
@Override
protected DeploymentSource getSelectedSource() {
return mySourceListModel.getSelectedItem();
}
@Override
protected void resetSelectedSourceFrom(@NotNull DeployToServerRunConfiguration<S, D> configuration) {
mySourceComboBox.setSelectedItem(configuration.getDeploymentSource());
}
@Override
protected void addDeploymentSourceUi(FormBuilder formBuilder) {
formBuilder.addLabeledComponent("Deployment:", mySourceComboBox);
}
}
public static class LockedSource<S extends ServerConfiguration, D extends DeploymentConfiguration>
extends DeployToServerSettingsEditor<S, D> {
private final DeploymentSource myLockedSource;
public LockedSource(@NotNull ServerType<S> type,
@NotNull DeploymentConfigurator<D, S> deploymentConfigurator,
@NotNull Project project,
@NotNull DeploymentSource lockedSource) {
super(type, deploymentConfigurator, project);
myLockedSource = lockedSource;
}
@Override
protected void addDeploymentSourceUi(FormBuilder formBuilder) {
//
}
@Override
protected void resetSelectedSourceFrom(@NotNull DeployToServerRunConfiguration<S, D> configuration) {
assert configuration.getDeploymentSource() == myLockedSource;
}
@Override
protected DeploymentSource getSelectedSource() {
return myLockedSource;
}
}
private static class WithAutoDetectCombo<S extends ServerConfiguration> extends RemoteServerCombo<S> {
private AutoDetectedItem myAutoDetectedItem;
WithAutoDetectCombo(@NotNull ServerType<S> serverType) {
super(serverType);
}
@NotNull
@Override
protected ServerItem getNoServersItem() {
return getServerType().canAutoDetectConfiguration() ? findOrCreateAutoDetectedItem() : super.getNoServersItem();
}
protected AutoDetectedItem findOrCreateAutoDetectedItem() {
if (myAutoDetectedItem == null) {
myAutoDetectedItem = new AutoDetectedItem();
}
return myAutoDetectedItem;
}
public void validateAutoDetectedItem() throws RuntimeConfigurationException {
if (myAutoDetectedItem != null && myAutoDetectedItem == getSelectedItem()) {
myAutoDetectedItem.validateConnection();
}
}
private enum TestConnectionState {
INITIAL {
@Override
public void validateConnection() throws RuntimeConfigurationException {
//
}
},
IN_PROGRESS {
@Override
public void validateConnection() throws RuntimeConfigurationException {
throw new RuntimeConfigurationWarning(CloudBundle.message("remote.server.combo.message.test.connection.in.progress"));
}
},
SUCCESSFUL {
@Override
public void validateConnection() throws RuntimeConfigurationException {
//
}
},
FAILED {
@Override
public void validateConnection() throws RuntimeConfigurationException {
throw new RuntimeConfigurationError(
CloudBundle.message("remote.server.combo.message.test.connection.failed")/*, () -> createAndEditNewServer()*/);
}
};
public abstract void validateConnection() throws RuntimeConfigurationException;
}
private class AutoDetectedItem extends RemoteServerCombo.ServerItemImpl {
private final AtomicReference<TestConnectionState> myTestConnectionStateA = new AtomicReference<>(TestConnectionState.INITIAL);
private volatile RemoteServer<S> myServerInstance;
private volatile long myLastStartedTestConnectionMillis = -1;
AutoDetectedItem() {
super(null);
}
@Override
public void render(@NotNull SimpleColoredComponent ui) {
ui.setIcon(getServerType().getIcon());
boolean failed = myTestConnectionStateA.get() == TestConnectionState.FAILED;
ui.append(CloudBundle.message("remote.server.combo.auto.detected.server", getServerType().getPresentableName()),
failed ? SimpleTextAttributes.ERROR_ATTRIBUTES : SimpleTextAttributes.REGULAR_ITALIC_ATTRIBUTES);
}
public void validateConnection() throws RuntimeConfigurationException {
myTestConnectionStateA.get().validateConnection();
}
@Override
public void onBrowseAction() {
createAndEditNewServer();
}
@Override
public void onItemChosen() {
if (myServerInstance == null) {
myServerInstance = RemoteServersManager.getInstance().createServer(getServerType());
RemoteServerConnectionTester tester = new RemoteServerConnectionTester(myServerInstance);
setTestConnectionState(TestConnectionState.IN_PROGRESS);
myLastStartedTestConnectionMillis = System.currentTimeMillis();
tester.testConnection(this::connectionTested);
}
}
@Nullable
@Override
public String getServerName() {
return null;
}
@Nullable
@Override
public RemoteServer<S> findRemoteServer() {
return myServerInstance;
}
private void setTestConnectionState(@NotNull TestConnectionState state) {
boolean changed = myTestConnectionStateA.getAndSet(state) != state;
if (changed) {
UIUtil.invokeLaterIfNeeded(WithAutoDetectCombo.this::fireStateChanged);
}
}
private void connectionTested(boolean wasConnected, @SuppressWarnings("unused") String errorStatus) {
assert myLastStartedTestConnectionMillis > 0;
waitABit(2000);
if (wasConnected) {
setTestConnectionState(TestConnectionState.SUCCESSFUL);
UIUtil.invokeLaterIfNeeded(() -> {
if (!Disposer.isDisposed(WithAutoDetectCombo.this)) {
assert myServerInstance != null;
RemoteServersManager.getInstance().addServer(myServerInstance);
refillModel(myServerInstance);
}
myServerInstance = null;
});
}
else {
setTestConnectionState(TestConnectionState.FAILED);
myServerInstance = null;
}
}
/**
* Too quick validation just flickers the screen, so we will ensure that validation message is shown for at least some time
*/
private void waitABit(@SuppressWarnings("SameParameterValue") long maxTotalDelayMillis) {
final long THRESHOLD_MS = 50;
long naturalDelay = System.currentTimeMillis() - myLastStartedTestConnectionMillis;
if (naturalDelay > 0 && naturalDelay + THRESHOLD_MS < maxTotalDelayMillis) {
try {
Thread.sleep(maxTotalDelayMillis - naturalDelay - THRESHOLD_MS);
}
catch (InterruptedException ignored) {
//
}
}
myLastStartedTestConnectionMillis = -1;
}
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package okhttp3;
import java.lang.ref.Reference;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import okhttp3.internal.Platform;
import okhttp3.internal.RouteDatabase;
import okhttp3.internal.Util;
import okhttp3.internal.http.StreamAllocation;
import okhttp3.internal.io.RealConnection;
import static okhttp3.internal.Platform.WARN;
import static okhttp3.internal.Util.closeQuietly;
/**
* Manages reuse of HTTP and SPDY connections for reduced network latency. HTTP requests that share
* the same {@link Address} may share a {@link Connection}. This class implements the policy of
* which connections to keep open for future use.
*/
public final class ConnectionPool {
/**
* Background threads are used to cleanup expired connections. There will be at most a single
* thread running per connection pool. The thread pool executor permits the pool itself to be
* garbage collected.
*/
private static final Executor executor = new ThreadPoolExecutor(0 /* corePoolSize */,
Integer.MAX_VALUE /* maximumPoolSize */, 60L /* keepAliveTime */, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>(), Util.threadFactory("OkHttp ConnectionPool", true));
/** The maximum number of idle connections for each address. */
private final int maxIdleConnections;
private final long keepAliveDurationNs;
private final Runnable cleanupRunnable = new Runnable() {
@Override public void run() {
while (true) {
long waitNanos = cleanup(System.nanoTime());
if (waitNanos == -1) return;
if (waitNanos > 0) {
long waitMillis = waitNanos / 1000000L;
waitNanos -= (waitMillis * 1000000L);
synchronized (ConnectionPool.this) {
try {
ConnectionPool.this.wait(waitMillis, (int) waitNanos);
} catch (InterruptedException ignored) {
}
}
}
}
}
};
private final Deque<RealConnection> connections = new ArrayDeque<>();
final RouteDatabase routeDatabase = new RouteDatabase();
boolean cleanupRunning;
/**
* Create a new connection pool with tuning parameters appropriate for a single-user application.
* The tuning parameters in this pool are subject to change in future OkHttp releases. Currently
* this pool holds up to 5 idle connections which will be evicted after 5 minutes of inactivity.
*/
public ConnectionPool() {
this(5, 5, TimeUnit.MINUTES);
}
public ConnectionPool(int maxIdleConnections, long keepAliveDuration, TimeUnit timeUnit) {
this.maxIdleConnections = maxIdleConnections;
this.keepAliveDurationNs = timeUnit.toNanos(keepAliveDuration);
// Put a floor on the keep alive duration, otherwise cleanup will spin loop.
if (keepAliveDuration <= 0) {
throw new IllegalArgumentException("keepAliveDuration <= 0: " + keepAliveDuration);
}
}
/** Returns the number of idle connections in the pool. */
public synchronized int idleConnectionCount() {
int total = 0;
for (RealConnection connection : connections) {
if (connection.allocations.isEmpty()) total++;
}
return total;
}
/**
* Returns total number of connections in the pool. Note that prior to OkHttp 2.7 this included
* only idle connections and SPDY connections. Since OkHttp 2.7 this includes all connections,
* both active and inactive. Use {@link #idleConnectionCount()} to count connections not currently
* in use.
*/
public synchronized int connectionCount() {
return connections.size();
}
/** Returns a recycled connection to {@code address}, or null if no such connection exists. */
RealConnection get(Address address, StreamAllocation streamAllocation) {
assert (Thread.holdsLock(this));
for (RealConnection connection : connections) {
if (connection.allocations.size() < connection.allocationLimit
&& address.equals(connection.route().address)
&& !connection.noNewStreams) {
streamAllocation.acquire(connection);
return connection;
}
}
return null;
}
void put(RealConnection connection) {
assert (Thread.holdsLock(this));
if (!cleanupRunning) {
cleanupRunning = true;
executor.execute(cleanupRunnable);
}
connections.add(connection);
}
/**
* Notify this pool that {@code connection} has become idle. Returns true if the connection has
* been removed from the pool and should be closed.
*/
boolean connectionBecameIdle(RealConnection connection) {
assert (Thread.holdsLock(this));
if (connection.noNewStreams || maxIdleConnections == 0) {
connections.remove(connection);
return true;
} else {
notifyAll(); // Awake the cleanup thread: we may have exceeded the idle connection limit.
return false;
}
}
/** Close and remove all idle connections in the pool. */
public void evictAll() {
List<RealConnection> evictedConnections = new ArrayList<>();
synchronized (this) {
for (Iterator<RealConnection> i = connections.iterator(); i.hasNext(); ) {
RealConnection connection = i.next();
if (connection.allocations.isEmpty()) {
connection.noNewStreams = true;
evictedConnections.add(connection);
i.remove();
}
}
}
for (RealConnection connection : evictedConnections) {
closeQuietly(connection.socket());
}
}
/**
* Performs maintenance on this pool, evicting the connection that has been idle the longest if
* either it has exceeded the keep alive limit or the idle connections limit.
*
* <p>Returns the duration in nanos to sleep until the next scheduled call to this method. Returns
* -1 if no further cleanups are required.
*/
long cleanup(long now) {
int inUseConnectionCount = 0;
int idleConnectionCount = 0;
RealConnection longestIdleConnection = null;
long longestIdleDurationNs = Long.MIN_VALUE;
// Find either a connection to evict, or the time that the next eviction is due.
synchronized (this) {
for (Iterator<RealConnection> i = connections.iterator(); i.hasNext(); ) {
RealConnection connection = i.next();
// If the connection is in use, keep searching.
if (pruneAndGetAllocationCount(connection, now) > 0) {
inUseConnectionCount++;
continue;
}
idleConnectionCount++;
// If the connection is ready to be evicted, we're done.
long idleDurationNs = now - connection.idleAtNanos;
if (idleDurationNs > longestIdleDurationNs) {
longestIdleDurationNs = idleDurationNs;
longestIdleConnection = connection;
}
}
if (longestIdleDurationNs >= this.keepAliveDurationNs
|| idleConnectionCount > this.maxIdleConnections) {
// We've found a connection to evict. Remove it from the list, then close it below (outside
// of the synchronized block).
connections.remove(longestIdleConnection);
} else if (idleConnectionCount > 0) {
// A connection will be ready to evict soon.
return keepAliveDurationNs - longestIdleDurationNs;
} else if (inUseConnectionCount > 0) {
// All connections are in use. It'll be at least the keep alive duration 'til we run again.
return keepAliveDurationNs;
} else {
// No connections, idle or in use.
cleanupRunning = false;
return -1;
}
}
closeQuietly(longestIdleConnection.socket());
// Cleanup again immediately.
return 0;
}
/**
* Prunes any leaked allocations and then returns the number of remaining live allocations on
* {@code connection}. Allocations are leaked if the connection is tracking them but the
* application code has abandoned them. Leak detection is imprecise and relies on garbage
* collection.
*/
private int pruneAndGetAllocationCount(RealConnection connection, long now) {
List<Reference<StreamAllocation>> references = connection.allocations;
for (int i = 0; i < references.size(); ) {
Reference<StreamAllocation> reference = references.get(i);
if (reference.get() != null) {
i++;
continue;
}
// We've discovered a leaked allocation. This is an application bug.
Platform.get().log(WARN, "A connection to " + connection.route().address().url()
+ " was leaked. Did you forget to close a response body?", null);
references.remove(i);
connection.noNewStreams = true;
// If this was the last allocation, the connection is eligible for immediate eviction.
if (references.isEmpty()) {
connection.idleAtNanos = now - keepAliveDurationNs;
return 0;
}
}
return references.size();
}
}
| |
package com.couchbase.lite.support;
import com.couchbase.lite.internal.InterfaceAudience;
import org.apache.http.auth.params.AuthPNames;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
public class CouchbaseLiteHttpClientFactory implements HttpClientFactory {
private CookieStore cookieStore;
private SSLSocketFactory sslSocketFactory;
private BasicHttpParams basicHttpParams;
public static int DEFAULT_CONNECTION_TIMEOUT_SECONDS = 60;
public static int DEFAULT_SO_TIMEOUT_SECONDS = 60 * 5;
/**
* Constructor
*/
public CouchbaseLiteHttpClientFactory(CookieStore cookieStore) {
this.cookieStore = cookieStore;
}
/**
* @param sslSocketFactoryFromUser This is to open up the system for end user to inject
* the sslSocket factories with their custom KeyStore
*/
@InterfaceAudience.Private
public void setSSLSocketFactory(SSLSocketFactory sslSocketFactoryFromUser) {
if (sslSocketFactory != null) {
throw new RuntimeException("SSLSocketFactory already set");
}
sslSocketFactory = sslSocketFactoryFromUser;
}
@InterfaceAudience.Private
public void setBasicHttpParams(BasicHttpParams basicHttpParams) {
this.basicHttpParams = basicHttpParams;
}
@Override
@InterfaceAudience.Private
public HttpClient getHttpClient() {
// workaround attempt for issue #81
// it does not seem like _not_ using the ThreadSafeClientConnManager actually
// caused any problems, but it seems wise to use it "just in case", since it provides
// extra safety and there are no observed side effects.
if (basicHttpParams == null) {
basicHttpParams = new BasicHttpParams();
basicHttpParams.setParameter(AuthPNames.CREDENTIAL_CHARSET, HTTP.UTF_8);
HttpConnectionParams.setConnectionTimeout(basicHttpParams, DEFAULT_CONNECTION_TIMEOUT_SECONDS * 1000);
HttpConnectionParams.setSoTimeout(basicHttpParams, DEFAULT_SO_TIMEOUT_SECONDS * 1000);
}
SchemeRegistry schemeRegistry = new SchemeRegistry();
schemeRegistry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
final SSLSocketFactory sslSocketFactory = SSLSocketFactory.getSocketFactory();
schemeRegistry.register(new Scheme("https", this.sslSocketFactory == null ? sslSocketFactory : this.sslSocketFactory, 443));
ClientConnectionManager cm = new ThreadSafeClientConnManager(basicHttpParams, schemeRegistry);
DefaultHttpClient client = new DefaultHttpClient(cm, basicHttpParams);
// synchronize access to the cookieStore in case there is another
// thread in the middle of updating it. wait until they are done so we get their changes.
synchronized (this) {
client.setCookieStore(cookieStore);
}
return client;
}
@InterfaceAudience.Private
public void addCookies(List<Cookie> cookies) {
if (cookieStore == null) {
return;
}
synchronized (this) {
for (Cookie cookie : cookies) {
cookieStore.addCookie(cookie);
}
}
}
public void deleteCookie(String name) {
// since CookieStore does not have a way to delete an individual cookie, do workaround:
// 1. get all cookies
// 2. filter list to strip out the one we want to delete
// 3. clear cookie store
// 4. re-add all cookies except the one we want to delete
if (cookieStore == null) {
return;
}
List<Cookie> cookies = cookieStore.getCookies();
List<Cookie> retainedCookies = new ArrayList<Cookie>();
for (Cookie cookie : cookies) {
if (!cookie.getName().equals(name)) {
retainedCookies.add(cookie);
}
}
cookieStore.clear();
for (Cookie retainedCookie : retainedCookies) {
cookieStore.addCookie(retainedCookie);
}
}
@InterfaceAudience.Private
public CookieStore getCookieStore() {
return cookieStore;
}
static class SelfSignedSSLSocketFactory extends SSLSocketFactory {
SSLContext sslContext = SSLContext.getInstance("TLS");
public SelfSignedSSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException,
KeyManagementException, KeyStoreException, UnrecoverableKeyException {
super(truststore);
TrustManager tm = new X509TrustManager() {
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException {
}
public X509Certificate[] getAcceptedIssuers() {
return null;
}
};
sslContext.init(null, new TrustManager[]{tm}, null);
}
@Override
public Socket createSocket(Socket socket, String host, int port, boolean autoClose)
throws IOException, UnknownHostException {
return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
}
@Override
public Socket createSocket() throws IOException {
return sslContext.getSocketFactory().createSocket();
}
}
/**
* This is a convenience method to allow couchbase lite to connect to servers
* that use self-signed SSL certs.
* <p/>
* *DO NOT USE THIS IN PRODUCTION*
* <p/>
* For more information, see:
* <p/>
* https://github.com/couchbase/couchbase-lite-java-core/pull/9
* http://stackoverflow.com/questions/2642777/trusting-all-certificates-using-httpclient-over-https
*/
@InterfaceAudience.Public
public void allowSelfSignedSSLCertificates() {
try {
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
trustStore.load(null, null);
SSLSocketFactory sf = new SelfSignedSSLSocketFactory(trustStore);
this.setSSLSocketFactory(sf);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| |
/**
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2011 Eric Haddad Koenig
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*
*/
package com.all.client.view;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.io.File;
import javax.swing.Icon;
import javax.swing.JTree;
import javax.swing.UIManager;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import com.all.appControl.control.ViewEngine;
import com.all.client.view.components.PreviewTree;
import com.all.core.common.view.SynthFonts;
import com.all.core.model.Model;
public class FileSystemTreeCellRenderer extends DefaultTreeCellRenderer {
private static final long serialVersionUID = 1;
private static final Color NORMAL_FOREGROUND_COLOR = new Color(25, 25, 25);
private static final Color TRANSPARENT = new Color(0, 0, 0, 0);
private final Icon folderIcon;
private final Icon trackIcon;
private final Icon fileIcon;
private final ViewEngine viewEngine;
public FileSystemTreeCellRenderer(ViewEngine viewEngine) {
super();
this.viewEngine = viewEngine;
this.setOpaque(false);
this.setBackground(TRANSPARENT);
folderIcon = UIManager.getDefaults().getIcon("icons.folderGray");
trackIcon = UIManager.getDefaults().getIcon("icons.trackBlue");
fileIcon = UIManager.getDefaults().getIcon("icons.fileGray");
setBackgroundNonSelectionColor(TRANSPARENT);
setBackgroundSelectionColor(TRANSPARENT);
}
@Override
public Component getTreeCellRendererComponent(JTree tree, Object value, boolean isSelected, boolean expanded,
boolean leaf, int row, boolean hasFocus) {
super.getTreeCellRendererComponent(tree, value, isSelected, expanded, leaf, row, hasFocus);
setForeground(NORMAL_FOREGROUND_COLOR);
if (isSelected) {
this.setName(SynthFonts.BOLD_FONT11_BLACK);
} else {
this.setName(SynthFonts.PLAIN_FONT11_BLACK);
}
Object userObject = ((DefaultMutableTreeNode) value).getUserObject();
if (userObject == null) {
this.setText("");
return this;
}
if (userObject instanceof File) {
File file = (File) userObject;
if (file.isDirectory()) {
this.setIcon(folderIcon);
setPreferredSize(new Dimension(PreviewTree.NON_LEAF_WIDTH, PreviewTree.NODE_HEIGHT));
} else {
setPreferredSize(new Dimension(PreviewTree.LEAF_WIDTH, PreviewTree.NODE_HEIGHT));
if (viewEngine.get(Model.TRACK_REPOSITORY).isFormatSupported(file)) {
this.setIcon(trackIcon);
} else {
this.setIcon(fileIcon);
}
}
this.setText(file.getName());
} else {
this.setIcon(null);
this.setText(userObject.toString());
}
return this;
}
}
| |
/* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.activiti.engine.test;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.activiti.engine.impl.test.TestHelper;
import org.activiti.engine.test.mock.ActivitiMockSupport;
import org.flowable.common.engine.api.FlowableException;
import org.flowable.engine.FormService;
import org.flowable.engine.HistoryService;
import org.flowable.engine.IdentityService;
import org.flowable.engine.ManagementService;
import org.flowable.engine.ProcessEngine;
import org.flowable.engine.ProcessEngineConfiguration;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.impl.cfg.ProcessEngineConfigurationImpl;
import org.flowable.engine.test.Deployment;
import org.junit.internal.AssumptionViolatedException;
import org.junit.rules.TestRule;
import org.junit.rules.TestWatcher;
import org.junit.runner.Description;
import org.junit.runners.model.MultipleFailureException;
import org.junit.runners.model.Statement;
/**
* Convenience for ProcessEngine and services initialization in the form of a JUnit rule.
*
* <p>
* Usage:
* </p>
*
* <pre>
* public class YourTest {
*
* @Rule
* public ActivitiRule activitiRule = new ActivitiRule();
*
* ...
* }
* </pre>
*
* <p>
* The ProcessEngine and the services will be made available to the test class through the getters of the activitiRule. The processEngine will be initialized by default with the flowable.cfg.xml
* resource on the classpath. To specify a different configuration file, pass the resource location in {@link #ActivitiRule(String) the appropriate constructor}. Process engines will be cached
* statically. Right before the first time the setUp is called for a given configuration resource, the process engine will be constructed.
* </p>
*
* <p>
* You can declare a deployment with the {@link Deployment} annotation. This base class will make sure that this deployment gets deployed before the setUp and
* {@link RepositoryService#deleteDeployment(String, boolean) cascade deleted} after the tearDown.
* </p>
*
* <p>
* The activitiRule also lets you {@link ActivitiRule#setCurrentTime(Date) set the current time used by the process engine}. This can be handy to control the exact time that is used by the engine in
* order to verify e.g. e.g. due dates of timers. Or start, end and duration times in the history service. In the tearDown, the internal clock will automatically be reset to use the current system
* time rather then the time that was set during a test method.
* </p>
*
* @author Tom Baeyens
*/
public class ActivitiRule implements TestRule {
protected String configurationResource = "flowable.cfg.xml";
protected String deploymentId;
protected ProcessEngineConfiguration processEngineConfiguration;
protected ProcessEngine processEngine;
protected RepositoryService repositoryService;
protected RuntimeService runtimeService;
protected TaskService taskService;
protected HistoryService historyService;
protected IdentityService identityService;
protected ManagementService managementService;
protected FormService formService;
protected ActivitiMockSupport mockSupport;
public ActivitiRule() {
}
public ActivitiRule(String configurationResource) {
this.configurationResource = configurationResource;
}
public ActivitiRule(ProcessEngine processEngine) {
setProcessEngine(processEngine);
}
/**
* Implementation based on {@link TestWatcher}.
*/
@Override
public Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
List<Throwable> errors = new ArrayList<Throwable>();
startingQuietly(description, errors);
try {
base.evaluate();
succeededQuietly(description, errors);
} catch (AssumptionViolatedException e) {
errors.add(e);
skippedQuietly(e, description, errors);
} catch (Throwable t) {
errors.add(t);
failedQuietly(t, description, errors);
} finally {
finishedQuietly(description, errors);
}
MultipleFailureException.assertEmpty(errors);
}
};
}
private void succeededQuietly(Description description, List<Throwable> errors) {
try {
succeeded(description);
} catch (Throwable t) {
errors.add(t);
}
}
private void failedQuietly(Throwable t, Description description,
List<Throwable> errors) {
try {
failed(t, description);
} catch (Throwable t1) {
errors.add(t1);
}
}
private void skippedQuietly(AssumptionViolatedException e,
Description description, List<Throwable> errors) {
try {
skipped(e, description);
} catch (Throwable t) {
errors.add(t);
}
}
private void startingQuietly(Description description, List<Throwable> errors) {
try {
starting(description);
} catch (Throwable t) {
errors.add(t);
}
}
private void finishedQuietly(Description description, List<Throwable> errors) {
try {
finished(description);
} catch (Throwable t) {
errors.add(t);
}
}
/**
* Invoked when a test succeeds
*/
protected void succeeded(Description description) {
}
/**
* Invoked when a test fails
*/
protected void failed(Throwable e, Description description) {
}
/**
* Invoked when a test is skipped due to a failed assumption.
*/
protected void skipped(AssumptionViolatedException e, Description description) {
}
protected void starting(Description description) {
if (processEngine == null) {
initializeProcessEngine();
}
if (processEngineConfiguration == null) {
initializeServices();
}
if (mockSupport == null) {
initializeMockSupport();
}
// Allow for mock configuration
configureProcessEngine();
// Allow for annotations
try {
TestHelper.annotationMockSupportSetup(Class.forName(description.getClassName()), description.getMethodName(), mockSupport);
} catch (ClassNotFoundException e) {
throw new FlowableException("Programmatic error: could not instantiate "
+ description.getClassName(), e);
}
try {
deploymentId = TestHelper.annotationDeploymentSetUp(processEngine,
Class.forName(description.getClassName()), description.getMethodName());
} catch (ClassNotFoundException e) {
throw new FlowableException("Programmatic error: could not instantiate "
+ description.getClassName(), e);
}
}
protected void initializeProcessEngine() {
processEngine = TestHelper.getProcessEngine(configurationResource);
}
protected void initializeServices() {
processEngineConfiguration = processEngine.getProcessEngineConfiguration();
repositoryService = processEngine.getRepositoryService();
runtimeService = processEngine.getRuntimeService();
taskService = processEngine.getTaskService();
historyService = processEngine.getHistoryService();
identityService = processEngine.getIdentityService();
managementService = processEngine.getManagementService();
formService = processEngine.getFormService();
}
protected void initializeMockSupport() {
if (ActivitiMockSupport.isMockSupportPossible(processEngine)) {
this.mockSupport = new ActivitiMockSupport(processEngine);
}
}
protected void configureProcessEngine() {
/* meant to be overridden */
}
protected void finished(Description description) {
// Remove the test deployment
try {
TestHelper.annotationDeploymentTearDown(processEngine, deploymentId,
Class.forName(description.getClassName()), description.getMethodName());
} catch (ClassNotFoundException e) {
throw new FlowableException("Programmatic error: could not instantiate "
+ description.getClassName(), e);
}
// Reset internal clock
processEngineConfiguration.getClock().reset();
// Rest mocks
if (mockSupport != null) {
TestHelper.annotationMockSupportTeardown(mockSupport);
}
}
public void setCurrentTime(Date currentTime) {
processEngineConfiguration.getClock().setCurrentTime(currentTime);
}
public String getConfigurationResource() {
return configurationResource;
}
public void setConfigurationResource(String configurationResource) {
this.configurationResource = configurationResource;
}
public ProcessEngine getProcessEngine() {
return processEngine;
}
public void setProcessEngine(ProcessEngine processEngine) {
this.processEngine = processEngine;
initializeServices();
}
public RepositoryService getRepositoryService() {
return repositoryService;
}
public void setRepositoryService(RepositoryService repositoryService) {
this.repositoryService = repositoryService;
}
public RuntimeService getRuntimeService() {
return runtimeService;
}
public void setRuntimeService(RuntimeService runtimeService) {
this.runtimeService = runtimeService;
}
public TaskService getTaskService() {
return taskService;
}
public void setTaskService(TaskService taskService) {
this.taskService = taskService;
}
public HistoryService getHistoryService() {
return historyService;
}
public void setHistoricDataService(HistoryService historicDataService) {
this.historyService = historicDataService;
}
public IdentityService getIdentityService() {
return identityService;
}
public void setIdentityService(IdentityService identityService) {
this.identityService = identityService;
}
public ManagementService getManagementService() {
return managementService;
}
public FormService getFormService() {
return formService;
}
public void setManagementService(ManagementService managementService) {
this.managementService = managementService;
}
public void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
}
public ActivitiMockSupport getMockSupport() {
return mockSupport;
}
public ActivitiMockSupport mockSupport() {
return mockSupport;
}
}
| |
/*
* The Alluxio Open Foundation licenses this work under the Apache License, version 2.0
* (the "License"). You may not use this work except in compliance with the License, which is
* available at www.apache.org/licenses/LICENSE-2.0
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied, as more fully set forth in the License.
*
* See the NOTICE file distributed with this work for information regarding copyright ownership.
*/
package alluxio.master.block.meta;
import alluxio.Constants;
import alluxio.StorageTierAssoc;
import alluxio.WorkerStorageTierAssoc;
import alluxio.client.block.options.GetWorkerReportOptions.WorkerInfoField;
import alluxio.grpc.StorageList;
import alluxio.util.CommonUtils;
import alluxio.wire.WorkerInfo;
import alluxio.wire.WorkerNetAddress;
import com.google.common.base.MoreObjects;
import com.google.common.base.Preconditions;
import com.google.common.collect.Sets;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import javax.annotation.concurrent.NotThreadSafe;
/**
* Metadata for an Alluxio worker. This class is not thread safe, so external locking is required.
*/
@NotThreadSafe
public final class MasterWorkerInfo {
private static final Logger LOG = LoggerFactory.getLogger(MasterWorkerInfo.class);
private static final String LIVE_WORKER_STATE = "In Service";
private static final String LOST_WORKER_STATE = "Out of Service";
private static final int BLOCK_SIZE_LIMIT = 100;
/** Worker's address. */
private final WorkerNetAddress mWorkerAddress;
/** The id of the worker. */
private final long mId;
/** Start time of the worker in ms. */
private final long mStartTimeMs;
/** Capacity of worker in bytes. */
private long mCapacityBytes;
/** Worker's used bytes. */
private long mUsedBytes;
/** Worker's last updated time in ms. */
private long mLastUpdatedTimeMs;
/** If true, the worker is considered registered. */
private boolean mIsRegistered;
/** Worker-specific mapping between storage tier alias and storage tier ordinal. */
private StorageTierAssoc mStorageTierAssoc;
/** Mapping from storage tier alias to total bytes. */
private Map<String, Long> mTotalBytesOnTiers;
/** Mapping from storage tier alias to used bytes. */
private Map<String, Long> mUsedBytesOnTiers;
/** ids of blocks the worker contains. */
private Set<Long> mBlocks;
/** ids of blocks the worker should remove. */
private Set<Long> mToRemoveBlocks;
/** Mapping from tier alias to lost storage paths. */
private Map<String, List<String>> mLostStorage;
/**
* Creates a new instance of {@link MasterWorkerInfo}.
*
* @param id the worker id to use
* @param address the worker address to use
*/
public MasterWorkerInfo(long id, WorkerNetAddress address) {
mWorkerAddress = Preconditions.checkNotNull(address, "address");
mId = id;
mStartTimeMs = System.currentTimeMillis();
mLastUpdatedTimeMs = System.currentTimeMillis();
mIsRegistered = false;
mStorageTierAssoc = null;
mTotalBytesOnTiers = new HashMap<>();
mUsedBytesOnTiers = new HashMap<>();
mBlocks = new HashSet<>();
mToRemoveBlocks = new HashSet<>();
mLostStorage = new HashMap<>();
}
/**
* Marks the worker as registered, while updating all of its metadata.
*
* @param globalStorageTierAssoc global mapping between storage aliases and ordinal position
* @param storageTierAliases list of storage tier aliases in order of their position in the
* hierarchy
* @param totalBytesOnTiers mapping from storage tier alias to total bytes
* @param usedBytesOnTiers mapping from storage tier alias to used byes
* @param blocks set of block ids on this worker
* @return A Set of blocks removed (or lost) from this worker
*/
public Set<Long> register(final StorageTierAssoc globalStorageTierAssoc,
final List<String> storageTierAliases, final Map<String, Long> totalBytesOnTiers,
final Map<String, Long> usedBytesOnTiers, final Set<Long> blocks) {
// If the storage aliases do not have strictly increasing ordinal value based on the total
// ordering, throw an error
for (int i = 0; i < storageTierAliases.size() - 1; i++) {
if (globalStorageTierAssoc.getOrdinal(storageTierAliases.get(i)) >= globalStorageTierAssoc
.getOrdinal(storageTierAliases.get(i + 1))) {
throw new IllegalArgumentException(
"Worker cannot place storage tier " + storageTierAliases.get(i) + " above "
+ storageTierAliases.get(i + 1) + " in the hierarchy");
}
}
mStorageTierAssoc = new WorkerStorageTierAssoc(storageTierAliases);
// validate the number of tiers
if (mStorageTierAssoc.size() != totalBytesOnTiers.size()
|| mStorageTierAssoc.size() != usedBytesOnTiers.size()) {
throw new IllegalArgumentException(
"totalBytesOnTiers and usedBytesOnTiers should have the same number of tiers as "
+ "storageTierAliases, but storageTierAliases has " + mStorageTierAssoc.size()
+ " tiers, while totalBytesOnTiers has " + totalBytesOnTiers.size()
+ " tiers and usedBytesOnTiers has " + usedBytesOnTiers.size() + " tiers");
}
// defensive copy
mTotalBytesOnTiers = new HashMap<>(totalBytesOnTiers);
mUsedBytesOnTiers = new HashMap<>(usedBytesOnTiers);
mCapacityBytes = 0;
for (long bytes : mTotalBytesOnTiers.values()) {
mCapacityBytes += bytes;
}
mUsedBytes = 0;
for (long bytes : mUsedBytesOnTiers.values()) {
mUsedBytes += bytes;
}
Set<Long> removedBlocks;
if (mIsRegistered) {
// This is a re-register of an existing worker. Assume the new block ownership data is more
// up-to-date and update the existing block information.
LOG.info("re-registering an existing workerId: {}", mId);
// Compute the difference between the existing block data, and the new data.
removedBlocks = Sets.difference(mBlocks, blocks);
} else {
removedBlocks = Collections.emptySet();
}
// Set the new block information.
mBlocks = new HashSet<>(blocks);
mIsRegistered = true;
return removedBlocks;
}
/**
* Adds a block to the worker.
*
* @param blockId the id of the block to be added
*/
public void addBlock(long blockId) {
mBlocks.add(blockId);
}
/**
* Removes a block from the worker.
*
* @param blockId the id of the block to be removed
*/
public void removeBlock(long blockId) {
mBlocks.remove(blockId);
mToRemoveBlocks.remove(blockId);
}
/**
* Adds a new worker lost storage path.
*
* @param tierAlias the tier alias
* @param dirPath the lost storage path
*/
public void addLostStorage(String tierAlias, String dirPath) {
List<String> paths = mLostStorage.getOrDefault(tierAlias, new ArrayList<>());
paths.add(dirPath);
mLostStorage.put(tierAlias, paths);
}
/**
* Adds new worker lost storage paths.
*
* @param lostStorage the lost storage to add
*/
public void addLostStorage(Map<String, StorageList> lostStorage) {
for (Map.Entry<String, StorageList> entry : lostStorage.entrySet()) {
List<String> paths = mLostStorage.getOrDefault(entry.getKey(), new ArrayList<>());
paths.addAll(entry.getValue().getStorageList());
mLostStorage.put(entry.getKey(), paths);
}
}
/**
* Gets the selected field information for this worker.
*
* @param fieldRange the client selected fields
* @param isLiveWorker the worker is live or not
* @return generated worker information
*/
public WorkerInfo generateWorkerInfo(Set<WorkerInfoField> fieldRange, boolean isLiveWorker) {
WorkerInfo info = new WorkerInfo();
Set<WorkerInfoField> checkedFieldRange = fieldRange != null ? fieldRange :
new HashSet<>(Arrays.asList(WorkerInfoField.values()));
for (WorkerInfoField field : checkedFieldRange) {
switch (field) {
case ADDRESS:
info.setAddress(mWorkerAddress);
break;
case WORKER_CAPACITY_BYTES:
info.setCapacityBytes(mCapacityBytes);
break;
case WORKER_CAPACITY_BYTES_ON_TIERS:
info.setCapacityBytesOnTiers(mTotalBytesOnTiers);
break;
case ID:
info.setId(mId);
break;
case LAST_CONTACT_SEC:
info.setLastContactSec(
(int) ((CommonUtils.getCurrentMs() - mLastUpdatedTimeMs) / Constants.SECOND_MS));
break;
case START_TIME_MS:
info.setStartTimeMs(mStartTimeMs);
break;
case STATE:
if (isLiveWorker) {
info.setState(LIVE_WORKER_STATE);
} else {
info.setState(LOST_WORKER_STATE);
}
break;
case WORKER_USED_BYTES:
info.setUsedBytes(mUsedBytes);
break;
case WORKER_USED_BYTES_ON_TIERS:
info.setUsedBytesOnTiers(mUsedBytesOnTiers);
break;
default:
LOG.warn("Unrecognized worker info field: " + field);
}
}
return info;
}
/**
* @return the worker's address
*/
public WorkerNetAddress getWorkerAddress() {
return mWorkerAddress;
}
/**
* @return the available space of the worker in bytes
*/
public long getAvailableBytes() {
return mCapacityBytes - mUsedBytes;
}
/**
* @return ids of all blocks the worker contains
*/
public Set<Long> getBlocks() {
return new HashSet<>(mBlocks);
}
/**
* @return the capacity of the worker in bytes
*/
public long getCapacityBytes() {
return mCapacityBytes;
}
/**
* @return the id of the worker
*/
public long getId() {
return mId;
}
/**
* @return the last updated time of the worker in ms
*/
public long getLastUpdatedTimeMs() {
return mLastUpdatedTimeMs;
}
/**
* @return ids of blocks the worker should remove
*/
public List<Long> getToRemoveBlocks() {
return new ArrayList<>(mToRemoveBlocks);
}
/**
* @return used space of the worker in bytes
*/
public long getUsedBytes() {
return mUsedBytes;
}
/**
* @return the storage tier mapping for the worker
*/
public StorageTierAssoc getStorageTierAssoc() {
return mStorageTierAssoc;
}
/**
* @return the total bytes on each storage tier
*/
public Map<String, Long> getTotalBytesOnTiers() {
return mTotalBytesOnTiers;
}
/**
* @return the used bytes on each storage tier
*/
public Map<String, Long> getUsedBytesOnTiers() {
return mUsedBytesOnTiers;
}
/**
* @return the start time in milliseconds
*/
public long getStartTime() {
return mStartTimeMs;
}
/**
* @return whether the worker has been registered yet
*/
public boolean isRegistered() {
return mIsRegistered;
}
/**
* @return the free bytes on each storage tier
*/
public Map<String, Long> getFreeBytesOnTiers() {
Map<String, Long> freeCapacityBytes = new HashMap<>();
for (Map.Entry<String, Long> entry : mTotalBytesOnTiers.entrySet()) {
freeCapacityBytes.put(entry.getKey(),
entry.getValue() - mUsedBytesOnTiers.get(entry.getKey()));
}
return freeCapacityBytes;
}
/**
* @return the map from tier alias to lost storage paths in this worker
*/
public Map<String, List<String>> getLostStorage() {
return new HashMap<>(mLostStorage);
}
/**
* @return true if this worker has lost storage, false otherwise
*/
public boolean hasLostStorage() {
return mLostStorage.size() > 0;
}
@Override
public String toString() {
Collection<Long> blocks = mBlocks;
String blockFieldName = "blocks";
// We truncate the list of block IDs to print, unless it is for DEBUG logs
if (!LOG.isDebugEnabled() && mBlocks.size() > BLOCK_SIZE_LIMIT) {
blockFieldName = "blocks-truncated";
blocks = mBlocks.stream().limit(BLOCK_SIZE_LIMIT).collect(Collectors.toList());
}
return MoreObjects.toStringHelper(this)
.add("id", mId)
.add("workerAddress", mWorkerAddress)
.add("capacityBytes", mCapacityBytes)
.add("usedBytes", mUsedBytes)
.add("lastUpdatedTimeMs", mLastUpdatedTimeMs)
.add("blockCount", mBlocks.size())
.add(blockFieldName, blocks)
.add("lostStorage", mLostStorage).toString();
}
/**
* Updates the last updated time of the worker in ms.
*/
public void updateLastUpdatedTimeMs() {
mLastUpdatedTimeMs = System.currentTimeMillis();
}
/**
* Adds or removes a block from the to-be-removed blocks set of the worker.
*
* @param add true if to add, to remove otherwise
* @param blockId the id of the block to be added or removed
*/
public void updateToRemovedBlock(boolean add, long blockId) {
if (add) {
if (mBlocks.contains(blockId)) {
mToRemoveBlocks.add(blockId);
}
} else {
mToRemoveBlocks.remove(blockId);
}
}
/**
* Sets the capacity of the worker in bytes.
*
* @param capacityBytesOnTiers used bytes on each storage tier
*/
public void updateCapacityBytes(Map<String, Long> capacityBytesOnTiers) {
mCapacityBytes = 0;
mTotalBytesOnTiers = capacityBytesOnTiers;
for (long t : mTotalBytesOnTiers.values()) {
mCapacityBytes += t;
}
}
/**
* Sets the used space of the worker in bytes.
*
* @param usedBytesOnTiers used bytes on each storage tier
*/
public void updateUsedBytes(Map<String, Long> usedBytesOnTiers) {
mUsedBytes = 0;
mUsedBytesOnTiers = new HashMap<>(usedBytesOnTiers);
for (long t : mUsedBytesOnTiers.values()) {
mUsedBytes += t;
}
}
/**
* Sets the used space of the worker in bytes.
*
* @param tierAlias alias of storage tier
* @param usedBytesOnTier used bytes on certain storage tier
*/
public void updateUsedBytes(String tierAlias, long usedBytesOnTier) {
mUsedBytes += usedBytesOnTier - mUsedBytesOnTiers.get(tierAlias);
mUsedBytesOnTiers.put(tierAlias, usedBytesOnTier);
}
}
| |
/*
* Copyright 2014 The Closure Compiler Authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.javascript.jscomp;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableSet;
import com.google.javascript.jscomp.NodeTraversal.AbstractPostOrderCallback;
import com.google.javascript.rhino.IR;
import com.google.javascript.rhino.JSDocInfo;
import com.google.javascript.rhino.JSDocInfoBuilder;
import com.google.javascript.rhino.Node;
import com.google.javascript.rhino.Token;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Process aliases in goog.modules.
* <pre>
* goog.module('namespace');
* var foo = goog.require('another.namespace');
* ...
* </pre>
*
* becomes
*
* <pre>
* goog.provide('namespace');
* goog.require('another.namespace');
* goog.scope(function() {
* var foo = another.namespace;
* ...
* });
* </pre>
*
* @author johnlenz@google.com (John Lenz)
*/
final class ClosureRewriteModule implements NodeTraversal.Callback, HotSwapCompilerPass {
// TODO(johnlenz): Don't use goog.scope as an intermediary; add type checker
// support instead.
// TODO(johnlenz): harden this class to warn about misuse
// TODO(johnlenz): handle non-namespace module identifiers aka 'foo/bar'
static final DiagnosticType INVALID_MODULE_IDENTIFIER =
DiagnosticType.error(
"JSC_GOOG_MODULE_INVALID_MODULE_IDENTIFIER",
"Module idenifiers must be string literals");
static final DiagnosticType INVALID_REQUIRE_IDENTIFIER =
DiagnosticType.error(
"JSC_GOOG_MODULE_INVALID_REQUIRE_IDENTIFIER",
"goog.require parameter must be a string literal.");
static final DiagnosticType INVALID_GET_IDENTIFIER =
DiagnosticType.error(
"JSC_GOOG_MODULE_INVALID_GET_IDENTIFIER",
"goog.module.get parameter must be a string literal.");
static final DiagnosticType INVALID_GET_CALL_SCOPE =
DiagnosticType.error(
"JSC_GOOG_MODULE_INVALID_GET_CALL_SCOPE",
"goog.module.get can not be called in global scope.");
static final DiagnosticType INVALID_GET_ALIAS =
DiagnosticType.error(
"JSC_GOOG_MODULE_INVALID_GET_ALIAS",
"goog.module.get should not be aliased.");
static final DiagnosticType INVALID_EXPORT_COMPUTED_PROPERTY =
DiagnosticType.error(
"JSC_GOOG_MODULE_INVALID_EXPORT_COMPUTED_PROPERTY",
"Computed properties are not yet supported in goog.module exports.");
static final DiagnosticType USELESS_USE_STRICT_DIRECTIVE =
DiagnosticType.warning(
"JSC_USELESS_USE_STRICT_DIRECTIVE",
"'use strict' is unnecessary in goog.module files.");
private static final ImmutableSet<String> USE_STRICT_ONLY = ImmutableSet.of("use strict");
private final AbstractCompiler compiler;
private class ModuleDescription {
Node moduleDecl;
String moduleNamespace = "";
Node requireInsertNode = null;
final Node moduleScopeRoot;
final Node moduleStatementRoot;
final List<Node> requires = new ArrayList<>();
final List<Node> provides = new ArrayList<>();
final List<Node> exports = new ArrayList<>();
public Scope moduleScope = null;
ModuleDescription(Node n) {
if (isLoadModuleCall(n)) {
this.moduleScopeRoot = getModuleScopeRootForLoadModuleCall(n);
this.moduleStatementRoot = getModuleStatementRootForLoadModuleCall(n);
} else {
this.moduleScopeRoot = n;
this.moduleStatementRoot = n;
}
}
}
// Per "goog.module" state need for rewriting.
private ModuleDescription current = null;
ClosureRewriteModule(AbstractCompiler compiler) {
this.compiler = compiler;
}
@Override
public void process(Node externs, Node root) {
// Each module is its own scope, prevent building a global scope,
// so we can use the scope for the file.
// TODO(johnlenz): this is a little odd, rework this once we have
// a concept of a module scope.
for (Node c = root.getFirstChild(); c != null; c = c.getNext()) {
Preconditions.checkState(c.isScript());
hotSwapScript(c, null);
}
}
@Override
public void hotSwapScript(Node scriptRoot, Node originalRoot) {
NodeTraversal.traverseEs6(compiler, scriptRoot, this);
}
@Override
public boolean shouldTraverse(NodeTraversal t, Node n, Node parent) {
boolean isModuleFile = isModuleFile(n);
if (isModuleFile) {
checkStrictModeDirective(t, n);
}
if (isModuleFile || isLoadModuleCall(n)) {
enterModule(n);
}
if (isGetModuleCall(n)) {
rewriteGetModuleCall(t, n);
}
if (inModule()) {
switch (n.getType()) {
case Token.SCRIPT:
current.moduleScope = t.getScope();
break;
case Token.BLOCK:
if (current.moduleScopeRoot == parent && parent.isFunction()) {
current.moduleScope = t.getScope();
}
break;
case Token.ASSIGN:
if (isGetModuleCallAlias(n)) {
rewriteGetModuleCallAlias(t, n);
}
break;
default:
if (current.moduleScopeRoot == parent && parent.isBlock()) {
current.moduleScope = t.getScope();
}
break;
}
}
return true;
}
private static void checkStrictModeDirective(NodeTraversal t, Node n) {
Preconditions.checkState(n.isScript());
Set<String> directives = n.getDirectives();
if (directives != null && directives.contains("use strict")) {
t.report(n, USELESS_USE_STRICT_DIRECTIVE);
} else {
if (directives == null) {
n.setDirectives(USE_STRICT_ONLY);
} else {
ImmutableSet.Builder<String> builder = new ImmutableSet.Builder<String>().add("use strict");
builder.addAll(directives);
n.setDirectives(builder.build());
}
}
}
private static boolean isCallTo(Node n, String qname) {
return n.isCall()
&& n.getFirstChild().matchesQualifiedName(qname);
}
private static boolean isLoadModuleCall(Node n) {
return isCallTo(n, "goog.loadModule");
}
private static boolean isGetModuleCall(Node n) {
return isCallTo(n, "goog.module.get");
}
private void rewriteGetModuleCall(NodeTraversal t, Node n) {
// "use(goog.module.get('a.namespace'))" to "use(a.namespace)"
Node namespace = n.getFirstChild().getNext();
if (!namespace.isString()) {
t.report(namespace, INVALID_GET_IDENTIFIER);
return;
}
if (!inModule() && t.inGlobalScope()) {
t.report(namespace, INVALID_GET_CALL_SCOPE);
return;
}
Node replacement = NodeUtil.newQName(compiler, namespace.getString());
replacement.srcrefTree(namespace);
n.getParent().replaceChild(n, replacement);
compiler.reportCodeChange();
}
private void rewriteGetModuleCallAlias(NodeTraversal t, Node n) {
// x = goog.module.get('a.namespace');
Preconditions.checkArgument(NodeUtil.isExprAssign(n.getParent()));
Preconditions.checkArgument(n.getFirstChild().isName());
Preconditions.checkArgument(isGetModuleCall(n.getLastChild()));
rewriteGetModuleCall(t, n.getLastChild());
String aliasName = n.getFirstChild().getQualifiedName();
Var alias = t.getScope().getVar(aliasName);
if (alias == null) {
t.report(n, INVALID_GET_ALIAS);
return;
}
// Only rewrite if original definition was of the form:
// let x = goog.forwardDeclare('a.namespace');
Node forwardDeclareCall = NodeUtil.getRValueOfLValue(alias.getNode());
if (forwardDeclareCall == null
|| !isCallTo(forwardDeclareCall, "goog.forwardDeclare")
|| forwardDeclareCall.getChildCount() != 2) {
t.report(n, INVALID_GET_ALIAS);
return;
}
Node argument = forwardDeclareCall.getLastChild();
if (!argument.isString() || !n.getLastChild().matchesQualifiedName(argument.getString())) {
t.report(n, INVALID_GET_ALIAS);
return;
}
Node replacement = NodeUtil.newQName(compiler, argument.getString());
replacement.srcrefTree(forwardDeclareCall);
// Rewrite goog.forwardDeclare
forwardDeclareCall.getParent().replaceChild(forwardDeclareCall, replacement);
// and remove goog.module.get
n.getParent().detachFromParent();
compiler.reportCodeChange();
}
private static boolean isModuleFile(Node n) {
return n.isScript() && n.hasChildren()
&& isGoogModuleCall(n.getFirstChild());
}
private void enterModule(Node n) {
current = new ModuleDescription(n);
}
private boolean inModule() {
return current != null;
}
private static boolean isGoogModuleCall(Node n) {
if (NodeUtil.isExprCall(n)) {
Node target = n.getFirstChild().getFirstChild();
return (target.matchesQualifiedName("goog.module"));
}
return false;
}
private static boolean isGetModuleCallAlias(Node n) {
return NodeUtil.isExprAssign(n.getParent())
&& n.getFirstChild().isName() && isGetModuleCall(n.getLastChild());
}
/**
* Rewrite:
* goog.module('foo')
* var bar = goog.require('bar');
* exports = something;
* to:
* goog.provide('foo');
* goog.require('ns.bar');
* goog.scope(function() {
* var bar = ns.bar;
* foo = something;
* });
*/
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (!inModule()) {
// Nothing to do if we aren't within a module file.
return;
}
switch (n.getType()) {
case Token.EXPR_RESULT:
// Handle "goog.module.declareLegacyNamespace". Currently, we simply
// need to remove it.
if (isCallTo(n.getFirstChild(),
"goog.module.declareLegacyNamespace")) {
n.detachFromParent();
}
break;
case Token.CALL:
if (isCallTo(n, "goog.module")) {
recordAndUpdateModule(t, n);
} else if (isCallTo(n, "goog.require")) {
recordRequire(t, n);
} else if (isLoadModuleCall(n)) {
rewriteModuleAsScope(n);
}
break;
case Token.GETPROP:
if (isExportPropAssign(n)) {
Node rhs = parent.getLastChild();
maybeUpdateExportDeclToNode(t, parent, rhs);
}
break;
case Token.NAME:
if (n.getString().equals("exports")) {
current.exports.add(n);
if (isAssignTarget(n)) {
maybeUpdateExportObjectDecl(t, n);
}
}
break;
case Token.SCRIPT:
// Exiting the script, fixup everything else;
rewriteModuleAsScope(n);
break;
case Token.RETURN:
// Remove the "return exports" for bundled goog.module files.
if (parent == current.moduleStatementRoot) {
n.detachFromParent();
}
break;
}
}
/**
* For exports like "exports = {prop: value}" update the declarations to enforce
* @const ness (and typedef exports).
*/
private void maybeUpdateExportObjectDecl(NodeTraversal t, Node n) {
Node parent = n.getParent();
Node rhs = parent.getLastChild();
// The export declaration itself
maybeUpdateExportDeclToNode(t, parent, rhs);
if (rhs.isObjectLit()) {
for (Node c = rhs.getFirstChild(); c != null; c = c.getNext()) {
if (c.isComputedProp()) {
t.report(c, INVALID_EXPORT_COMPUTED_PROPERTY);
} else if (c.isStringKey()) {
Node value = c.hasChildren() ? c.getFirstChild() : IR.name(c.getString());
maybeUpdateExportDeclToNode(t, c, value);
}
}
}
}
private void maybeUpdateExportDeclToNode(
NodeTraversal t, Node target, Node value) {
// If the RHS is a typedef, clone the declaration.
// Hack alert: clone the typedef declaration if one exists
// this is a simple attempt that covers the common case of the
// exports being in the same scope as the typedef declaration.
// Otherwise the type name might be invalid.
if (value.isName()) {
Scope currentScope = t.getScope();
Var v = t.getScope().getVar(value.getString());
if (v != null) {
Scope varScope = v.getScope();
if (varScope.getDepth() == currentScope.getDepth()) {
JSDocInfo info = v.getJSDocInfo();
if (info != null && info.hasTypedefType()) {
JSDocInfoBuilder builder = JSDocInfoBuilder.copyFrom(info);
target.setJSDocInfo(builder.build());
return;
}
}
}
}
// Don't add @const on class declarations, @const on classes has a
// different meaning (it means "not subclassable").
// "goog.defineClass" hasn't been rewritten yet, so check for that
// explicitly.
JSDocInfo info = target.getJSDocInfo();
if ((info != null && info.isConstructorOrInterface()
|| isCallTo(value, "goog.defineClass"))) {
return;
}
// Not a known typedef export, simple declare the props to be @const,
// this is valid because we freeze module export objects.
JSDocInfoBuilder builder = JSDocInfoBuilder.maybeCopyFrom(info);
builder.recordConstancy();
target.setJSDocInfo(builder.build());
}
/**
* @return Whether the getprop is used as an assignment target, and that
* target represents a module export.
* Note: that "export.name = value" is an export, while "export.name.foo = value"
* is not (it is an assignment to a property of an exported value).
*/
private static boolean isExportPropAssign(Node n) {
Preconditions.checkState(n.isGetProp());
Node target = n.getFirstChild();
return isAssignTarget(n) && target.isName()
&& target.getString().equals("exports");
}
private static boolean isAssignTarget(Node n) {
Node parent = n.getParent();
return parent.isAssign() && parent.getFirstChild() == n;
}
private void recordAndUpdateModule(NodeTraversal t, Node call) {
Node idNode = call.getLastChild();
if (!idNode.isString()) {
t.report(idNode, INVALID_MODULE_IDENTIFIER);
return;
}
current.moduleNamespace = idNode.getString();
current.moduleDecl = call;
// rewrite "goog.module('foo')" to "goog.provide('foo')"
Node target = call.getFirstChild();
target.getLastChild().setString("provide");
current.provides.add(call);
}
private void recordRequire(NodeTraversal t, Node call) {
Node idNode = call.getLastChild();
if (!idNode.isString()) {
t.report(idNode, INVALID_REQUIRE_IDENTIFIER);
return;
}
current.requires.add(call);
}
private void updateRequires(List<Node> requires) {
for (Node node : requires) {
updateRequire(node);
}
}
private void updateRequire(Node call) {
if (call.getParent().isExprResult()) {
// The goog.require is the entire statement. There is no var, so there's nothing to do.
return;
}
String namespace = call.getLastChild().getString();
if (current.requireInsertNode == null) {
current.requireInsertNode = getInsertRoot(call);
}
// rewrite:
// var foo = goog.require('ns.foo')
// to
// goog.require('foo');
// var foo = ns.foo;
// replace the goog.require statement with a reference to the namespace.
Node replacement = NodeUtil.newQName(compiler, namespace).srcrefTree(call);
call.getParent().replaceChild(call, replacement);
// readd the goog.require statement
Node require = IR.exprResult(call).srcref(call);
Node insertAt = current.requireInsertNode;
insertAt.getParent().addChildBefore(require, insertAt);
}
private List<String> collectRoots(ModuleDescription module) {
List<String> result = new ArrayList<>();
for (Node n : module.provides) {
result.add(getRootName(n.getFirstChild().getNext()));
}
for (Node n : module.requires) {
result.add(getRootName(n.getFirstChild().getNext()));
}
return result;
}
private String getRootName(Node n) {
String qname = n.getString();
int endPos = qname.indexOf('.');
return (endPos == -1) ? qname : qname.substring(0, endPos);
}
private void rewriteModuleAsScope(Node root) {
// Moving everything following the goog.module/goog.requires into a
// goog.scope so that the aliases can be resolved.
Node moduleRoot = current.moduleStatementRoot;
// The moduleDecl will be null if it is invalid.
Node srcref = current.moduleDecl != null ? current.moduleDecl : root;
ImmutableSet<String> roots = ImmutableSet.copyOf(collectRoots(current));
updateRootShadows(current.moduleScope, roots);
updateRequires(current.requires);
updateExports(current.exports);
Node block = IR.block();
Node scope = IR.exprResult(IR.call(
IR.getprop(IR.name("goog"), IR.string("scope")),
IR.function(IR.name(""), IR.paramList(), block)))
.srcrefTree(srcref);
// Skip goog.module, etc.
Node fromNode = skipHeaderNodes(moduleRoot);
Preconditions.checkNotNull(fromNode);
moveChildrenAfter(fromNode, block);
moduleRoot.addChildAfter(scope, fromNode);
if (root.isCall()) {
Node expr = root.getParent();
Preconditions.checkState(expr.isExprResult(), expr);
expr.getParent().addChildrenAfter(moduleRoot.removeChildren(), expr);
expr.detachFromParent();
}
compiler.reportCodeChange();
// reset the module.
current = null;
}
private void updateExports(List<Node> exports) {
for (Node n : exports) {
Node replacement = NodeUtil.newQName(compiler, current.moduleNamespace);
replacement.srcrefTree(n);
n.getParent().replaceChild(n, replacement);
}
}
private void updateRootShadows(Scope s, ImmutableSet<String> roots) {
final Map<String, String> nameMap = new HashMap<>();
for (String root : roots) {
if (s.getOwnSlot(root) != null) {
nameMap.put(root, root + "_module");
}
}
if (nameMap.isEmpty()) {
// Don't traverse if there is nothing to do.
return;
}
NodeTraversal.traverseEs6(compiler, s.getRootNode(), new AbstractPostOrderCallback() {
@Override
public void visit(NodeTraversal t, Node n, Node parent) {
if (n.isName()) {
String rename = nameMap.get(n.getString());
if (rename != null) {
n.setString(rename);
}
}
}
});
}
private Node getModuleScopeRootForLoadModuleCall(Node n) {
Preconditions.checkState(n.isCall());
Node fn = n.getLastChild();
Preconditions.checkState(fn.isFunction());
return fn.getLastChild();
}
private Node getModuleStatementRootForLoadModuleCall(Node n) {
Node scopeRoot = getModuleScopeRootForLoadModuleCall(n);
if (scopeRoot.isFunction()) {
return scopeRoot.getLastChild();
} else {
return scopeRoot;
}
}
private Node skipHeaderNodes(Node script) {
Node lastHeaderNode = null;
Node child = script.getFirstChild();
while (child != null && isHeaderNode(child)) {
lastHeaderNode = child;
child = child.getNext();
}
return lastHeaderNode;
}
private boolean isHeaderNode(Node n) {
if (n.isEmpty()) {
return true;
}
if (NodeUtil.isExprCall(n)) {
Node target = n.getFirstChild().getFirstChild();
return (
target.matchesQualifiedName("goog.module")
|| target.matchesQualifiedName("goog.provide")
|| target.matchesQualifiedName("goog.require")
|| target.matchesQualifiedName("goog.setTestOnly"));
}
return false;
}
private void moveChildrenAfter(Node fromNode, Node targetBlock) {
Node parent = fromNode.getParent();
while (fromNode.getNext() != null) {
Node child = parent.removeChildAfter(fromNode);
targetBlock.addChildToBack(child);
}
}
private Node getInsertRoot(Node n) {
while (n.getParent() != current.moduleStatementRoot) {
n = n.getParent();
}
return n;
}
}
| |
package org.fossasia.phimpme.editor.view.imagezoom;
import static org.fossasia.phimpme.utilities.ActivitySwitchHelper.getContext;
import android.content.Context;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.GestureDetector.OnGestureListener;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.ScaleGestureDetector.OnScaleGestureListener;
import android.view.ViewConfiguration;
public class ImageViewTouch extends ImageViewTouchBase {
static final float SCROLL_DELTA_THRESHOLD = 1.0f;
protected ScaleGestureDetector mScaleDetector;
protected GestureDetector mGestureDetector;
protected int mTouchSlop;
protected float mScaleFactor;
protected int mDoubleTapDirection;
protected OnGestureListener mGestureListener;
protected OnScaleGestureListener mScaleListener;
protected boolean mDoubleTapEnabled = true;
protected boolean mScaleEnabled = true;
protected boolean mScrollEnabled = true;
private OnImageViewTouchDoubleTapListener mDoubleTapListener;
private OnImageViewTouchSingleTapListener mSingleTapListener;
private OnImageFlingListener mFlingListener;
public ImageViewTouch(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void init() {
super.init();
mTouchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
mGestureListener = getGestureListener();
mScaleListener = getScaleListener();
mScaleDetector = new ScaleGestureDetector(getContext(), mScaleListener);
mGestureDetector = new GestureDetector(getContext(), mGestureListener, null, true);
mDoubleTapDirection = 1;
}
public void setDoubleTapListener(OnImageViewTouchDoubleTapListener listener) {
mDoubleTapListener = listener;
}
public void setSingleTapListener(OnImageViewTouchSingleTapListener listener) {
mSingleTapListener = listener;
}
public void setFlingListener(OnImageFlingListener listener) {
mFlingListener = listener;
}
public void setDoubleTapEnabled(boolean value) {
mDoubleTapEnabled = value;
}
public void setScaleEnabled(boolean value) {
mScaleEnabled = value;
setDoubleTapEnabled(value);
}
public void setScrollEnabled(boolean value) {
mScrollEnabled = value;
}
public boolean getDoubleTapEnabled() {
return mDoubleTapEnabled;
}
protected OnGestureListener getGestureListener() {
return new GestureListener();
}
protected OnScaleGestureListener getScaleListener() {
return new ScaleListener();
}
@Override
protected void _setImageDrawable(
final Drawable drawable, final Matrix initial_matrix, float min_zoom, float max_zoom) {
super._setImageDrawable(drawable, initial_matrix, min_zoom, max_zoom);
mScaleFactor = getMaxScale() / 3;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mScaleDetector.onTouchEvent(event);
if (!mScaleDetector.isInProgress()) {
mGestureDetector.onTouchEvent(event);
}
int action = event.getAction();
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_UP:
if (getScale() < getMinScale()) {
zoomTo(getMinScale(), 500);
}
break;
}
return true;
}
@Override
protected void onZoomAnimationCompleted(float scale) {
if (LOG_ENABLED) {
Log.d(LOG_TAG, "onZoomAnimationCompleted. scale: " + scale + ", minZoom: " + getMinScale());
}
if (scale < getMinScale()) {
zoomTo(getMinScale(), 50);
}
}
// protected float onDoubleTapPost(float scale, float maxZoom) {
// if (mDoubleTapDirection == 1) {
// mDoubleTapDirection = -1;
// return maxZoom;
// } else {
// mDoubleTapDirection = 1;
// return 1f;
// }
// }
protected float onDoubleTapPost(float scale, float maxZoom) {
if (mDoubleTapDirection == 1) {
if ((scale + (mScaleFactor * 2)) <= maxZoom) {
return scale + mScaleFactor;
} else {
mDoubleTapDirection = -1;
return maxZoom;
}
} else {
mDoubleTapDirection = 1;
return 1f;
}
}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (!mScrollEnabled) return false;
if (e1 == null || e2 == null) return false;
if (e1.getPointerCount() > 1 || e2.getPointerCount() > 1) return false;
if (mScaleDetector.isInProgress()) return false;
if (getScale() == 1f) return false;
mUserScaled = true;
// scrollBy(distanceX, distanceY);
scrollBy(-distanceX, -distanceY);
// RectF r = getBitmapRect();
// System.out.println(r.left + " " + r.top + " " + r.right + " "
// + r.bottom);
invalidate();
return true;
}
/**
* @param e1
* @param e2
* @param velocityX
* @param velocityY
* @return
*/
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
if (!mScrollEnabled) return false;
if (mFlingListener != null) {
mFlingListener.onFling(e1, e2, velocityX, velocityY);
}
if (e1.getPointerCount() > 1 || e2.getPointerCount() > 1) return false;
if (mScaleDetector.isInProgress()) return false;
if (getScale() == 1f) return false;
float diffX = e2.getX() - e1.getX();
float diffY = e2.getY() - e1.getY();
if (Math.abs(velocityX) > 800 || Math.abs(velocityY) > 800) {
mUserScaled = true;
// System.out.println("on fling scroll");
scrollBy(diffX / 2, diffY / 2, 300);
invalidate();
return true;
}
return false;
}
/**
* Determines whether this ImageViewTouch can be scrolled.
*
* @param direction - positive direction value means scroll from right to left, negative value
* means scroll from left to right
* @return true if there is some more place to scroll, false - otherwise.
*/
public boolean canScroll(int direction) {
RectF bitmapRect = getBitmapRect();
updateRect(bitmapRect, mScrollRect);
Rect imageViewRect = new Rect();
getGlobalVisibleRect(imageViewRect);
if (null == bitmapRect) {
return false;
}
if (bitmapRect.right >= imageViewRect.right) {
if (direction < 0) {
return Math.abs(bitmapRect.right - imageViewRect.right) > SCROLL_DELTA_THRESHOLD;
}
}
double bitmapScrollRectDelta = Math.abs(bitmapRect.left - mScrollRect.left);
return bitmapScrollRectDelta > SCROLL_DELTA_THRESHOLD;
}
/** @author */
public class GestureListener extends GestureDetector.SimpleOnGestureListener {
@Override
public boolean onSingleTapConfirmed(MotionEvent e) {
if (null != mSingleTapListener) {
mSingleTapListener.onSingleTapConfirmed();
}
return super.onSingleTapConfirmed(e);
}
@Override
public boolean onDoubleTap(MotionEvent e) {
Log.i(LOG_TAG, "onDoubleTap. double tap enabled? " + mDoubleTapEnabled);
if (mDoubleTapEnabled) {
mUserScaled = true;
float scale = getScale();
float targetScale = scale;
targetScale = onDoubleTapPost(scale, getMaxScale());
targetScale = Math.min(getMaxScale(), Math.max(targetScale, getMinScale()));
zoomTo(targetScale, e.getX(), e.getY(), DEFAULT_ANIMATION_DURATION);
invalidate();
}
if (null != mDoubleTapListener) {
mDoubleTapListener.onDoubleTap();
}
return super.onDoubleTap(e);
}
@Override
public void onLongPress(MotionEvent e) {
if (isLongClickable()) {
if (!mScaleDetector.isInProgress()) {
setPressed(true);
performLongClick();
}
}
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
return ImageViewTouch.this.onScroll(e1, e2, distanceX, distanceY);
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
return ImageViewTouch.this.onFling(e1, e2, velocityX, velocityY);
}
} // end inner class
public class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
protected boolean mScaled = false;
@Override
public boolean onScale(ScaleGestureDetector detector) {
float span = detector.getCurrentSpan() - detector.getPreviousSpan();
float targetScale = getScale() * detector.getScaleFactor();
// System.out.println("span--->" + span);
if (mScaleEnabled) {
if (mScaled && span != 0) {
mUserScaled = true;
targetScale = Math.min(getMaxScale(), Math.max(targetScale, getMinScale() - 0.1f));
zoomTo(targetScale, detector.getFocusX(), detector.getFocusY());
mDoubleTapDirection = 1;
invalidate();
return true;
}
// This is to prevent a glitch the first time
// image is scaled.
if (!mScaled) mScaled = true;
}
return true;
}
} // end inner class
public void resetImage() {
float scale = getScale();
float targetScale = scale;
targetScale = Math.min(getMaxScale(), Math.max(targetScale, getMinScale()));
zoomTo(targetScale, 0, 0, DEFAULT_ANIMATION_DURATION);
invalidate();
}
public interface OnImageViewTouchDoubleTapListener {
void onDoubleTap();
}
public interface OnImageViewTouchSingleTapListener {
void onSingleTapConfirmed();
}
public interface OnImageFlingListener {
void onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY);
}
}
| |
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.pulsar.client.impl;
import static org.apache.pulsar.client.util.MathUtils.signSafeMod;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import static org.testng.Assert.fail;
import io.netty.channel.EventLoopGroup;
import io.netty.util.Timer;
import io.netty.util.concurrent.DefaultThreadFactory;
import com.google.api.client.util.Lists;
import java.lang.reflect.Field;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadFactory;
import org.apache.pulsar.client.api.Message;
import org.apache.pulsar.client.api.MessageRouter;
import org.apache.pulsar.client.api.MessageRoutingMode;
import org.apache.pulsar.client.api.Producer;
import org.apache.pulsar.client.api.Schema;
import org.apache.pulsar.client.api.TopicMetadata;
import org.apache.pulsar.client.impl.conf.ClientConfigurationData;
import org.apache.pulsar.client.impl.conf.ProducerConfigurationData;
import org.apache.pulsar.client.impl.customroute.PartialRoundRobinMessageRouterImpl;
import org.apache.pulsar.common.api.proto.MessageMetadata;
import org.apache.pulsar.common.util.netty.EventLoopUtil;
import org.assertj.core.util.Sets;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
/**
* Unit Tests of {@link PartitionedProducerImpl}.
*/
public class PartitionedProducerImplTest {
private static final String TOPIC_NAME = "testTopicName";
private PulsarClientImpl client;
private ProducerBuilderImpl producerBuilderImpl;
private Schema schema;
private ProducerInterceptors producerInterceptors;
private CompletableFuture<Producer> producerCreatedFuture;
@BeforeTest
public void setup() {
client = mock(PulsarClientImpl.class);
schema = mock(Schema.class);
producerInterceptors = mock(ProducerInterceptors.class);
producerCreatedFuture = new CompletableFuture<>();
ClientConfigurationData clientConfigurationData = mock(ClientConfigurationData.class);
Timer timer = mock(Timer.class);
producerBuilderImpl = new ProducerBuilderImpl(client, Schema.BYTES);
when(client.getConfiguration()).thenReturn(clientConfigurationData);
when(client.timer()).thenReturn(timer);
when(client.newProducer()).thenReturn(producerBuilderImpl);
when(client.newProducerImpl(anyString(), anyInt(), any(), any(), any(), any(), any()))
.thenAnswer(invocationOnMock -> {
return new ProducerImpl<>(client, invocationOnMock.getArgument(0),
invocationOnMock.getArgument(2), invocationOnMock.getArgument(5),
invocationOnMock.getArgument(1), invocationOnMock.getArgument(3),
invocationOnMock.getArgument(4), invocationOnMock.getArgument(6));
});
}
@Test
public void testSinglePartitionMessageRouterImplInstance() throws NoSuchFieldException, IllegalAccessException {
ProducerConfigurationData producerConfigurationData = new ProducerConfigurationData();
producerConfigurationData.setMessageRoutingMode(MessageRoutingMode.SinglePartition);
MessageRouter messageRouter = getMessageRouter(producerConfigurationData);
assertTrue(messageRouter instanceof SinglePartitionMessageRouterImpl);
}
@Test
public void testRoundRobinPartitionMessageRouterImplInstance() throws NoSuchFieldException, IllegalAccessException {
ProducerConfigurationData producerConfigurationData = new ProducerConfigurationData();
producerConfigurationData.setMessageRoutingMode(MessageRoutingMode.RoundRobinPartition);
MessageRouter messageRouter = getMessageRouter(producerConfigurationData);
assertTrue(messageRouter instanceof RoundRobinPartitionMessageRouterImpl);
}
@Test
public void testCustomMessageRouterInstance() throws NoSuchFieldException, IllegalAccessException {
ProducerConfigurationData producerConfigurationData = new ProducerConfigurationData();
producerConfigurationData.setMessageRoutingMode(MessageRoutingMode.CustomPartition);
producerConfigurationData.setCustomMessageRouter(new CustomMessageRouter());
MessageRouter messageRouter = getMessageRouter(producerConfigurationData);
assertTrue(messageRouter instanceof CustomMessageRouter);
}
@Test
public void testPartialPartition() {
final MessageRouter router = new PartialRoundRobinMessageRouterImpl(3);
final Set<Integer> actualSet = Sets.newHashSet();
final Message<byte[]> msg = MessageImpl
.create(new MessageMetadata(), ByteBuffer.wrap(new byte[0]), Schema.BYTES, null);
for (int i = 0; i < 10; i++) {
final TopicMetadata metadata = new TopicMetadataImpl(10);
actualSet.add(router.choosePartition(msg, metadata));
}
assertEquals(actualSet.size(), 3);
try {
new PartialRoundRobinMessageRouterImpl(0);
fail();
} catch (Exception e) {
assertEquals(e.getClass(), IllegalArgumentException.class);
}
}
@Test
public void testPartialPartitionWithKey() {
final MessageRouter router = new PartialRoundRobinMessageRouterImpl(3);
final Hash hash = Murmur3Hash32.getInstance();
final List<Integer> expectedHashList = Lists.newArrayList();
final List<Integer> actualHashList = Lists.newArrayList();
for (int i = 0; i < 10; i++) {
final String key = String.valueOf(i);
final Message<byte[]> msg = MessageImpl
.create(new MessageMetadata().setPartitionKey(key), ByteBuffer.wrap(new byte[0]), Schema.BYTES, null);
final TopicMetadata metadata = new TopicMetadataImpl(10);
expectedHashList.add(signSafeMod(hash.makeHash(key), 10));
actualHashList.add(router.choosePartition(msg, metadata));
}
assertNotEquals(actualHashList, expectedHashList);
}
private MessageRouter getMessageRouter(ProducerConfigurationData producerConfigurationData)
throws NoSuchFieldException, IllegalAccessException {
PartitionedProducerImpl impl = new PartitionedProducerImpl(
client, TOPIC_NAME, producerConfigurationData,
2, producerCreatedFuture, schema, producerInterceptors);
Field routerPolicy = impl.getClass().getDeclaredField("routerPolicy");
routerPolicy.setAccessible(true);
MessageRouter messageRouter = (MessageRouter) routerPolicy.get(impl);
assertNotNull(messageRouter);
return messageRouter;
}
private class CustomMessageRouter implements MessageRouter {
@Override
public int choosePartition(Message<?> msg, TopicMetadata metadata) {
int partitionIndex = Integer.parseInt(msg.getKey()) % metadata.numPartitions();
return partitionIndex;
}
}
@Test
public void testGetStats() throws Exception {
String topicName = "test-stats";
ClientConfigurationData conf = new ClientConfigurationData();
conf.setServiceUrl("pulsar://localhost:6650");
conf.setStatsIntervalSeconds(100);
ThreadFactory threadFactory = new DefaultThreadFactory("client-test-stats", Thread.currentThread().isDaemon());
EventLoopGroup eventLoopGroup = EventLoopUtil.newEventLoopGroup(conf.getNumIoThreads(), false, threadFactory);
PulsarClientImpl clientImpl = new PulsarClientImpl(conf, eventLoopGroup);
ProducerConfigurationData producerConfData = new ProducerConfigurationData();
producerConfData.setMessageRoutingMode(MessageRoutingMode.CustomPartition);
producerConfData.setCustomMessageRouter(new CustomMessageRouter());
assertEquals(Long.parseLong("100"), clientImpl.getConfiguration().getStatsIntervalSeconds());
PartitionedProducerImpl impl = new PartitionedProducerImpl(
clientImpl, topicName, producerConfData,
1, null, null, null);
impl.getStats();
}
@Test
public void testGetStatsWithoutArriveUpdateInterval() throws Exception {
String topicName = "test-stats-without-arrive-interval";
ClientConfigurationData conf = new ClientConfigurationData();
conf.setServiceUrl("pulsar://localhost:6650");
conf.setStatsIntervalSeconds(100);
ThreadFactory threadFactory =
new DefaultThreadFactory("client-test-stats", Thread.currentThread().isDaemon());
EventLoopGroup eventLoopGroup = EventLoopUtil
.newEventLoopGroup(conf.getNumIoThreads(), false, threadFactory);
PulsarClientImpl clientImpl = new PulsarClientImpl(conf, eventLoopGroup);
ProducerConfigurationData producerConfData = new ProducerConfigurationData();
producerConfData.setMessageRoutingMode(MessageRoutingMode.CustomPartition);
producerConfData.setCustomMessageRouter(new CustomMessageRouter());
assertEquals(Long.parseLong("100"), clientImpl.getConfiguration().getStatsIntervalSeconds());
PartitionedProducerImpl<byte[]> impl = new PartitionedProducerImpl<>(
clientImpl, topicName, producerConfData,
1, null, null, null);
impl.getProducers().get(0).getStats().incrementSendFailed();
ProducerStatsRecorderImpl stats = impl.getStats();
assertEquals(stats.getTotalSendFailed(), 0);
// When close producer, the ProducerStatsRecorder will update stats immediately
impl.close();
stats = impl.getStats();
assertEquals(stats.getTotalSendFailed(), 1);
}
@Test
public void testGetNumOfPartitions() throws Exception {
String topicName = "test-get-num-of-partitions";
ClientConfigurationData conf = new ClientConfigurationData();
conf.setServiceUrl("pulsar://localhost:6650");
conf.setStatsIntervalSeconds(100);
ThreadFactory threadFactory = new DefaultThreadFactory("client-test-stats", Thread.currentThread().isDaemon());
EventLoopGroup eventLoopGroup = EventLoopUtil.newEventLoopGroup(conf.getNumIoThreads(), false, threadFactory);
PulsarClientImpl clientImpl = new PulsarClientImpl(conf, eventLoopGroup);
ProducerConfigurationData producerConfData = new ProducerConfigurationData();
producerConfData.setMessageRoutingMode(MessageRoutingMode.CustomPartition);
producerConfData.setCustomMessageRouter(new CustomMessageRouter());
PartitionedProducerImpl partitionedProducerImpl = new PartitionedProducerImpl(
clientImpl, topicName, producerConfData, 1, null, null, null);
assertEquals(partitionedProducerImpl.getNumOfPartitions(), 1);
String nonPartitionedTopicName = "test-get-num-of-partitions-for-non-partitioned-topic";
ProducerConfigurationData producerConfDataNonPartitioned = new ProducerConfigurationData();
ProducerImpl producerImpl = new ProducerImpl(clientImpl, nonPartitionedTopicName, producerConfDataNonPartitioned,
null, 0, null, null, Optional.empty());
assertEquals(producerImpl.getNumOfPartitions(), 0);
}
}
| |
/**
* Copyright (c) 2014, Oliver Kleine, Institute of Telematics, University of Luebeck
* All rights reserved
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
* following conditions are met:
*
* - Redistributions of source messageCode must retain the above copyright notice, this list of conditions and the following
* disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
* following disclaimer in the documentation and/or other materials provided with the distribution.
*
* - Neither the name of the University of Luebeck nor the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package de.uzl.itm.jaxb4osm.jaxb;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Multimap;
import de.uzl.itm.jaxb4osm.tools.WayElementFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import java.util.*;
/**
* JAXB compliant class for the osm (root) element in OSM files (Open Street Map)
*
* @author Oliver Kleine
*/
public class OsmElement extends AbstractOsmElement{
private static Logger log = LoggerFactory.getLogger(OsmElement.class.getName());
private Map<Long, NodeElement> nodeElements;
private Map<Long, WayElement> wayElements;
private Multimap<Long, Long> nodeReferences;
/**
* Creates a new empty instance of {@link OsmElement}
*/
public OsmElement(){
initialze();
}
private OsmElement(PlainOsmElement plainOsmElement, WayElementFilter filter){
super(plainOsmElement);
initialze();
//Add <node> elements
this.addNodeElements(plainOsmElement.getNodeElements());
//Add <way> elements that match the given filter criteria
for(WayElement wayElement : plainOsmElement.getWayElements()){
if(filter.matchesCriteria(wayElement)){
this.addWayElement(wayElement);
}
}
}
private void initialze(){
this.nodeElements = new HashMap<>();
this.nodeReferences = HashMultimap.create();
this.wayElements = new HashMap<>();
}
public void addNodeElements(Collection<NodeElement> nodeElements){
for(NodeElement nodeElement : nodeElements){
addNodeElement(nodeElement);
}
}
public void addNodeElement(NodeElement nodeElement){
this.nodeElements.put(nodeElement.getID(), nodeElement);
}
public boolean removeNodeElement(long nodeID){
return this.nodeElements.remove(nodeID) != null;
}
/**
* Returns a {@link java.util.Map} with the values of the nodes ID attributes as keys and the
* {@link NodeElement}s as values
*
* @return a {@link java.util.Map} with the values of the nodes ID attributes as keys and the
* {@link NodeElement}s as values
*/
public ImmutableList<NodeElement> getNodeElements() {
return new ImmutableList.Builder<NodeElement>().addAll(this.nodeElements.values()).build();
}
/**
* Returns the {@link NodeElement} that has the given ID or
* <code>null</code> if no such node was found.
*
* @param nodeID the ID to lookup the corresponding node for
*
* @return the {@link NodeElement} that has the given ID or
* <code>null</code> if no such node was found.
*/
public NodeElement getNodeElement(long nodeID){
return this.nodeElements.get(nodeID);
}
/**
* Adds the given {@link WayElement}s and updates the references returned
* by {@link #getReferencingWayIDs(long)} properly.
*
* @param wayElements the {@link WayElement}s to be added
*
* @return the number of added {@link WayElement}s.
*
* <b>Note:</b> Elements with {@link WayElement#getID()} returning an ID that is already contained will not be
* added, i.e. already contained ways are not overwritten! That's why the returned number may vary from the size
* of the given {@link java.util.Collection}.
*/
public int addWayElements(Collection<WayElement> wayElements){
int counter = 0;
for(WayElement wayElement : wayElements){
if(this.addWayElement(wayElement)){
counter++;
}
}
return counter;
}
/**
* Adds the given {@link WayElement} and updates the references returned
* by {@link #getReferencingWayIDs(long)} properly.
*
* @param wayElement the {@link WayElement} to be added
*
* @return <code>true</code> if the element was successfully added or <code>false</code> otherwise
*
* <b>Note:</b> Elements with {@link WayElement#getID()} returning an ID that is already contained will not be
* added, i.e. already contained ways are not overwritten!
*/
public boolean addWayElement(WayElement wayElement){
if(this.wayElements.containsKey(wayElement.getID()))
return false;
this.wayElements.put(wayElement.getID(), wayElement);
for(NdElement ndElement : wayElement.getNdElements()){
this.nodeReferences.put(ndElement.getReference(), wayElement.getID());
}
return true;
}
/**
* Removes the {@link WayElement} with the given ID and updates the references
* returned by {@link #getReferencingWayIDs(long)} properly.
*
* @param wayID the ID of the {@link WayElement} to be removed
*
* @return <code>true</code> if the element was successfully removed or <code>false</code> otherwise, i.e. there
* was no way with the given ID
*/
public boolean removeWayElement(long wayID){
WayElement wayElement = this.wayElements.remove(wayID);
if(wayElement == null)
return false;
for(NdElement ndElement : wayElement.getNdElements()){
this.nodeReferences.remove(ndElement.getReference(), wayElement.getID());
}
return true;
}
/**
* Returns an {@link com.google.common.collect.ImmutableList} containing the already added
* {@link WayElement}s
*
* <b>Note:</b> The reason for making the result immutable is to keep the references returned by
* {@link #getReferencingWayIDs(long)} properly
*
* @return an {@link com.google.common.collect.ImmutableList} containing the already added
* {@link WayElement}s
*/
public ImmutableList<WayElement> getWayElements(){
return new ImmutableList.Builder<WayElement>().addAll(this.wayElements.values()).build();
}
/**
* Returns the {@link WayElement} that has the given ID or
* <code>null</code> if no such way was found.
*
* @return the {@link WayElement} that has the given ID or
* <code>null</code> if no such way was found.
*/
public WayElement getWayElement(long wayID){
return this.wayElements.get(wayID);
}
/**
* Returns an {@link com.google.common.collect.ImmutableSet} containing the IDs of the
* {@link WayElement}s that were already added and refer to the given
* nodeID.
*
* <b>Note:</b> The reason for making the result immutable is to keep the references returned by
* {@link #getReferencingWayIDs(long)} properly
*
* @return an {@link com.google.common.collect.ImmutableSet} containing the IDs of the
* {@link WayElement}s that were already added and refer to the given
* nodeID.
*/
public ImmutableSet<Long> getReferencingWayIDs(long nodeID){
if(!this.nodeReferences.containsKey(nodeID))
return new ImmutableSet.Builder<Long>().build();
return new ImmutableSet.Builder<Long>().addAll(this.nodeReferences.get(nodeID)).build();
}
/**
* This class is for internal use only and is public due to the restrictions (or bug?) of the
* {@link javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter} not to be applicable on XML root elements.
*/
@XmlRootElement(name = "osm")
@XmlType (propOrder={
PROP_VERSION, PROP_GENERATOR, PROP_COPYRIGHT, PROP_ATTRIBUTION, PROP_LICENSE,
PROP_BOUNDS, PROP_NODE, PROP_WAY
})
@XmlSeeAlso(AbstractOsmElement.class)
public static class PlainOsmElement extends AbstractOsmElement{
@XmlElement(name = ELEM_NODE)
private List<NodeElement> nodeElements;
@XmlElement(name = ELEM_WAY)
private List<WayElement> wayElements;
private PlainOsmElement(){
this.initialize();
}
private PlainOsmElement(OsmElement osmElement){
super(osmElement);
this.initialize();
this.addNodeElements(osmElement.getNodeElements());
this.addWayElements(osmElement.getWayElements());
}
private void initialize(){
this.nodeElements = new ArrayList<>();
this.wayElements = new ArrayList<>();
}
private void addNodeElements(Collection<NodeElement> nodeElements){
this.nodeElements.addAll(nodeElements);
}
private List<NodeElement> getNodeElements(){
return this.nodeElements;
}
private void addWayElements(Collection<WayElement> wayElements){
this.wayElements.addAll(wayElements);
}
private List<WayElement> getWayElements(){
return this.wayElements;
}
}
public static class OsmElementAdapter extends XmlAdapter<PlainOsmElement, OsmElement>{
public OsmElement unmarshal(PlainOsmElement plainOsmElement, WayElementFilter wayElementFilter){
return new OsmElement(plainOsmElement, wayElementFilter);
}
@Override
public OsmElement unmarshal(PlainOsmElement plainOsmElement) throws Exception {
return unmarshal(plainOsmElement, WayElementFilter.ANY_WAY) ;
}
@Override
public PlainOsmElement marshal(OsmElement osmElement) throws Exception {
return new PlainOsmElement(osmElement);
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.math3.optim.univariate;
import org.apache.commons.math3.analysis.QuinticFunction;
import org.apache.commons.math3.analysis.UnivariateFunction;
import org.apache.commons.math3.analysis.function.Sin;
import org.apache.commons.math3.analysis.function.StepFunction;
import org.apache.commons.math3.analysis.FunctionUtils;
import org.apache.commons.math3.exception.NumberIsTooLargeException;
import org.apache.commons.math3.exception.NumberIsTooSmallException;
import org.apache.commons.math3.exception.TooManyEvaluationsException;
import org.apache.commons.math3.optim.ConvergenceChecker;
import org.apache.commons.math3.optim.nonlinear.scalar.GoalType;
import org.apache.commons.math3.optim.MaxEval;
import org.apache.commons.math3.stat.descriptive.DescriptiveStatistics;
import org.apache.commons.math3.util.FastMath;
import org.junit.Assert;
import org.junit.Test;
/**
*/
public final class BrentOptimizerTest {
@Test
public void testSinMin() {
UnivariateFunction f = new Sin();
UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14);
Assert.assertEquals(3 * Math.PI / 2, optimizer.optimize(new MaxEval(200),
new UnivariateObjectiveFunction(f),
GoalType.MINIMIZE,
new SearchInterval(4, 5)).getPoint(), 1e-8);
Assert.assertTrue(optimizer.getEvaluations() <= 50);
Assert.assertEquals(200, optimizer.getMaxEvaluations());
Assert.assertEquals(3 * Math.PI / 2, optimizer.optimize(new MaxEval(200),
new UnivariateObjectiveFunction(f),
GoalType.MINIMIZE,
new SearchInterval(1, 5)).getPoint(), 1e-8);
Assert.assertTrue(optimizer.getEvaluations() <= 100);
Assert.assertTrue(optimizer.getEvaluations() >= 15);
try {
optimizer.optimize(new MaxEval(10),
new UnivariateObjectiveFunction(f),
GoalType.MINIMIZE,
new SearchInterval(4, 5));
Assert.fail("an exception should have been thrown");
} catch (TooManyEvaluationsException fee) {
// expected
}
}
@Test
public void testSinMinWithValueChecker() {
final UnivariateFunction f = new Sin();
final ConvergenceChecker<UnivariatePointValuePair> checker = new SimpleUnivariateValueChecker(1e-5, 1e-14);
// The default stopping criterion of Brent's algorithm should not
// pass, but the search will stop at the given relative tolerance
// for the function value.
final UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14, checker);
final UnivariatePointValuePair result = optimizer.optimize(new MaxEval(200),
new UnivariateObjectiveFunction(f),
GoalType.MINIMIZE,
new SearchInterval(4, 5));
Assert.assertEquals(3 * Math.PI / 2, result.getPoint(), 1e-3);
}
@Test
public void testBoundaries() {
final double lower = -1.0;
final double upper = +1.0;
UnivariateFunction f = new UnivariateFunction() {
public double value(double x) {
if (x < lower) {
throw new NumberIsTooSmallException(x, lower, true);
} else if (x > upper) {
throw new NumberIsTooLargeException(x, upper, true);
} else {
return x;
}
}
};
UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14);
Assert.assertEquals(lower,
optimizer.optimize(new MaxEval(100),
new UnivariateObjectiveFunction(f),
GoalType.MINIMIZE,
new SearchInterval(lower, upper)).getPoint(),
1.0e-8);
Assert.assertEquals(upper,
optimizer.optimize(new MaxEval(100),
new UnivariateObjectiveFunction(f),
GoalType.MAXIMIZE,
new SearchInterval(lower, upper)).getPoint(),
1.0e-8);
}
@Test
public void testQuinticMin() {
// The function has local minima at -0.27195613 and 0.82221643.
UnivariateFunction f = new QuinticFunction();
UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-14);
Assert.assertEquals(-0.27195613, optimizer.optimize(new MaxEval(200),
new UnivariateObjectiveFunction(f),
GoalType.MINIMIZE,
new SearchInterval(-0.3, -0.2)).getPoint(), 1.0e-8);
Assert.assertEquals( 0.82221643, optimizer.optimize(new MaxEval(200),
new UnivariateObjectiveFunction(f),
GoalType.MINIMIZE,
new SearchInterval(0.3, 0.9)).getPoint(), 1.0e-8);
Assert.assertTrue(optimizer.getEvaluations() <= 50);
// search in a large interval
Assert.assertEquals(-0.27195613, optimizer.optimize(new MaxEval(200),
new UnivariateObjectiveFunction(f),
GoalType.MINIMIZE,
new SearchInterval(-1.0, 0.2)).getPoint(), 1.0e-8);
Assert.assertTrue(optimizer.getEvaluations() <= 50);
}
@Test
public void testQuinticMinStatistics() {
// The function has local minima at -0.27195613 and 0.82221643.
UnivariateFunction f = new QuinticFunction();
UnivariateOptimizer optimizer = new BrentOptimizer(1e-11, 1e-14);
final DescriptiveStatistics[] stat = new DescriptiveStatistics[2];
for (int i = 0; i < stat.length; i++) {
stat[i] = new DescriptiveStatistics();
}
final double min = -0.75;
final double max = 0.25;
final int nSamples = 200;
final double delta = (max - min) / nSamples;
for (int i = 0; i < nSamples; i++) {
final double start = min + i * delta;
stat[0].addValue(optimizer.optimize(new MaxEval(40),
new UnivariateObjectiveFunction(f),
GoalType.MINIMIZE,
new SearchInterval(min, max, start)).getPoint());
stat[1].addValue(optimizer.getEvaluations());
}
final double meanOptValue = stat[0].getMean();
final double medianEval = stat[1].getPercentile(50);
Assert.assertTrue(meanOptValue > -0.2719561281);
Assert.assertTrue(meanOptValue < -0.2719561280);
Assert.assertEquals(23, (int) medianEval);
// MATH-1121: Ensure that the iteration counter is incremented.
Assert.assertTrue(optimizer.getIterations() > 0);
}
@Test
public void testQuinticMax() {
// The quintic function has zeros at 0, +-0.5 and +-1.
// The function has a local maximum at 0.27195613.
UnivariateFunction f = new QuinticFunction();
UnivariateOptimizer optimizer = new BrentOptimizer(1e-12, 1e-14);
Assert.assertEquals(0.27195613, optimizer.optimize(new MaxEval(100),
new UnivariateObjectiveFunction(f),
GoalType.MAXIMIZE,
new SearchInterval(0.2, 0.3)).getPoint(), 1e-8);
try {
optimizer.optimize(new MaxEval(5),
new UnivariateObjectiveFunction(f),
GoalType.MAXIMIZE,
new SearchInterval(0.2, 0.3));
Assert.fail("an exception should have been thrown");
} catch (TooManyEvaluationsException miee) {
// expected
}
}
@Test
public void testMinEndpoints() {
UnivariateFunction f = new Sin();
UnivariateOptimizer optimizer = new BrentOptimizer(1e-8, 1e-14);
// endpoint is minimum
double result = optimizer.optimize(new MaxEval(50),
new UnivariateObjectiveFunction(f),
GoalType.MINIMIZE,
new SearchInterval(3 * Math.PI / 2, 5)).getPoint();
Assert.assertEquals(3 * Math.PI / 2, result, 1e-6);
result = optimizer.optimize(new MaxEval(50),
new UnivariateObjectiveFunction(f),
GoalType.MINIMIZE,
new SearchInterval(4, 3 * Math.PI / 2)).getPoint();
Assert.assertEquals(3 * Math.PI / 2, result, 1e-6);
}
@Test
public void testMath832() {
final UnivariateFunction f = new UnivariateFunction() {
public double value(double x) {
final double sqrtX = FastMath.sqrt(x);
final double a = 1e2 * sqrtX;
final double b = 1e6 / x;
final double c = 1e4 / sqrtX;
return a + b + c;
}
};
UnivariateOptimizer optimizer = new BrentOptimizer(1e-10, 1e-8);
final double result = optimizer.optimize(new MaxEval(1483),
new UnivariateObjectiveFunction(f),
GoalType.MINIMIZE,
new SearchInterval(Double.MIN_VALUE,
Double.MAX_VALUE)).getPoint();
Assert.assertEquals(804.9355825, result, 1e-6);
}
/**
* Contrived example showing that prior to the resolution of MATH-855
* (second revision), the algorithm would not return the best point if
* it happened to be the initial guess.
*/
@Test
public void testKeepInitIfBest() {
final double minSin = 3 * Math.PI / 2;
final double offset = 1e-8;
final double delta = 1e-7;
final UnivariateFunction f1 = new Sin();
final UnivariateFunction f2 = new StepFunction(new double[] { minSin, minSin + offset, minSin + 2 * offset},
new double[] { 0, -1, 0 });
final UnivariateFunction f = FunctionUtils.add(f1, f2);
// A slightly less stringent tolerance would make the test pass
// even with the previous implementation.
final double relTol = 1e-8;
final UnivariateOptimizer optimizer = new BrentOptimizer(relTol, 1e-100);
final double init = minSin + 1.5 * offset;
final UnivariatePointValuePair result
= optimizer.optimize(new MaxEval(200),
new UnivariateObjectiveFunction(f),
GoalType.MINIMIZE,
new SearchInterval(minSin - 6.789 * delta,
minSin + 9.876 * delta,
init));
final double sol = result.getPoint();
final double expected = init;
// System.out.println("numEval=" + numEval);
// System.out.println("min=" + init + " f=" + f.value(init));
// System.out.println("sol=" + sol + " f=" + f.value(sol));
// System.out.println("exp=" + expected + " f=" + f.value(expected));
Assert.assertTrue("Best point not reported", f.value(sol) <= f.value(expected));
}
/**
* Contrived example showing that prior to the resolution of MATH-855,
* the algorithm, by always returning the last evaluated point, would
* sometimes not report the best point it had found.
*/
@Test
public void testMath855() {
final double minSin = 3 * Math.PI / 2;
final double offset = 1e-8;
final double delta = 1e-7;
final UnivariateFunction f1 = new Sin();
final UnivariateFunction f2 = new StepFunction(new double[] { minSin, minSin + offset, minSin + 5 * offset },
new double[] { 0, -1, 0 });
final UnivariateFunction f = FunctionUtils.add(f1, f2);
final UnivariateOptimizer optimizer = new BrentOptimizer(1e-8, 1e-100);
final UnivariatePointValuePair result
= optimizer.optimize(new MaxEval(200),
new UnivariateObjectiveFunction(f),
GoalType.MINIMIZE,
new SearchInterval(minSin - 6.789 * delta,
minSin + 9.876 * delta));
final double sol = result.getPoint();
final double expected = 4.712389027602411;
// System.out.println("min=" + (minSin + offset) + " f=" + f.value(minSin + offset));
// System.out.println("sol=" + sol + " f=" + f.value(sol));
// System.out.println("exp=" + expected + " f=" + f.value(expected));
Assert.assertTrue("Best point not reported", f.value(sol) <= f.value(expected));
}
}
| |
/*
* Copyright 2013-present Facebook, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.facebook.buck.jvm.java;
import static java.util.jar.Attributes.Name.IMPLEMENTATION_VERSION;
import static java.util.jar.Attributes.Name.MANIFEST_VERSION;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import com.facebook.buck.io.ProjectFilesystem;
import com.facebook.buck.step.ExecutionContext;
import com.facebook.buck.step.TestExecutionContext;
import com.facebook.buck.testutil.TestConsole;
import com.facebook.buck.testutil.Zip;
import com.facebook.buck.testutil.integration.TemporaryPaths;
import com.facebook.buck.zip.CustomZipOutputStream;
import com.facebook.buck.zip.ZipConstants;
import com.facebook.buck.zip.ZipOutputStreams;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Sets;
import org.apache.commons.compress.archivers.zip.ZipUtil;
import org.junit.Rule;
import org.junit.Test;
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.jar.Attributes;
import java.util.jar.JarInputStream;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class JarDirectoryStepTest {
@Rule public TemporaryPaths folder = new TemporaryPaths();
@Test
public void shouldNotThrowAnExceptionWhenAddingDuplicateEntries() throws IOException {
Path zipup = folder.newFolder("zipup");
Path first = createZip(zipup.resolve("a.zip"), "example.txt");
Path second = createZip(zipup.resolve("b.zip"), "example.txt", "com/example/Main.class");
JarDirectoryStep step = new JarDirectoryStep(
new ProjectFilesystem(zipup),
Paths.get("output.jar"),
ImmutableSortedSet.of(first.getFileName(), second.getFileName()),
"com.example.Main",
/* manifest file */ null);
ExecutionContext context = TestExecutionContext.newInstance();
int returnCode = step.execute(context);
assertEquals(0, returnCode);
Path zip = zipup.resolve("output.jar");
assertTrue(Files.exists(zip));
// "example.txt" "Main.class" and the MANIFEST.MF.
assertZipFileCountIs(3, zip);
assertZipContains(zip, "example.txt");
}
@Test
public void shouldFailIfMainClassMissing() throws IOException {
Path zipup = folder.newFolder("zipup");
Path zip = createZip(zipup.resolve("a.zip"), "com/example/Main.class");
JarDirectoryStep step = new JarDirectoryStep(
new ProjectFilesystem(zipup),
Paths.get("output.jar"),
ImmutableSortedSet.of(zip.getFileName()),
"com.example.MissingMain",
/* manifest file */ null);
TestConsole console = new TestConsole();
ExecutionContext context = TestExecutionContext.newBuilder()
.setConsole(console)
.build();
int returnCode = step.execute(context);
assertEquals(1, returnCode);
assertEquals(
"ERROR: Main class com.example.MissingMain does not exist.\n",
console.getTextWrittenToStdErr());
}
@Test
public void shouldNotComplainWhenDuplicateDirectoryNamesAreAdded() throws IOException {
Path zipup = folder.newFolder();
Path first = createZip(zipup.resolve("first.zip"), "dir/example.txt", "dir/root1file.txt");
Path second = createZip(
zipup.resolve("second.zip"),
"dir/example.txt",
"dir/root2file.txt",
"com/example/Main.class");
JarDirectoryStep step = new JarDirectoryStep(
new ProjectFilesystem(zipup),
Paths.get("output.jar"),
ImmutableSortedSet.of(first.getFileName(), second.getFileName()),
"com.example.Main",
/* manifest file */ null);
ExecutionContext context = TestExecutionContext.newInstance();
int returnCode = step.execute(context);
assertEquals(0, returnCode);
Path zip = zipup.resolve("output.jar");
// The three below plus the manifest and Main.class.
assertZipFileCountIs(5, zip);
assertZipContains(zip, "dir/example.txt", "dir/root1file.txt", "dir/root2file.txt");
}
@Test
public void entriesFromTheGivenManifestShouldOverrideThoseInTheJars() throws IOException {
String expected = "1.4";
// Write the manifest, setting the implementation version
Path tmp = folder.newFolder();
Manifest manifest = new Manifest();
manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), expected);
Path manifestFile = tmp.resolve("manifest");
try (OutputStream fos = Files.newOutputStream(manifestFile)) {
manifest.write(fos);
}
// Write another manifest, setting the implementation version to something else
manifest = new Manifest();
manifest.getMainAttributes().putValue(MANIFEST_VERSION.toString(), "1.0");
manifest.getMainAttributes().putValue(IMPLEMENTATION_VERSION.toString(), "1.0");
Path input = tmp.resolve("input.jar");
try (CustomZipOutputStream out = ZipOutputStreams.newOutputStream(input)) {
ZipEntry entry = new ZipEntry("META-INF/MANIFEST.MF");
out.putNextEntry(entry);
manifest.write(out);
}
Path output = tmp.resolve("output.jar");
JarDirectoryStep step = new JarDirectoryStep(
new ProjectFilesystem(tmp),
Paths.get("output.jar"),
ImmutableSortedSet.of(Paths.get("input.jar")),
/* main class */ null,
Paths.get("manifest"),
/* merge manifest */ true,
/* blacklist */ ImmutableSet.<String>of());
ExecutionContext context = TestExecutionContext.newInstance();
assertEquals(0, step.execute(context));
try (Zip zip = new Zip(output, false)) {
byte[] rawManifest = zip.readFully("META-INF/MANIFEST.MF");
manifest = new Manifest(new ByteArrayInputStream(rawManifest));
String version = manifest.getMainAttributes().getValue(IMPLEMENTATION_VERSION);
assertEquals(expected, version);
}
}
@Test
public void jarsShouldContainDirectoryEntries() throws IOException {
Path zipup = folder.newFolder("dir-zip");
Path subdir = zipup.resolve("dir/subdir");
Files.createDirectories(subdir);
Files.write(subdir.resolve("a.txt"), "cake".getBytes());
JarDirectoryStep step = new JarDirectoryStep(
new ProjectFilesystem(zipup),
Paths.get("output.jar"),
ImmutableSortedSet.of(zipup),
/* main class */ null,
/* manifest file */ null);
ExecutionContext context = TestExecutionContext.newInstance();
int returnCode = step.execute(context);
assertEquals(0, returnCode);
Path zip = zipup.resolve("output.jar");
assertTrue(Files.exists(zip));
// Iterate over each of the entries, expecting to see the directory names as entries.
Set<String> expected = Sets.newHashSet("dir/", "dir/subdir/");
try (ZipInputStream is = new ZipInputStream(Files.newInputStream(zip))) {
for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
expected.remove(entry.getName());
}
}
assertTrue("Didn't see entries for: " + expected, expected.isEmpty());
}
@Test
public void shouldNotMergeManifestsIfRequested() throws IOException {
Manifest fromJar = createManifestWithExampleSection(ImmutableMap.of("Not-Seen", "ever"));
Manifest fromUser = createManifestWithExampleSection(ImmutableMap.of("cake", "cheese"));
Manifest seenManifest = jarDirectoryAndReadManifest(fromJar, fromUser, false);
assertEquals(fromUser.getEntries(), seenManifest.getEntries());
}
@Test
public void shouldMergeManifestsIfAsked() throws IOException {
Manifest fromJar = createManifestWithExampleSection(ImmutableMap.of("Not-Seen", "ever"));
Manifest fromUser = createManifestWithExampleSection(ImmutableMap.of("cake", "cheese"));
Manifest seenManifest = jarDirectoryAndReadManifest(fromJar, fromUser, true);
Manifest expectedManifest = new Manifest(fromJar);
expectedManifest.getEntries().putAll(fromUser.getEntries());
assertEquals(expectedManifest.getEntries(), seenManifest.getEntries());
}
@Test
public void shouldNotIncludeFilesInBlacklist() throws IOException {
Path zipup = folder.newFolder();
Path first = createZip(
zipup.resolve("first.zip"),
"dir/file1.txt",
"dir/file2.txt",
"com/example/Main.class");
JarDirectoryStep step = new JarDirectoryStep(
new ProjectFilesystem(zipup),
Paths.get("output.jar"),
ImmutableSortedSet.of(first.getFileName()),
"com.example.Main",
/* manifest file */ null,
/* merge manifests */ true,
/* blacklist */ ImmutableSet.of(".*2.*"));
ExecutionContext context = TestExecutionContext.newInstance();
int returnCode = step.execute(context);
assertEquals(0, returnCode);
Path zip = zipup.resolve("output.jar");
// file1.txt, Main.class, plus the manifest.
assertZipFileCountIs(3, zip);
assertZipContains(zip, "dir/file1.txt");
assertZipDoesNotContain(zip, "dir/file2.txt");
}
@Test
public void timesAreSanitized() throws IOException {
Path zipup = folder.newFolder("dir-zip");
// Create a jar file with a file and a directory.
Path subdir = zipup.resolve("dir");
Files.createDirectories(subdir);
Files.write(subdir.resolve("a.txt"), "cake".getBytes());
Path outputJar = folder.getRoot().resolve("output.jar");
JarDirectoryStep step =
new JarDirectoryStep(
new ProjectFilesystem(folder.getRoot()),
outputJar,
ImmutableSortedSet.of(zipup),
/* main class */ null,
/* manifest file */ null);
ExecutionContext context = TestExecutionContext.newInstance();
int returnCode = step.execute(context);
assertEquals(0, returnCode);
// Iterate over each of the entries, expecting to see all zeros in the time fields.
assertTrue(Files.exists(outputJar));
Date dosEpoch = new Date(ZipUtil.dosToJavaTime(ZipConstants.DOS_EPOCH_START));
try (ZipInputStream is = new ZipInputStream(new FileInputStream(outputJar.toFile()))) {
for (ZipEntry entry = is.getNextEntry(); entry != null; entry = is.getNextEntry()) {
assertEquals(entry.getName(), dosEpoch, new Date(entry.getTime()));
}
}
}
private Manifest createManifestWithExampleSection(Map<String, String> attributes) {
Manifest manifest = new Manifest();
Attributes attrs = new Attributes();
for (Map.Entry<String, String> stringStringEntry : attributes.entrySet()) {
attrs.put(new Attributes.Name(stringStringEntry.getKey()), stringStringEntry.getValue());
}
manifest.getEntries().put("example", attrs);
return manifest;
}
private Manifest jarDirectoryAndReadManifest(
Manifest fromJar,
Manifest fromUser,
boolean mergeEntries)
throws IOException {
// Create a jar with a manifest we'd expect to see merged.
Path originalJar = folder.newFile("unexpected.jar");
JarOutputStream ignored =
new JarOutputStream(Files.newOutputStream(originalJar), fromJar);
ignored.close();
// Now create the actual manifest
Path manifestFile = folder.newFile("actual_manfiest.mf");
try (OutputStream os = Files.newOutputStream(manifestFile)) {
fromUser.write(os);
}
Path tmp = folder.newFolder();
Path output = tmp.resolve("example.jar");
JarDirectoryStep step = new JarDirectoryStep(
new ProjectFilesystem(tmp),
output,
ImmutableSortedSet.of(originalJar),
/* main class */ null,
manifestFile,
mergeEntries,
/* blacklist */ ImmutableSet.<String>of());
ExecutionContext context = TestExecutionContext.newInstance();
step.execute(context);
// Now verify that the created manifest matches the expected one.
try (JarInputStream jis = new JarInputStream(Files.newInputStream(output))) {
return jis.getManifest();
}
}
private Path createZip(Path zipFile, String... fileNames) throws IOException {
try (Zip zip = new Zip(zipFile, true)) {
for (String fileName : fileNames) {
zip.add(fileName, "");
}
}
return zipFile;
}
private void assertZipFileCountIs(int expected, Path zip) throws IOException {
Set<String> fileNames = getFileNames(zip);
assertEquals(fileNames.toString(), expected, fileNames.size());
}
private void assertZipContains(Path zip, String... files) throws IOException {
final Set<String> contents = getFileNames(zip);
for (String file : files) {
assertTrue(String.format("%s -> %s", file, contents), contents.contains(file));
}
}
private void assertZipDoesNotContain(Path zip, String... files) throws IOException {
final Set<String> contents = getFileNames(zip);
for (String file : files) {
assertFalse(String.format("%s -> %s", file, contents), contents.contains(file));
}
}
private Set<String> getFileNames(Path zipFile) throws IOException {
try (Zip zip = new Zip(zipFile, false)) {
return zip.getFileNames();
}
}
}
| |
/**
*============================================================================
* Copyright The Ohio State University Research Foundation, The University of Chicago -
* Argonne National Laboratory, Emory University, SemanticBits LLC, and
* Ekagra Software Technologies Ltd.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-core/LICENSE.txt for details.
*============================================================================
**/
package gov.nih.nci.cagrid.workflow.service.impl.client;
import java.io.InputStream;
import java.rmi.RemoteException;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import javax.xml.namespace.QName;
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.addressing.EndpointReferenceType;
import org.apache.axis.types.URI.MalformedURIException;
import org.oasis.wsrf.properties.GetResourcePropertyResponse;
import org.globus.gsi.GlobusCredential;
import gov.nih.nci.cagrid.workflow.service.impl.stubs.TavernaWorkflowServiceImplPortType;
import gov.nih.nci.cagrid.workflow.service.impl.stubs.service.TavernaWorkflowServiceImplServiceAddressingLocator;
import gov.nih.nci.cagrid.workflow.service.impl.common.TavernaWorkflowServiceImplI;
import gov.nih.nci.cagrid.introduce.security.client.ServiceSecurityClient;
/**
* This class is autogenerated, DO NOT EDIT GENERATED GRID SERVICE ACCESS METHODS.
*
* This client is generated automatically by Introduce to provide a clean unwrapped API to the
* service.
*
* On construction the class instance will contact the remote service and retrieve it's security
* metadata description which it will use to configure the Stub specifically for each method call.
*
* @created by Introduce Toolkit version 1.3
*/
public class TavernaWorkflowServiceImplClient extends TavernaWorkflowServiceImplClientBase implements TavernaWorkflowServiceImplI{
private CountDownLatch doneSignal =null;
public TavernaWorkflowServiceImplClient(String url) throws MalformedURIException, RemoteException {
this(url,null);
}
public TavernaWorkflowServiceImplClient(String url, GlobusCredential proxy) throws MalformedURIException, RemoteException {
super(url,proxy);
}
public TavernaWorkflowServiceImplClient(EndpointReferenceType epr) throws MalformedURIException, RemoteException {
this(epr,null);
}
public TavernaWorkflowServiceImplClient(EndpointReferenceType epr, GlobusCredential proxy) throws MalformedURIException, RemoteException {
super(epr,proxy);
}
public TavernaWorkflowServiceImplClient(EndpointReferenceType epr, CountDownLatch doneSignal, String dummyArg) throws MalformedURIException, RemoteException {
this(epr,null);
this.doneSignal = doneSignal;
}
public static void usage(){
System.out.println(TavernaWorkflowServiceImplClient.class.getName() + " -url <service url>");
}
public static void main(String [] args){
System.out.println("Running the Grid Service Client");
try{
if(!(args.length < 2)){
if(args[0].equals("-url")){
TavernaWorkflowServiceImplClient client = new TavernaWorkflowServiceImplClient(args[1]);
// place client calls here if you want to use this main as a
// test....
} else {
usage();
System.exit(1);
}
} else {
usage();
System.exit(1);
}
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
}
}
public void deliver(List topicPath, EndpointReferenceType producer, Object message) {
org.oasis.wsrf.properties.ResourcePropertyValueChangeNotificationType changeMessage = ((org.globus.wsrf.core.notification.ResourcePropertyValueChangeNotificationElementType) message)
.getResourcePropertyValueChangeNotification();
if (changeMessage != null) {
System.out.println("Got notification2");
doneSignal.countDown();
}
}
public org.oasis.wsrf.lifetime.DestroyResponse destroy(org.oasis.wsrf.lifetime.Destroy params) throws RemoteException {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"destroy");
return portType.destroy(params);
}
}
public org.oasis.wsrf.lifetime.SetTerminationTimeResponse setTerminationTime(org.oasis.wsrf.lifetime.SetTerminationTime params) throws RemoteException {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"setTerminationTime");
return portType.setTerminationTime(params);
}
}
public void cancel() throws RemoteException, gov.nih.nci.cagrid.workflow.service.impl.stubs.types.CannotCancelWorkflowFault {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"cancel");
gov.nih.nci.cagrid.workflow.service.impl.stubs.CancelRequest params = new gov.nih.nci.cagrid.workflow.service.impl.stubs.CancelRequest();
gov.nih.nci.cagrid.workflow.service.impl.stubs.CancelResponse boxedResult = portType.cancel(params);
}
}
public workflowmanagementfactoryservice.WorkflowStatusEventType[] getDetailedStatus() throws RemoteException, gov.nih.nci.cagrid.workflow.service.impl.stubs.types.WorkflowException {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"getDetailedStatus");
gov.nih.nci.cagrid.workflow.service.impl.stubs.GetDetailedStatusRequest params = new gov.nih.nci.cagrid.workflow.service.impl.stubs.GetDetailedStatusRequest();
gov.nih.nci.cagrid.workflow.service.impl.stubs.GetDetailedStatusResponse boxedResult = portType.getDetailedStatus(params);
return boxedResult.getDetailedStatusOutputElement();
}
}
public workflowmanagementfactoryservice.WorkflowStatusType getStatus() throws RemoteException, gov.nih.nci.cagrid.workflow.service.impl.stubs.types.WorkflowException {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"getStatus");
gov.nih.nci.cagrid.workflow.service.impl.stubs.GetStatusRequest params = new gov.nih.nci.cagrid.workflow.service.impl.stubs.GetStatusRequest();
gov.nih.nci.cagrid.workflow.service.impl.stubs.GetStatusResponse boxedResult = portType.getStatus(params);
return boxedResult.getWorkflowStatusElement();
}
}
public workflowmanagementfactoryservice.WorkflowOutputType getWorkflowOutput() throws RemoteException, gov.nih.nci.cagrid.workflow.service.impl.stubs.types.WorkflowException {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"getWorkflowOutput");
gov.nih.nci.cagrid.workflow.service.impl.stubs.GetWorkflowOutputRequest params = new gov.nih.nci.cagrid.workflow.service.impl.stubs.GetWorkflowOutputRequest();
gov.nih.nci.cagrid.workflow.service.impl.stubs.GetWorkflowOutputResponse boxedResult = portType.getWorkflowOutput(params);
return boxedResult.getWorkflowOutputElement();
}
}
public workflowmanagementfactoryservice.WorkflowStatusType pause() throws RemoteException, gov.nih.nci.cagrid.workflow.service.impl.stubs.types.WorkflowException, gov.nih.nci.cagrid.workflow.service.impl.stubs.types.CannotPauseWorkflowFault {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"pause");
gov.nih.nci.cagrid.workflow.service.impl.stubs.PauseRequest params = new gov.nih.nci.cagrid.workflow.service.impl.stubs.PauseRequest();
gov.nih.nci.cagrid.workflow.service.impl.stubs.PauseResponse boxedResult = portType.pause(params);
return boxedResult.getWorkflowStatusElement();
}
}
public workflowmanagementfactoryservice.WorkflowStatusType resume() throws RemoteException, gov.nih.nci.cagrid.workflow.service.impl.stubs.types.WorkflowException, gov.nih.nci.cagrid.workflow.service.impl.stubs.types.CannotResumeWorkflowFault {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"resume");
gov.nih.nci.cagrid.workflow.service.impl.stubs.ResumeRequest params = new gov.nih.nci.cagrid.workflow.service.impl.stubs.ResumeRequest();
gov.nih.nci.cagrid.workflow.service.impl.stubs.ResumeResponse boxedResult = portType.resume(params);
return boxedResult.getWorkflowStatusElement();
}
}
public workflowmanagementfactoryservice.WorkflowStatusType start(workflowmanagementfactoryservice.StartInputType startInputElement) throws RemoteException, gov.nih.nci.cagrid.workflow.service.impl.stubs.types.CannotStartWorkflowFault {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"start");
gov.nih.nci.cagrid.workflow.service.impl.stubs.StartRequest params = new gov.nih.nci.cagrid.workflow.service.impl.stubs.StartRequest();
gov.nih.nci.cagrid.workflow.service.impl.stubs.StartRequestStartInputElement startInputElementContainer = new gov.nih.nci.cagrid.workflow.service.impl.stubs.StartRequestStartInputElement();
startInputElementContainer.setStartInputElement(startInputElement);
params.setStartInputElement(startInputElementContainer);
gov.nih.nci.cagrid.workflow.service.impl.stubs.StartResponse boxedResult = portType.start(params);
return boxedResult.getWorkflowStatusElement();
}
}
public org.oasis.wsrf.properties.GetMultipleResourcePropertiesResponse getMultipleResourceProperties(org.oasis.wsrf.properties.GetMultipleResourceProperties_Element params) throws RemoteException {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"getMultipleResourceProperties");
return portType.getMultipleResourceProperties(params);
}
}
public org.oasis.wsrf.properties.GetResourcePropertyResponse getResourceProperty(javax.xml.namespace.QName params) throws RemoteException {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"getResourceProperty");
return portType.getResourceProperty(params);
}
}
public org.oasis.wsrf.properties.QueryResourcePropertiesResponse queryResourceProperties(org.oasis.wsrf.properties.QueryResourceProperties_Element params) throws RemoteException {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"queryResourceProperties");
return portType.queryResourceProperties(params);
}
}
public org.oasis.wsn.SubscribeResponse subscribe(org.oasis.wsn.Subscribe params) throws RemoteException {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"subscribe");
return portType.subscribe(params);
}
}
public void setDelegatedCredential(org.cagrid.gaards.cds.delegated.stubs.types.DelegatedCredentialReference delegatedCredentialReference) throws RemoteException, gov.nih.nci.cagrid.workflow.service.impl.stubs.types.CannotSetCredential {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"setDelegatedCredential");
gov.nih.nci.cagrid.workflow.service.impl.stubs.SetDelegatedCredentialRequest params = new gov.nih.nci.cagrid.workflow.service.impl.stubs.SetDelegatedCredentialRequest();
gov.nih.nci.cagrid.workflow.service.impl.stubs.SetDelegatedCredentialRequestDelegatedCredentialReference delegatedCredentialReferenceContainer = new gov.nih.nci.cagrid.workflow.service.impl.stubs.SetDelegatedCredentialRequestDelegatedCredentialReference();
delegatedCredentialReferenceContainer.setDelegatedCredentialReference(delegatedCredentialReference);
params.setDelegatedCredentialReference(delegatedCredentialReferenceContainer);
gov.nih.nci.cagrid.workflow.service.impl.stubs.SetDelegatedCredentialResponse boxedResult = portType.setDelegatedCredential(params);
}
}
public org.cagrid.transfer.context.stubs.types.TransferServiceContextReference putInputData(java.lang.String filename) throws RemoteException {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"putInputData");
gov.nih.nci.cagrid.workflow.service.impl.stubs.PutInputDataRequest params = new gov.nih.nci.cagrid.workflow.service.impl.stubs.PutInputDataRequest();
params.setFilename(filename);
gov.nih.nci.cagrid.workflow.service.impl.stubs.PutInputDataResponse boxedResult = portType.putInputData(params);
return boxedResult.getTransferServiceContextReference();
}
}
public org.cagrid.transfer.context.stubs.types.TransferServiceContextReference getOutputData() throws RemoteException {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"getOutputData");
gov.nih.nci.cagrid.workflow.service.impl.stubs.GetOutputDataRequest params = new gov.nih.nci.cagrid.workflow.service.impl.stubs.GetOutputDataRequest();
gov.nih.nci.cagrid.workflow.service.impl.stubs.GetOutputDataResponse boxedResult = portType.getOutputData(params);
return boxedResult.getTransferServiceContextReference();
}
}
public workflowmanagementfactoryservice.WorkflowStatusType startWorkflow(workflowmanagementfactoryservice.StartInputType startInputElement) throws RemoteException, gov.nih.nci.cagrid.workflow.service.impl.stubs.types.CannotStartWorkflowFault {
synchronized(portTypeMutex){
configureStubSecurity((Stub)portType,"startWorkflow");
gov.nih.nci.cagrid.workflow.service.impl.stubs.StartWorkflowRequest params = new gov.nih.nci.cagrid.workflow.service.impl.stubs.StartWorkflowRequest();
gov.nih.nci.cagrid.workflow.service.impl.stubs.StartWorkflowRequestStartInputElement startInputElementContainer = new gov.nih.nci.cagrid.workflow.service.impl.stubs.StartWorkflowRequestStartInputElement();
startInputElementContainer.setStartInputElement(startInputElement);
params.setStartInputElement(startInputElementContainer);
gov.nih.nci.cagrid.workflow.service.impl.stubs.StartWorkflowResponse boxedResult = portType.startWorkflow(params);
return boxedResult.getWorkflowStatusElement();
}
}
}
| |
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.chrome.browser.media.remote;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentActivity;
import android.support.v4.media.TransportMediator;
import android.support.v4.media.TransportPerformer;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;
import com.google.android.gms.cast.CastMediaControlIntent;
import org.chromium.chrome.R;
import org.chromium.chrome.browser.media.remote.RemoteVideoInfo.PlayerState;
import org.chromium.third_party.android.media.MediaController;
/**
* The activity that's opened by clicking the video flinging (casting) notification.
*
* TODO(cimamoglu): Refactor to merge some common logic with {@link TransportControl}.
*/
public class ExpandedControllerActivity
extends FragmentActivity implements MediaRouteController.UiListener {
private static final int PROGRESS_UPDATE_PERIOD_IN_MS = 1000;
// The alpha value for the poster/placeholder image, an integer between 0 and 256 (opaque).
private static final int POSTER_IMAGE_ALPHA = 200;
private Handler mHandler;
// We don't use the standard android.media.MediaController, but a custom one.
// See the class itself for details.
private MediaController mMediaController;
private FullscreenMediaRouteButton mMediaRouteButton;
private MediaRouteController mMediaRouteController;
private RemoteVideoInfo mVideoInfo;
private String mScreenName;
private TransportMediator mTransportMediator;
/**
* Handle actions from on-screen media controls.
*/
private TransportPerformer mTransportPerformer = new TransportPerformer() {
@Override
public void onStart() {
if (mMediaRouteController == null) return;
mMediaRouteController.resume();
}
@Override
public void onStop() {
if (mMediaRouteController == null) return;
onPause();
mMediaRouteController.release();
}
@Override
public void onPause() {
if (mMediaRouteController == null) return;
mMediaRouteController.pause();
}
@Override
public long onGetDuration() {
if (mMediaRouteController == null) return 0;
return mMediaRouteController.getDuration();
}
@Override
public long onGetCurrentPosition() {
if (mMediaRouteController == null) return 0;
return mMediaRouteController.getPosition();
}
@Override
public void onSeekTo(long pos) {
if (mMediaRouteController == null) return;
mMediaRouteController.seekTo((int) pos);
}
@Override
public boolean onIsPlaying() {
if (mMediaRouteController == null) return false;
return mMediaRouteController.isPlaying();
}
@Override
public int onGetTransportControlFlags() {
int flags = TransportMediator.FLAG_KEY_MEDIA_REWIND
| TransportMediator.FLAG_KEY_MEDIA_FAST_FORWARD;
if (mMediaRouteController != null && mMediaRouteController.isPlaying()) {
flags |= TransportMediator.FLAG_KEY_MEDIA_PAUSE;
} else {
flags |= TransportMediator.FLAG_KEY_MEDIA_PLAY;
}
return flags;
}
};
private Runnable mProgressUpdater = new Runnable() {
@Override
public void run() {
if (mMediaRouteController.isPlaying()) {
mMediaController.updateProgress();
mHandler.postDelayed(this, PROGRESS_UPDATE_PERIOD_IN_MS);
} else {
mHandler.removeCallbacks(this);
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMediaRouteController =
RemoteMediaPlayerController.instance().getCurrentlyPlayingMediaRouteController();
if (mMediaRouteController == null || mMediaRouteController.routeIsDefaultRoute()) {
// We don't want to do anything for the default (local) route
finish();
return;
}
// Make the activity full screen.
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// requestWindowFeature must be called before adding content.
setContentView(R.layout.expanded_cast_controller);
mHandler = new Handler();
ViewGroup rootView = (ViewGroup) findViewById(android.R.id.content);
rootView.setBackgroundColor(Color.BLACK);
mMediaRouteController.addUiListener(this);
// Create transport controller to control video, giving the callback
// interface to receive actions from.
mTransportMediator = new TransportMediator(this, mTransportPerformer);
// Create and initialize the media control UI.
mMediaController = (MediaController) findViewById(R.id.cast_media_controller);
mMediaController.setMediaPlayer(mTransportMediator);
View button = getLayoutInflater().inflate(R.layout.cast_controller_media_route_button,
rootView, false);
if (button instanceof FullscreenMediaRouteButton) {
mMediaRouteButton = (FullscreenMediaRouteButton) button;
rootView.addView(mMediaRouteButton);
mMediaRouteButton.bringToFront();
mMediaRouteButton.initialize(mMediaRouteController);
} else {
mMediaRouteButton = null;
}
// Initialize the video info.
setVideoInfo(new RemoteVideoInfo(null, 0, RemoteVideoInfo.PlayerState.STOPPED, 0, null));
mMediaController.refresh();
scheduleProgressUpdate();
}
@Override
protected void onResume() {
super.onResume();
if (mVideoInfo.state == PlayerState.FINISHED) finish();
if (mMediaRouteController == null) return;
mMediaRouteController.prepareMediaRoute();
ImageView iv = (ImageView) findViewById(R.id.cast_background_image);
if (iv == null) return;
Bitmap posterBitmap = mMediaRouteController.getPoster();
if (posterBitmap != null) iv.setImageBitmap(posterBitmap);
iv.setImageAlpha(POSTER_IMAGE_ALPHA);
}
@Override
protected void onDestroy() {
cleanup();
super.onDestroy();
}
@Override
public boolean dispatchKeyEvent(KeyEvent event) {
int keyCode = event.getKeyCode();
if ((keyCode != KeyEvent.KEYCODE_VOLUME_DOWN && keyCode != KeyEvent.KEYCODE_VOLUME_UP)
|| mVideoInfo.state == PlayerState.FINISHED) {
return super.dispatchKeyEvent(event);
}
return handleVolumeKeyEvent(mMediaRouteController, event);
}
private void cleanup() {
if (mHandler != null) mHandler.removeCallbacks(mProgressUpdater);
if (mMediaRouteController != null) mMediaRouteController.removeUiListener(this);
mMediaRouteController = null;
mProgressUpdater = null;
}
/**
* Sets the remote's video information to display.
*/
private final void setVideoInfo(RemoteVideoInfo videoInfo) {
if ((mVideoInfo == null) ? (videoInfo == null) : mVideoInfo.equals(videoInfo)) return;
mVideoInfo = videoInfo;
onVideoInfoChanged();
}
private void scheduleProgressUpdate() {
mHandler.removeCallbacks(mProgressUpdater);
if (mMediaRouteController.isPlaying()) {
mHandler.post(mProgressUpdater);
}
}
/**
* Sets the name to display for the device.
*/
private void setScreenName(String screenName) {
if (TextUtils.equals(mScreenName, screenName)) return;
mScreenName = screenName;
onScreenNameChanged();
}
private void onVideoInfoChanged() {
updateUi();
}
private void onScreenNameChanged() {
updateUi();
}
private void updateUi() {
if (mMediaController == null || mMediaRouteController == null) return;
String deviceName = mMediaRouteController.getRouteName();
String castText = "";
if (deviceName != null) {
castText = getResources().getString(R.string.cast_casting_video, deviceName);
}
TextView castTextView = (TextView) findViewById(R.id.cast_screen_title);
castTextView.setText(castText);
mMediaController.refresh();
}
@Override
public void onRouteSelected(String name, MediaRouteController mediaRouteController) {
setScreenName(name);
}
@Override
public void onRouteUnselected(MediaRouteController mediaRouteController) {
finish();
}
@Override
public void onPrepared(MediaRouteController mediaRouteController) {
// No implementation.
}
@Override
public void onError(int error, String message) {
if (error == CastMediaControlIntent.ERROR_CODE_SESSION_START_FAILED) finish();
}
@Override
public void onPlaybackStateChanged(PlayerState oldState, PlayerState newState) {
RemoteVideoInfo videoInfo = new RemoteVideoInfo(mVideoInfo);
videoInfo.state = newState;
setVideoInfo(videoInfo);
scheduleProgressUpdate();
if (newState == PlayerState.FINISHED || newState == PlayerState.INVALIDATED) {
// If we are switching to a finished state, stop the notifications.
finish();
}
}
@Override
public void onDurationUpdated(int durationMillis) {
RemoteVideoInfo videoInfo = new RemoteVideoInfo(mVideoInfo);
videoInfo.durationMillis = durationMillis;
setVideoInfo(videoInfo);
}
@Override
public void onPositionChanged(int positionMillis) {
RemoteVideoInfo videoInfo = new RemoteVideoInfo(mVideoInfo);
videoInfo.currentTimeMillis = positionMillis;
setVideoInfo(videoInfo);
}
@Override
public void onTitleChanged(String title) {
RemoteVideoInfo videoInfo = new RemoteVideoInfo(mVideoInfo);
videoInfo.title = title;
setVideoInfo(videoInfo);
}
/**
* Modify remote volume by handling volume keys.
*
* @param controller The remote controller through which the volume will be modified.
* @param event The key event. Its keycode needs to be either {@code KEYCODE_VOLUME_DOWN} or
* {@code KEYCODE_VOLUME_UP} otherwise this method will return false.
* @return True if the event is handled.
*/
private boolean handleVolumeKeyEvent(MediaRouteController controller, KeyEvent event) {
if (!controller.isBeingCast()) return false;
int action = event.getAction();
int keyCode = event.getKeyCode();
// Intercept the volume keys to affect only remote volume.
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_DOWN:
if (action == KeyEvent.ACTION_DOWN) controller.setRemoteVolume(-1);
return true;
case KeyEvent.KEYCODE_VOLUME_UP:
if (action == KeyEvent.ACTION_DOWN) controller.setRemoteVolume(1);
return true;
default:
return false;
}
}
/**
* Launches the ExpandedControllerActivity as a new task.
*
* @param context the Context to start this activity within.
*/
public static void startActivity(Context context) {
if (context == null) return;
Intent intent = new Intent(context, ExpandedControllerActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
| |
/*
* Copyright 2012 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.api.internal.artifacts.repositories.resolver;
import com.google.common.collect.ImmutableSet;
import org.gradle.api.artifacts.component.ModuleComponentIdentifier;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.ModuleComponentRepositoryAccess;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.DescriptorParseContext;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.GradlePomModuleDescriptorParser;
import org.gradle.api.internal.artifacts.ivyservice.ivyresolve.parser.MetaDataParser;
import org.gradle.api.internal.artifacts.repositories.transport.RepositoryTransport;
import org.gradle.api.internal.component.ArtifactType;
import org.gradle.internal.Transformers;
import org.gradle.internal.component.external.model.*;
import org.gradle.internal.component.model.*;
import org.gradle.internal.resolve.result.BuildableArtifactSetResolveResult;
import org.gradle.internal.resolve.result.BuildableModuleComponentMetaDataResolveResult;
import org.gradle.internal.resolve.result.DefaultResourceAwareResolveResult;
import org.gradle.internal.resolve.result.ResourceAwareResolveResult;
import org.gradle.internal.resource.ExternalResourceName;
import org.gradle.internal.resource.LocallyAvailableExternalResource;
import org.gradle.internal.resource.ResourceNotFoundException;
import org.gradle.internal.resource.local.FileStore;
import org.gradle.internal.resource.local.LocallyAvailableResourceFinder;
import java.net.URI;
import java.util.*;
public class MavenResolver extends ExternalResourceResolver {
private final URI root;
private final List<URI> artifactRoots = new ArrayList<URI>();
private final MavenMetadataLoader mavenMetaDataLoader;
private final MetaDataParser metaDataParser;
public MavenResolver(String name, URI rootUri, RepositoryTransport transport,
LocallyAvailableResourceFinder<ModuleComponentArtifactMetaData> locallyAvailableResourceFinder,
FileStore<ModuleComponentArtifactMetaData> artifactFileStore) {
super(name, transport.isLocal(),
transport.getRepository(),
transport.getResourceAccessor(),
new ChainedVersionLister(new MavenVersionLister(transport.getRepository()), new ResourceVersionLister(transport.getRepository())),
locallyAvailableResourceFinder,
artifactFileStore);
this.metaDataParser = new GradlePomModuleDescriptorParser();
this.mavenMetaDataLoader = new MavenMetadataLoader(transport.getRepository());
this.root = rootUri;
updatePatterns();
}
@Override
public String toString() {
return String.format("Maven repository '%s'", getName());
}
public URI getRoot() {
return root;
}
protected void doResolveComponentMetaData(DependencyMetaData dependency, ModuleComponentIdentifier moduleComponentIdentifier, BuildableModuleComponentMetaDataResolveResult result) {
if (isSnapshotVersion(moduleComponentIdentifier)) {
final MavenUniqueSnapshotModuleSource uniqueSnapshotVersion = findUniqueSnapshotVersion(moduleComponentIdentifier, result);
if (uniqueSnapshotVersion != null) {
resolveUniqueSnapshotDependency(dependency, moduleComponentIdentifier, result, uniqueSnapshotVersion);
return;
}
}
resolveStaticDependency(dependency, moduleComponentIdentifier, result, super.createArtifactResolver());
}
protected boolean isMetaDataArtifact(ArtifactType artifactType) {
return artifactType == ArtifactType.MAVEN_POM;
}
@Override
protected MutableModuleComponentResolveMetaData processMetaData(MutableModuleComponentResolveMetaData metaData) {
if (metaData.getId().getVersion().endsWith("-SNAPSHOT")) {
metaData.setChanging(true);
}
return metaData;
}
private void resolveUniqueSnapshotDependency(DependencyMetaData dependency, ModuleComponentIdentifier module, BuildableModuleComponentMetaDataResolveResult result, MavenUniqueSnapshotModuleSource snapshotSource) {
resolveStaticDependency(dependency, module, result, createArtifactResolver(snapshotSource));
if (result.getState() == BuildableModuleComponentMetaDataResolveResult.State.Resolved) {
result.getMetaData().setSource(snapshotSource);
}
}
private boolean isSnapshotVersion(ModuleComponentIdentifier module) {
return module.getVersion().endsWith("-SNAPSHOT");
}
@Override
protected ExternalResourceArtifactResolver createArtifactResolver(ModuleSource moduleSource) {
if (moduleSource instanceof MavenUniqueSnapshotModuleSource) {
final String timestamp = ((MavenUniqueSnapshotModuleSource) moduleSource).getTimestamp();
return new MavenUniqueSnapshotExternalResourceArtifactResolver(super.createArtifactResolver(moduleSource), timestamp);
}
return super.createArtifactResolver(moduleSource);
}
public void addArtifactLocation(URI baseUri) {
artifactRoots.add(baseUri);
updatePatterns();
}
private M2ResourcePattern getWholePattern() {
return new M2ResourcePattern(root, MavenPattern.M2_PATTERN);
}
private void updatePatterns() {
setIvyPatterns(Collections.singletonList(getWholePattern()));
List<ResourcePattern> artifactPatterns = new ArrayList<ResourcePattern>();
artifactPatterns.add(getWholePattern());
for (URI artifactRoot : artifactRoots) {
artifactPatterns.add(new M2ResourcePattern(artifactRoot, MavenPattern.M2_PATTERN));
}
setArtifactPatterns(artifactPatterns);
}
@Override
protected IvyArtifactName getMetaDataArtifactName(String moduleName) {
return new DefaultIvyArtifactName(moduleName, "pom", "pom");
}
private MavenUniqueSnapshotModuleSource findUniqueSnapshotVersion(ModuleComponentIdentifier module, ResourceAwareResolveResult result) {
ExternalResourceName metadataLocation = getWholePattern().toModuleVersionPath(module).resolve("maven-metadata.xml");
result.attempted(metadataLocation);
MavenMetadata mavenMetadata = parseMavenMetadata(metadataLocation.getUri());
if (mavenMetadata.timestamp != null) {
// we have found a timestamp, so this is a snapshot unique version
String timestamp = String.format("%s-%s", mavenMetadata.timestamp, mavenMetadata.buildNumber);
return new MavenUniqueSnapshotModuleSource(timestamp);
}
return null;
}
private MavenMetadata parseMavenMetadata(URI metadataLocation) {
try {
return mavenMetaDataLoader.load(metadataLocation);
} catch (ResourceNotFoundException e) {
return new MavenMetadata();
}
}
@Override
public boolean isM2compatible() {
return true;
}
public ModuleComponentRepositoryAccess getLocalAccess() {
return new MavenLocalRepositoryAccess();
}
public ModuleComponentRepositoryAccess getRemoteAccess() {
return new MavenRemoteRepositoryAccess();
}
@Override
protected MutableModuleComponentResolveMetaData createMetaDataForDependency(DependencyMetaData dependency) {
return new DefaultMavenModuleResolveMetaData(dependency);
}
protected MutableModuleComponentResolveMetaData parseMetaDataFromResource(LocallyAvailableExternalResource cachedResource, DescriptorParseContext context) {
return metaDataParser.parseMetaData(context, cachedResource);
}
protected static MavenModuleResolveMetaData mavenMetaData(ModuleComponentResolveMetaData metaData) {
return Transformers.cast(MavenModuleResolveMetaData.class).transform(metaData);
}
private class MavenLocalRepositoryAccess extends LocalRepositoryAccess {
@Override
protected void resolveConfigurationArtifacts(ModuleComponentResolveMetaData module, ConfigurationMetaData configuration, BuildableArtifactSetResolveResult result) {
if (mavenMetaData(module).isKnownJarPackaging()) {
ModuleComponentArtifactMetaData artifact = module.artifact("jar", "jar", null);
result.resolved(ImmutableSet.of(artifact));
}
}
@Override
protected void resolveJavadocArtifacts(ModuleComponentResolveMetaData module, BuildableArtifactSetResolveResult result) {
// Javadoc artifacts are optional, so we need to probe for them remotely
}
@Override
protected void resolveSourceArtifacts(ModuleComponentResolveMetaData module, BuildableArtifactSetResolveResult result) {
// Javadoc artifacts are optional, so we need to probe for them remotely
}
}
private class MavenRemoteRepositoryAccess extends RemoteRepositoryAccess {
@Override
protected void resolveConfigurationArtifacts(ModuleComponentResolveMetaData module, ConfigurationMetaData configuration, BuildableArtifactSetResolveResult result) {
MavenModuleResolveMetaData mavenMetaData = mavenMetaData(module);
if (mavenMetaData.isPomPackaging()) {
Set<ComponentArtifactMetaData> artifacts = new LinkedHashSet<ComponentArtifactMetaData>();
artifacts.addAll(findOptionalArtifacts(module, "jar", null));
result.resolved(artifacts);
} else {
ModuleComponentArtifactMetaData artifactMetaData = module.artifact(mavenMetaData.getPackaging(), mavenMetaData.getPackaging(), null);
if (createArtifactResolver(module.getSource()).artifactExists(artifactMetaData, new DefaultResourceAwareResolveResult())) {
result.resolved(ImmutableSet.of(artifactMetaData));
} else {
ModuleComponentArtifactMetaData artifact = module.artifact("jar", "jar", null);
result.resolved(ImmutableSet.of(artifact));
}
}
}
@Override
protected void resolveJavadocArtifacts(ModuleComponentResolveMetaData module, BuildableArtifactSetResolveResult result) {
result.resolved(findOptionalArtifacts(module, "javadoc", "javadoc"));
}
@Override
protected void resolveSourceArtifacts(ModuleComponentResolveMetaData module, BuildableArtifactSetResolveResult result) {
result.resolved(findOptionalArtifacts(module, "source", "sources"));
}
}
}
| |
//
// Pythagoras - a collection of geometry classes
// http://github.com/samskivert/pythagoras
package pythagoras.d;
/**
* Math utility methods.
*/
public class MathUtil
{
/** A small number. */
public static final double EPSILON = 0.00001f;
/** The circle constant, Tau (τ) http://tauday.com/ */
public static final double TAU = (Math.PI * 2);
/** Twice Pi. */
public static final double TWO_PI = TAU;
/** Pi times one half. */
public static final double HALF_PI = (Math.PI * 0.5);
/**
* A cheaper version of {@link Math#round} that doesn't handle the special cases.
*/
public static int round (double v) {
return (v < 0f) ? (int)(v - 0.5f) : (int)(v + 0.5f);
}
/**
* Returns the floor of v as an integer without calling the relatively expensive
* {@link Math#floor}.
*/
public static int ifloor (double v) {
int iv = (int)v;
return (v >= 0f || iv == v || iv == Integer.MIN_VALUE) ? iv : (iv - 1);
}
/**
* Returns the ceiling of v as an integer without calling the relatively expensive
* {@link Math#ceil}.
*/
public static int iceil (double v) {
int iv = (int)v;
return (v <= 0f || iv == v || iv == Integer.MAX_VALUE) ? iv : (iv + 1);
}
/**
* Clamps a value to the range [lower, upper].
*/
public static double clamp (double v, double lower, double upper) {
if (v < lower) return lower;
else if (v > upper) return upper;
else return v;
}
/**
* Rounds a value to the nearest multiple of a target.
*/
public static double roundNearest (double v, double target) {
target = Math.abs(target);
if (v >= 0) {
return target * Math.floor((v + 0.5f * target) / target);
} else {
return target * Math.ceil((v - 0.5f * target) / target);
}
}
/**
* Checks whether the value supplied is in [lower, upper].
*/
public static boolean isWithin (double v, double lower, double upper) {
return v >= lower && v <= upper;
}
/**
* Returns a random value according to the normal distribution with the provided mean and
* standard deviation.
*
* @param normal a normally distributed random value.
* @param mean the desired mean.
* @param stddev the desired standard deviation.
*/
public static double normal (double normal, double mean, double stddev) {
return stddev*normal + mean;
}
/**
* Returns a random value according to the exponential distribution with the provided mean.
*
* @param random a uniformly distributed random value.
* @param mean the desired mean.
*/
public static double exponential (double random, double mean) {
return -Math.log(1f - random) * mean;
}
/**
* Linearly interpolates between two angles, taking the shortest path around the circle.
* This assumes that both angles are in [-pi, +pi].
*/
public static double lerpa (double a1, double a2, double t) {
double ma1 = mirrorAngle(a1), ma2 = mirrorAngle(a2);
double d = Math.abs(a2 - a1), md = Math.abs(ma1 - ma2);
return (d < md) ? lerp(a1, a2, t) : mirrorAngle(lerp(ma1, ma2, t));
}
/**
* Linearly interpolates between v1 and v2 by the parameter t.
*/
public static double lerp (double v1, double v2, double t) {
return v1 + t*(v2 - v1);
}
/**
* Determines whether two values are "close enough" to equal.
*/
public static boolean epsilonEquals (double v1, double v2) {
return Math.abs(v1 - v2) < EPSILON;
}
/**
* Returns the (shortest) distance between two angles, assuming that both angles are in
* [-pi, +pi].
*/
public static double angularDistance (double a1, double a2) {
double ma1 = mirrorAngle(a1), ma2 = mirrorAngle(a2);
return Math.min(Math.abs(a1 - a2), Math.abs(ma1 - ma2));
}
/**
* Returns the (shortest) difference between two angles, assuming that both angles are in
* [-pi, +pi].
*/
public static double angularDifference (double a1, double a2) {
double ma1 = mirrorAngle(a1), ma2 = mirrorAngle(a2);
double diff = a1 - a2, mdiff = ma2 - ma1;
return (Math.abs(diff) < Math.abs(mdiff)) ? diff : mdiff;
}
/**
* Returns an angle in the range [-pi, pi).
*/
public static double normalizeAngle (double a) {
while (a < -Math.PI) {
a += TWO_PI;
}
while (a >= Math.PI) {
a -= TWO_PI;
}
return a;
}
/**
* Returns an angle in the range [0, 2pi).
*/
public static double normalizeAnglePositive (double a) {
while (a < 0f) {
a += TWO_PI;
}
while (a >= TWO_PI) {
a -= TWO_PI;
}
return a;
}
/**
* Returns the mirror angle of the specified angle (assumed to be in [-pi, +pi]).
*/
public static double mirrorAngle (double a) {
return (a > 0f ? Math.PI : -Math.PI) - a;
}
/**
* Sets the number of decimal places to show when formatting values. By default, they are
* formatted to three decimal places.
*/
public static void setToStringDecimalPlaces (int places) {
if (places < 0) throw new IllegalArgumentException("Decimal places must be >= 0.");
TO_STRING_DECIMAL_PLACES = places;
}
/**
* Formats the supplied value, truncated to the currently configured number of decimal places.
* The value is also always preceded by a sign (e.g. +1.0 or -0.5).
*/
public static String toString (double value) {
return toString(value, TO_STRING_DECIMAL_PLACES);
}
/**
* Formats the supplied doubleing point value, truncated to the given number of decimal places.
* The value is also always preceded by a sign (e.g. +1.0 or -0.5).
*/
public static String toString (double value, int decimalPlaces) {
StringBuilder buf = new StringBuilder();
if (value >= 0) buf.append("+");
else {
buf.append("-");
value = -value;
}
int ivalue = (int)value;
buf.append(ivalue);
if (decimalPlaces > 0) {
buf.append(".");
for (int ii = 0; ii < decimalPlaces; ii++) {
value = (value - ivalue) * 10;
ivalue = (int)value;
buf.append(ivalue);
}
// trim trailing zeros
for (int ii = 0; ii < decimalPlaces-1; ii++) {
if (buf.charAt(buf.length()-1) == '0') {
buf.setLength(buf.length()-1);
}
}
}
return buf.toString();
}
protected static int TO_STRING_DECIMAL_PLACES = 3;
}
| |
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.docgen;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Matcher;
/**
* Helper class used for expanding link references in rule and attribute documentation.
*
* <p>See {@link com.google.devtools.build.docgen.DocgenConsts.BLAZE_RULE_LINK} for the regex used
* to match link references.
*/
public class RuleLinkExpander {
private static final String EXAMPLES_SUFFIX = "_examples";
private static final String ARGS_SUFFIX = "_args";
private static final String IMPLICIT_OUTPUTS_SUFFIX = "_implicit_outputs";
private static final String FUNCTIONS_PAGE = "functions";
private static final ImmutableSet<String> STATIC_PAGES =
ImmutableSet.<String>of(
"common-definitions", "make-variables", "predefined-python-variables");
private static final ImmutableMap<String, String> FUNCTIONS =
ImmutableMap.<String, String>builder()
.put("load", FUNCTIONS_PAGE)
.put("package", FUNCTIONS_PAGE)
.put("package_group", FUNCTIONS_PAGE)
.put("description", FUNCTIONS_PAGE)
.put("distribs", FUNCTIONS_PAGE)
.put("licenses", FUNCTIONS_PAGE)
.put("exports_files", FUNCTIONS_PAGE)
.put("glob", FUNCTIONS_PAGE)
.put("select", FUNCTIONS_PAGE)
.put("workspace", FUNCTIONS_PAGE)
.build();
private final String productName;
private final Map<String, String> ruleIndex = new HashMap<>();
private final boolean singlePage;
RuleLinkExpander(String productName, Map<String, String> ruleIndex, boolean singlePage) {
this.productName = productName;
this.ruleIndex.putAll(ruleIndex);
this.ruleIndex.putAll(FUNCTIONS);
this.singlePage = singlePage;
}
RuleLinkExpander(String productName, boolean singlePage) {
this.productName = productName;
this.ruleIndex.putAll(FUNCTIONS);
this.singlePage = singlePage;
}
public void addIndex(Map<String, String> ruleIndex) {
this.ruleIndex.putAll(ruleIndex);
}
private void appendRuleLink(Matcher matcher, StringBuffer sb, String ruleName, String ref) {
String ruleFamily = ruleIndex.get(ruleName);
String link = singlePage
? "#" + ref
: ruleFamily + ".html#" + ref;
matcher.appendReplacement(sb, Matcher.quoteReplacement(link));
}
/*
* Match and replace all ${link rule.attribute} references.
*/
private String expandRuleLinks(String htmlDoc) throws IllegalArgumentException {
Matcher matcher = DocgenConsts.BLAZE_RULE_LINK.matcher(htmlDoc);
StringBuffer sb = new StringBuffer(htmlDoc.length());
while (matcher.find()) {
// The first capture group matches the entire reference, e.g. "cc_binary.deps".
String ref = matcher.group(1);
// The second capture group only matches the rule name, e.g. "cc_binary" in "cc_binary.deps".
String name = matcher.group(2);
// The name in the reference is the name of a rule. Get the rule family for the rule and
// replace the reference with a link with the form of rule-family.html#rule.attribute. For
// example, ${link cc_library.deps} expands to c-cpp.html#cc_library.deps.
if (ruleIndex.containsKey(name)) {
appendRuleLink(matcher, sb, name, ref);
continue;
}
// The name is referencing the examples, arguments, or implicit outputs of a rule (e.g.
// "cc_library_args", "cc_library_examples", or "java_binary_implicit_outputs"). Strip the
// suffix and then try matching the name to a rule family.
if (name.endsWith(EXAMPLES_SUFFIX)
|| name.endsWith(ARGS_SUFFIX)
|| name.endsWith(IMPLICIT_OUTPUTS_SUFFIX)) {
int endIndex;
if (name.endsWith(EXAMPLES_SUFFIX)) {
endIndex = name.indexOf(EXAMPLES_SUFFIX);
} else if (name.endsWith(ARGS_SUFFIX)) {
endIndex = name.indexOf(ARGS_SUFFIX);
} else {
endIndex = name.indexOf(IMPLICIT_OUTPUTS_SUFFIX);
}
String ruleName = name.substring(0, endIndex);
if (ruleIndex.containsKey(ruleName)) {
appendRuleLink(matcher, sb, ruleName, ref);
continue;
}
}
// The name is not the name of a rule but is the name of a static page, such as
// common-definitions. Generate a link to that page.
if (STATIC_PAGES.contains(name)) {
String link = singlePage
? "#" + name
: name + ".html";
// For referencing headings on a static page, use the following syntax:
// ${link static_page_name#heading_name}, example: ${link make-variables#gendir}
String pageHeading = matcher.group(4);
if (pageHeading != null) {
throw new IllegalArgumentException(
"Invalid link syntax for BE page: " + matcher.group()
+ "\nUse ${link static-page#heading} syntax instead.");
}
matcher.appendReplacement(sb, Matcher.quoteReplacement(link));
continue;
}
// If the reference does not match any rule or static page, throw an exception.
throw new IllegalArgumentException(
"Rule family " + name + " in link tag does not match any rule or BE page: "
+ matcher.group());
}
matcher.appendTail(sb);
return sb.toString();
}
/*
* Match and replace all ${link rule#heading} references.
*/
private String expandRuleHeadingLinks(String htmlDoc) throws IllegalArgumentException {
Matcher matcher = DocgenConsts.BLAZE_RULE_HEADING_LINK.matcher(htmlDoc);
StringBuffer sb = new StringBuffer(htmlDoc.length());
while (matcher.find()) {
// The second capture group only matches the rule name, e.g. "cc_library" in
// "cc_library#some_heading"
String name = matcher.group(2);
// The third capture group only matches the heading, e.g. "some_heading" in
// "cc_library#some_heading"
String heading = matcher.group(3);
// The name in the reference is the name of a rule. Get the rule family for the rule and
// replace the reference with the link in the form of rule-family.html#heading. Examples of
// this include custom <a name="heading"> tags in the description or examples for the rule.
if (ruleIndex.containsKey(name)) {
String ruleFamily = ruleIndex.get(name);
String link = singlePage
? "#" + heading
: ruleFamily + ".html#" + heading;
matcher.appendReplacement(sb, Matcher.quoteReplacement(link));
continue;
}
// The name is of a static page, such as common.definitions. Generate a link to that page, and
// append the page heading. For example, ${link common-definitions#label-expansion} expands to
// common-definitions.html#label-expansion.
if (STATIC_PAGES.contains(name)) {
String link = singlePage
? "#" + heading
: name + ".html#" + heading;
matcher.appendReplacement(sb, Matcher.quoteReplacement(link));
continue;
}
// Links to the user manual are handled specially. Meh.
if ("user-manual".equals(name)) {
String link = productName.toLowerCase(Locale.US) + "-" + name + ".html#" + heading;
matcher.appendReplacement(sb, Matcher.quoteReplacement(link));
continue;
}
// If the reference does not match any rule or static page, throw an exception.
throw new IllegalArgumentException(
"Rule family " + name + " in link tag does not match any rule or BE page: "
+ matcher.group());
}
matcher.appendTail(sb);
return sb.toString();
}
/**
* Expands all rule references in the input HTML documentation.
*
* @param htmlDoc The input HTML documentation with ${link foo.bar} references.
* @return The HTML documentation with all link references expanded.
*/
public String expand(String htmlDoc) throws IllegalArgumentException {
String expanded = expandRuleLinks(htmlDoc);
return expandRuleHeadingLinks(expanded);
}
/**
* Expands the rule reference.
*
* <p>This method is used to expand references in the BE velocity templates.
*
* @param ref The rule reference to expand.
* @return The expanded rule reference.
*/
public String expandRef(String ref) throws IllegalArgumentException {
return expand("${link " + ref + "}");
}
}
| |
package org.owasp.webgoat.lessons;
import org.apache.ecs.Element;
import org.apache.ecs.ElementContainer;
import org.apache.ecs.StringElement;
import org.apache.ecs.html.Body;
import org.apache.ecs.html.Form;
import org.apache.ecs.html.Head;
import org.apache.ecs.html.Html;
import org.apache.ecs.html.IMG;
import org.apache.ecs.html.PRE;
import org.apache.ecs.html.Title;
import org.owasp.webgoat.session.ParameterNotFoundException;
import org.owasp.webgoat.session.Screen;
import org.owasp.webgoat.session.WebSession;
import org.owasp.webgoat.session.WebgoatContext;
import org.owasp.webgoat.session.WebgoatProperties;
import org.owasp.webgoat.util.BeanProvider;
import org.owasp.webgoat.util.LabelManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
*************************************************************************************************
*
*
* This file is part of WebGoat, an Open Web Application Security Project utility. For details,
* please see http://www.owasp.org/
*
* Copyright (c) 2002 - 20014 Bruce Mayhew
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with this program; if
* not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
* 02111-1307, USA.
*
* Getting Source ==============
*
* Source for this application is maintained at https://github.com/WebGoat/WebGoat, a repository for free software
* projects.
*
* @author Bruce Mayhew <a href="http://code.google.com/p/webgoat">WebGoat</a>
* @since October 28, 2003
* @version $Id: $Id
*/
public abstract class AbstractLesson extends Screen implements Comparable<Object> {
private static final Logger logger = LoggerFactory.getLogger(AbstractLesson.class);
/**
* Description of the Field
*/
public final static String ADMIN_ROLE = "admin";
/** Constant <code>CHALLENGE_ROLE="challenge"</code> */
public final static String CHALLENGE_ROLE = "challenge";
/**
* Description of the Field
*/
public final static String HACKED_ADMIN_ROLE = "hacked_admin";
/**
* Description of the Field
*/
public final static String USER_ROLE = "user";
private static int count = 1;
private Integer id = null;
final static IMG nextGrey = new IMG("images/right16.gif").setAlt("Next").setBorder(0).setHspace(0).setVspace(0);
final static IMG previousGrey = new IMG("images/left14.gif").setAlt("Previous").setBorder(0).setHspace(0)
.setVspace(0);
private Integer ranking;
private Category category;
private boolean hidden;
private String sourceFileName;
private Map<String, String> lessonPlanFileName = new HashMap<String, String>();
private String lessonSolutionFileName;
private WebgoatContext webgoatContext;
private LinkedList<String> availableLanguages = new LinkedList<String>();
private String defaultLanguage = "en";
private LabelManager labelManager = null;
/**
* Constructor for the Lesson object
*/
public AbstractLesson() {
id = new Integer(++count);
}
/**
* <p>getName.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getName() {
String className = getClass().getName();
return className.substring(className.lastIndexOf('.') + 1);
}
/**
* <p>Setter for the field <code>ranking</code>.</p>
*
* @param ranking a {@link java.lang.Integer} object.
*/
public void setRanking(Integer ranking) {
this.ranking = ranking;
}
/**
* <p>Setter for the field <code>hidden</code>.</p>
*
* @param hidden a boolean.
*/
public void setHidden(boolean hidden) {
this.hidden = hidden;
}
/**
* <p>update.</p>
*
* @param properties a {@link org.owasp.webgoat.session.WebgoatProperties} object.
*/
public void update(WebgoatProperties properties) {
String className = getClass().getName();
className = className.substring(className.lastIndexOf(".") + 1);
setRanking(new Integer(properties.getIntProperty("lesson." + className + ".ranking", getDefaultRanking()
.intValue())));
String categoryRankingKey = "category." + getDefaultCategory().getName() + ".ranking";
// System.out.println("Category ranking key: " + categoryRankingKey);
Category tempCategory = Category.getCategory(getDefaultCategory().getName());
tempCategory.setRanking(new Integer(properties.getIntProperty(categoryRankingKey, getDefaultCategory()
.getRanking().intValue())));
category = tempCategory;
setHidden(properties.getBooleanProperty("lesson." + className + ".hidden", getDefaultHidden()));
// System.out.println(className + " in " + tempCategory.getName() + "
// (Category Ranking: " + tempCategory.getRanking() + " Lesson ranking:
// " + getRanking() + ", hidden:" + hidden +")");
}
/**
* <p>isCompleted.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @return a boolean.
*/
public boolean isCompleted(WebSession s) {
return getLessonTracker(s, this).getCompleted();
}
/**
* {@inheritDoc}
*
* Description of the Method
*/
public int compareTo(Object obj) {
return this.getRanking().compareTo(((AbstractLesson) obj).getRanking());
}
/**
* {@inheritDoc}
*
* Description of the Method
*/
public boolean equals(Object obj) {
return this.getScreenId() == ((AbstractLesson) obj).getScreenId();
}
/**
* Gets the category attribute of the Lesson object
*
* @return The category value
*/
public Category getCategory() {
return category;
}
/**
* <p>getDefaultRanking.</p>
*
* @return a {@link java.lang.Integer} object.
*/
protected abstract Integer getDefaultRanking();
/**
* <p>getDefaultCategory.</p>
*
* @return a {@link org.owasp.webgoat.lessons.Category} object.
*/
protected abstract Category getDefaultCategory();
/**
* <p>getDefaultHidden.</p>
*
* @return a boolean.
*/
protected abstract boolean getDefaultHidden();
/**
* <p>getSubmitMethod</p>
*
* @return a {@link java.lang.String} object.
*/
public abstract String getSubmitMethod();
/**
* Gets the fileMethod attribute of the Lesson class
*
* @param reader Description of the Parameter
* @param methodName Description of the Parameter
* @param numbers Description of the Parameter
* @return The fileMethod value
*/
public static String getFileMethod(BufferedReader reader, String methodName, boolean numbers) {
int count = 0;
StringBuffer sb = new StringBuffer();
boolean echo = false;
boolean startCount = false;
int parenCount = 0;
try {
String line;
while ((line = reader.readLine()) != null) {
if ((line.indexOf(methodName) != -1)
&& ((line.indexOf("public") != -1) || (line.indexOf("protected") != -1) || (line
.indexOf("private") != -1))) {
echo = true;
startCount = true;
}
if (echo && startCount) {
if (numbers) {
sb.append(pad(++count) + " ");
}
sb.append(line + "\n");
}
if (echo && (line.indexOf("{") != -1)) {
parenCount++;
}
if (echo && (line.indexOf("}") != -1)) {
parenCount--;
if (parenCount == 0) {
startCount = false;
echo = false;
}
}
}
reader.close();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
return (sb.toString());
}
/**
* Reads text from a file into an ElementContainer. Each line in the file is
* represented in the ElementContainer by a StringElement. Each
* StringElement is appended with a new-line character.
*
* @param reader Description of the Parameter
* @param numbers Description of the Parameter
* @return Description of the Return Value
*/
public static String readFromFile(BufferedReader reader, boolean numbers) {
return (getFileText(reader, numbers));
}
/**
* Gets the fileText attribute of the Screen class
*
* @param reader Description of the Parameter
* @param numbers Description of the Parameter
* @return The fileText value
*/
public static String getFileText(BufferedReader reader, boolean numbers) {
int count = 0;
StringBuffer sb = new StringBuffer();
try {
String line;
while ((line = reader.readLine()) != null) {
if (numbers) {
sb.append(pad(++count) + " ");
}
sb.append(line + System.getProperty("line.separator"));
}
reader.close();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
return (sb.toString());
}
/**
* Will this screen be included in an enterprise edition.
*
* @return The ranking value
*/
public boolean isEnterprise() {
return false;
}
/**
* Gets the hintCount attribute of the Lesson object
*
* @param s The user's WebSession
* @return The hintCount value
*/
public int getHintCount(WebSession s) {
return getHints(s).size();
}
/**
* <p>getHints.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @return a {@link java.util.List} object.
*/
protected abstract List<String> getHints(WebSession s);
// @TODO we need to restrict access at the service layer
// rather than passing session object around
/**
* <p>getHintsPublic.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @return a {@link java.util.List} object.
*/
public List<String> getHintsPublic(WebSession s) {
List<String> hints = getHints(s);
return hints;
}
/**
* Fill in a minor hint that will help people who basically get it, but are
* stuck on somthing silly.
*
* @param s The users WebSession
* @return The hint1 value
* @param hintNumber a int.
*/
public String getHint(WebSession s, int hintNumber) {
return "Hint: " + getHints(s).get(hintNumber);
}
/**
* Gets the instructions attribute of the AbstractLesson object
*
* @return The instructions value
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
*/
public abstract String getInstructions(WebSession s);
/**
* Gets the lessonPlan attribute of the Lesson object
*
* @return The lessonPlan value
*/
public String getLessonName() {
return this.getClass().getSimpleName();
}
/**
* Gets the title attribute of the HelloScreen object
*
* @return The title value
*/
public abstract String getTitle();
/**
* Gets the content of lessonPlanURL
*
* @param s The user's WebSession
* @return The HTML content of the current lesson plan
*/
public String getLessonPlan(WebSession s) {
StringBuffer src = new StringBuffer();
String lang = s.getCurrrentLanguage();
try {
// System.out.println("Loading lesson plan file: " +
// getLessonPlanFileName());
String filename = getLessonPlanFileName(lang);
if (filename == null) {
filename = getLessonPlanFileName(getDefaultLanguage());
}
src.append(readFromFile(new BufferedReader(new FileReader(filename)), false));
} catch (Exception e) {
// s.setMessage( "Could not find lesson plan for " +
// getLessonName());
src = new StringBuffer("Could not find lesson plan for: " + getLessonName() + " and language " + lang);
}
return src.toString();
}
/**
* Gets the ranking attribute of the Lesson object
*
* @return The ranking value
*/
public Integer getRanking() {
if (ranking != null) {
return ranking;
} else {
return getDefaultRanking();
}
}
/**
* Gets the hidden value of the Lesson Object
*
* @return The hidden value
*/
public boolean getHidden() {
return this.hidden;
}
/**
* Gets the role attribute of the AbstractLesson object
*
* @return The role value
*/
public String getRole() {
// FIXME: Each lesson should have a role assigned to it. Each
// user/student
// should also have a role(s) assigned. The user would only be allowed
// to see lessons that correspond to their role. Eventually these roles
// will be stored in the internal database. The user will be able to
// hack
// into the database and change their role. This will allow the user to
// see the admin screens, once they figure out how to turn the admin
// switch on.
return USER_ROLE;
}
/**
* Gets the uniqueID attribute of the AbstractLesson object
*
* @return The uniqueID value
*/
public int getScreenId() {
return id.intValue();
}
/**
* <p>getHtml_DELETE_ME.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @return a {@link java.lang.String} object.
*/
public String getHtml_DELETE_ME(WebSession s) {
String html = null;
// FIXME: This doesn't work for the labs since they do not implement
// createContent().
String rawHtml = createContent(s).toString();
// System.out.println("Getting raw html content: " +
// rawHtml.substring(0, Math.min(rawHtml.length(), 100)));
html = convertMetachars(AbstractLesson.readFromFile(new BufferedReader(new StringReader(rawHtml)), true));
// System.out.println("Getting encoded html content: " +
// html.substring(0, Math.min(html.length(), 100)));
return html;
}
/**
* <p>getSource.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @return a {@link java.lang.String} object.
*/
public String getSource(WebSession s) {
String source = null;
String src = null;
try {
// System.out.println("Loading source file: " +
// getSourceFileName());
src = convertMetacharsJavaCode(readFromFile(new BufferedReader(new FileReader(getSourceFileName())), true));
// TODO: For styled line numbers and better memory efficiency,
// use a custom FilterReader
// that performs the convertMetacharsJavaCode() transform plus
// optionally adds a styled
// line number. Wouldn't color syntax be great too?
} catch (Exception e) {
s.setMessage("Could not find source file");
src = ("Could not find the source file or source file does not exist.<br/>"
+ "Send this message to: <a href=\"mailto:" + s.getWebgoatContext().getFeedbackAddress()
+ "?subject=Source " + getSourceFileName() + " not found. Lesson: "
+ s.getCurrentLesson().getLessonName() + "\">" + s.getWebgoatContext()
.getFeedbackAddress() + "</a>");
}
Html html = new Html();
Head head = new Head();
head.addElement(new Title(getSourceFileName()));
Body body = new Body();
body.addElement(new StringElement(src));
html.addElement(head);
html.addElement(body);
source = html.toString();
return source;
}
/**
* <p>getRawSource.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @return a {@link java.lang.String} object.
*/
public String getRawSource(WebSession s) {
String src;
try {
logger.debug("Loading source file: " + getSourceFileName());
src = readFromFile(new BufferedReader(new FileReader(getSourceFileName())), false);
} catch (FileNotFoundException e) {
s.setMessage("Could not find source file");
src = ("Could not find the source file or source file does not exist.<br/>"
+ "Send this message to: <a href=\"mailto:" + s.getWebgoatContext().getFeedbackAddress()
+ "?subject=Source " + getSourceFileName() + " not found. Lesson: "
+ s.getCurrentLesson().getLessonName() + "\">" + s.getWebgoatContext()
.getFeedbackAddress() + "</a>");
}
return src;
}
/**
* <p>getSolution.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @return a {@link java.lang.String} object.
*/
public String getSolution(WebSession s) {
String src = null;
try {
// System.out.println("Solution: " + getLessonSolutionFileName());
src = readFromFile(new BufferedReader(new FileReader(getLessonSolutionFileName())), false);
} catch (Exception e) {
logger.error("Could not find solution for {}", getLessonSolutionFileName());
s.setMessage("Could not find the solution file");
src = ("Could not find the solution file or solution file does not exist.<br/>"
+ "Send this message to: <a href=\"mailto:" + s.getWebgoatContext().getFeedbackAddress()
+ "?subject=Solution " + getLessonSolutionFileName() + " not found. Lesson: "
+ s.getCurrentLesson().getLessonName() + "\">" + s.getWebgoatContext()
.getFeedbackAddress() + "</a>");
}
// Solutions are html files
return src;
}
/**
* <p>Returns the default "path" portion of a lesson's URL.</p>
*
*
* Legacy webgoat lesson links are of the form
* "attack?Screen=Xmenu=Ystage=Z". This method returns the path portion of
* the url, i.e., "attack" in the string above.
*
* Newer, Spring-Controller-based classes will override this method to
* return "*.do"-styled paths.
*
* @return a {@link java.lang.String} object.
*/
protected String getPath() {
return "#attack";
}
/**
* Get the link that can be used to request this screen.
*
* Rendering the link in the browser may result in Javascript sending
* additional requests to perform necessary actions or to obtain data
* relevant to the lesson or the element of the lesson selected by the
* user. Thanks to using the hash mark "#" and Javascript handling the
* clicks, the user will experience less waiting as the pages do not have
* to reload entirely.
*
* @return a {@link java.lang.String} object.
*/
public String getLink() {
StringBuffer link = new StringBuffer(getPath());
// mvc update:
return link
.append("/").append(getScreenId())
.append("/").append(getCategory().getRanking()).toString();
}
/**
* Get the link to the target servlet.
*
* Unlike getLink() this method does not require rendering the output of
* the request to the link in order to execute the servlet's method with
* conventional HTTP query parameters.
*
* @return a {@link java.lang.String} object.
*/
public String getServletLink() {
StringBuffer link = new StringBuffer("attack");
return link
.append("?Screen=").append(getScreenId())
.append("&menu=").append(getCategory().getRanking()).toString();
}
/**
* Get the link to the jsp page used to render this screen.
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @return a {@link java.lang.String} object.
*/
public String getPage(WebSession s) {
return null;
}
/**
* Get the link to the jsp template page used to render this screen.
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @return a {@link java.lang.String} object.
*/
public String getTemplatePage(WebSession s) {
return null;
}
/**
* <p>getCurrentAction.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @return a {@link java.lang.String} object.
*/
public abstract String getCurrentAction(WebSession s);
/**
* Initiates lesson restart functionality
*/
public abstract void restartLesson();
/**
* <p>setCurrentAction.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @param lessonScreen a {@link java.lang.String} object.
*/
public abstract void setCurrentAction(WebSession s, String lessonScreen);
/**
* Override this method to implement accesss control in a lesson.
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @param functionId a {@link java.lang.String} object.
* @param employeeId a int.
* @return a boolean.
*/
public boolean isAuthorized(WebSession s, int employeeId, String functionId) {
return false;
}
/**
* Override this method to implement accesss control in a lesson.
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @param functionId a {@link java.lang.String} object.
* @param role a {@link java.lang.String} object.
* @return a boolean.
*/
public boolean isAuthorized(WebSession s, String role, String functionId) {
logger.info("Checking if " + role + " authorized for: " + functionId);
boolean authorized = false;
try {
String query = "SELECT * FROM auth WHERE role = '" + role + "' and functionid = '" + functionId + "'";
try {
Statement answer_statement = WebSession.getConnection(s)
.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet answer_results = answer_statement.executeQuery(query);
authorized = answer_results.first();
logger.info("authorized: " + authorized);
} catch (SQLException sqle) {
s.setMessage("Error authorizing");
logger.error("Error authorizing", sqle);
}
} catch (Exception e) {
s.setMessage("Error authorizing");
logger.error("Error authorizing", e);
}
return authorized;
}
/**
* <p>getUserId.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @return a int.
* @throws org.owasp.webgoat.session.ParameterNotFoundException if any.
*/
public int getUserId(WebSession s) throws ParameterNotFoundException {
return -1;
}
/**
* <p>getUserName.</p>
*
* @param s a {@link org.owasp.webgoat.session.WebSession} object.
* @return a {@link java.lang.String} object.
* @throws org.owasp.webgoat.session.ParameterNotFoundException if any.
*/
public String getUserName(WebSession s) throws ParameterNotFoundException {
return null;
}
/**
* Description of the Method
*
* @param windowName Description of the Parameter
* @return Description of the Return Value
*/
public static String makeWindowScript(String windowName) {
// FIXME: make this string static
StringBuffer script = new StringBuffer();
script.append("<script language=\"JavaScript\">\n");
script.append(" <!--\n");
script.append(" function makeWindow(url) {\n");
script.append("\n");
script.append(" agent = navigator.userAgent;\n");
script.append("\n");
script.append(" params = \"\";\n");
script.append(" params += \"toolbar=0,\";\n");
script.append(" params += \"location=0,\";\n");
script.append(" params += \"directories=0,\";\n");
script.append(" params += \"status=0,\";\n");
script.append(" params += \"menubar=0,\";\n");
script.append(" params += \"scrollbars=1,\";\n");
script.append(" params += \"resizable=1,\";\n");
script.append(" params += \"width=500,\";\n");
script.append(" params += \"height=350\";\n");
script.append("\n");
script.append(" // close the window to vary the window size\n");
script.append(" if (typeof(win) == \"object\" && !win.closed){\n");
script.append(" win.close();\n");
script.append(" }\n");
script.append("\n");
script.append(" win = window.open(url, '" + windowName + "' , params);\n");
script.append("\n");
script.append(" // bring the window to the front\n");
script.append(" win.focus();\n");
script.append(" }\n");
script.append(" //-->\n");
script.append(" </script>\n");
return script.toString();
}
/**
* Simply reads a url into an Element for display. CAUTION: you might want
* to tinker with any non-https links (href)
*
* @param url Description of the Parameter
* @return Description of the Return Value
*/
public static Element readFromURL(String url) {
ElementContainer ec = new ElementContainer();
try {
URL u = new URL(url);
HttpURLConnection huc = (HttpURLConnection) u.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(huc.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
ec.addElement(new StringElement(line));
}
reader.close();
} catch (Exception e) {
System.out.println(e);
e.printStackTrace();
}
return (ec);
}
/**
* Description of the Method
*
* @param reader Description of the Parameter
* @param numbers Description of the Parameter
* @param methodName Description of the Parameter
* @return Description of the Return Value
*/
public static Element readMethodFromFile(BufferedReader reader, String methodName, boolean numbers) {
PRE pre = new PRE().addElement(getFileMethod(reader, methodName, numbers));
return (pre);
}
/**
* Description of the Method
*
* @param s Description of the Parameter
*/
public void handleRequest(WebSession s) {
// call createContent first so messages will go somewhere
Form form = new Form(getFormAction(), Form.POST).setName("form").setEncType("");
form.addElement(createContent(s));
setContent(form);
s.getRequest().getRequestURL();
}
/**
* <p>getFormAction.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getFormAction() {
return getLink();
}
/**
* Description of the Method
*
* @return Description of the Return Value
*/
public String toString() {
return getTitle();
}
/**
* <p>Getter for the field <code>defaultLanguage</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getDefaultLanguage() {
return this.defaultLanguage;
}
/**
* <p>Getter for the field <code>lessonPlanFileName</code>.</p>
*
* @param lang a {@link java.lang.String} object.
* @return a {@link java.lang.String} object.
*/
public String getLessonPlanFileName(String lang) {
String ret = lessonPlanFileName.get(lang);
if (ret == null) {
ret = lessonPlanFileName.get(getDefaultLanguage());
}
return ret;
}
/**
* <p>Setter for the field <code>lessonPlanFileName</code>.</p>
*
* @param lang a {@link java.lang.String} object.
* @param lessonPlanFileName a {@link java.lang.String} object.
*/
public void setLessonPlanFileName(String lang, String lessonPlanFileName) {
this.lessonPlanFileName.put(lang, lessonPlanFileName);
this.availableLanguages.add(lang);
}
/**
* <p>Getter for the field <code>availableLanguages</code>.</p>
*
* @return a {@link java.util.List} object.
*/
public List<String> getAvailableLanguages() {
return this.availableLanguages;
}
/**
* <p>Getter for the field <code>lessonSolutionFileName</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getLessonSolutionFileName() {
return lessonSolutionFileName;
}
/**
* <p>Setter for the field <code>lessonSolutionFileName</code>.</p>
*
* @param lessonSolutionFileName a {@link java.lang.String} object.
*/
public void setLessonSolutionFileName(String lessonSolutionFileName) {
this.lessonSolutionFileName = lessonSolutionFileName;
}
/**
* <p>Getter for the field <code>sourceFileName</code>.</p>
*
* @return a {@link java.lang.String} object.
*/
public String getSourceFileName() {
return sourceFileName;
}
/**
* <p>Setter for the field <code>sourceFileName</code>.</p>
*
* @param sourceFileName a {@link java.lang.String} object.
*/
public void setSourceFileName(String sourceFileName) {
logger.debug("Setting source file of lesson " + this + " to: " + sourceFileName);
this.sourceFileName = sourceFileName;
}
/**
* <p>Getter for the field <code>webgoatContext</code>.</p>
*
* @return a {@link org.owasp.webgoat.session.WebgoatContext} object.
*/
public WebgoatContext getWebgoatContext() {
return webgoatContext;
}
/**
* <p>Setter for the field <code>webgoatContext</code>.</p>
*
* @param webgoatContext a {@link org.owasp.webgoat.session.WebgoatContext} object.
*/
public void setWebgoatContext(WebgoatContext webgoatContext) {
this.webgoatContext = webgoatContext;
}
/**
* <p>Getter for the field <code>labelManager</code>.</p>
*
* @return a {@link org.owasp.webgoat.util.LabelManager} object.
*/
protected LabelManager getLabelManager() {
if (labelManager == null) {
labelManager = BeanProvider.getBean("labelManager", LabelManager.class);
}
return labelManager;
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package freemarker.cache;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import org.junit.Test;
import freemarker.core.TemplateConfigurer;
import freemarker.template.Configuration;
public class TemplateConfigurerFactoryTest {
private Configuration cfg = new Configuration(Configuration.VERSION_2_3_22);
@Test
public void testCondition1() throws IOException, TemplateConfigurerFactoryException {
TemplateConfigurer tc = newTemplateConfigurer(1);
TemplateConfigurerFactory tcf = new ConditionalTemplateConfigurerFactory(new FileNameGlobMatcher("*.ftlx"), tc);
tcf.setConfiguration(cfg);
assertNotApplicable(tcf, "x.ftl");
assertApplicable(tcf, "x.ftlx", tc);
}
@Test
public void testCondition2() throws IOException, TemplateConfigurerFactoryException {
TemplateConfigurer tc = newTemplateConfigurer(1);
TemplateConfigurerFactory tcf = new ConditionalTemplateConfigurerFactory(
new FileNameGlobMatcher("*.ftlx"),
new ConditionalTemplateConfigurerFactory(
new FileNameGlobMatcher("x.*"), tc));
tcf.setConfiguration(cfg);
assertNotApplicable(tcf, "x.ftl");
assertNotApplicable(tcf, "y.ftlx");
assertApplicable(tcf, "x.ftlx", tc);
}
@Test
public void testMerging() throws IOException, TemplateConfigurerFactoryException {
TemplateConfigurer tc1 = newTemplateConfigurer(1);
TemplateConfigurer tc2 = newTemplateConfigurer(2);
TemplateConfigurer tc3 = newTemplateConfigurer(3);
TemplateConfigurerFactory tcf = new MergingTemplateConfigurerFactory(
new ConditionalTemplateConfigurerFactory(new FileNameGlobMatcher("*.ftlx"), tc1),
new ConditionalTemplateConfigurerFactory(new FileNameGlobMatcher("*a*.*"), tc2),
new ConditionalTemplateConfigurerFactory(new FileNameGlobMatcher("*b*.*"), tc3));
tcf.setConfiguration(cfg);
assertNotApplicable(tcf, "x.ftl");
assertApplicable(tcf, "x.ftlx", tc1);
assertApplicable(tcf, "a.ftl", tc2);
assertApplicable(tcf, "b.ftl", tc3);
assertApplicable(tcf, "a.ftlx", tc1, tc2);
assertApplicable(tcf, "b.ftlx", tc1, tc3);
assertApplicable(tcf, "ab.ftl", tc2, tc3);
assertApplicable(tcf, "ab.ftlx", tc1, tc2, tc3);
assertNotApplicable(new MergingTemplateConfigurerFactory(), "x.ftl");
}
@Test
public void testFirstMatch() throws IOException, TemplateConfigurerFactoryException {
TemplateConfigurer tc1 = newTemplateConfigurer(1);
TemplateConfigurer tc2 = newTemplateConfigurer(2);
TemplateConfigurer tc3 = newTemplateConfigurer(3);
FirstMatchTemplateConfigurerFactory tcf = new FirstMatchTemplateConfigurerFactory(
new ConditionalTemplateConfigurerFactory(new FileNameGlobMatcher("*.ftlx"), tc1),
new ConditionalTemplateConfigurerFactory(new FileNameGlobMatcher("*a*.*"), tc2),
new ConditionalTemplateConfigurerFactory(new FileNameGlobMatcher("*b*.*"), tc3));
tcf.setConfiguration(cfg);
try {
assertNotApplicable(tcf, "x.ftl");
} catch (TemplateConfigurerFactoryException e) {
assertThat(e.getMessage(), containsString("x.ftl"));
}
tcf.setNoMatchErrorDetails("Test details");
try {
assertNotApplicable(tcf, "x.ftl");
} catch (TemplateConfigurerFactoryException e) {
assertThat(e.getMessage(), containsString("Test details"));
}
tcf.setAllowNoMatch(true);
assertNotApplicable(tcf, "x.ftl");
assertApplicable(tcf, "x.ftlx", tc1);
assertApplicable(tcf, "a.ftl", tc2);
assertApplicable(tcf, "b.ftl", tc3);
assertApplicable(tcf, "a.ftlx", tc1);
assertApplicable(tcf, "b.ftlx", tc1);
assertApplicable(tcf, "ab.ftl", tc2);
assertApplicable(tcf, "ab.ftlx", tc1);
assertNotApplicable(new FirstMatchTemplateConfigurerFactory().allowNoMatch(true), "x.ftl");
}
@Test
public void testComplex() throws IOException, TemplateConfigurerFactoryException {
TemplateConfigurer tcA = newTemplateConfigurer(1);
TemplateConfigurer tcBSpec = newTemplateConfigurer(2);
TemplateConfigurer tcBCommon = newTemplateConfigurer(3);
TemplateConfigurer tcHH = newTemplateConfigurer(4);
TemplateConfigurer tcHtml = newTemplateConfigurer(5);
TemplateConfigurer tcXml = newTemplateConfigurer(6);
TemplateConfigurer tcNWS = newTemplateConfigurer(7);
TemplateConfigurerFactory tcf = new MergingTemplateConfigurerFactory(
new FirstMatchTemplateConfigurerFactory(
new ConditionalTemplateConfigurerFactory(new PathGlobMatcher("a/**"), tcA),
new ConditionalTemplateConfigurerFactory(new PathGlobMatcher("b/**"),
new MergingTemplateConfigurerFactory(
new ConditionalTemplateConfigurerFactory(new FileNameGlobMatcher("*"), tcBCommon),
new ConditionalTemplateConfigurerFactory(new FileNameGlobMatcher("*.s.*"), tcBSpec))))
.allowNoMatch(true),
new FirstMatchTemplateConfigurerFactory(
new ConditionalTemplateConfigurerFactory(new FileNameGlobMatcher("*.hh"), tcHH),
new ConditionalTemplateConfigurerFactory(new FileNameGlobMatcher("*.*h"), tcHtml),
new ConditionalTemplateConfigurerFactory(new FileNameGlobMatcher("*.*x"), tcXml))
.allowNoMatch(true),
new ConditionalTemplateConfigurerFactory(new FileNameGlobMatcher("*.nws.*"), tcNWS));
tcf.setConfiguration(cfg);
assertNotApplicable(tcf, "x.ftl");
assertApplicable(tcf, "b/x.ftl", tcBCommon);
assertApplicable(tcf, "b/x.s.ftl", tcBCommon, tcBSpec);
assertApplicable(tcf, "b/x.s.ftlh", tcBCommon, tcBSpec, tcHtml);
assertApplicable(tcf, "b/x.s.nws.ftlx", tcBCommon, tcBSpec, tcXml, tcNWS);
assertApplicable(tcf, "a/x.s.nws.ftlx", tcA, tcXml, tcNWS);
assertApplicable(tcf, "a.hh", tcHH);
assertApplicable(tcf, "a.nws.hh", tcHH, tcNWS);
}
@Test
public void testSetConfiguration() {
TemplateConfigurer tc = new TemplateConfigurer();
ConditionalTemplateConfigurerFactory tcf = new ConditionalTemplateConfigurerFactory(new FileNameGlobMatcher("*"), tc);
assertNull(tcf.getConfiguration());
assertNull(tc.getParentConfiguration());
tcf.setConfiguration(cfg);
assertEquals(cfg, tcf.getConfiguration());
assertEquals(cfg, tc.getParentConfiguration());
// Ignored:
tcf.setConfiguration(cfg);
try {
tcf.setConfiguration(Configuration.getDefaultConfiguration());
fail();
} catch (IllegalStateException e) {
assertThat(e.getMessage(), containsString("TemplateConfigurerFactory"));
}
}
@SuppressWarnings("boxing")
private TemplateConfigurer newTemplateConfigurer(int id) {
TemplateConfigurer tc = new TemplateConfigurer();
tc.setCustomAttribute("id", id);
tc.setCustomAttribute("contains" + id, true);
return tc;
}
private void assertNotApplicable(TemplateConfigurerFactory tcf, String sourceName)
throws IOException, TemplateConfigurerFactoryException {
assertNull(tcf.get(sourceName, "dummy"));
}
private void assertApplicable(TemplateConfigurerFactory tcf, String sourceName, TemplateConfigurer... expectedTCs)
throws IOException, TemplateConfigurerFactoryException {
TemplateConfigurer mergedTC = tcf.get(sourceName, "dummy");
assertNotNull("TC should have its parents Configuration set", mergedTC.getParentConfiguration());
List<String> mergedTCAttNames = Arrays.asList(mergedTC.getCustomAttributeNames());
for (TemplateConfigurer expectedTC : expectedTCs) {
Integer tcId = (Integer) expectedTC.getCustomAttribute("id");
if (tcId == null) {
fail("TemplateConfigurer-s must be created with newTemplateConfigurer(id) in this test");
}
if (!mergedTCAttNames.contains("contains" + tcId)) {
fail("TemplateConfigurer with ID " + tcId + " is missing from the asserted value");
}
}
for (String attName: mergedTCAttNames) {
if (!containsCustomAttr(attName, expectedTCs)) {
fail("The asserted TemplateConfigurer contains an unexpected custom attribute: " + attName);
}
}
assertEquals(expectedTCs[expectedTCs.length - 1].getCustomAttribute("id"), mergedTC.getCustomAttribute("id"));
}
private boolean containsCustomAttr(String attName, TemplateConfigurer... expectedTCs) {
for (TemplateConfigurer expectedTC : expectedTCs) {
if (expectedTC.getCustomAttribute(attName) != null) {
return true;
}
}
return false;
}
}
| |
package org.sagebionetworks.repo.model;
import org.sagebionetworks.schema.adapter.JSONEntity;
import org.sagebionetworks.schema.adapter.JSONObjectAdapter;
import org.sagebionetworks.schema.adapter.JSONObjectAdapterException;
/**
* Low-level bundle to transport an Entity and related data objects between the
* Synapse platform and external clients.
*
* This bundle should be used for the creation of Entities; it only includes the
* entity and its annotations and ACL.
*
* @author bkng
*
*/
public class EntityBundleCreate implements JSONEntity {
private static final String JSON_ENTITY = EntityBundle.JSON_ENTITY;
private static final String JSON_ENTITY_TYPE = EntityBundle.JSON_ENTITY_TYPE;
private static final String JSON_ANNOTATIONS = EntityBundle.JSON_ANNOTATIONS;
private static final String JSON_ACL = EntityBundle.JSON_ACL;
private static final String JSON_ACCESS_REQUIREMENT = EntityBundle.JSON_ACCESS_REQUIREMENTS;
private Entity entity;
private String entityType;
private Annotations annotations;
private AccessControlList acl;
private AccessRequirement accessRequirement;
public AccessRequirement getAccessRequirement() {
return accessRequirement;
}
public void setAccessRequirement(AccessRequirement accessRequirement) {
this.accessRequirement = accessRequirement;
}
/**
* Create a new EntityBundle
*/
public EntityBundleCreate() {}
/**
* Create a new EntityBundle and initialize from a JSONObjectAdapter.
*
* @param initializeFrom
* @throws JSONObjectAdapterException
*/
public EntityBundleCreate(JSONObjectAdapter initializeFrom) throws JSONObjectAdapterException {
this();
initializeFromJSONObject(initializeFrom);
}
@Override
public JSONObjectAdapter initializeFromJSONObject(
JSONObjectAdapter toInitFrom) throws JSONObjectAdapterException {
if (toInitFrom == null) {
throw new IllegalArgumentException("org.sagebionetworks.schema.adapter.JSONObjectAdapter cannot be null");
}
if (toInitFrom.has(JSON_ENTITY)) {
entityType = toInitFrom.getString(JSON_ENTITY_TYPE);
JSONObjectAdapter joa = (JSONObjectAdapter) toInitFrom.getJSONObject(JSON_ENTITY);
entity = (Entity) EntityInstanceFactory.singleton().newInstance(entityType);
entity.initializeFromJSONObject(joa);
}
if (toInitFrom.has(JSON_ANNOTATIONS)) {
JSONObjectAdapter joa = (JSONObjectAdapter) toInitFrom.getJSONObject(JSON_ANNOTATIONS);
if (annotations == null)
annotations = new Annotations();
annotations.initializeFromJSONObject(joa);
}
if (toInitFrom.has(JSON_ACL)) {
JSONObjectAdapter joa = (JSONObjectAdapter) toInitFrom.getJSONObject(JSON_ACL);
if (acl == null)
acl = new AccessControlList();
acl.initializeFromJSONObject(joa);
}
if (toInitFrom.has(JSON_ACCESS_REQUIREMENT)) {
JSONObjectAdapter joa = (JSONObjectAdapter) toInitFrom.getJSONObject(JSON_ACCESS_REQUIREMENT);
String contentType = joa.getString("concreteType");
accessRequirement = AccessRequirementInstanceFactory.singleton().newInstance(contentType);
}
return toInitFrom;
}
@Override
public JSONObjectAdapter writeToJSONObject(JSONObjectAdapter writeTo)
throws JSONObjectAdapterException {
if (writeTo == null) {
throw new IllegalArgumentException("JSONObjectAdapter cannot be null");
}
if (entity != null) {
JSONObjectAdapter joa = writeTo.createNew();
entity.writeToJSONObject(joa);
writeTo.put(JSON_ENTITY, joa);
writeTo.put(JSON_ENTITY_TYPE, entityType);
}
if (annotations != null) {
JSONObjectAdapter joa = writeTo.createNew();
annotations.writeToJSONObject(joa);
writeTo.put(JSON_ANNOTATIONS, joa);
}
if (acl != null) {
JSONObjectAdapter joa = writeTo.createNew();
acl.writeToJSONObject(joa);
writeTo.put(JSON_ACL, joa);
}
if (accessRequirement!=null) {
JSONObjectAdapter joa = writeTo.createNew();
accessRequirement.writeToJSONObject(joa);
writeTo.put(JSON_ACCESS_REQUIREMENT, joa);
}
return writeTo;
}
/**
* Get the Entity in this bundle.
*/
public Entity getEntity() {
return entity;
}
/**
* Set the Entity in this bundle.
*/
public void setEntity(Entity entity) {
this.entity = entity;
String s = entity.getClass().toString();
// trim "Class " from the above String
entityType = s.substring(s.lastIndexOf(" ") + 1);
}
/**
* Get the Annotations for the Entity in this bundle.
*/
public Annotations getAnnotations() {
return annotations;
}
/**
* Set the Annotations for this bundle. Should correspond to the Entity in
* the bundle.
*/
public void setAnnotations(Annotations annotations) {
this.annotations = annotations;
}
/**
* Get the AccessControlList for the Entity in this bundle.
*/
public AccessControlList getAccessControlList() {
return acl;
}
/**
* Set the AccessControlList for this bundle. Should correspond to the
* Entity in this bundle.
*/
public void setAccessControlList(AccessControlList acl) {
this.acl = acl;
}
@Override
public String toString() {
return "EntityBundleCreate [entity=" + entity + ", entityType="
+ entityType + ", annotations=" + annotations + ", acl=" + acl
+ ", accessRequirement=" + accessRequirement + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime
* result
+ ((accessRequirement == null) ? 0 : accessRequirement
.hashCode());
result = prime * result + ((acl == null) ? 0 : acl.hashCode());
result = prime * result
+ ((annotations == null) ? 0 : annotations.hashCode());
result = prime * result + ((entity == null) ? 0 : entity.hashCode());
result = prime * result
+ ((entityType == null) ? 0 : entityType.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
EntityBundleCreate other = (EntityBundleCreate) obj;
if (accessRequirement == null) {
if (other.accessRequirement != null)
return false;
} else if (!accessRequirement.equals(other.accessRequirement))
return false;
if (acl == null) {
if (other.acl != null)
return false;
} else if (!acl.equals(other.acl))
return false;
if (annotations == null) {
if (other.annotations != null)
return false;
} else if (!annotations.equals(other.annotations))
return false;
if (entity == null) {
if (other.entity != null)
return false;
} else if (!entity.equals(other.entity))
return false;
if (entityType == null) {
if (other.entityType != null)
return false;
} else if (!entityType.equals(other.entityType))
return false;
return true;
}
}
| |
package org.robolectric.shadows;
import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException;
import android.content.Intent;
import android.location.Criteria;
import android.location.GpsStatus.Listener;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Looper;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Shadow for {@link android.location.LocationManager}.
*/
@Implements(LocationManager.class)
public class ShadowLocationManager {
private final Map<String, LocationProviderEntry> providersEnabled = new LinkedHashMap<>();
private final Map<String, Location> lastKnownLocations = new HashMap<>();
private final Map<PendingIntent, Criteria> requestLocationUdpateCriteriaPendingIntents = new HashMap<>();
private final Map<PendingIntent, String> requestLocationUdpateProviderPendingIntents = new HashMap<>();
private final ArrayList<LocationListener> removedLocationListeners = new ArrayList<>();
private final ArrayList<Listener> gpsStatusListeners = new ArrayList<>();
private Criteria lastBestProviderCriteria;
private boolean lastBestProviderEnabled;
private String bestEnabledProvider, bestDisabledProvider;
/** Location listeners along with metadata on when they should be fired. */
private static final class ListenerRegistration {
final long minTime;
final float minDistance;
final LocationListener listener;
final String provider;
Location lastSeenLocation;
long lastSeenTime;
ListenerRegistration(String provider, long minTime, float minDistance, Location locationAtCreation,
LocationListener listener) {
this.provider = provider;
this.minTime = minTime;
this.minDistance = minDistance;
this.lastSeenTime = locationAtCreation == null ? 0 : locationAtCreation.getTime();
this.lastSeenLocation = locationAtCreation;
this.listener = listener;
}
}
/** Mapped by provider. */
private final Map<String, List<ListenerRegistration>> locationListeners =
new HashMap<>();
@Implementation
public boolean isProviderEnabled(String provider) {
LocationProviderEntry map = providersEnabled.get(provider);
if (map != null) {
Boolean isEnabled = map.getKey();
return isEnabled == null ? true : isEnabled;
}
return false;
}
@Implementation
public List<String> getAllProviders() {
Set<String> allKnownProviders = new LinkedHashSet<>(providersEnabled.keySet());
allKnownProviders.add(LocationManager.GPS_PROVIDER);
allKnownProviders.add(LocationManager.NETWORK_PROVIDER);
allKnownProviders.add(LocationManager.PASSIVE_PROVIDER);
return new ArrayList<>(allKnownProviders);
}
/**
* Sets the value to return from {@link #isProviderEnabled(String)} for the given {@code provider}
*
* @param provider
* name of the provider whose status to set
* @param isEnabled
* whether that provider should appear enabled
*/
public void setProviderEnabled(String provider, boolean isEnabled) {
setProviderEnabled(provider, isEnabled, null);
}
public void setProviderEnabled(String provider, boolean isEnabled, List<Criteria> criteria) {
LocationProviderEntry providerEntry = providersEnabled.get(provider);
if (providerEntry == null) {
providerEntry = new LocationProviderEntry();
}
providerEntry.enabled = isEnabled;
providerEntry.criteria = criteria;
providersEnabled.put(provider, providerEntry);
List<LocationListener> locationUpdateListeners = new ArrayList<>(getRequestLocationUpdateListeners());
for (LocationListener locationUpdateListener : locationUpdateListeners) {
if (isEnabled) {
locationUpdateListener.onProviderEnabled(provider);
} else {
locationUpdateListener.onProviderDisabled(provider);
}
}
// Send intent to notify about provider status
final Intent intent = new Intent();
intent.putExtra(LocationManager.KEY_PROVIDER_ENABLED, isEnabled);
ShadowApplication.getInstance().sendBroadcast(intent);
Set<PendingIntent> requestLocationUdpatePendingIntentSet = requestLocationUdpateCriteriaPendingIntents
.keySet();
for (PendingIntent requestLocationUdpatePendingIntent : requestLocationUdpatePendingIntentSet) {
try {
requestLocationUdpatePendingIntent.send();
} catch (CanceledException e) {
requestLocationUdpateCriteriaPendingIntents
.remove(requestLocationUdpatePendingIntent);
}
}
// if this provider gets disabled and it was the best active provider, then it's not anymore
if (provider.equals(bestEnabledProvider) && !isEnabled) {
bestEnabledProvider = null;
}
}
@Implementation
public List<String> getProviders(boolean enabledOnly) {
ArrayList<String> enabledProviders = new ArrayList<>();
for (String provider : getAllProviders()) {
if (!enabledOnly || providersEnabled.get(provider) != null) {
enabledProviders.add(provider);
}
}
return enabledProviders;
}
@Implementation
public Location getLastKnownLocation(String provider) {
return lastKnownLocations.get(provider);
}
@Implementation
public boolean addGpsStatusListener(Listener listener) {
if (!gpsStatusListeners.contains(listener)) {
gpsStatusListeners.add(listener);
}
return true;
}
@Implementation
public void removeGpsStatusListener(Listener listener) {
gpsStatusListeners.remove(listener);
}
@Implementation
public String getBestProvider(Criteria criteria, boolean enabled) {
lastBestProviderCriteria = criteria;
lastBestProviderEnabled = enabled;
if (criteria == null) {
return getBestProviderWithNoCriteria(enabled);
}
return getBestProviderWithCriteria(criteria, enabled);
}
private String getBestProviderWithCriteria(Criteria criteria, boolean enabled) {
List<String> providers = getProviders(enabled);
int powerRequirement = criteria.getPowerRequirement();
int accuracy = criteria.getAccuracy();
for (String provider : providers) {
LocationProviderEntry locationProviderEntry = providersEnabled.get(provider);
if (locationProviderEntry == null) {
continue;
}
List<Criteria> criteriaList = locationProviderEntry.getValue();
if (criteriaList == null) {
continue;
}
for (Criteria criteriaListItem : criteriaList) {
if (criteria.equals(criteriaListItem)) {
return provider;
} else if (criteriaListItem.getAccuracy() == accuracy) {
return provider;
} else if (criteriaListItem.getPowerRequirement() == powerRequirement) {
return provider;
}
}
}
// TODO: these conditions are incomplete
for (String provider : providers) {
if (provider.equals(LocationManager.NETWORK_PROVIDER) && (accuracy == Criteria.ACCURACY_COARSE || powerRequirement == Criteria.POWER_LOW)) {
return provider;
} else if (provider.equals(LocationManager.GPS_PROVIDER) && accuracy == Criteria.ACCURACY_FINE && powerRequirement != Criteria.POWER_LOW) {
return provider;
}
}
// No enabled provider found with the desired criteria, then return the the first registered provider(?)
return providers.isEmpty()? null : providers.get(0);
}
private String getBestProviderWithNoCriteria(boolean enabled) {
List<String> providers = getProviders(enabled);
if (enabled && bestEnabledProvider != null) {
return bestEnabledProvider;
} else if (bestDisabledProvider != null) {
return bestDisabledProvider;
} else if (providers.contains(LocationManager.GPS_PROVIDER)) {
return LocationManager.GPS_PROVIDER;
} else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
return LocationManager.NETWORK_PROVIDER;
}
return null;
}
@Implementation
public void requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener) {
addLocationListener(provider, listener, minTime, minDistance);
}
private void addLocationListener(String provider, LocationListener listener, long minTime, float minDistance) {
List<ListenerRegistration> providerListeners = locationListeners.get(provider);
if (providerListeners == null) {
providerListeners = new ArrayList<>();
locationListeners.put(provider, providerListeners);
}
providerListeners.add(new ListenerRegistration(provider,
minTime, minDistance, copyOf(getLastKnownLocation(provider)), listener));
}
@Implementation
public void requestLocationUpdates(String provider, long minTime, float minDistance, LocationListener listener,
Looper looper) {
addLocationListener(provider, listener, minTime, minDistance);
}
@Implementation
public void requestLocationUpdates(long minTime, float minDistance, Criteria criteria, PendingIntent pendingIntent) {
if (pendingIntent == null) {
throw new IllegalStateException("Intent must not be null");
}
if (getBestProvider(criteria, true) == null) {
throw new IllegalArgumentException("no providers found for criteria");
}
requestLocationUdpateCriteriaPendingIntents.put(pendingIntent, criteria);
}
@Implementation
public void requestLocationUpdates(String provider, long minTime, float minDistance,
PendingIntent pendingIntent) {
if (pendingIntent == null) {
throw new IllegalStateException("Intent must not be null");
}
if (!providersEnabled.containsKey(provider)) {
throw new IllegalArgumentException("no providers found");
}
requestLocationUdpateProviderPendingIntents.put(pendingIntent, provider);
}
@Implementation
public void removeUpdates(LocationListener listener) {
removedLocationListeners.add(listener);
}
private void cleanupRemovedLocationListeners() {
for (Map.Entry<String, List<ListenerRegistration>> entry : locationListeners.entrySet()) {
List<ListenerRegistration> listenerRegistrations = entry.getValue();
for (int i = listenerRegistrations.size() - 1; i >= 0; i--) {
LocationListener listener = listenerRegistrations.get(i).listener;
if(removedLocationListeners.contains(listener)) {
listenerRegistrations.remove(i);
}
}
}
}
@Implementation
public void removeUpdates(PendingIntent pendingIntent) {
while (requestLocationUdpateCriteriaPendingIntents.remove(pendingIntent) != null);
while (requestLocationUdpateProviderPendingIntents.remove(pendingIntent) != null);
}
public boolean hasGpsStatusListener(Listener listener) {
return gpsStatusListeners.contains(listener);
}
/**
* Non-Android accessor.
*
* <p>
* Gets the criteria value used in the last call to {@link #getBestProvider(android.location.Criteria, boolean)}
*
* @return the criteria used to find the best provider
*/
public Criteria getLastBestProviderCriteria() {
return lastBestProviderCriteria;
}
/**
* Non-Android accessor.
*
* <p>
* Gets the enabled value used in the last call to {@link #getBestProvider(android.location.Criteria, boolean)}
*
* @return the enabled value used to find the best provider
*/
public boolean getLastBestProviderEnabledOnly() {
return lastBestProviderEnabled;
}
/**
* Sets the value to return from {@link #getBestProvider(android.location.Criteria, boolean)} for the given
* {@code provider}
*
* @param provider name of the provider who should be considered best
* @param enabled Enabled
* @param criteria List of criteria
* @throws Exception if provider is not known
* @return false If provider is not enabled but it is supposed to be set as the best enabled provider don't set it, otherwise true
*/
public boolean setBestProvider(String provider, boolean enabled, List<Criteria> criteria) throws Exception {
if (!getAllProviders().contains(provider)) {
throw new IllegalStateException("Best provider is not a known provider");
}
// If provider is not enabled but it is supposed to be set as the best enabled provider don't set it.
for (String prvdr : providersEnabled.keySet()) {
if (provider.equals(prvdr) && providersEnabled.get(prvdr).enabled != enabled) {
return false;
}
}
if (enabled) {
bestEnabledProvider = provider;
if (provider.equals(bestDisabledProvider)) {
bestDisabledProvider = null;
}
} else {
bestDisabledProvider = provider;
if (provider.equals(bestEnabledProvider)) {
bestEnabledProvider = null;
}
}
if (criteria == null) {
return true;
}
LocationProviderEntry entry;
if (!providersEnabled.containsKey(provider)) {
entry = new LocationProviderEntry();
entry.enabled = enabled;
entry.criteria = criteria;
} else {
entry = providersEnabled.get(provider);
}
providersEnabled.put(provider, entry);
return true;
}
public boolean setBestProvider(String provider, boolean enabled) throws Exception {
return setBestProvider(provider, enabled, null);
}
/**
* Sets the value to return from {@link #getLastKnownLocation(String)} for the given {@code provider}
*
* @param provider
* name of the provider whose location to set
* @param location
* the last known location for the provider
*/
public void setLastKnownLocation(String provider, Location location) {
lastKnownLocations.put(provider, location);
}
/**
* Non-Android accessor.
*
* @return lastRequestedLocationUpdatesLocationListener
*/
public List<LocationListener> getRequestLocationUpdateListeners() {
cleanupRemovedLocationListeners();
List<LocationListener> all = new ArrayList<>();
for (Map.Entry<String, List<ListenerRegistration>> entry : locationListeners.entrySet()) {
for (ListenerRegistration reg : entry.getValue()) {
all.add(reg.listener);
}
}
return all;
}
public void simulateLocation(Location location) {
cleanupRemovedLocationListeners();
setLastKnownLocation(location.getProvider(), location);
List<ListenerRegistration> providerListeners = locationListeners.get(
location.getProvider());
if (providerListeners == null) return;
for (ListenerRegistration listenerReg : providerListeners) {
if(listenerReg.lastSeenLocation != null && location != null) {
float distanceChange = distanceBetween(location, listenerReg.lastSeenLocation);
boolean withinMinDistance = distanceChange < listenerReg.minDistance;
boolean exceededMinTime = location.getTime() - listenerReg.lastSeenTime > listenerReg.minTime;
if (withinMinDistance || !exceededMinTime) continue;
}
listenerReg.lastSeenLocation = copyOf(location);
listenerReg.lastSeenTime = location == null ? 0 : location.getTime();
listenerReg.listener.onLocationChanged(copyOf(location));
}
cleanupRemovedLocationListeners();
}
private Location copyOf(Location location) {
if (location == null) return null;
Location copy = new Location(location);
copy.setAccuracy(location.getAccuracy());
copy.setAltitude(location.getAltitude());
copy.setBearing(location.getBearing());
copy.setExtras(location.getExtras());
copy.setLatitude(location.getLatitude());
copy.setLongitude(location.getLongitude());
copy.setProvider(location.getProvider());
copy.setSpeed(location.getSpeed());
copy.setTime(location.getTime());
return copy;
}
/**
* Returns the distance between the two locations in meters.
* Adapted from: http://stackoverflow.com/questions/837872/calculate-distance-in-meters-when-you-know-longitude-and-latitude-in-java
*/
private static float distanceBetween(Location location1, Location location2) {
double earthRadius = 3958.75;
double latDifference = Math.toRadians(location2.getLatitude() - location1.getLatitude());
double lonDifference = Math.toRadians(location2.getLongitude() - location2.getLongitude());
double a = Math.sin(latDifference/2) * Math.sin(latDifference/2) +
Math.cos(Math.toRadians(location1.getLatitude())) * Math.cos(Math.toRadians(location2.getLatitude())) *
Math.sin(lonDifference/2) * Math.sin(lonDifference/2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
double dist = Math.abs(earthRadius * c);
int meterConversion = 1609;
return new Float(dist * meterConversion);
}
public Map<PendingIntent, Criteria> getRequestLocationUdpateCriteriaPendingIntents() {
return requestLocationUdpateCriteriaPendingIntents;
}
public Map<PendingIntent, String> getRequestLocationUdpateProviderPendingIntents() {
return requestLocationUdpateProviderPendingIntents;
}
public Collection<String> getProvidersForListener(LocationListener listener) {
cleanupRemovedLocationListeners();
Set<String> providers = new HashSet<>();
for (List<ListenerRegistration> listenerRegistrations : locationListeners.values()) {
for (ListenerRegistration listenerRegistration : listenerRegistrations) {
if (listenerRegistration.listener == listener) {
providers.add(listenerRegistration.provider);
}
}
}
return providers;
}
final private class LocationProviderEntry implements Map.Entry<Boolean, List<Criteria>> {
private Boolean enabled;
private List<Criteria> criteria;
@Override
public Boolean getKey() {
return enabled;
}
@Override
public List<Criteria> getValue() {
return criteria;
}
@Override
public List<Criteria> setValue(List<Criteria> criteria) {
List<Criteria> oldCriteria = this.criteria;
this.criteria = criteria;
return oldCriteria;
}
}
}
| |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.cloud;
import java.lang.invoke.MethodHandles;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.math3.primes.Primes;
import org.apache.lucene.util.LuceneTestCase.Slow;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.request.UpdateRequest;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.cloud.ClusterState;
import org.apache.solr.common.cloud.Replica;
import org.apache.solr.common.cloud.Slice;
import org.apache.solr.common.cloud.ZkStateReader;
import org.apache.solr.common.params.ModifiableSolrParams;
import org.apache.solr.common.util.NamedList;
import org.apache.zookeeper.KeeperException;
import org.junit.BeforeClass;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Slow
public class TestStressInPlaceUpdates extends AbstractFullDistribZkTestBase {
private static final Logger log = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());
@BeforeClass
public static void beforeSuperClass() throws Exception {
schemaString = "schema-inplace-updates.xml";
configString = "solrconfig-tlog.xml";
// sanity check that autocommits are disabled
initCore(configString, schemaString);
assertEquals(-1, h.getCore().getSolrConfig().getUpdateHandlerInfo().autoCommmitMaxTime);
assertEquals(-1, h.getCore().getSolrConfig().getUpdateHandlerInfo().autoSoftCommmitMaxTime);
assertEquals(-1, h.getCore().getSolrConfig().getUpdateHandlerInfo().autoCommmitMaxDocs);
assertEquals(-1, h.getCore().getSolrConfig().getUpdateHandlerInfo().autoSoftCommmitMaxDocs);
}
public TestStressInPlaceUpdates() {
super();
sliceCount = 1;
fixShardCount(3);
}
protected final ConcurrentHashMap<Integer, DocInfo> model = new ConcurrentHashMap<>();
protected Map<Integer, DocInfo> committedModel = new HashMap<>();
protected long snapshotCount;
protected long committedModelClock;
protected int clientIndexUsedForCommit;
protected volatile int lastId;
protected final String field = "val_l";
private void initModel(int ndocs) {
for (int i = 0; i < ndocs; i++) {
// seed versions w/-1 so "from scratch" adds/updates will fail optimistic concurrency checks
// if some other thread beats us to adding the id
model.put(i, new DocInfo(-1L, 0, 0));
}
committedModel.putAll(model);
}
SolrClient leaderClient = null;
@Test
@ShardsFixed(num = 3)
public void stressTest() throws Exception {
waitForRecoveriesToFinish(true);
this.leaderClient = getClientForLeader();
assertNotNull("Couldn't obtain client for the leader of the shard", this.leaderClient);
final int commitPercent = 5 + random().nextInt(20);
final int softCommitPercent = 30 + random().nextInt(75); // what percent of the commits are soft
final int deletePercent = 4 + random().nextInt(25);
final int deleteByQueryPercent = random().nextInt(8);
final int ndocs = atLeast(5);
int nWriteThreads = 5 + random().nextInt(12);
int fullUpdatePercent = 5 + random().nextInt(50);
// query variables
final int percentRealtimeQuery = 75;
// number of cumulative read/write operations by all threads
final AtomicLong operations = new AtomicLong(5000);
int nReadThreads = 5 + random().nextInt(12);
// testing
// final int commitPercent = 5;
// final int softCommitPercent = 100; // what percent of the commits are soft
// final int deletePercent = 0;
// final int deleteByQueryPercent = 50;
// final int ndocs = 10;
// int nWriteThreads = 10;
//
// final int maxConcurrentCommits = nWriteThreads; // number of committers at a time... it
// should be <= maxWarmingSearchers
//
// query variables
// final int percentRealtimeQuery = 101;
// final AtomicLong operations = new AtomicLong(50000); // number of query operations to
// perform in total
// int nReadThreads = 10;
//
// int fullUpdatePercent = 20;
if (log.isInfoEnabled()) {
log.info(
"{}",
Arrays.asList(
"commitPercent",
commitPercent,
"softCommitPercent",
softCommitPercent,
"deletePercent",
deletePercent,
"deleteByQueryPercent",
deleteByQueryPercent,
"ndocs",
ndocs,
"nWriteThreads",
nWriteThreads,
"percentRealtimeQuery",
percentRealtimeQuery,
"operations",
operations,
"nReadThreads",
nReadThreads));
}
initModel(ndocs);
List<Thread> threads = new ArrayList<>();
for (int i = 0; i < nWriteThreads; i++) {
Thread thread =
new Thread("WRITER" + i) {
Random rand = new Random(random().nextInt());
@Override
public void run() {
try {
while (operations.decrementAndGet() > 0) {
int oper = rand.nextInt(50);
if (oper < commitPercent) {
Map<Integer, DocInfo> newCommittedModel;
long version;
synchronized (TestStressInPlaceUpdates.this) {
// take a snapshot of the model
// this is safe to do w/o synchronizing on the model because it's a
// ConcurrentHashMap
newCommittedModel = new HashMap<>(model);
version = snapshotCount++;
int chosenClientIndex = rand.nextInt(clients.size());
if (rand.nextInt(100) < softCommitPercent) {
log.info("softCommit start");
clients.get(chosenClientIndex).commit(true, true, true);
log.info("softCommit end");
} else {
log.info("hardCommit start");
clients.get(chosenClientIndex).commit();
log.info("hardCommit end");
}
// install this model snapshot only if it's newer than the current one
if (version >= committedModelClock) {
if (VERBOSE) {
log.info("installing new committedModel version={}", committedModelClock);
}
clientIndexUsedForCommit = chosenClientIndex;
committedModel = newCommittedModel;
committedModelClock = version;
}
}
continue;
}
int id;
if (rand.nextBoolean()) {
id = rand.nextInt(ndocs);
} else {
id = lastId; // reuse the last ID half of the time to force more race conditions
}
// set the lastId before we actually change it sometimes to try and
// uncover more race conditions between writing and reading
boolean before = rand.nextBoolean();
if (before) {
lastId = id;
}
DocInfo info = model.get(id);
// yield after getting the next version to increase the odds of updates happening
// out of order
if (rand.nextBoolean()) Thread.yield();
if (oper < commitPercent + deletePercent + deleteByQueryPercent) {
final boolean dbq = (oper >= commitPercent + deletePercent);
final String delType = dbq ? "DBI" : "DBQ";
log.info("{} id {}: {}", delType, id, info);
Long returnedVersion = null;
try {
returnedVersion =
deleteDocAndGetVersion(
Integer.toString(id),
params("_version_", Long.toString(info.version)),
dbq);
log.info(
"{}: Deleting id={}, version={}. Returned version={}",
delType,
id,
info.version,
returnedVersion);
} catch (RuntimeException e) {
if (e.getMessage() != null && e.getMessage().contains("version conflict")
|| e.getMessage() != null && e.getMessage().contains("Conflict")) {
// Its okay for a leader to reject a concurrent request
log.warn("Conflict during {}, rejected id={}, {}", delType, id, e);
returnedVersion = null;
} else {
throw e;
}
}
// only update model if update had no conflict & the version is newer
synchronized (model) {
DocInfo currInfo = model.get(id);
if (null != returnedVersion
&& (Math.abs(returnedVersion.longValue()) > Math.abs(currInfo.version))) {
model.put(id, new DocInfo(returnedVersion.longValue(), 0, 0));
}
}
} else {
int val1 = info.intFieldValue;
long val2 = info.longFieldValue;
int nextVal1 = val1;
long nextVal2 = val2;
int addOper = rand.nextInt(30);
Long returnedVersion;
// if document was never indexed or was deleted FULL UPDATE
if (addOper < fullUpdatePercent || info.version <= 0) {
nextVal1 = Primes.nextPrime(val1 + 1);
nextVal2 = nextVal1 * 1000000000l;
try {
returnedVersion =
addDocAndGetVersion(
"id",
id,
"title_s",
"title" + id,
"val1_i_dvo",
nextVal1,
"val2_l_dvo",
nextVal2,
"_version_",
info.version);
log.info(
"FULL: Writing id={}, val=[{},{}], version={}, Prev was=[{},{}]. Returned version={}",
id,
nextVal1,
nextVal2,
info.version,
val1,
val2,
returnedVersion);
} catch (RuntimeException e) {
if (e.getMessage() != null && e.getMessage().contains("version conflict")
|| e.getMessage() != null && e.getMessage().contains("Conflict")) {
// Its okay for a leader to reject a concurrent request
log.warn("Conflict during full update, rejected id={}, {}", id, e);
returnedVersion = null;
} else {
throw e;
}
}
} else {
// PARTIAL
nextVal2 = val2 + val1;
try {
returnedVersion =
addDocAndGetVersion(
"id",
id,
"val2_l_dvo",
map("inc", String.valueOf(val1)),
"_version_",
info.version);
log.info(
"PARTIAL: Writing id={}, val=[{},{}], version={}, Prev was=[{},{}]. Returned version={}",
id,
nextVal1,
nextVal2,
info.version,
val1,
val2,
returnedVersion);
} catch (RuntimeException e) {
if (e.getMessage() != null && e.getMessage().contains("version conflict")
|| e.getMessage() != null && e.getMessage().contains("Conflict")) {
// Its okay for a leader to reject a concurrent request
log.warn("Conflict during partial update, rejected id={}, {}", id, e);
} else if (e.getMessage() != null
&& e.getMessage().contains("Document not found for update.")
&& e.getMessage().contains("id=" + id)) {
log.warn(
"Attempted a partial update for a recently deleted document, rejected id={}, {}",
id,
e);
} else {
throw e;
}
returnedVersion = null;
}
}
// only update model if update had no conflict & the version is newer
synchronized (model) {
DocInfo currInfo = model.get(id);
if (null != returnedVersion
&& (Math.abs(returnedVersion.longValue()) > Math.abs(currInfo.version))) {
model.put(id, new DocInfo(returnedVersion.longValue(), nextVal1, nextVal2));
}
}
}
if (!before) {
lastId = id;
}
}
} catch (Throwable e) {
operations.set(-1L);
log.error("", e);
throw new RuntimeException(e);
}
}
};
threads.add(thread);
}
// Read threads
for (int i = 0; i < nReadThreads; i++) {
Thread thread =
new Thread("READER" + i) {
Random rand = new Random(random().nextInt());
@Override
public void run() {
try {
while (operations.decrementAndGet() >= 0) {
// bias toward a recently changed doc
int id = rand.nextInt(100) < 25 ? lastId : rand.nextInt(ndocs);
// when indexing, we update the index, then the model
// so when querying, we should first check the model, and then the index
boolean realTime = rand.nextInt(100) < percentRealtimeQuery;
DocInfo expected;
if (realTime) {
expected = model.get(id);
} else {
synchronized (TestStressInPlaceUpdates.this) {
expected = committedModel.get(id);
}
}
if (VERBOSE) {
log.info("querying id {}", id);
}
ModifiableSolrParams params = new ModifiableSolrParams();
if (realTime) {
params.set("wt", "json");
params.set("qt", "/get");
params.set("ids", Integer.toString(id));
} else {
params.set("wt", "json");
params.set("q", "id:" + Integer.toString(id));
params.set("omitHeader", "true");
}
int clientId = rand.nextInt(clients.size());
if (!realTime) clientId = clientIndexUsedForCommit;
QueryResponse response = clients.get(clientId).query(params);
if (response.getResults().size() == 0) {
// there's no info we can get back with a delete, so not much we can check
// without further synchronization
} else if (response.getResults().size() == 1) {
final SolrDocument actual = response.getResults().get(0);
final String msg =
"Realtime=" + realTime + ", expected=" + expected + ", actual=" + actual;
assertNotNull(msg, actual);
final Long foundVersion = (Long) actual.getFieldValue("_version_");
assertNotNull(msg, foundVersion);
assertTrue(
msg + "... solr doc has non-positive version???",
0 < foundVersion.longValue());
final Integer intVal = (Integer) actual.getFieldValue("val1_i_dvo");
assertNotNull(msg, intVal);
final Long longVal = (Long) actual.getFieldValue("val2_l_dvo");
assertNotNull(msg, longVal);
assertTrue(
msg
+ " ...solr returned older version then model. "
+ "should not be possible given the order of operations in writer threads",
Math.abs(expected.version) <= foundVersion.longValue());
if (foundVersion.longValue() == expected.version) {
assertEquals(msg, expected.intFieldValue, intVal.intValue());
assertEquals(msg, expected.longFieldValue, longVal.longValue());
}
// Some things we can assert about any Doc returned from solr,
// even if it's newer then our (expected) model information...
assertTrue(
msg + " ...how did a doc in solr get a non positive intVal?", 0 < intVal);
assertTrue(
msg + " ...how did a doc in solr get a non positive longVal?", 0 < longVal);
assertEquals(
msg
+ " ...intVal and longVal in solr doc are internally (modulo) inconsistent w/eachother",
0,
(longVal % intVal));
// NOTE: when foundVersion is greater then the version read from the model, it's
// not possible to make any assertions about the field values in solr relative
// to the field values in the model -- ie: we can *NOT* assert
// expected.longFieldVal <= doc.longVal
//
// it's tempting to think that this would be possible if we changed our model to
// preserve the "old" valuess when doing a delete, but that's still no garuntee
// because of how oportunistic concurrency works with negative versions: When
// adding a doc, we can assert that it must not exist with version<0, but we
// can't assert that the *reason* it doesn't exist was because of a delete with
// the specific version of "-42". So a wrtier thread might (1) prep to add a doc
// for the first time with "intValue=1,_version_=-1", and that add may succeed
// and (2) return some version X which is put in the model. but inbetween #1
// and #2 other threads may have added & deleted the doc repeatedly, updating
// the model with intValue=7,_version_=-42, and a reader thread might meanwhile
// read from the model before #2 and expect intValue=5, but get intValue=1 from
// solr (with a greater version)
} else {
fail(
String.format(
Locale.ENGLISH, "There were more than one result: {}", response));
}
}
} catch (Throwable e) {
operations.set(-1L);
log.error("", e);
throw new RuntimeException(e);
}
}
};
threads.add(thread);
}
// Start all threads
for (Thread thread : threads) {
thread.start();
}
for (Thread thread : threads) {
thread.join();
}
{ // final pass over uncommitted model with RTG
for (SolrClient client : clients) {
for (Map.Entry<Integer, DocInfo> entry : model.entrySet()) {
final Integer id = entry.getKey();
final DocInfo expected = entry.getValue();
final SolrDocument actual = client.getById(id.toString());
String msg = "RTG: " + id + "=" + expected;
if (null == actual) {
// a deleted or non-existent document
// sanity check of the model agrees...
assertTrue(
msg + " is deleted/non-existent in Solr, but model has non-neg version",
expected.version < 0);
assertEquals(msg + " is deleted/non-existent in Solr", expected.intFieldValue, 0);
assertEquals(msg + " is deleted/non-existent in Solr", expected.longFieldValue, 0);
} else {
msg = msg + " <==VS==> " + actual;
assertEquals(msg, expected.intFieldValue, actual.getFieldValue("val1_i_dvo"));
assertEquals(msg, expected.longFieldValue, actual.getFieldValue("val2_l_dvo"));
assertEquals(msg, expected.version, actual.getFieldValue("_version_"));
assertTrue(
msg + " doc exists in solr, but version is negative???", 0 < expected.version);
}
}
}
}
{
// do a final search and compare every result with the model because commits don't provide any
// sort of concrete versioning (or optimistic concurrency constraints) there's no way to
// garuntee that our committedModel matches what was in Solr at the time of the last commit.
// It's possible other threads made additional writes to solr before the commit was processed,
// but after the committedModel variable was assigned it's new value. what we can do however,
// is commit all completed updates, and *then* compare solr search results against the (new)
// committed model....
// NOTE: this does an automatic commit for us & ensures replicas are up to date
waitForThingsToLevelOut(30, TimeUnit.SECONDS);
committedModel = new HashMap<>(model);
// first, prune the model of any docs that have negative versions
// ie: were never actually added, or were ultimately deleted.
for (int i = 0; i < ndocs; i++) {
DocInfo info = committedModel.get(i);
if (info.version < 0) {
// first, a quick sanity check of the model itself...
assertEquals(
"Inconsistent int value in model for deleted doc" + i + "=" + info,
0,
info.intFieldValue);
assertEquals(
"Inconsistent long value in model for deleted doc" + i + "=" + info,
0L,
info.longFieldValue);
committedModel.remove(i);
}
}
for (SolrClient client : clients) {
QueryResponse rsp = client.query(params("q", "*:*", "sort", "id asc", "rows", ndocs + ""));
for (SolrDocument actual : rsp.getResults()) {
final Integer id = Integer.parseInt(actual.getFieldValue("id").toString());
final DocInfo expected = committedModel.get(id);
assertNotNull("Doc found but missing/deleted from model: " + actual, expected);
final String msg = "Search: " + id + "=" + expected + " <==VS==> " + actual;
assertEquals(msg, expected.intFieldValue, actual.getFieldValue("val1_i_dvo"));
assertEquals(msg, expected.longFieldValue, actual.getFieldValue("val2_l_dvo"));
assertEquals(msg, expected.version, actual.getFieldValue("_version_"));
assertTrue(msg + " doc exists in solr, but version is negative???", 0 < expected.version);
// also sanity check the model (which we already know matches the doc)
assertEquals(
"Inconsistent (modulo) values in model for id " + id + "=" + expected,
0,
(expected.longFieldValue % expected.intFieldValue));
}
assertEquals(committedModel.size(), rsp.getResults().getNumFound());
}
}
}
/** Used for storing the info for a document in an in-memory model. */
private static class DocInfo {
long version;
int intFieldValue;
long longFieldValue;
public DocInfo(long version, int val1, long val2) {
// must either be real positive version, or negative deleted version/indicator
assert version != 0;
this.version = version;
this.intFieldValue = val1;
this.longFieldValue = val2;
}
@Override
public String toString() {
return "[version="
+ version
+ ", intValue="
+ intFieldValue
+ ",longValue="
+ longFieldValue
+ "]";
}
}
protected long addDocAndGetVersion(Object... fields) throws Exception {
SolrInputDocument doc = new SolrInputDocument();
addFields(doc, fields);
ModifiableSolrParams params = new ModifiableSolrParams();
params.add("versions", "true");
UpdateRequest ureq = new UpdateRequest();
ureq.setParams(params);
ureq.add(doc);
UpdateResponse resp;
// send updates to leader, to avoid SOLR-8733
resp = ureq.process(leaderClient);
long returnedVersion =
Long.parseLong(((NamedList<?>) resp.getResponse().get("adds")).getVal(0).toString());
assertTrue(
"Due to SOLR-8733, sometimes returned version is 0. Let us assert that we have successfully"
+ " worked around that problem here.",
returnedVersion > 0);
return returnedVersion;
}
protected long deleteDocAndGetVersion(
String id, ModifiableSolrParams params, boolean deleteByQuery) throws Exception {
params.add("versions", "true");
UpdateRequest ureq = new UpdateRequest();
ureq.setParams(params);
if (deleteByQuery) {
ureq.deleteByQuery("id:" + id);
} else {
ureq.deleteById(id);
}
UpdateResponse resp;
// send updates to leader, to avoid SOLR-8733
resp = ureq.process(leaderClient);
String key = deleteByQuery ? "deleteByQuery" : "deletes";
long returnedVersion =
Long.parseLong(((NamedList<?>) resp.getResponse().get(key)).getVal(0).toString());
assertTrue(
"Due to SOLR-8733, sometimes returned version is 0. Let us assert that we have successfully"
+ " worked around that problem here.",
returnedVersion < 0);
return returnedVersion;
}
/**
* Method gets the SolrClient for the leader replica. This is needed for a workaround for
* SOLR-8733.
*/
public SolrClient getClientForLeader() throws KeeperException, InterruptedException {
ZkStateReader zkStateReader = cloudClient.getZkStateReader();
cloudClient.getZkStateReader().forceUpdateCollection(DEFAULT_COLLECTION);
ClusterState clusterState = cloudClient.getZkStateReader().getClusterState();
Replica leader = null;
Slice shard1 = clusterState.getCollection(DEFAULT_COLLECTION).getSlice(SHARD1);
leader = shard1.getLeader();
for (int i = 0; i < clients.size(); i++) {
String leaderBaseUrl = zkStateReader.getBaseUrlForNodeName(leader.getNodeName());
if (((HttpSolrClient) clients.get(i)).getBaseURL().startsWith(leaderBaseUrl))
return clients.get(i);
}
return null;
}
}
| |
/*
* Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java.awt;
import java.awt.peer.TextComponentPeer;
import java.awt.event.*;
import java.util.EventListener;
import java.io.ObjectOutputStream;
import java.io.ObjectInputStream;
import java.io.IOException;
import sun.awt.InputMethodSupport;
import java.text.BreakIterator;
import javax.swing.text.AttributeSet;
import javax.accessibility.*;
import java.awt.im.InputMethodRequests;
import sun.security.util.SecurityConstants;
/**
* The <code>TextComponent</code> class is the superclass of
* any component that allows the editing of some text.
* <p>
* A text component embodies a string of text. The
* <code>TextComponent</code> class defines a set of methods
* that determine whether or not this text is editable. If the
* component is editable, it defines another set of methods
* that supports a text insertion caret.
* <p>
* In addition, the class defines methods that are used
* to maintain a current <em>selection</em> from the text.
* The text selection, a substring of the component's text,
* is the target of editing operations. It is also referred
* to as the <em>selected text</em>.
*
* @author Sami Shaio
* @author Arthur van Hoff
* @since JDK1.0
*/
public class TextComponent extends Component implements Accessible {
/**
* The value of the text.
* A <code>null</code> value is the same as "".
*
* @serial
* @see #setText(String)
* @see #getText()
*/
String text;
/**
* A boolean indicating whether or not this
* <code>TextComponent</code> is editable.
* It will be <code>true</code> if the text component
* is editable and <code>false</code> if not.
*
* @serial
* @see #isEditable()
*/
boolean editable = true;
/**
* The selection refers to the selected text, and the
* <code>selectionStart</code> is the start position
* of the selected text.
*
* @serial
* @see #getSelectionStart()
* @see #setSelectionStart(int)
*/
int selectionStart;
/**
* The selection refers to the selected text, and the
* <code>selectionEnd</code>
* is the end position of the selected text.
*
* @serial
* @see #getSelectionEnd()
* @see #setSelectionEnd(int)
*/
int selectionEnd;
// A flag used to tell whether the background has been set by
// developer code (as opposed to AWT code). Used to determine
// the background color of non-editable TextComponents.
boolean backgroundSetByClientCode = false;
transient protected TextListener textListener;
/*
* JDK 1.1 serialVersionUID
*/
private static final long serialVersionUID = -2214773872412987419L;
/**
* Constructs a new text component initialized with the
* specified text. Sets the value of the cursor to
* <code>Cursor.TEXT_CURSOR</code>.
* @param text the text to be displayed; if
* <code>text</code> is <code>null</code>, the empty
* string <code>""</code> will be displayed
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless</code>
* returns true
* @see java.awt.GraphicsEnvironment#isHeadless
* @see java.awt.Cursor
*/
TextComponent(String text) throws HeadlessException {
GraphicsEnvironment.checkHeadless();
this.text = (text != null) ? text : "";
setCursor(Cursor.getPredefinedCursor(Cursor.TEXT_CURSOR));
}
private void enableInputMethodsIfNecessary() {
if (checkForEnableIM) {
checkForEnableIM = false;
try {
Toolkit toolkit = Toolkit.getDefaultToolkit();
boolean shouldEnable = false;
if (toolkit instanceof InputMethodSupport) {
shouldEnable = ((InputMethodSupport)toolkit)
.enableInputMethodsForTextComponent();
}
enableInputMethods(shouldEnable);
} catch (Exception e) {
// if something bad happens, just don't enable input methods
}
}
}
/**
* Enables or disables input method support for this text component. If input
* method support is enabled and the text component also processes key events,
* incoming events are offered to the current input method and will only be
* processed by the component or dispatched to its listeners if the input method
* does not consume them. Whether and how input method support for this text
* component is enabled or disabled by default is implementation dependent.
*
* @param enable true to enable, false to disable
* @see #processKeyEvent
* @since 1.2
*/
public void enableInputMethods(boolean enable) {
checkForEnableIM = false;
super.enableInputMethods(enable);
}
boolean areInputMethodsEnabled() {
// moved from the constructor above to here and addNotify below,
// this call will initialize the toolkit if not already initialized.
if (checkForEnableIM) {
enableInputMethodsIfNecessary();
}
// TextComponent handles key events without touching the eventMask or
// having a key listener, so just check whether the flag is set
return (eventMask & AWTEvent.INPUT_METHODS_ENABLED_MASK) != 0;
}
public InputMethodRequests getInputMethodRequests() {
TextComponentPeer peer = (TextComponentPeer)this.peer;
if (peer != null) return peer.getInputMethodRequests();
else return null;
}
/**
* Makes this Component displayable by connecting it to a
* native screen resource.
* This method is called internally by the toolkit and should
* not be called directly by programs.
* @see java.awt.TextComponent#removeNotify
*/
public void addNotify() {
super.addNotify();
enableInputMethodsIfNecessary();
}
/**
* Removes the <code>TextComponent</code>'s peer.
* The peer allows us to modify the appearance of the
* <code>TextComponent</code> without changing its
* functionality.
*/
public void removeNotify() {
synchronized (getTreeLock()) {
TextComponentPeer peer = (TextComponentPeer)this.peer;
if (peer != null) {
text = peer.getText();
selectionStart = peer.getSelectionStart();
selectionEnd = peer.getSelectionEnd();
}
super.removeNotify();
}
}
/**
* Sets the text that is presented by this
* text component to be the specified text.
* @param t the new text;
* if this parameter is <code>null</code> then
* the text is set to the empty string ""
* @see java.awt.TextComponent#getText
*/
public synchronized void setText(String t) {
boolean skipTextEvent = (text == null || text.isEmpty())
&& (t == null || t.isEmpty());
text = (t != null) ? t : "";
TextComponentPeer peer = (TextComponentPeer)this.peer;
// Please note that we do not want to post an event
// if TextArea.setText() or TextField.setText() replaces an empty text
// by an empty text, that is, if component's text remains unchanged.
if (peer != null && !skipTextEvent) {
peer.setText(text);
}
}
/**
* Returns the text that is presented by this text component.
* By default, this is an empty string.
*
* @return the value of this <code>TextComponent</code>
* @see java.awt.TextComponent#setText
*/
public synchronized String getText() {
TextComponentPeer peer = (TextComponentPeer)this.peer;
if (peer != null) {
text = peer.getText();
}
return text;
}
/**
* Returns the selected text from the text that is
* presented by this text component.
* @return the selected text of this text component
* @see java.awt.TextComponent#select
*/
public synchronized String getSelectedText() {
return getText().substring(getSelectionStart(), getSelectionEnd());
}
/**
* Indicates whether or not this text component is editable.
* @return <code>true</code> if this text component is
* editable; <code>false</code> otherwise.
* @see java.awt.TextComponent#setEditable
* @since JDK1.0
*/
public boolean isEditable() {
return editable;
}
/**
* Sets the flag that determines whether or not this
* text component is editable.
* <p>
* If the flag is set to <code>true</code>, this text component
* becomes user editable. If the flag is set to <code>false</code>,
* the user cannot change the text of this text component.
* By default, non-editable text components have a background color
* of SystemColor.control. This default can be overridden by
* calling setBackground.
*
* @param b a flag indicating whether this text component
* is user editable.
* @see java.awt.TextComponent#isEditable
* @since JDK1.0
*/
public synchronized void setEditable(boolean b) {
if (editable == b) {
return;
}
editable = b;
TextComponentPeer peer = (TextComponentPeer)this.peer;
if (peer != null) {
peer.setEditable(b);
}
}
/**
* Gets the background color of this text component.
*
* By default, non-editable text components have a background color
* of SystemColor.control. This default can be overridden by
* calling setBackground.
*
* @return This text component's background color.
* If this text component does not have a background color,
* the background color of its parent is returned.
* @see #setBackground(Color)
* @since JDK1.0
*/
public Color getBackground() {
if (!editable && !backgroundSetByClientCode) {
return SystemColor.control;
}
return super.getBackground();
}
/**
* Sets the background color of this text component.
*
* @param c The color to become this text component's color.
* If this parameter is null then this text component
* will inherit the background color of its parent.
* @see #getBackground()
* @since JDK1.0
*/
public void setBackground(Color c) {
backgroundSetByClientCode = true;
super.setBackground(c);
}
/**
* Gets the start position of the selected text in
* this text component.
* @return the start position of the selected text
* @see java.awt.TextComponent#setSelectionStart
* @see java.awt.TextComponent#getSelectionEnd
*/
public synchronized int getSelectionStart() {
TextComponentPeer peer = (TextComponentPeer)this.peer;
if (peer != null) {
selectionStart = peer.getSelectionStart();
}
return selectionStart;
}
/**
* Sets the selection start for this text component to
* the specified position. The new start point is constrained
* to be at or before the current selection end. It also
* cannot be set to less than zero, the beginning of the
* component's text.
* If the caller supplies a value for <code>selectionStart</code>
* that is out of bounds, the method enforces these constraints
* silently, and without failure.
* @param selectionStart the start position of the
* selected text
* @see java.awt.TextComponent#getSelectionStart
* @see java.awt.TextComponent#setSelectionEnd
* @since JDK1.1
*/
public synchronized void setSelectionStart(int selectionStart) {
/* Route through select method to enforce consistent policy
* between selectionStart and selectionEnd.
*/
select(selectionStart, getSelectionEnd());
}
/**
* Gets the end position of the selected text in
* this text component.
* @return the end position of the selected text
* @see java.awt.TextComponent#setSelectionEnd
* @see java.awt.TextComponent#getSelectionStart
*/
public synchronized int getSelectionEnd() {
TextComponentPeer peer = (TextComponentPeer)this.peer;
if (peer != null) {
selectionEnd = peer.getSelectionEnd();
}
return selectionEnd;
}
/**
* Sets the selection end for this text component to
* the specified position. The new end point is constrained
* to be at or after the current selection start. It also
* cannot be set beyond the end of the component's text.
* If the caller supplies a value for <code>selectionEnd</code>
* that is out of bounds, the method enforces these constraints
* silently, and without failure.
* @param selectionEnd the end position of the
* selected text
* @see java.awt.TextComponent#getSelectionEnd
* @see java.awt.TextComponent#setSelectionStart
* @since JDK1.1
*/
public synchronized void setSelectionEnd(int selectionEnd) {
/* Route through select method to enforce consistent policy
* between selectionStart and selectionEnd.
*/
select(getSelectionStart(), selectionEnd);
}
/**
* Selects the text between the specified start and end positions.
* <p>
* This method sets the start and end positions of the
* selected text, enforcing the restriction that the start position
* must be greater than or equal to zero. The end position must be
* greater than or equal to the start position, and less than or
* equal to the length of the text component's text. The
* character positions are indexed starting with zero.
* The length of the selection is
* <code>endPosition</code> - <code>startPosition</code>, so the
* character at <code>endPosition</code> is not selected.
* If the start and end positions of the selected text are equal,
* all text is deselected.
* <p>
* If the caller supplies values that are inconsistent or out of
* bounds, the method enforces these constraints silently, and
* without failure. Specifically, if the start position or end
* position is greater than the length of the text, it is reset to
* equal the text length. If the start position is less than zero,
* it is reset to zero, and if the end position is less than the
* start position, it is reset to the start position.
*
* @param selectionStart the zero-based index of the first
character (<code>char</code> value) to be selected
* @param selectionEnd the zero-based end position of the
text to be selected; the character (<code>char</code> value) at
<code>selectionEnd</code> is not selected
* @see java.awt.TextComponent#setSelectionStart
* @see java.awt.TextComponent#setSelectionEnd
* @see java.awt.TextComponent#selectAll
*/
public synchronized void select(int selectionStart, int selectionEnd) {
String text = getText();
if (selectionStart < 0) {
selectionStart = 0;
}
if (selectionStart > text.length()) {
selectionStart = text.length();
}
if (selectionEnd > text.length()) {
selectionEnd = text.length();
}
if (selectionEnd < selectionStart) {
selectionEnd = selectionStart;
}
this.selectionStart = selectionStart;
this.selectionEnd = selectionEnd;
TextComponentPeer peer = (TextComponentPeer)this.peer;
if (peer != null) {
peer.select(selectionStart, selectionEnd);
}
}
/**
* Selects all the text in this text component.
* @see java.awt.TextComponent#select
*/
public synchronized void selectAll() {
this.selectionStart = 0;
this.selectionEnd = getText().length();
TextComponentPeer peer = (TextComponentPeer)this.peer;
if (peer != null) {
peer.select(selectionStart, selectionEnd);
}
}
/**
* Sets the position of the text insertion caret.
* The caret position is constrained to be between 0
* and the last character of the text, inclusive.
* If the passed-in value is greater than this range,
* the value is set to the last character (or 0 if
* the <code>TextComponent</code> contains no text)
* and no error is returned. If the passed-in value is
* less than 0, an <code>IllegalArgumentException</code>
* is thrown.
*
* @param position the position of the text insertion caret
* @exception IllegalArgumentException if <code>position</code>
* is less than zero
* @since JDK1.1
*/
public synchronized void setCaretPosition(int position) {
if (position < 0) {
throw new IllegalArgumentException("position less than zero.");
}
int maxposition = getText().length();
if (position > maxposition) {
position = maxposition;
}
TextComponentPeer peer = (TextComponentPeer)this.peer;
if (peer != null) {
peer.setCaretPosition(position);
} else {
select(position, position);
}
}
/**
* Returns the position of the text insertion caret.
* The caret position is constrained to be between 0
* and the last character of the text, inclusive.
* If the text or caret have not been set, the default
* caret position is 0.
*
* @return the position of the text insertion caret
* @see #setCaretPosition(int)
* @since JDK1.1
*/
public synchronized int getCaretPosition() {
TextComponentPeer peer = (TextComponentPeer)this.peer;
int position = 0;
if (peer != null) {
position = peer.getCaretPosition();
} else {
position = selectionStart;
}
int maxposition = getText().length();
if (position > maxposition) {
position = maxposition;
}
return position;
}
/**
* Adds the specified text event listener to receive text events
* from this text component.
* If <code>l</code> is <code>null</code>, no exception is
* thrown and no action is performed.
* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
* >AWT Threading Issues</a> for details on AWT's threading model.
*
* @param l the text event listener
* @see #removeTextListener
* @see #getTextListeners
* @see java.awt.event.TextListener
*/
public synchronized void addTextListener(TextListener l) {
if (l == null) {
return;
}
textListener = AWTEventMulticaster.add(textListener, l);
newEventsOnly = true;
}
/**
* Removes the specified text event listener so that it no longer
* receives text events from this text component
* If <code>l</code> is <code>null</code>, no exception is
* thrown and no action is performed.
* <p>Refer to <a href="doc-files/AWTThreadIssues.html#ListenersThreads"
* >AWT Threading Issues</a> for details on AWT's threading model.
*
* @param l the text listener
* @see #addTextListener
* @see #getTextListeners
* @see java.awt.event.TextListener
* @since JDK1.1
*/
public synchronized void removeTextListener(TextListener l) {
if (l == null) {
return;
}
textListener = AWTEventMulticaster.remove(textListener, l);
}
/**
* Returns an array of all the text listeners
* registered on this text component.
*
* @return all of this text component's <code>TextListener</code>s
* or an empty array if no text
* listeners are currently registered
*
*
* @see #addTextListener
* @see #removeTextListener
* @since 1.4
*/
public synchronized TextListener[] getTextListeners() {
return getListeners(TextListener.class);
}
/**
* Returns an array of all the objects currently registered
* as <code><em>Foo</em>Listener</code>s
* upon this <code>TextComponent</code>.
* <code><em>Foo</em>Listener</code>s are registered using the
* <code>add<em>Foo</em>Listener</code> method.
*
* <p>
* You can specify the <code>listenerType</code> argument
* with a class literal, such as
* <code><em>Foo</em>Listener.class</code>.
* For example, you can query a
* <code>TextComponent</code> <code>t</code>
* for its text listeners with the following code:
*
* <pre>TextListener[] tls = (TextListener[])(t.getListeners(TextListener.class));</pre>
*
* If no such listeners exist, this method returns an empty array.
*
* @param listenerType the type of listeners requested; this parameter
* should specify an interface that descends from
* <code>java.util.EventListener</code>
* @return an array of all objects registered as
* <code><em>Foo</em>Listener</code>s on this text component,
* or an empty array if no such
* listeners have been added
* @exception ClassCastException if <code>listenerType</code>
* doesn't specify a class or interface that implements
* <code>java.util.EventListener</code>
*
* @see #getTextListeners
* @since 1.3
*/
public <T extends EventListener> T[] getListeners(Class<T> listenerType) {
EventListener l = null;
if (listenerType == TextListener.class) {
l = textListener;
} else {
return super.getListeners(listenerType);
}
return AWTEventMulticaster.getListeners(l, listenerType);
}
// REMIND: remove when filtering is done at lower level
boolean eventEnabled(AWTEvent e) {
if (e.id == TextEvent.TEXT_VALUE_CHANGED) {
if ((eventMask & AWTEvent.TEXT_EVENT_MASK) != 0 ||
textListener != null) {
return true;
}
return false;
}
return super.eventEnabled(e);
}
/**
* Processes events on this text component. If the event is a
* <code>TextEvent</code>, it invokes the <code>processTextEvent</code>
* method else it invokes its superclass's <code>processEvent</code>.
* <p>Note that if the event parameter is <code>null</code>
* the behavior is unspecified and may result in an
* exception.
*
* @param e the event
*/
protected void processEvent(AWTEvent e) {
if (e instanceof TextEvent) {
processTextEvent((TextEvent)e);
return;
}
super.processEvent(e);
}
/**
* Processes text events occurring on this text component by
* dispatching them to any registered <code>TextListener</code> objects.
* <p>
* NOTE: This method will not be called unless text events
* are enabled for this component. This happens when one of the
* following occurs:
* <ul>
* <li>A <code>TextListener</code> object is registered
* via <code>addTextListener</code>
* <li>Text events are enabled via <code>enableEvents</code>
* </ul>
* <p>Note that if the event parameter is <code>null</code>
* the behavior is unspecified and may result in an
* exception.
*
* @param e the text event
* @see Component#enableEvents
*/
protected void processTextEvent(TextEvent e) {
TextListener listener = textListener;
if (listener != null) {
int id = e.getID();
switch (id) {
case TextEvent.TEXT_VALUE_CHANGED:
listener.textValueChanged(e);
break;
}
}
}
/**
* Returns a string representing the state of this
* <code>TextComponent</code>. This
* method is intended to be used only for debugging purposes, and the
* content and format of the returned string may vary between
* implementations. The returned string may be empty but may not be
* <code>null</code>.
*
* @return the parameter string of this text component
*/
protected String paramString() {
String str = super.paramString() + ",text=" + getText();
if (editable) {
str += ",editable";
}
return str + ",selection=" + getSelectionStart() + "-" + getSelectionEnd();
}
/**
* Assigns a valid value to the canAccessClipboard instance variable.
*/
private boolean canAccessClipboard() {
SecurityManager sm = System.getSecurityManager();
if (sm == null) return true;
try {
sm.checkPermission(SecurityConstants.AWT.ACCESS_CLIPBOARD_PERMISSION);
return true;
} catch (SecurityException e) {}
return false;
}
/*
* Serialization support.
*/
/**
* The textComponent SerializedDataVersion.
*
* @serial
*/
private int textComponentSerializedDataVersion = 1;
/**
* Writes default serializable fields to stream. Writes
* a list of serializable TextListener(s) as optional data.
* The non-serializable TextListener(s) are detected and
* no attempt is made to serialize them.
*
* @serialData Null terminated sequence of zero or more pairs.
* A pair consists of a String and Object.
* The String indicates the type of object and
* is one of the following :
* textListenerK indicating and TextListener object.
*
* @see AWTEventMulticaster#save(ObjectOutputStream, String, EventListener)
* @see java.awt.Component#textListenerK
*/
private void writeObject(java.io.ObjectOutputStream s)
throws IOException
{
// Serialization support. Since the value of the fields
// selectionStart, selectionEnd, and text aren't necessarily
// up to date, we sync them up with the peer before serializing.
TextComponentPeer peer = (TextComponentPeer)this.peer;
if (peer != null) {
text = peer.getText();
selectionStart = peer.getSelectionStart();
selectionEnd = peer.getSelectionEnd();
}
s.defaultWriteObject();
AWTEventMulticaster.save(s, textListenerK, textListener);
s.writeObject(null);
}
/**
* Read the ObjectInputStream, and if it isn't null,
* add a listener to receive text events fired by the
* TextComponent. Unrecognized keys or values will be
* ignored.
*
* @exception HeadlessException if
* <code>GraphicsEnvironment.isHeadless()</code> returns
* <code>true</code>
* @see #removeTextListener
* @see #addTextListener
* @see java.awt.GraphicsEnvironment#isHeadless
*/
private void readObject(ObjectInputStream s)
throws ClassNotFoundException, IOException, HeadlessException
{
GraphicsEnvironment.checkHeadless();
s.defaultReadObject();
// Make sure the state we just read in for text,
// selectionStart and selectionEnd has legal values
this.text = (text != null) ? text : "";
select(selectionStart, selectionEnd);
Object keyOrNull;
while(null != (keyOrNull = s.readObject())) {
String key = ((String)keyOrNull).intern();
if (textListenerK == key) {
addTextListener((TextListener)(s.readObject()));
} else {
// skip value for unrecognized key
s.readObject();
}
}
enableInputMethodsIfNecessary();
}
/////////////////
// Accessibility support
////////////////
/**
* Gets the AccessibleContext associated with this TextComponent.
* For text components, the AccessibleContext takes the form of an
* AccessibleAWTTextComponent.
* A new AccessibleAWTTextComponent instance is created if necessary.
*
* @return an AccessibleAWTTextComponent that serves as the
* AccessibleContext of this TextComponent
* @since 1.3
*/
public AccessibleContext getAccessibleContext() {
if (accessibleContext == null) {
accessibleContext = new AccessibleAWTTextComponent();
}
return accessibleContext;
}
/**
* This class implements accessibility support for the
* <code>TextComponent</code> class. It provides an implementation of the
* Java Accessibility API appropriate to text component user-interface
* elements.
* @since 1.3
*/
protected class AccessibleAWTTextComponent extends AccessibleAWTComponent
implements AccessibleText, TextListener
{
/*
* JDK 1.3 serialVersionUID
*/
private static final long serialVersionUID = 3631432373506317811L;
/**
* Constructs an AccessibleAWTTextComponent. Adds a listener to track
* caret change.
*/
public AccessibleAWTTextComponent() {
TextComponent.this.addTextListener(this);
}
/**
* TextListener notification of a text value change.
*/
public void textValueChanged(TextEvent textEvent) {
Integer cpos = Integer.valueOf(TextComponent.this.getCaretPosition());
firePropertyChange(ACCESSIBLE_TEXT_PROPERTY, null, cpos);
}
/**
* Gets the state set of the TextComponent.
* The AccessibleStateSet of an object is composed of a set of
* unique AccessibleStates. A change in the AccessibleStateSet
* of an object will cause a PropertyChangeEvent to be fired
* for the AccessibleContext.ACCESSIBLE_STATE_PROPERTY property.
*
* @return an instance of AccessibleStateSet containing the
* current state set of the object
* @see AccessibleStateSet
* @see AccessibleState
* @see #addPropertyChangeListener
*/
public AccessibleStateSet getAccessibleStateSet() {
AccessibleStateSet states = super.getAccessibleStateSet();
if (TextComponent.this.isEditable()) {
states.add(AccessibleState.EDITABLE);
}
return states;
}
/**
* Gets the role of this object.
*
* @return an instance of AccessibleRole describing the role of the
* object (AccessibleRole.TEXT)
* @see AccessibleRole
*/
public AccessibleRole getAccessibleRole() {
return AccessibleRole.TEXT;
}
/**
* Get the AccessibleText associated with this object. In the
* implementation of the Java Accessibility API for this class,
* return this object, which is responsible for implementing the
* AccessibleText interface on behalf of itself.
*
* @return this object
*/
public AccessibleText getAccessibleText() {
return this;
}
// --- interface AccessibleText methods ------------------------
/**
* Many of these methods are just convenience methods; they
* just call the equivalent on the parent
*/
/**
* Given a point in local coordinates, return the zero-based index
* of the character under that Point. If the point is invalid,
* this method returns -1.
*
* @param p the Point in local coordinates
* @return the zero-based index of the character under Point p.
*/
public int getIndexAtPoint(Point p) {
return -1;
}
/**
* Determines the bounding box of the character at the given
* index into the string. The bounds are returned in local
* coordinates. If the index is invalid a null rectangle
* is returned.
*
* @param i the index into the String >= 0
* @return the screen coordinates of the character's bounding box
*/
public Rectangle getCharacterBounds(int i) {
return null;
}
/**
* Returns the number of characters (valid indicies)
*
* @return the number of characters >= 0
*/
public int getCharCount() {
return TextComponent.this.getText().length();
}
/**
* Returns the zero-based offset of the caret.
*
* Note: The character to the right of the caret will have the
* same index value as the offset (the caret is between
* two characters).
*
* @return the zero-based offset of the caret.
*/
public int getCaretPosition() {
return TextComponent.this.getCaretPosition();
}
/**
* Returns the AttributeSet for a given character (at a given index).
*
* @param i the zero-based index into the text
* @return the AttributeSet of the character
*/
public AttributeSet getCharacterAttribute(int i) {
return null; // No attributes in TextComponent
}
/**
* Returns the start offset within the selected text.
* If there is no selection, but there is
* a caret, the start and end offsets will be the same.
* Return 0 if the text is empty, or the caret position
* if no selection.
*
* @return the index into the text of the start of the selection >= 0
*/
public int getSelectionStart() {
return TextComponent.this.getSelectionStart();
}
/**
* Returns the end offset within the selected text.
* If there is no selection, but there is
* a caret, the start and end offsets will be the same.
* Return 0 if the text is empty, or the caret position
* if no selection.
*
* @return the index into the text of the end of the selection >= 0
*/
public int getSelectionEnd() {
return TextComponent.this.getSelectionEnd();
}
/**
* Returns the portion of the text that is selected.
*
* @return the text, null if no selection
*/
public String getSelectedText() {
String selText = TextComponent.this.getSelectedText();
// Fix for 4256662
if (selText == null || selText.equals("")) {
return null;
}
return selText;
}
/**
* Returns the String at a given index.
*
* @param part the AccessibleText.CHARACTER, AccessibleText.WORD,
* or AccessibleText.SENTENCE to retrieve
* @param index an index within the text >= 0
* @return the letter, word, or sentence,
* null for an invalid index or part
*/
public String getAtIndex(int part, int index) {
if (index < 0 || index >= TextComponent.this.getText().length()) {
return null;
}
switch (part) {
case AccessibleText.CHARACTER:
return TextComponent.this.getText().substring(index, index+1);
case AccessibleText.WORD: {
String s = TextComponent.this.getText();
BreakIterator words = BreakIterator.getWordInstance();
words.setText(s);
int end = words.following(index);
return s.substring(words.previous(), end);
}
case AccessibleText.SENTENCE: {
String s = TextComponent.this.getText();
BreakIterator sentence = BreakIterator.getSentenceInstance();
sentence.setText(s);
int end = sentence.following(index);
return s.substring(sentence.previous(), end);
}
default:
return null;
}
}
private static final boolean NEXT = true;
private static final boolean PREVIOUS = false;
/**
* Needed to unify forward and backward searching.
* The method assumes that s is the text assigned to words.
*/
private int findWordLimit(int index, BreakIterator words, boolean direction,
String s) {
// Fix for 4256660 and 4256661.
// Words iterator is different from character and sentence iterators
// in that end of one word is not necessarily start of another word.
// Please see java.text.BreakIterator JavaDoc. The code below is
// based on nextWordStartAfter example from BreakIterator.java.
int last = (direction == NEXT) ? words.following(index)
: words.preceding(index);
int current = (direction == NEXT) ? words.next()
: words.previous();
while (current != BreakIterator.DONE) {
for (int p = Math.min(last, current); p < Math.max(last, current); p++) {
if (Character.isLetter(s.charAt(p))) {
return last;
}
}
last = current;
current = (direction == NEXT) ? words.next()
: words.previous();
}
return BreakIterator.DONE;
}
/**
* Returns the String after a given index.
*
* @param part the AccessibleText.CHARACTER, AccessibleText.WORD,
* or AccessibleText.SENTENCE to retrieve
* @param index an index within the text >= 0
* @return the letter, word, or sentence, null for an invalid
* index or part
*/
public String getAfterIndex(int part, int index) {
if (index < 0 || index >= TextComponent.this.getText().length()) {
return null;
}
switch (part) {
case AccessibleText.CHARACTER:
if (index+1 >= TextComponent.this.getText().length()) {
return null;
}
return TextComponent.this.getText().substring(index+1, index+2);
case AccessibleText.WORD: {
String s = TextComponent.this.getText();
BreakIterator words = BreakIterator.getWordInstance();
words.setText(s);
int start = findWordLimit(index, words, NEXT, s);
if (start == BreakIterator.DONE || start >= s.length()) {
return null;
}
int end = words.following(start);
if (end == BreakIterator.DONE || end >= s.length()) {
return null;
}
return s.substring(start, end);
}
case AccessibleText.SENTENCE: {
String s = TextComponent.this.getText();
BreakIterator sentence = BreakIterator.getSentenceInstance();
sentence.setText(s);
int start = sentence.following(index);
if (start == BreakIterator.DONE || start >= s.length()) {
return null;
}
int end = sentence.following(start);
if (end == BreakIterator.DONE || end >= s.length()) {
return null;
}
return s.substring(start, end);
}
default:
return null;
}
}
/**
* Returns the String before a given index.
*
* @param part the AccessibleText.CHARACTER, AccessibleText.WORD,
* or AccessibleText.SENTENCE to retrieve
* @param index an index within the text >= 0
* @return the letter, word, or sentence, null for an invalid index
* or part
*/
public String getBeforeIndex(int part, int index) {
if (index < 0 || index > TextComponent.this.getText().length()-1) {
return null;
}
switch (part) {
case AccessibleText.CHARACTER:
if (index == 0) {
return null;
}
return TextComponent.this.getText().substring(index-1, index);
case AccessibleText.WORD: {
String s = TextComponent.this.getText();
BreakIterator words = BreakIterator.getWordInstance();
words.setText(s);
int end = findWordLimit(index, words, PREVIOUS, s);
if (end == BreakIterator.DONE) {
return null;
}
int start = words.preceding(end);
if (start == BreakIterator.DONE) {
return null;
}
return s.substring(start, end);
}
case AccessibleText.SENTENCE: {
String s = TextComponent.this.getText();
BreakIterator sentence = BreakIterator.getSentenceInstance();
sentence.setText(s);
int end = sentence.following(index);
end = sentence.previous();
int start = sentence.previous();
if (start == BreakIterator.DONE) {
return null;
}
return s.substring(start, end);
}
default:
return null;
}
}
} // end of AccessibleAWTTextComponent
private boolean checkForEnableIM = true;
}
| |
/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.beans;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import junit.framework.TestCase;
import org.springframework.beans.propertyeditors.CustomNumberEditor;
import org.springframework.beans.propertyeditors.StringTrimmerEditor;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
/**
* @author Juergen Hoeller
* @since 18.01.2006
*/
public class BeanWrapperGenericsTests extends TestCase {
public void testGenericSet() {
GenericBean gb = new GenericBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
Set input = new HashSet();
input.add("4");
input.add("5");
bw.setPropertyValue("integerSet", input);
assertTrue(gb.getIntegerSet().contains(new Integer(4)));
assertTrue(gb.getIntegerSet().contains(new Integer(5)));
}
public void testGenericSetWithConversionFailure() {
GenericBean gb = new GenericBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
Set input = new HashSet();
input.add(new TestBean());
try {
bw.setPropertyValue("integerSet", input);
fail("Should have thrown TypeMismatchException");
}
catch (TypeMismatchException ex) {
assertTrue(ex.getMessage().indexOf("java.lang.Integer") != -1);
}
}
public void testGenericList() throws MalformedURLException {
GenericBean gb = new GenericBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
List input = new ArrayList();
input.add("http://localhost:8080");
input.add("http://localhost:9090");
bw.setPropertyValue("resourceList", input);
assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
assertEquals(new UrlResource("http://localhost:9090"), gb.getResourceList().get(1));
}
public void testGenericListElement() throws MalformedURLException {
GenericBean gb = new GenericBean();
gb.setResourceList(new ArrayList<Resource>());
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("resourceList[0]", "http://localhost:8080");
assertEquals(new UrlResource("http://localhost:8080"), gb.getResourceList().get(0));
}
public void testGenericMap() {
GenericBean gb = new GenericBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
Map input = new HashMap();
input.put("4", "5");
input.put("6", "7");
bw.setPropertyValue("shortMap", input);
assertEquals(new Integer(5), gb.getShortMap().get(new Short("4")));
assertEquals(new Integer(7), gb.getShortMap().get(new Short("6")));
}
public void testGenericMapElement() {
GenericBean gb = new GenericBean();
gb.setShortMap(new HashMap<Short, Integer>());
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("shortMap[4]", "5");
assertEquals(new Integer(5), bw.getPropertyValue("shortMap[4]"));
assertEquals(new Integer(5), gb.getShortMap().get(new Short("4")));
}
public void testGenericMapWithKeyType() {
GenericBean gb = new GenericBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
Map input = new HashMap();
input.put("4", "5");
input.put("6", "7");
bw.setPropertyValue("longMap", input);
assertEquals("5", gb.getLongMap().get(new Long("4")));
assertEquals("7", gb.getLongMap().get(new Long("6")));
}
public void testGenericMapElementWithKeyType() {
GenericBean gb = new GenericBean();
gb.setLongMap(new HashMap<Long, Integer>());
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("longMap[4]", "5");
assertEquals("5", gb.getLongMap().get(new Long("4")));
assertEquals("5", bw.getPropertyValue("longMap[4]"));
}
public void testGenericMapWithCollectionValue() {
GenericBean gb = new GenericBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false));
Map input = new HashMap();
HashSet value1 = new HashSet();
value1.add(new Integer(1));
input.put("1", value1);
ArrayList value2 = new ArrayList();
value2.add(Boolean.TRUE);
input.put("2", value2);
bw.setPropertyValue("collectionMap", input);
assertTrue(gb.getCollectionMap().get(new Integer(1)) instanceof HashSet);
assertTrue(gb.getCollectionMap().get(new Integer(2)) instanceof ArrayList);
}
public void testGenericMapElementWithCollectionValue() {
GenericBean gb = new GenericBean();
gb.setCollectionMap(new HashMap<Number, Collection<? extends Object>>());
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.registerCustomEditor(Number.class, new CustomNumberEditor(Integer.class, false));
HashSet value1 = new HashSet();
value1.add(new Integer(1));
bw.setPropertyValue("collectionMap[1]", value1);
assertTrue(gb.getCollectionMap().get(new Integer(1)) instanceof HashSet);
}
public void testGenericListOfLists() throws MalformedURLException {
GenericBean gb = new GenericBean();
List<List<Integer>> list = new LinkedList<List<Integer>>();
list.add(new LinkedList<Integer>());
gb.setListOfLists(list);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfLists[0][0]", new Integer(5));
assertEquals(new Integer(5), bw.getPropertyValue("listOfLists[0][0]"));
assertEquals(new Integer(5), gb.getListOfLists().get(0).get(0));
}
public void testGenericListOfListsWithElementConversion() throws MalformedURLException {
GenericBean gb = new GenericBean();
List<List<Integer>> list = new LinkedList<List<Integer>>();
list.add(new LinkedList<Integer>());
gb.setListOfLists(list);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfLists[0][0]", "5");
assertEquals(new Integer(5), bw.getPropertyValue("listOfLists[0][0]"));
assertEquals(new Integer(5), gb.getListOfLists().get(0).get(0));
}
public void testGenericListOfArrays() throws MalformedURLException {
GenericBean gb = new GenericBean();
List<String[]> list = new LinkedList<String[]>();
list.add(new String[] {"str1", "str2"});
gb.setListOfArrays(list);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfArrays[0][1]", "str3 ");
assertEquals("str3 ", bw.getPropertyValue("listOfArrays[0][1]"));
assertEquals("str3 ", gb.getListOfArrays().get(0)[1]);
}
public void testGenericListOfArraysWithElementConversion() throws MalformedURLException {
GenericBean gb = new GenericBean();
List<String[]> list = new LinkedList<String[]>();
list.add(new String[] {"str1", "str2"});
gb.setListOfArrays(list);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.registerCustomEditor(String.class, new StringTrimmerEditor(false));
bw.setPropertyValue("listOfArrays[0][1]", "str3 ");
assertEquals("str3", bw.getPropertyValue("listOfArrays[0][1]"));
assertEquals("str3", gb.getListOfArrays().get(0)[1]);
}
public void testGenericListOfMaps() throws MalformedURLException {
GenericBean gb = new GenericBean();
List<Map<Integer, Long>> list = new LinkedList<Map<Integer, Long>>();
list.add(new HashMap<Integer, Long>());
gb.setListOfMaps(list);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfMaps[0][10]", new Long(5));
assertEquals(new Long(5), bw.getPropertyValue("listOfMaps[0][10]"));
assertEquals(new Long(5), gb.getListOfMaps().get(0).get(10));
}
public void testGenericListOfMapsWithElementConversion() throws MalformedURLException {
GenericBean gb = new GenericBean();
List<Map<Integer, Long>> list = new LinkedList<Map<Integer, Long>>();
list.add(new HashMap<Integer, Long>());
gb.setListOfMaps(list);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfMaps[0][10]", "5");
assertEquals(new Long(5), bw.getPropertyValue("listOfMaps[0][10]"));
assertEquals(new Long(5), gb.getListOfMaps().get(0).get(10));
}
public void testGenericMapOfMaps() throws MalformedURLException {
GenericBean gb = new GenericBean();
Map<String, Map<Integer, Long>> map = new HashMap<String, Map<Integer, Long>>();
map.put("mykey", new HashMap<Integer, Long>());
gb.setMapOfMaps(map);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfMaps[mykey][10]", new Long(5));
assertEquals(new Long(5), bw.getPropertyValue("mapOfMaps[mykey][10]"));
assertEquals(new Long(5), gb.getMapOfMaps().get("mykey").get(10));
}
public void testGenericMapOfMapsWithElementConversion() throws MalformedURLException {
GenericBean gb = new GenericBean();
Map<String, Map<Integer, Long>> map = new HashMap<String, Map<Integer, Long>>();
map.put("mykey", new HashMap<Integer, Long>());
gb.setMapOfMaps(map);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfMaps[mykey][10]", "5");
assertEquals(new Long(5), bw.getPropertyValue("mapOfMaps[mykey][10]"));
assertEquals(new Long(5), gb.getMapOfMaps().get("mykey").get(10));
}
public void testGenericMapOfLists() throws MalformedURLException {
GenericBean gb = new GenericBean();
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
map.put(new Integer(1), new LinkedList<Integer>());
gb.setMapOfLists(map);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfLists[1][0]", new Integer(5));
assertEquals(new Integer(5), bw.getPropertyValue("mapOfLists[1][0]"));
assertEquals(new Integer(5), gb.getMapOfLists().get(new Integer(1)).get(0));
}
public void testGenericMapOfListsWithElementConversion() throws MalformedURLException {
GenericBean gb = new GenericBean();
Map<Integer, List<Integer>> map = new HashMap<Integer, List<Integer>>();
map.put(new Integer(1), new LinkedList<Integer>());
gb.setMapOfLists(map);
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfLists[1][0]", "5");
assertEquals(new Integer(5), bw.getPropertyValue("mapOfLists[1][0]"));
assertEquals(new Integer(5), gb.getMapOfLists().get(new Integer(1)).get(0));
}
public void testGenericTypeNestingMapOfInteger() throws Exception {
Map<String, String> map = new HashMap<String, String>();
map.put("testKey", "100");
NestedGenericCollectionBean gb = new NestedGenericCollectionBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfInteger", map);
Object obj = gb.getMapOfInteger().get("testKey");
assertTrue(obj instanceof Integer);
}
public void testGenericTypeNestingMapOfListOfInteger() throws Exception {
Map<String, List<String>> map = new HashMap<String, List<String>>();
List<String> list = Arrays.asList(new String[] {"1", "2", "3"});
map.put("testKey", list);
NestedGenericCollectionBean gb = new NestedGenericCollectionBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfListOfInteger", map);
Object obj = gb.getMapOfListOfInteger().get("testKey").get(0);
assertTrue(obj instanceof Integer);
assertEquals(1, ((Integer) obj).intValue());
}
public void testGenericTypeNestingListOfMapOfInteger() throws Exception {
List<Map<String, String>> list = new LinkedList<Map<String, String>>();
Map<String, String> map = new HashMap<String, String>();
map.put("testKey", "5");
list.add(map);
NestedGenericCollectionBean gb = new NestedGenericCollectionBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("listOfMapOfInteger", list);
Object obj = gb.getListOfMapOfInteger().get(0).get("testKey");
assertTrue(obj instanceof Integer);
assertEquals(5, ((Integer) obj).intValue());
}
public void testGenericTypeNestingMapOfListOfListOfInteger() throws Exception {
Map<String, List<List<String>>> map = new HashMap<String, List<List<String>>>();
List<String> list = Arrays.asList(new String[] {"1", "2", "3"});
map.put("testKey", Collections.singletonList(list));
NestedGenericCollectionBean gb = new NestedGenericCollectionBean();
BeanWrapper bw = new BeanWrapperImpl(gb);
bw.setPropertyValue("mapOfListOfListOfInteger", map);
Object obj = gb.getMapOfListOfListOfInteger().get("testKey").get(0).get(0);
assertTrue(obj instanceof Integer);
assertEquals(1, ((Integer) obj).intValue());
}
public void testComplexGenericMap() {
Map inputMap = new HashMap();
List inputKey = new LinkedList();
inputKey.add("1");
List inputValue = new LinkedList();
inputValue.add("10");
inputMap.put(inputKey, inputValue);
ComplexMapHolder holder = new ComplexMapHolder();
BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("genericMap", inputMap);
assertEquals(new Integer(1), holder.getGenericMap().keySet().iterator().next().get(0));
assertEquals(new Long(10), holder.getGenericMap().values().iterator().next().get(0));
}
public void testComplexGenericMapWithCollectionConversion() {
Map inputMap = new HashMap();
Set inputKey = new HashSet();
inputKey.add("1");
Set inputValue = new HashSet();
inputValue.add("10");
inputMap.put(inputKey, inputValue);
ComplexMapHolder holder = new ComplexMapHolder();
BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("genericMap", inputMap);
assertEquals(new Integer(1), holder.getGenericMap().keySet().iterator().next().get(0));
assertEquals(new Long(10), holder.getGenericMap().values().iterator().next().get(0));
}
public void testComplexGenericIndexedMapEntry() {
List inputValue = new LinkedList();
inputValue.add("10");
ComplexMapHolder holder = new ComplexMapHolder();
BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("genericIndexedMap[1]", inputValue);
assertEquals(new Integer(1), holder.getGenericIndexedMap().keySet().iterator().next());
assertEquals(new Long(10), holder.getGenericIndexedMap().values().iterator().next().get(0));
}
public void testComplexGenericIndexedMapEntryWithCollectionConversion() {
Set inputValue = new HashSet();
inputValue.add("10");
ComplexMapHolder holder = new ComplexMapHolder();
BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("genericIndexedMap[1]", inputValue);
assertEquals(new Integer(1), holder.getGenericIndexedMap().keySet().iterator().next());
assertEquals(new Long(10), holder.getGenericIndexedMap().values().iterator().next().get(0));
}
public void testComplexDerivedIndexedMapEntry() {
List inputValue = new LinkedList();
inputValue.add("10");
ComplexMapHolder holder = new ComplexMapHolder();
BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("derivedIndexedMap[1]", inputValue);
assertEquals(new Integer(1), holder.getDerivedIndexedMap().keySet().iterator().next());
assertEquals(new Long(10), holder.getDerivedIndexedMap().values().iterator().next().get(0));
}
public void testComplexDerivedIndexedMapEntryWithCollectionConversion() {
Set inputValue = new HashSet();
inputValue.add("10");
ComplexMapHolder holder = new ComplexMapHolder();
BeanWrapper bw = new BeanWrapperImpl(holder);
bw.setPropertyValue("derivedIndexedMap[1]", inputValue);
assertEquals(new Integer(1), holder.getDerivedIndexedMap().keySet().iterator().next());
assertEquals(new Long(10), holder.getDerivedIndexedMap().values().iterator().next().get(0));
}
private static class NestedGenericCollectionBean {
private Map<String, Integer> mapOfInteger;
private Map<String, List<Integer>> mapOfListOfInteger;
private List<Map<String, Integer>> listOfMapOfInteger;
private Map<String, List<List<Integer>>> mapOfListOfListOfInteger;
public Map<String, Integer> getMapOfInteger() {
return mapOfInteger;
}
public void setMapOfInteger(Map<String, Integer> mapOfInteger) {
this.mapOfInteger = mapOfInteger;
}
public Map<String, List<Integer>> getMapOfListOfInteger() {
return mapOfListOfInteger;
}
public void setMapOfListOfInteger(Map<String, List<Integer>> mapOfListOfInteger) {
this.mapOfListOfInteger = mapOfListOfInteger;
}
public List<Map<String, Integer>> getListOfMapOfInteger() {
return listOfMapOfInteger;
}
public void setListOfMapOfInteger(List<Map<String, Integer>> listOfMapOfInteger) {
this.listOfMapOfInteger = listOfMapOfInteger;
}
public Map<String, List<List<Integer>>> getMapOfListOfListOfInteger() {
return mapOfListOfListOfInteger;
}
public void setMapOfListOfListOfInteger(Map<String, List<List<Integer>>> mapOfListOfListOfInteger) {
this.mapOfListOfListOfInteger = mapOfListOfListOfInteger;
}
}
private static class ComplexMapHolder {
private Map<List<Integer>, List<Long>> genericMap;
private Map<Integer, List<Long>> genericIndexedMap = new HashMap<Integer, List<Long>>();
private DerivedMap derivedIndexedMap = new DerivedMap();
public void setGenericMap(Map<List<Integer>, List<Long>> genericMap) {
this.genericMap = genericMap;
}
public Map<List<Integer>, List<Long>> getGenericMap() {
return genericMap;
}
public void setGenericIndexedMap(Map<Integer, List<Long>> genericIndexedMap) {
this.genericIndexedMap = genericIndexedMap;
}
public Map<Integer, List<Long>> getGenericIndexedMap() {
return genericIndexedMap;
}
public void setDerivedIndexedMap(DerivedMap derivedIndexedMap) {
this.derivedIndexedMap = derivedIndexedMap;
}
public DerivedMap getDerivedIndexedMap() {
return derivedIndexedMap;
}
}
private static class DerivedMap extends HashMap<Integer, List<Long>> {
}
}
| |
/*
* Licensed to Crate.IO GmbH ("Crate") under one or more contributor
* license agreements. See the NOTICE file distributed with this work for
* additional information regarding copyright ownership. Crate licenses
* this file to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may
* obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* However, if you have executed another commercial license agreement
* with Crate these terms will supersede the license and you may use the
* software solely pursuant to the terms of the relevant commercial agreement.
*/
package io.crate.operation.merge;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import io.crate.core.MultiFutureCallback;
import io.crate.core.collections.Bucket;
import io.crate.core.collections.BucketPage;
import io.crate.core.collections.Row;
import io.crate.operation.PageConsumeListener;
import io.crate.operation.PageDownstream;
import io.crate.operation.RejectionAwareExecutor;
import io.crate.operation.collect.collectors.TopRowUpstream;
import io.crate.operation.projectors.RowReceiver;
import org.elasticsearch.common.logging.ESLogger;
import org.elasticsearch.common.logging.Loggers;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
public class IteratorPageDownstream implements PageDownstream {
private static final ESLogger LOGGER = Loggers.getLogger(IteratorPageDownstream.class);
private final RowReceiver rowReceiver;
private final Executor executor;
private final AtomicBoolean finished = new AtomicBoolean(false);
private final PagingIterator<Row> pagingIterator;
private final TopRowUpstream topRowUpstream;
private volatile PageConsumeListener pausedListener;
private volatile Iterator<Row> pausedIterator;
private boolean downstreamWantsMore = true;
public IteratorPageDownstream(final RowReceiver rowReceiver,
final PagingIterator<Row> pagingIterator,
Optional<Executor> executor) {
this.pagingIterator = pagingIterator;
this.executor = executor.or(MoreExecutors.directExecutor());
this.rowReceiver = rowReceiver;
this.topRowUpstream = new TopRowUpstream(
this.executor,
new Runnable() {
@Override
public void run() {
try {
processBuckets(pausedIterator, pausedListener);
} catch (Throwable t) {
fail(t);
pausedListener.finish();
}
}
},
new Runnable() {
@Override
public void run() {
if (finished.compareAndSet(true, false)) {
try {
if (processBuckets(pagingIterator.repeat().iterator(), PageConsumeListener.NO_OP_LISTENER)) {
consumeRemaining();
}
finished.set(true);
rowReceiver.finish();
} catch (Throwable t) {
fail(t);
}
} else {
LOGGER.trace("Received repeat, but wasn't finished");
}
}
}
);
rowReceiver.setUpstream(topRowUpstream);
}
private boolean processBuckets(Iterator<Row> iterator, PageConsumeListener listener) {
while (iterator.hasNext()) {
if (finished.get()) {
listener.finish();
return false;
}
Row row = iterator.next();
boolean wantMore = rowReceiver.setNextRow(row);
if (topRowUpstream.shouldPause()) {
pausedListener = listener;
pausedIterator = iterator;
topRowUpstream.pauseProcessed();
return true;
}
if (!wantMore) {
downstreamWantsMore = false;
listener.finish();
return false;
}
}
listener.needMore();
return true;
}
@Override
public void nextPage(BucketPage page, final PageConsumeListener listener) {
FutureCallback<List<Bucket>> finalCallback = new FutureCallback<List<Bucket>>() {
@Override
public void onSuccess(List<Bucket> buckets) {
pagingIterator.merge(numberedBuckets(buckets));
try {
processBuckets(pagingIterator, listener);
} catch (Throwable t) {
fail(t);
listener.finish();
}
}
@Override
public void onFailure(@Nonnull Throwable t) {
fail(t);
listener.finish();
}
};
/**
* Wait for all buckets to arrive before doing any work to make sure that the job context is present on all nodes
* Otherwise there could be race condition.
* E.g. if a FetchProjector finishes early with data from one node and wants to close the remaining contexts it
* could be that one node doesn't even have a context to close yet and that context would remain open.
*
* NOTE: this doesn't use Futures.allAsList because in the case of failures it should still wait for the other
* upstreams before taking any action
*/
Executor executor = RejectionAwareExecutor.wrapExecutor(this.executor, finalCallback);
MultiFutureCallback<Bucket> multiFutureCallback = new MultiFutureCallback<>(page.buckets().size(), finalCallback);
for (ListenableFuture<Bucket> bucketFuture : page.buckets()) {
Futures.addCallback(bucketFuture, multiFutureCallback, executor);
}
}
private Iterable<? extends NumberedIterable<Row>> numberedBuckets(List<Bucket> buckets) {
return Iterables.transform(buckets, new Function<Bucket, NumberedIterable<Row>>() {
int number = -1;
@Nullable
@Override
public NumberedIterable<Row> apply(Bucket input) {
number++;
return new NumberedIterable<>(number, input);
}
});
}
@Override
public void finish() {
if (finished.compareAndSet(false, true)) {
if (downstreamWantsMore) {
consumeRemaining();
}
rowReceiver.finish();
}
}
private void consumeRemaining() {
pagingIterator.finish();
while (pagingIterator.hasNext()) {
Row row = pagingIterator.next();
boolean wantMore = rowReceiver.setNextRow(row);
if (!wantMore) {
break;
}
}
}
@Override
public void fail(Throwable t) {
if (finished.compareAndSet(false, true)) {
rowReceiver.fail(t);
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.