repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
Scrik/Cauldron-1
eclipse/cauldron/src/main/java/cpw/mods/fml/common/LoaderException.java
677
/* * Forge Mod Loader * Copyright (c) 2012-2013 cpw. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v2.1 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * Contributors: * cpw - implementation */ package cpw.mods.fml.common; public class LoaderException extends RuntimeException { /** * */ private static final long serialVersionUID = -5675297950958861378L; public LoaderException(Throwable wrapped) { super(wrapped); } public LoaderException() { } }
gpl-3.0
sbbic/core
qadevOOo/tests/java/ifc/i18n/_XExtendedIndexEntrySupplier.java
14238
/* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. * * This file incorporates work covered by the following license notice: * * 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 . */ package ifc.i18n; import com.sun.star.i18n.CollatorOptions; import com.sun.star.i18n.XExtendedIndexEntrySupplier; import com.sun.star.lang.Locale; import java.util.HashMap; import lib.MultiMethodTest; public class _XExtendedIndexEntrySupplier extends MultiMethodTest { public XExtendedIndexEntrySupplier oObj; protected Locale[] locales = null; protected HashMap<Integer, String[]> algorithms = new HashMap<Integer, String[]>(); public void _compareIndexEntry() { requiredMethod("getIndexKey()"); Locale locale = new Locale("zh", "CN", ""); String val1 = new String(new char[]{UnicodeStringPair.getUnicodeValue(0), UnicodeStringPair.getUnicodeValue(1)}); String val2 = new String(new char[]{UnicodeStringPair.getUnicodeValue(1), UnicodeStringPair.getUnicodeValue(0)}); short result1 = oObj.compareIndexEntry(val1, "", locale, val1, "", locale); short result2 = oObj.compareIndexEntry(val1, "", locale, val2, "", locale); short result3 = oObj.compareIndexEntry(val2, "", locale, val1, "", locale); tRes.tested("compareIndexEntry()", result1 == 0 && result2 + result3 == 0); } /* * gets the list of all algorithms for each listed language * is OK if everyone of the returned lists are filled */ public void _getAlgorithmList() { requiredMethod("getLocaleList()"); boolean result = true; boolean locResult = false; for (int i = 0; i < locales.length; i++) { String[] algNames = oObj.getAlgorithmList(locales[i]); algorithms.put(Integer.valueOf(i), algNames); locResult = algNames != null && algNames.length > 0; System.out.println("Locale " + i + ": " + locales[i].Country+","+locales[i].Language); for (int j=0; j<algNames.length; j++) { System.out.println("\tAlgorithm " + j + ": " + algNames[j]); } if (!locResult) { log.println("No Algorithm found for " + locales[i].Country + "," + locales[i].Language); } result &= locResult; } tRes.tested("getAlgorithmList()", result); } public void _getIndexKey() { requiredMethod("loadAlgorithm()"); char[] characters = new char[] { 19968 }; String getIndexFor = new String(characters); for (int i = 0; i < locales.length; i++) { log.println("Language: " + locales[i].Language); for (int j = 0; j < algorithms.size(); j++) { String[] algs = algorithms.get(Integer.valueOf(j)); for (int k=0;k<algs.length;k++) { log.println("\t Algorythm :" + algs[k]); oObj.loadAlgorithm(locales[i], algs[k], CollatorOptions.CollatorOptions_IGNORE_CASE); log.println("\t\t Get: " + oObj.getIndexKey(getIndexFor, "", locales[i])); } } } tRes.tested("getIndexKey()", true); } /* * gets a list of all locales, is OK if this list isn't empty */ public void _getLocaleList() { locales = oObj.getLocaleList(); tRes.tested("getLocaleList()", locales.length > 0); } /* * gets one phonetic canidate for the chinese local * is ok if 'yi' is returned as expected. */ public void _getPhoneticCandidate() { requiredMethod("getLocaleList()"); boolean res = true; Locale loc = new Locale("zh", "CN", ""); for (int i = 0;i<UnicodeStringPair.getValCount();i++) { char[] c = new char[]{UnicodeStringPair.getUnicodeValue(i)}; String getting = oObj.getPhoneticCandidate(new String(c), loc); boolean locResult = getting.equals(UnicodeStringPair.getExpectedPhoneticString(i)); if (!locResult) { log.println("Char: "+ c[0] + " (" + (int)c[0] + ")"); log.println("Expected " + UnicodeStringPair.getExpectedPhoneticString(i)); log.println("Getting " + getting); } res &= locResult; } tRes.tested("getPhoneticCandidate()", res); } /* * loads all algorithms available in all language. * Is OK if no exception occurs and the method returns * true for each valid algorithm and false otherwise */ public void _loadAlgorithm() { requiredMethod("getAlgorithmList()"); boolean res = true; for (int i = 0; i < algorithms.size(); i++) { String[] names = algorithms.get(Integer.valueOf(i)); log.println("loading algorithms for " + locales[i].Country + "," + locales[i].Language); for (int j = 0; j < names.length; j++) { log.println("\t Loading " + names[j]); boolean localres = oObj.loadAlgorithm(locales[i], names[j], CollatorOptions.CollatorOptions_IGNORE_CASE); if (!localres) { log.println("\t ... didn't work - FAILED"); } else { log.println("\t ... worked - OK"); } res &= localres; } } tRes.tested("loadAlgorithm()", res); } /* * checks the method usePhoneticEntry(). Only the languages ja, ko and zh * should return true. Has OK state if exactly this is the case. */ public void _usePhoneticEntry() { requiredMethod("getLocaleList()"); boolean res = true; for (int i = 0; i < locales.length; i++) { boolean expected = false; if (locales[i].Language.equals("ja") || locales[i].Language.equals("ko") || locales[i].Language.equals("zh")) { expected = true; } boolean locResult = oObj.usePhoneticEntry(locales[i]) == expected; if (!locResult) { log.println("Failure for language " + locales[i].Language); log.println("Expected " + expected); log.println("Getting " + oObj.usePhoneticEntry(locales[i])); } res &= locResult; } tRes.tested("usePhoneticEntry()", res); } /** * Helper class to handle the phonetic equivalence of unicode characters * This class delivers an amount of unicode characters and the equivalent phonetics * for the "getPhoneticCandidate" test. Euivalents are only usable for zh,CN locale. */ public static class UnicodeStringPair { static final int valCount = 78; static final String[] sStringEquivalence = new String[valCount]; static final char[] iUnicodeEquivalence = new char[valCount]; static { fillValues(); } public static int getValCount() { return valCount; } public static String getExpectedPhoneticString(int index) { if (index >= valCount) return null; return sStringEquivalence[index]; } public static char getUnicodeValue(int index) { if (index > valCount) return 0; return iUnicodeEquivalence[index]; } private static void fillValues() { iUnicodeEquivalence[0] = 20049; sStringEquivalence[0] = "zhong"; iUnicodeEquivalence[1] = 19968; sStringEquivalence[1] = "yi"; iUnicodeEquivalence[2] = 19969; sStringEquivalence[2] = "ding"; iUnicodeEquivalence[3] = 19970; sStringEquivalence[3] = "kao"; iUnicodeEquivalence[4] = 19971; sStringEquivalence[4] = "qi"; iUnicodeEquivalence[5] = 19972; sStringEquivalence[5] = "shang"; iUnicodeEquivalence[6] = 19973; sStringEquivalence[6] = "xia"; iUnicodeEquivalence[7] = 19975; sStringEquivalence[7] = "wan"; iUnicodeEquivalence[8] = 19976; sStringEquivalence[8] = "zhang"; iUnicodeEquivalence[9] = 19977; sStringEquivalence[9] = "san"; iUnicodeEquivalence[10] = 19978; sStringEquivalence[10] = "shang"; iUnicodeEquivalence[11] = 19979; sStringEquivalence[11] = "xia"; iUnicodeEquivalence[12] = 19980; sStringEquivalence[12] = "ji"; iUnicodeEquivalence[13] = 19981; sStringEquivalence[13] = "bu"; iUnicodeEquivalence[14] = 19982; sStringEquivalence[14] = "yu"; iUnicodeEquivalence[15] = 19983; sStringEquivalence[15] = "mian"; iUnicodeEquivalence[16] = 19984; sStringEquivalence[16] = "gai"; iUnicodeEquivalence[17] = 19985; sStringEquivalence[17] = "chou"; iUnicodeEquivalence[18] = 19986; sStringEquivalence[18] = "chou"; iUnicodeEquivalence[19] = 19987; sStringEquivalence[19] = "zhuan"; iUnicodeEquivalence[20] = 19988; sStringEquivalence[20] = "qie"; iUnicodeEquivalence[21] = 19989; sStringEquivalence[21] = "pi"; iUnicodeEquivalence[22] = 19990; sStringEquivalence[22] = "shi"; iUnicodeEquivalence[23] = 19991; sStringEquivalence[23] = "shi"; iUnicodeEquivalence[24] = 19992; sStringEquivalence[24] = "qiu"; iUnicodeEquivalence[25] = 19993; sStringEquivalence[25] = "bing"; iUnicodeEquivalence[26] = 19994; sStringEquivalence[26] = "ye"; iUnicodeEquivalence[27] = 19995; sStringEquivalence[27] = "cong"; iUnicodeEquivalence[28] = 19996; sStringEquivalence[28] = "dong"; iUnicodeEquivalence[29] = 19997; sStringEquivalence[29] = "si"; iUnicodeEquivalence[30] = 19998; sStringEquivalence[30] = "cheng"; iUnicodeEquivalence[31] = 19999; sStringEquivalence[31] = "diu"; iUnicodeEquivalence[32] = 20000; sStringEquivalence[32] = "qiu"; iUnicodeEquivalence[33] = 20001; sStringEquivalence[33] = "liang"; iUnicodeEquivalence[34] = 20002; sStringEquivalence[34] = "diu"; iUnicodeEquivalence[35] = 20003; sStringEquivalence[35] = "you"; iUnicodeEquivalence[36] = 20004; sStringEquivalence[36] = "liang"; iUnicodeEquivalence[37] = 20005; sStringEquivalence[37] = "yan"; iUnicodeEquivalence[38] = 20006; sStringEquivalence[38] = "bing"; iUnicodeEquivalence[39] = 20007; sStringEquivalence[39] = "sang"; iUnicodeEquivalence[40] = 20008; sStringEquivalence[40] = "shu"; iUnicodeEquivalence[41] = 20009; sStringEquivalence[41] = "jiu"; iUnicodeEquivalence[42] = 20010; sStringEquivalence[42] = "ge"; iUnicodeEquivalence[43] = 20011; sStringEquivalence[43] = "ya"; iUnicodeEquivalence[44] = 20012; sStringEquivalence[44] = "qiang"; iUnicodeEquivalence[45] = 20013; sStringEquivalence[45] = "zhong"; iUnicodeEquivalence[46] = 20014; sStringEquivalence[46] = "ji"; iUnicodeEquivalence[47] = 20015; sStringEquivalence[47] = "jie"; iUnicodeEquivalence[48] = 20016; sStringEquivalence[48] = "feng"; iUnicodeEquivalence[49] = 20017; sStringEquivalence[49] = "guan"; iUnicodeEquivalence[50] = 20018; sStringEquivalence[50] = "chuan"; iUnicodeEquivalence[51] = 20019; sStringEquivalence[51] = "chan"; iUnicodeEquivalence[52] = 20020; sStringEquivalence[52] = "lin"; iUnicodeEquivalence[53] = 20021; sStringEquivalence[53] = "zhuo"; iUnicodeEquivalence[54] = 20022; sStringEquivalence[54] = "zhu"; iUnicodeEquivalence[55] = 20024; sStringEquivalence[55] = "wan"; iUnicodeEquivalence[56] = 20025; sStringEquivalence[56] = "dan"; iUnicodeEquivalence[57] = 20026; sStringEquivalence[57] = "wei"; iUnicodeEquivalence[58] = 20027; sStringEquivalence[58] = "zhu"; iUnicodeEquivalence[59] = 20028; sStringEquivalence[59] = "jing"; iUnicodeEquivalence[60] = 20029; sStringEquivalence[60] = "li"; iUnicodeEquivalence[61] = 20030; sStringEquivalence[61] = "ju"; iUnicodeEquivalence[62] = 20031; sStringEquivalence[62] = "pie"; iUnicodeEquivalence[63] = 20032; sStringEquivalence[63] = "fu"; iUnicodeEquivalence[64] = 20033; sStringEquivalence[64] = "yi"; iUnicodeEquivalence[65] = 20034; sStringEquivalence[65] = "yi"; iUnicodeEquivalence[66] = 20035; sStringEquivalence[66] = "nai"; iUnicodeEquivalence[67] = 20037; sStringEquivalence[67] = "jiu"; iUnicodeEquivalence[68] = 20038; sStringEquivalence[68] = "jiu"; iUnicodeEquivalence[69] = 20039; sStringEquivalence[69] = "tuo"; iUnicodeEquivalence[70] = 20040; sStringEquivalence[70] = "me"; iUnicodeEquivalence[71] = 20041; sStringEquivalence[71] = "yi"; iUnicodeEquivalence[72] = 20043; sStringEquivalence[72] = "zhi"; iUnicodeEquivalence[73] = 20044; sStringEquivalence[73] = "wu"; iUnicodeEquivalence[74] = 20045; sStringEquivalence[74] = "zha"; iUnicodeEquivalence[75] = 20046; sStringEquivalence[75] = "hu"; iUnicodeEquivalence[76] = 20047; sStringEquivalence[76] = "fa"; iUnicodeEquivalence[77] = 20048; sStringEquivalence[77] = "le"; } } }
gpl-3.0
jvanz/core
android/source/src/java/org/libreoffice/overlay/DocumentOverlayView.java
12279
/* -*- Mode: Java; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* * This file is part of the LibreOffice project. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.libreoffice.overlay; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PointF; import android.graphics.RectF; import android.util.AttributeSet; import android.view.MotionEvent; import android.view.View; import org.libreoffice.canvas.Cursor; import org.libreoffice.canvas.GraphicSelection; import org.libreoffice.canvas.SelectionHandle; import org.libreoffice.canvas.SelectionHandleEnd; import org.libreoffice.canvas.SelectionHandleMiddle; import org.libreoffice.canvas.SelectionHandleStart; import org.mozilla.gecko.gfx.ImmutableViewportMetrics; import org.mozilla.gecko.gfx.LayerView; import org.mozilla.gecko.gfx.RectUtils; import java.util.ArrayList; import java.util.List; /** * Document overlay view is responsible for showing the client drawn overlay * elements like cursor, selection and graphic selection, and manipulate them. */ public class DocumentOverlayView extends View implements View.OnTouchListener { private static final String LOGTAG = DocumentOverlayView.class.getSimpleName(); private static final int CURSOR_BLINK_TIME = 500; private boolean mInitialized = false; private List<RectF> mSelections = new ArrayList<RectF>(); private List<RectF> mScaledSelections = new ArrayList<RectF>(); private Paint mSelectionPaint = new Paint(); private boolean mSelectionsVisible; private GraphicSelection mGraphicSelection; private boolean mGraphicSelectionMove = false; private LayerView mLayerView; private SelectionHandle mHandleMiddle; private SelectionHandle mHandleStart; private SelectionHandle mHandleEnd; private Cursor mCursor; private SelectionHandle mDragHandle = null; public DocumentOverlayView(Context context) { super(context); } public DocumentOverlayView(Context context, AttributeSet attrs) { super(context, attrs); } public DocumentOverlayView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } /** * Initialize the selection and cursor view. */ public void initialize(LayerView layerView) { if (!mInitialized) { setOnTouchListener(this); mLayerView = layerView; mCursor = new Cursor(); mCursor.setVisible(false); mSelectionPaint.setColor(Color.BLUE); mSelectionPaint.setAlpha(50); mSelectionsVisible = false; mGraphicSelection = new GraphicSelection(); mGraphicSelection.setVisible(false); postDelayed(cursorAnimation, CURSOR_BLINK_TIME); mHandleMiddle = new SelectionHandleMiddle(getContext()); mHandleStart = new SelectionHandleStart(getContext()); mHandleEnd = new SelectionHandleEnd(getContext()); mInitialized = true; } } /** * Change the cursor position. * @param position - new position of the cursor */ public void changeCursorPosition(RectF position) { if (RectUtils.fuzzyEquals(mCursor.mPosition, position)) { return; } mCursor.mPosition = position; ImmutableViewportMetrics metrics = mLayerView.getViewportMetrics(); repositionWithViewport(metrics.viewportRectLeft, metrics.viewportRectTop, metrics.zoomFactor); } /** * Change the text selection rectangles. * @param selectionRects - list of text selection rectangles */ public void changeSelections(List<RectF> selectionRects) { mSelections = selectionRects; ImmutableViewportMetrics metrics = mLayerView.getViewportMetrics(); repositionWithViewport(metrics.viewportRectLeft, metrics.viewportRectTop, metrics.zoomFactor); } /** * Change the graphic selection rectangle. * @param rectangle - new graphic selection rectangle */ public void changeGraphicSelection(RectF rectangle) { if (RectUtils.fuzzyEquals(mGraphicSelection.mRectangle, rectangle)) { return; } mGraphicSelection.mRectangle = rectangle; ImmutableViewportMetrics metrics = mLayerView.getViewportMetrics(); repositionWithViewport(metrics.viewportRectLeft, metrics.viewportRectTop, metrics.zoomFactor); } public void repositionWithViewport(float x, float y, float zoom) { RectF rect = convertToScreen(mCursor.mPosition, x, y, zoom); mCursor.reposition(rect); rect = convertToScreen(mHandleMiddle.mDocumentPosition, x, y, zoom); mHandleMiddle.reposition(rect.left, rect.bottom); rect = convertToScreen(mHandleStart.mDocumentPosition, x, y, zoom); mHandleStart.reposition(rect.left, rect.bottom); rect = convertToScreen(mHandleEnd.mDocumentPosition, x, y, zoom); mHandleEnd.reposition(rect.left, rect.bottom); mScaledSelections.clear(); for (RectF selection : mSelections) { RectF scaledSelection = convertToScreen(selection, x, y, zoom); mScaledSelections.add(scaledSelection); } RectF scaledGraphicSelection = convertToScreen(mGraphicSelection.mRectangle, x, y, zoom); mGraphicSelection.reposition(scaledGraphicSelection); invalidate(); } /** * Convert the input rectangle from document to screen coordinates * according to current viewport data (x, y, zoom). */ private static RectF convertToScreen(RectF inputRect, float x, float y, float zoom) { RectF rect = RectUtils.scale(inputRect, zoom); rect.offset(-x, -y); return rect; } /** * Drawing on canvas. */ @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); mCursor.draw(canvas); mHandleMiddle.draw(canvas); mHandleStart.draw(canvas); mHandleEnd.draw(canvas); if (mSelectionsVisible) { for (RectF selection : mScaledSelections) { canvas.drawRect(selection, mSelectionPaint); } } mGraphicSelection.draw(canvas); } /** * Cursor animation function. Switch the alpha between opaque and fully transparent. */ private Runnable cursorAnimation = new Runnable() { public void run() { if (mCursor.isVisible()) { mCursor.cycleAlpha(); invalidate(); } postDelayed(cursorAnimation, CURSOR_BLINK_TIME); } }; /** * Show the cursor on the view. */ public void showCursor() { if (!mCursor.isVisible()) { mCursor.setVisible(true); invalidate(); } } /** * Hide the cursor. */ public void hideCursor() { if (mCursor.isVisible()) { mCursor.setVisible(false); invalidate(); } } /** * Show text selection rectangles. */ public void showSelections() { if (!mSelectionsVisible) { mSelectionsVisible = true; invalidate(); } } /** * Hide text selection rectangles. */ public void hideSelections() { if (mSelectionsVisible) { mSelectionsVisible = false; invalidate(); } } /** * Show the graphic selection on the view. */ public void showGraphicSelection() { if (!mGraphicSelection.isVisible()) { mGraphicSelectionMove = false; mGraphicSelection.reset(); mGraphicSelection.setVisible(true); invalidate(); } } /** * Hide the graphic selection. */ public void hideGraphicSelection() { if (mGraphicSelection.isVisible()) { mGraphicSelection.setVisible(false); invalidate(); } } /** * Handle the triggered touch event. */ @Override public boolean onTouch(View view, MotionEvent event) { PointF point = new PointF(event.getX(), event.getY()); switch (event.getActionMasked()) { case MotionEvent.ACTION_DOWN: { if (mGraphicSelection.isVisible()) { // Check if inside graphic selection was hit if (mGraphicSelection.contains(point.x, point.y)) { mGraphicSelectionMove = true; mGraphicSelection.dragStart(point); invalidate(); return true; } } else { if (mHandleStart.contains(point.x, point.y)) { mHandleStart.dragStart(point); mDragHandle = mHandleStart; return true; } else if (mHandleEnd.contains(point.x, point.y)) { mHandleEnd.dragStart(point); mDragHandle = mHandleEnd; return true; } else if (mHandleMiddle.contains(point.x, point.y)) { mHandleMiddle.dragStart(point); mDragHandle = mHandleMiddle; return true; } } } case MotionEvent.ACTION_UP: { if (mGraphicSelection.isVisible() && mGraphicSelectionMove) { mGraphicSelection.dragEnd(point); mGraphicSelectionMove = false; invalidate(); return true; } else if (mDragHandle != null) { mDragHandle.dragEnd(point); mDragHandle = null; } } case MotionEvent.ACTION_MOVE: { if (mGraphicSelection.isVisible() && mGraphicSelectionMove) { mGraphicSelection.dragging(point); invalidate(); return true; } else if (mDragHandle != null) { mDragHandle.dragging(point); } } } return false; } /** * Change the handle document position. * @param type - the type of the handle * @param position - the new document position */ public void positionHandle(SelectionHandle.HandleType type, RectF position) { SelectionHandle handle = getHandleForType(type); if (RectUtils.fuzzyEquals(handle.mDocumentPosition, position)) { return; } RectUtils.assign(handle.mDocumentPosition, position); ImmutableViewportMetrics metrics = mLayerView.getViewportMetrics(); repositionWithViewport(metrics.viewportRectLeft, metrics.viewportRectTop, metrics.zoomFactor); } /** * Hide the handle. * @param type - type of the handle */ public void hideHandle(SelectionHandle.HandleType type) { SelectionHandle handle = getHandleForType(type); if (handle.isVisible()) { handle.setVisible(false); invalidate(); } } /** * Show the handle. * @param type - type of the handle */ public void showHandle(SelectionHandle.HandleType type) { SelectionHandle handle = getHandleForType(type); if (!handle.isVisible()) { handle.setVisible(true); invalidate(); } } /** * Returns the handle instance for the input type. */ private SelectionHandle getHandleForType(SelectionHandle.HandleType type) { switch(type) { case START: return mHandleStart; case END: return mHandleEnd; case MIDDLE: return mHandleMiddle; } return null; } } /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
gpl-3.0
s20121035/rk3288_android5.1_repo
external/jsilver/src/com/google/clearsilver/jsilver/functions/Function.java
972
/* * Copyright (C) 2010 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.clearsilver.jsilver.functions; import com.google.clearsilver.jsilver.values.Value; /** * Plugin for JSilver functions made available to templates. e.g &lt;cs var:my_function(x, y) &gt; */ public interface Function { /** * Execute a function. Should always return a result. */ Value execute(Value... args); boolean isEscapingFunction(); }
gpl-3.0
aebert1/BigTransport
build/tmp/recompileMc/sources/net/minecraft/client/gui/inventory/GuiScreenHorseInventory.java
3656
package net.minecraft.client.gui.inventory; import net.minecraft.client.Minecraft; import net.minecraft.client.renderer.GlStateManager; import net.minecraft.entity.passive.EntityHorse; import net.minecraft.inventory.ContainerHorseInventory; import net.minecraft.inventory.IInventory; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; @SideOnly(Side.CLIENT) public class GuiScreenHorseInventory extends GuiContainer { private static final ResourceLocation horseGuiTextures = new ResourceLocation("textures/gui/container/horse.png"); /** The player inventory bound to this GUI. */ private IInventory playerInventory; /** The horse inventory bound to this GUI. */ private IInventory horseInventory; /** The EntityHorse whose inventory is currently being accessed. */ private EntityHorse horseEntity; /** The mouse x-position recorded during the last rendered frame. */ private float mousePosx; /** The mouse y-position recorded during the last renderered frame. */ private float mousePosY; public GuiScreenHorseInventory(IInventory playerInv, IInventory horseInv, EntityHorse horse) { super(new ContainerHorseInventory(playerInv, horseInv, horse, Minecraft.getMinecraft().thePlayer)); this.playerInventory = playerInv; this.horseInventory = horseInv; this.horseEntity = horse; this.allowUserInput = false; } /** * Draw the foreground layer for the GuiContainer (everything in front of the items) * * @param mouseX Mouse x coordinate * @param mouseY Mouse y coordinate */ protected void drawGuiContainerForegroundLayer(int mouseX, int mouseY) { this.fontRendererObj.drawString(this.horseInventory.getDisplayName().getUnformattedText(), 8, 6, 4210752); this.fontRendererObj.drawString(this.playerInventory.getDisplayName().getUnformattedText(), 8, this.ySize - 96 + 2, 4210752); } /** * Draws the background layer of this container (behind the items). * * @param partialTicks How far into the current tick the game is, with 0.0 being the start of the tick and 1.0 being * the end. * @param mouseX Mouse x coordinate * @param mouseY Mouse y coordinate */ protected void drawGuiContainerBackgroundLayer(float partialTicks, int mouseX, int mouseY) { GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F); this.mc.getTextureManager().bindTexture(horseGuiTextures); int i = (this.width - this.xSize) / 2; int j = (this.height - this.ySize) / 2; this.drawTexturedModalRect(i, j, 0, 0, this.xSize, this.ySize); if (this.horseEntity.isChested()) { this.drawTexturedModalRect(i + 79, j + 17, 0, this.ySize, 90, 54); } if (this.horseEntity.getType().isHorse()) { this.drawTexturedModalRect(i + 7, j + 35, 0, this.ySize + 54, 18, 18); } GuiInventory.drawEntityOnScreen(i + 51, j + 60, 17, (float)(i + 51) - this.mousePosx, (float)(j + 75 - 50) - this.mousePosY, this.horseEntity); } /** * Draws the screen and all the components in it. * * @param mouseX Mouse x coordinate * @param mouseY Mouse y coordinate * @param partialTicks How far into the current tick (1/20th of a second) the game is */ public void drawScreen(int mouseX, int mouseY, float partialTicks) { this.mousePosx = (float)mouseX; this.mousePosY = (float)mouseY; super.drawScreen(mouseX, mouseY, partialTicks); } }
gpl-3.0
PiLogic/PlotSquared
src/main/java/com/plotsquared/bukkit/events/PlotUnlinkEvent.java
3422
//////////////////////////////////////////////////////////////////////////////////////////////////// // PlotSquared - A plot manager and world generator for the Bukkit API / // Copyright (c) 2014 IntellectualSites/IntellectualCrafters / // / // 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 3 of the License, or / // (at your option) any later version. / // / // This program is distributed in the hope that it will be useful, / // but WITHOUT ANY WARRANTY; without even the implied warranty of / // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the / // GNU 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA / // / // You can contact us via: support@intellectualsites.com / //////////////////////////////////////////////////////////////////////////////////////////////////// package com.plotsquared.bukkit.events; import java.util.ArrayList; import org.bukkit.World; import org.bukkit.event.Cancellable; import org.bukkit.event.Event; import org.bukkit.event.HandlerList; import com.intellectualcrafters.plot.object.PlotId; /** * @author Empire92 */ public class PlotUnlinkEvent extends Event implements Cancellable { private static HandlerList handlers = new HandlerList(); private final ArrayList<PlotId> plots; private final World world; private boolean cancelled; /** * Called when a mega-plot is unlinked. * * @param world World in which the event occurred * @param plots Plots that are involved in the event */ public PlotUnlinkEvent(final World world, final ArrayList<PlotId> plots) { this.plots = plots; this.world = world; } public static HandlerList getHandlerList() { return handlers; } /** * Get the plots involved * * @return PlotId */ public ArrayList<PlotId> getPlots() { return this.plots; } public World getWorld() { return this.world; } @Override public HandlerList getHandlers() { return handlers; } @Override public boolean isCancelled() { return this.cancelled; } @Override public void setCancelled(final boolean b) { this.cancelled = b; } }
gpl-3.0
PoGoTools/PoGoTools
goiv/src/main/java/com/kamron/pogoiv/logic/IVCombination.java
2737
package com.kamron.pogoiv.logic; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; /** * Created by Johan on 2016-08-18. * A class which represents an IV value */ public class IVCombination { public final int att; public final int def; public final int sta; public final int percentPerfect; public IVCombination(int att, int def, int sta) { this.att = att; this.def = def; this.sta = sta; percentPerfect = Math.round((att + def + sta) / 45f * 100); } public static IVCombination MAX = new IVCombination(15, 15, 15); @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } IVCombination that = (IVCombination) o; return att == that.att && def == that.def && sta == that.sta; } /** * Get the highest of the stats in the iv combination. * For example, in the iv combination 7 5 11 * this method would return 11. * * @return a number between 0 and 15 which is the highest stat in this combination */ public int getHighestStat() { return Collections.max(Arrays.asList(att, def, sta)); } /** * Returns a boolean array that represent which values are the highest in an iv. * Examples: Iv 14-14-7 would be [true,true,false] * iv 4,6,1 would be [false, true, false] */ public Boolean[] getHighestStatSignature() { Boolean[] attDefSta = new Boolean[3]; int maxStat = getHighestStat(); attDefSta[0] = att >= maxStat; attDefSta[1] = def >= maxStat; attDefSta[2] = sta >= maxStat; return attDefSta; } /** * Get total IV (attack + defence + stamina) value. * * @return total IV */ public int getTotal() { return att + def + sta; } @Override public int hashCode() { int result = att; result = 31 * result + def; result = 31 * result + sta; return result; } public String toString() { return "Att: " + this.att + " def: " + this.def + " sta: " + this.sta + " %: " + percentPerfect; } /** * A comparator that compares IVCombinations by their total. * Note: this comparator imposes orderings that are inconsistent with equals: compare(o1, o2) == 0 does not imply * o1.equals(o2). */ public static Comparator<IVCombination> totalComparator = new Comparator<IVCombination>() { @Override public int compare(IVCombination o1, IVCombination o2) { return o1.getTotal() - o2.getTotal(); } }; }
gpl-3.0
gesellix/MasterPassword
MasterPassword/Java/masterpassword-gui/src/main/java/com/lyndir/masterpassword/gui/ModelAuthenticationPanel.java
8019
package com.lyndir.masterpassword.gui; import static com.lyndir.lhunath.opal.system.util.StringUtils.strf; import com.google.common.base.Function; import com.google.common.base.Preconditions; import com.google.common.collect.*; import com.lyndir.lhunath.opal.system.logging.Logger; import com.lyndir.masterpassword.model.MPUser; import com.lyndir.masterpassword.model.MPUserFileManager; import com.lyndir.masterpassword.gui.util.Components; import java.awt.*; import java.awt.event.*; import javax.annotation.Nullable; import javax.swing.*; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import javax.swing.plaf.metal.MetalComboBoxEditor; import org.jetbrains.annotations.NotNull; /** * @author lhunath, 2014-06-11 */ public class ModelAuthenticationPanel extends AuthenticationPanel implements ItemListener, ActionListener, DocumentListener { @SuppressWarnings("UnusedDeclaration") private static final Logger logger = Logger.get( ModelAuthenticationPanel.class ); private final JComboBox<ModelUser> userField; private final JLabel masterPasswordLabel; private final JPasswordField masterPasswordField; public ModelAuthenticationPanel(final UnlockFrame unlockFrame) { super( unlockFrame ); add( Components.stud() ); // Avatar avatarLabel.addMouseListener( new MouseAdapter() { @Override public void mouseClicked(final MouseEvent e) { ModelUser selectedUser = getSelectedUser(); if (selectedUser != null) { selectedUser.setAvatar( selectedUser.getAvatar() + 1 ); updateUser( false ); } } } ); // User JLabel userLabel = Components.label( "User:" ); add( userLabel ); userField = Components.comboBox( readConfigUsers() ); userField.setFont( Res.valueFont().deriveFont( 12f ) ); userField.addItemListener( this ); userField.addActionListener( this ); userField.setEditor( new MetalComboBoxEditor() { @Override protected JTextField createEditorComponent() { JTextField editorComponents = Components.textField(); editorComponents.setForeground( Color.red ); return editorComponents; } } ); add( userField ); add( Components.stud() ); // Master Password masterPasswordLabel = Components.label( "Master Password:" ); add( masterPasswordLabel ); masterPasswordField = Components.passwordField(); masterPasswordField.addActionListener( this ); masterPasswordField.getDocument().addDocumentListener( this ); add( masterPasswordField ); } @Override public Component getFocusComponent() { return masterPasswordField.isVisible()? masterPasswordField: null; } @Override protected void updateUser(boolean repack) { ModelUser selectedUser = getSelectedUser(); if (selectedUser != null) { avatarLabel.setIcon( Res.avatar( selectedUser.getAvatar() ) ); boolean showPasswordField = !selectedUser.keySaved(); if (masterPasswordField.isVisible() != showPasswordField) { masterPasswordLabel.setVisible( showPasswordField ); masterPasswordField.setVisible( showPasswordField ); repack = true; } } super.updateUser( repack ); } @Override protected ModelUser getSelectedUser() { int selectedIndex = userField.getSelectedIndex(); if (selectedIndex < 0) return null; return userField.getModel().getElementAt( selectedIndex ); } @NotNull @Override public char[] getMasterPassword() { return masterPasswordField.getPassword(); } @Override public Iterable<? extends JButton> getButtons() { return ImmutableList.of( new JButton( Res.iconAdd() ) { { addActionListener( new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { String fullName = JOptionPane.showInputDialog( ModelAuthenticationPanel.this, // "Enter your full name, ensuring it is correctly spelled and capitalized:", "New User", JOptionPane.QUESTION_MESSAGE ); MPUserFileManager.get().addUser( new MPUser( fullName ) ); userField.setModel( new DefaultComboBoxModel<>( readConfigUsers() ) ); updateUser( true ); } } ); setToolTipText( "Add a new user to the list." ); } }, new JButton( Res.iconDelete() ) { { addActionListener( new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { ModelUser deleteUser = getSelectedUser(); if (deleteUser == null) return; if (JOptionPane.showConfirmDialog( ModelAuthenticationPanel.this, // strf( "Are you sure you want to delete the user and sites remembered for:\n%s.", deleteUser.getFullName() ), // "Delete User", JOptionPane.OK_CANCEL_OPTION, JOptionPane.QUESTION_MESSAGE ) == JOptionPane.CANCEL_OPTION) return; MPUserFileManager.get().deleteUser( deleteUser.getModel() ); userField.setModel( new DefaultComboBoxModel<>( readConfigUsers() ) ); updateUser( true ); } } ); setToolTipText( "Delete the selected user." ); } }, new JButton( Res.iconQuestion() ) { { addActionListener( new ActionListener() { @Override public void actionPerformed(final ActionEvent e) { JOptionPane.showMessageDialog( ModelAuthenticationPanel.this, // strf( "Reads users and sites from the directory at:\n%s", MPUserFileManager.get().getPath().getAbsolutePath() ), // "Help", JOptionPane.INFORMATION_MESSAGE ); } } ); setToolTipText( "More information." ); } } ); } @Override public void reset() { masterPasswordField.setText( "" ); } private ModelUser[] readConfigUsers() { return FluentIterable.from( MPUserFileManager.get().getUsers() ).transform( new Function<MPUser, ModelUser>() { @Nullable @Override public ModelUser apply(@Nullable final MPUser model) { return new ModelUser( Preconditions.checkNotNull( model ) ); } } ).toArray( ModelUser.class ); } @Override public void itemStateChanged(final ItemEvent e) { updateUser( false ); } @Override public void actionPerformed(final ActionEvent e) { updateUser( false ); unlockFrame.trySignIn( userField ); } @Override public void insertUpdate(final DocumentEvent e) { updateUser( false ); } @Override public void removeUpdate(final DocumentEvent e) { updateUser( false ); } @Override public void changedUpdate(final DocumentEvent e) { updateUser( false ); } }
gpl-3.0
acz-icm/coansys
commons/src/main/java/pl/edu/icm/coansys/commons/pig/udf/ByteArrayToText.java
1826
/* * This file is part of CoAnSys project. * Copyright (c) 2012-2015 ICM-UW * * CoAnSys is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * CoAnSys is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with CoAnSys. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.coansys.commons.pig.udf; import java.io.IOException; import org.apache.pig.EvalFunc; import org.apache.pig.data.DataByteArray; import org.apache.pig.data.DataType; import org.apache.pig.data.Tuple; import org.apache.pig.data.TupleFactory; import org.apache.pig.impl.logicalLayer.FrontendException; import org.apache.pig.impl.logicalLayer.schema.Schema; /** * * @author pdendek */ public class ByteArrayToText extends EvalFunc<Tuple> { @Override public Schema outputSchema(Schema p_input) { try { return Schema.generateNestedSchema(DataType.TUPLE, DataType.CHARARRAY); } catch (FrontendException e) { throw new IllegalStateException(e); } } @Override public Tuple exec(Tuple input) throws IOException { Tuple t = TupleFactory.getInstance().newTuple(); t.append(((DataByteArray) input.get(0)).toString()); return t; } public static void main(String[] args){ String s = "bla"; DataByteArray dba = new DataByteArray(); dba.set(s.getBytes()); System.out.println(dba.toString()); } }
agpl-3.0
aihua/opennms
features/rest/model/src/main/java/org/opennms/web/rest/model/v2/AlarmCollectionDTO.java
2061
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2017-2017 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2017 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.web.rest.model.v2; import org.codehaus.jackson.annotate.JsonProperty; import org.opennms.core.config.api.JaxbListWrapper; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import java.util.Collection; import java.util.List; @XmlRootElement(name="alarms") @XmlAccessorType(XmlAccessType.NONE) public class AlarmCollectionDTO extends JaxbListWrapper<AlarmDTO> { public AlarmCollectionDTO() { // No-arg constructor for JAXB } public AlarmCollectionDTO(final Collection<? extends AlarmDTO> alarms) { super(alarms); } @XmlElement(name="alarm") @JsonProperty("alarm") public List<AlarmDTO> getObjects() { return super.getObjects(); } }
agpl-3.0
quikkian-ua-devops/will-financials
kfs-core/src/main/java/edu/arizona/kfs/vnd/batch/EcustomsDailyStep.java
1357
package edu.arizona.kfs.vnd.batch; import java.util.Date; import org.apache.log4j.Logger; import org.kuali.kfs.sys.batch.AbstractStep; import org.kuali.kfs.sys.context.SpringContext; import edu.arizona.kfs.vnd.service.EcustomsService; /** * UAF-66 MOD-PA7000-02 ECustoms - US Export Compliance * * This step generates the daily eCustoms data files. * * @author Adam Kost kosta@email.arizona.edu */ public class EcustomsDailyStep extends AbstractStep { private static final Logger LOG = Logger.getLogger(EcustomsDailyStep.class); private static transient volatile EcustomsService ecustomsService; private EcustomsService getEcustomsService() { if (ecustomsService == null) { ecustomsService = SpringContext.getBean(EcustomsService.class); } return ecustomsService; } @Override public boolean execute(String jobName, Date jobRunDate) throws InterruptedException { boolean retval = false; try { retval = getEcustomsService().createEcustomsDailyFile(jobName, jobRunDate); } catch (Exception e) { LOG.error("Error when running EcustomsDailyStep: " + e.getMessage()); throw new InterruptedException(e.getMessage()); // retval = false; } return retval; } }
agpl-3.0
sangohan/gwt-chronoscope
chronoscope-api/src/main/java/org/timepedia/chronoscope/client/event/OverlayChangeEvent.java
898
package org.timepedia.chronoscope.client.event; import org.timepedia.chronoscope.client.XYPlot; import org.timepedia.chronoscope.client.Overlay; import org.timepedia.exporter.client.ExportPackage; import org.timepedia.exporter.client.Exportable; import org.timepedia.exporter.client.Export; /** * */ @ExportPackage("chronoscope") public class OverlayChangeEvent extends PlotEvent<OverlayChangeHandler> implements Exportable { public static Type<OverlayChangeHandler> TYPE = new Type<OverlayChangeHandler>(); @Export public Overlay getOverlay() { return overlay; } private Overlay overlay; public OverlayChangeEvent(XYPlot plot, Overlay o) { super(plot); this.overlay = o; } public Type getAssociatedType() { return TYPE; } protected void dispatch(OverlayChangeHandler overlayChangeHandler) { overlayChangeHandler.onOverlayChanged(this); } }
lgpl-2.1
4ment/beast-mcmc
src/dr/util/DataTable.java
11903
/* * DataTable.java * * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard * * This file is part of BEAST. * See the NOTICE file distributed with this work for additional * information regarding copyright ownership and licensing. * * BEAST is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * BEAST 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 BEAST; if not, write to the * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, * Boston, MA 02110-1301 USA */ package dr.util; import java.io.*; import java.util.*; /** * @author Andrew Rambaut * @version $Id$ */ public interface DataTable<T> { int getColumnCount(); int getRowCount(); String[] getColumnLabels(); String[] getRowLabels(); T getColumn(int columnIndex); T getRow(int rowIndex); T[] getData(); public class Double implements DataTable<double[]> { private Double(Reader source, boolean hasColumnLabels, boolean hasRowLabels, boolean isCSV) throws IOException { this(source, hasColumnLabels, hasRowLabels, false, isCSV); } private Double(Reader source, boolean hasColumnLabels, boolean hasRowLabels, boolean includeFirstColumnLabel, boolean isCSV) throws IOException { BufferedReader reader = new BufferedReader(source); String line = reader.readLine(); if (line == null) { throw new IllegalArgumentException("Empty file"); } int columnCount = -1; String delim = (isCSV ? "," : "\t"); if (hasColumnLabels) { List<String> columnLabels = new ArrayList<String>(); StringTokenizer tokenizer = new StringTokenizer(line, delim); if (hasRowLabels && !line.startsWith(delim)) { // potentially the first token is the name of the row labels String name = tokenizer.nextToken().trim(); if (includeFirstColumnLabel) { columnLabels.add(name); } } while (tokenizer.hasMoreTokens()) { String label = tokenizer.nextToken().trim(); columnLabels.add(label); } this.columnLabels = new String[columnLabels.size()]; columnLabels.toArray(this.columnLabels); columnCount = columnLabels.size(); line = reader.readLine(); } List<String> rowLabels = new ArrayList<String>(); List<double[]> rows = new ArrayList<double[]>(); int rowIndex = 1; while (line != null) { StringTokenizer tokenizer = new StringTokenizer(line, delim); if (columnCount == -1) { columnCount = tokenizer.countTokens(); if (hasRowLabels) { columnCount --; } } if (hasRowLabels) { String label = tokenizer.nextToken().trim(); rowLabels.add(label); } double[] row = new double[columnCount]; int columnIndex = 0; while (tokenizer.hasMoreTokens()) { String value = tokenizer.nextToken(); try { row[columnIndex] = java.lang.Double.valueOf(value); } catch (NumberFormatException nfe) { row[columnIndex] = java.lang.Double.NaN; // throw new IllegalArgumentException("Non numerical value at row " + (rowIndex + 1) + // ", column " + (columnIndex + 1)); } columnIndex ++; } if (columnIndex != columnCount - (includeFirstColumnLabel ? 1 : 0)) { throw new IllegalArgumentException("Wrong number of values on row " + (rowIndex + 1) + ", expecting " + columnCount + " but actually " + columnIndex); } rows.add(row); line = reader.readLine(); rowIndex++; } if (hasRowLabels) { this.rowLabels = new String[rowLabels.size()]; rowLabels.toArray(this.rowLabels); } data = new double[rows.size()][]; rows.toArray(data); } public int getColumnCount() { return columnLabels.length; } public int getRowCount() { return rowLabels.length; } public String[] getColumnLabels() { return columnLabels; } public String[] getRowLabels() { return rowLabels; } public double[] getColumn(final int columnIndex) { double[] column = new double[data.length]; for (int i = 0; i < data.length; i++) { column[i] = data[i][columnIndex]; } return column; } public double[] getRow(final int rowIndex) { return data[rowIndex]; } public double[][] getData() { return data; } private String[] columnLabels; private String[] rowLabels; private double[][] data; public static DataTable<double []> parse(Reader source) throws IOException { return new DataTable.Double(source, true, true, false); } public static DataTable<double []> parse(Reader source, boolean isCSV) throws IOException { return new DataTable.Double(source, true, true, isCSV); } public static DataTable<double []> parse(Reader source, boolean columnLabels, boolean rowLabels) throws IOException { return new DataTable.Double(source, columnLabels, rowLabels, false); } public static DataTable<double []> parse(Reader source, boolean columnLabels, boolean rowLabels, boolean isCSV) throws IOException { return new DataTable.Double(source, columnLabels, rowLabels, isCSV); } } class Text implements DataTable<String[]> { private Text(Reader source, boolean hasColumnLabels, boolean hasRowLabels, boolean isCSV) throws IOException { this(source, hasColumnLabels, hasRowLabels, false, isCSV); } private Text(Reader source, boolean hasColumnLabels, boolean hasRowLabels, boolean includeFirstColumnLabel, boolean isCSV) throws IOException { BufferedReader reader = new BufferedReader(source); String delim = (isCSV ? "," : "\t"); String line = reader.readLine(); if (line == null) { throw new IllegalArgumentException("Empty file"); } int columnCount = -1; if (hasColumnLabels) { List<String> columnLabels = new ArrayList<String>(); StringTokenizer tokenizer = new StringTokenizer(line, delim); if (hasRowLabels && !line.startsWith(delim)) { // potentially the first token is the name of the row labels String name = tokenizer.nextToken().trim(); if (includeFirstColumnLabel) { columnLabels.add(name); } } while (tokenizer.hasMoreTokens()) { String label = tokenizer.nextToken().trim(); columnLabels.add(label); } this.columnLabels = new String[columnLabels.size()]; columnLabels.toArray(this.columnLabels); columnCount = columnLabels.size(); line = reader.readLine(); } List<String> rowLabels = new ArrayList<String>(); List<String[]> rows = new ArrayList<String[]>(); int rowIndex = 1; while (line != null) { StringTokenizer tokenizer = new StringTokenizer(line, delim); if (columnCount == -1) { columnCount = tokenizer.countTokens(); if (hasRowLabels) { columnCount --; } } if (hasRowLabels) { String label = tokenizer.nextToken().trim(); rowLabels.add(label); } String[] row = new String [columnCount]; int columnIndex = 0; while (tokenizer.hasMoreTokens()) { row[columnIndex] = tokenizer.nextToken().trim(); columnIndex ++; } if (columnIndex != columnCount - (includeFirstColumnLabel ? 1 : 0)) { throw new IllegalArgumentException("Wrong number of values on row " + (rowIndex + 1) + ", expecting " + columnCount + " but actually " + columnIndex); } rows.add(row); line = reader.readLine(); rowIndex++; } if (hasRowLabels) { this.rowLabels = new String[rowLabels.size()]; rowLabels.toArray(this.rowLabels); } data = new String[rows.size()][]; rows.toArray(data); } public int getColumnCount() { return data[0].length; } public int getRowCount() { return data.length; } public String[] getColumnLabels() { return columnLabels; } public String[] getRowLabels() { return rowLabels; } public String[] getColumn(final int columnIndex) { String[] column = new String[data.length]; for (int i = 0; i < data.length; i++) { column[i] = data[i][columnIndex]; } return column; } public String[] getRow(final int rowIndex) { return data[rowIndex]; } public String[][] getData() { return data; } private String[] columnLabels; private String[] rowLabels; private String[][] data; public static DataTable<String []> parse(Reader source) throws IOException { return new DataTable.Text(source, true, true, false); } public static DataTable<String []> parse(Reader source, boolean isCSV) throws IOException { return new DataTable.Text(source, true, true, isCSV); } public static DataTable<String []> parse(Reader source, boolean columnLabels, boolean rowLabels) throws IOException { return new DataTable.Text(source, columnLabels, rowLabels, false); } public static DataTable<String []> parse(Reader source, boolean columnLabels, boolean rowLabels, boolean isCSV) throws IOException { return new DataTable.Text(source, columnLabels, rowLabels, isCSV); } public static DataTable<String []> parse(Reader source, boolean columnLabels, boolean rowLabels, boolean firstColumnLabel, boolean isCSV) throws IOException { return new DataTable.Text(source, columnLabels, rowLabels, firstColumnLabel, isCSV); } } }
lgpl-2.1
lucene-gosen/lucene-gosen
src/main/java/net/java/sen/filter/reading/OverrideFilter.java
2307
/* * Copyright (C) 2007 * Matt Francis <asbel@neosheffield.co.uk> * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 2.1 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * */ package net.java.sen.filter.reading; import java.util.HashMap; import java.util.List; import java.util.Map; import net.java.sen.dictionary.Token; import net.java.sen.filter.ReadingFilter; import net.java.sen.filter.ReadingNode; /** * A reading filter that overrides decisions on reading visibility made by * earlier filters. Typically this filter will be set as the last in a * chain of filters to allow changes to be made interactively */ public class OverrideFilter implements ReadingFilter { /** * A map of visibility override settings. Where an entry exists for a given * integer index, any <code>ReadingNode</code> starting at that index will * have its visibility set to the stored value */ private Map<Integer,Boolean> visibility = new HashMap<Integer,Boolean>(); public void filterReadings(List<Token> tokens, ReadingNode readingNode) { for (ReadingNode node = readingNode; node != null; node = node.next) { Boolean visible = visibility.get(tokens.get(node.firstToken).getStart()); if (visible != null) { node.visible = visible; } } } public void reset() { visibility.clear(); } /** * Sets a visibility override at a given character index * * @param position The position to set the override at * @param visible The visibility to set. <code>null</code> removes the * override */ public void setVisible(int position, Boolean visible) { visibility.put(position,visible); } }
lgpl-2.1
apetresc/JFreeChart
src/main/java/org/jfree/chart/labels/BoxAndWhiskerToolTipGenerator.java
5407
/* =========================================================== * JFreeChart : a free chart library for the Java(tm) platform * =========================================================== * * (C) Copyright 2000-2008, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jfreechart/index.html * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ------------------------------------ * BoxAndWhiskerToolTipGenerator.java * ------------------------------------ * (C) Copyright 2004-2008, by David Browning and Contributors. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * Changes * ------- * 02-Jun-2004 : Version 1 (DG); * 23-Mar-2005 : Implemented PublicCloneable (DG); * */ package org.jfree.chart.labels; import java.io.Serializable; import java.text.MessageFormat; import java.text.NumberFormat; import org.jfree.data.category.CategoryDataset; import org.jfree.data.statistics.BoxAndWhiskerCategoryDataset; import org.jfree.util.PublicCloneable; /** * An item label generator for plots that use data from a * {@link BoxAndWhiskerCategoryDataset}. * <P> * The tooltip text and item label text are composed using a * {@link java.text.MessageFormat} object, that can aggregate some or all of * the following string values into a message. * <table> * <tr><td>0</td><td>Series Name</td></tr> * <tr><td>1</td><td>X (value or date)</td></tr> * <tr><td>2</td><td>Mean</td></tr> * <tr><td>3</td><td>Median</td></tr> * <tr><td>4</td><td>Minimum</td></tr> * <tr><td>5</td><td>Maximum</td></tr> * <tr><td>6</td><td>Quartile 1</td></tr> * <tr><td>7</td><td>Quartile 3</td></tr> * </table> */ public class BoxAndWhiskerToolTipGenerator extends StandardCategoryToolTipGenerator implements CategoryToolTipGenerator, Cloneable, PublicCloneable, Serializable { /** For serialization. */ private static final long serialVersionUID = -6076837753823076334L; /** The default tooltip format string. */ public static final String DEFAULT_TOOL_TIP_FORMAT = "X: {1} Mean: {2} Median: {3} Min: {4} Max: {5} Q1: {6} Q3: {7} "; /** * Creates a default tool tip generator. */ public BoxAndWhiskerToolTipGenerator() { super(DEFAULT_TOOL_TIP_FORMAT, NumberFormat.getInstance()); } /** * Creates a tool tip formatter. * * @param format the tool tip format string. * @param formatter the formatter. */ public BoxAndWhiskerToolTipGenerator(String format, NumberFormat formatter) { super(format, formatter); } /** * Creates the array of items that can be passed to the * {@link MessageFormat} class for creating labels. * * @param dataset the dataset (<code>null</code> not permitted). * @param series the series (zero-based index). * @param item the item (zero-based index). * * @return The items (never <code>null</code>). */ protected Object[] createItemArray(CategoryDataset dataset, int series, int item) { Object[] result = new Object[8]; result[0] = dataset.getRowKey(series); Number y = dataset.getValue(series, item); NumberFormat formatter = getNumberFormat(); result[1] = formatter.format(y); if (dataset instanceof BoxAndWhiskerCategoryDataset) { BoxAndWhiskerCategoryDataset d = (BoxAndWhiskerCategoryDataset) dataset; result[2] = formatter.format(d.getMeanValue(series, item)); result[3] = formatter.format(d.getMedianValue(series, item)); result[4] = formatter.format(d.getMinRegularValue(series, item)); result[5] = formatter.format(d.getMaxRegularValue(series, item)); result[6] = formatter.format(d.getQ1Value(series, item)); result[7] = formatter.format(d.getQ3Value(series, item)); } return result; } /** * Tests if this object is equal to another. * * @param obj the other object. * * @return A boolean. */ public boolean equals(Object obj) { if (obj == this) { return true; } if (obj instanceof BoxAndWhiskerToolTipGenerator) { return super.equals(obj); } return false; } }
lgpl-2.1
Alfresco/community-edition
projects/repository/source/test-java/org/alfresco/repo/jscript/RhinoScriptTest.java
19126
/* * #%L * Alfresco Repository * %% * Copyright (C) 2005 - 2016 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * Alfresco 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. * * Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.alfresco.repo.jscript; import java.io.InputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import junit.framework.TestCase; import org.alfresco.model.ContentModel; import org.alfresco.repo.dictionary.DictionaryComponent; import org.alfresco.repo.dictionary.DictionaryDAO; import org.alfresco.repo.dictionary.M2Model; import org.alfresco.repo.node.BaseNodeServiceTest; import org.alfresco.repo.security.authentication.AuthenticationComponent; import org.alfresco.repo.transaction.RetryingTransactionHelper.RetryingTransactionCallback; import org.alfresco.service.ServiceRegistry; import org.alfresco.service.cmr.repository.ChildAssociationRef; import org.alfresco.service.cmr.repository.ContentService; import org.alfresco.service.cmr.repository.ContentWriter; import org.alfresco.service.cmr.repository.NodeRef; import org.alfresco.service.cmr.repository.NodeService; import org.alfresco.service.cmr.repository.ScriptService; import org.alfresco.service.cmr.repository.StoreRef; import org.alfresco.service.namespace.QName; import org.alfresco.service.transaction.TransactionService; import org.alfresco.test_category.OwnJVMTestsCategory; import org.alfresco.util.ApplicationContextHelper; import org.junit.experimental.categories.Category; import org.mozilla.javascript.Context; import org.mozilla.javascript.Scriptable; import org.mozilla.javascript.ScriptableObject; import org.springframework.context.ApplicationContext; /** * @author Kevin Roast */ @Category(OwnJVMTestsCategory.class) public class RhinoScriptTest extends TestCase { private static final ApplicationContext ctx = ApplicationContextHelper.getApplicationContext(); private ContentService contentService; private NodeService nodeService; private TransactionService transactionService; private ServiceRegistry serviceRegistry; private AuthenticationComponent authenticationComponent; private ScriptService scriptService; /* * @see junit.framework.TestCase#setUp() */ protected void setUp() throws Exception { super.setUp(); transactionService = (TransactionService)ctx.getBean("transactionComponent"); contentService = (ContentService)ctx.getBean("contentService"); nodeService = (NodeService)ctx.getBean("nodeService"); scriptService = (ScriptService)ctx.getBean("scriptService"); serviceRegistry = (ServiceRegistry)ctx.getBean("ServiceRegistry"); this.authenticationComponent = (AuthenticationComponent)ctx.getBean("authenticationComponent"); this.authenticationComponent.setSystemUserAsCurrentUser(); DictionaryDAO dictionaryDao = (DictionaryDAO)ctx.getBean("dictionaryDAO"); // load the system model ClassLoader cl = BaseNodeServiceTest.class.getClassLoader(); InputStream modelStream = cl.getResourceAsStream("alfresco/model/contentModel.xml"); assertNotNull(modelStream); M2Model model = M2Model.createModel(modelStream); dictionaryDao.putModel(model); // load the test model modelStream = cl.getResourceAsStream("org/alfresco/repo/node/BaseNodeServiceTest_model.xml"); assertNotNull(modelStream); model = M2Model.createModel(modelStream); dictionaryDao.putModel(model); DictionaryComponent dictionary = new DictionaryComponent(); dictionary.setDictionaryDAO(dictionaryDao); BaseNodeServiceTest.loadModel(ctx); } @Override protected void tearDown() throws Exception { authenticationComponent.clearCurrentSecurityContext(); super.tearDown(); } public void testRhinoIntegration() { transactionService.getRetryingTransactionHelper().doInTransaction( new RetryingTransactionCallback<Object>() { public Object execute() throws Exception { // check that rhino script engine is available Context cx = Context.enter(); try { // The easiest way to embed Rhino is just to create a new scope this way whenever // you need one. However, initStandardObjects is an expensive method to call and it // allocates a fair amount of memory. Scriptable scope = cx.initStandardObjects(); // Now we can evaluate a script. Let's create a new associative array object // using the object literal notation to create the members Object result = cx.evaluateString(scope, "obj = {a:1, b:['x','y']}", "TestJS1", 1, null); Scriptable obj = (Scriptable)scope.get("obj", scope); // Should resolve a non-null value assertNotNull(obj.get("a", obj)); // should resolve "obj.a == 1" - JavaScript objects come back as Number assertEquals(new Double(1.0), obj.get("a", obj)); // try another script eval - this time a function call returning a result result = cx.evaluateString(scope, "function f(x) {return x+1} f(7)", "TestJS2", 1, null); assertEquals(8.0, Context.toNumber(result)); } finally { Context.exit(); } return null; } }); } public void testJSObjectWrapping() { transactionService.getRetryingTransactionHelper().doInTransaction( new RetryingTransactionCallback<Object>() { public Object execute() throws Exception { StoreRef store = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "rhino_" + System.currentTimeMillis()); NodeRef root = nodeService.getRootNode(store); BaseNodeServiceTest.buildNodeGraph(nodeService, root); Context cx = Context.enter(); try { Scriptable scope = cx.initStandardObjects(); // add logger object so we can perform output from within scripts ScriptableObject.putProperty(scope, "logger", new ScriptLogger()); // wrap a simple NodeRef Java object // we can use Java style method calls within the script to access it's properties List<ChildAssociationRef> childAssocs = nodeService.getChildAssocs(root); NodeRef ref1 = childAssocs.get(0).getChildRef(); Object wrappedNodeRef = Context.javaToJS(ref1, scope); ScriptableObject.putProperty(scope, "rootref", wrappedNodeRef); // evaluate script that touches the wrapped NodeRef Object result = cx.evaluateString(scope, "obj = rootref.getId()", "TestJS3", 1, null); assertEquals(ref1.getId(), Context.toString(result)); // wrap a scriptable Alfresco Node object - the Node object is a wrapper like TemplateNode ScriptNode node1 = new ScriptNode(root, serviceRegistry, scope); Object wrappedNode = Context.javaToJS(node1, scope); ScriptableObject.putProperty(scope, "root", wrappedNode); // evaluate scripts that perform methods on the wrapped Node result = cx.evaluateString(scope, TESTSCRIPT1, "TestJS4", 1, null); } finally { Context.exit(); } return null; } }); } public void testScriptService() { transactionService.getRetryingTransactionHelper().doInTransaction( new RetryingTransactionCallback<Object>() { public Object execute() throws Exception { StoreRef store = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "rhino_" + System.currentTimeMillis()); NodeRef root = nodeService.getRootNode(store); BaseNodeServiceTest.buildNodeGraph(nodeService, root); try { Map<String, Object> model = new HashMap<String, Object>(); model.put("out", System.out); // create an Alfresco scriptable Node object // the Node object is a wrapper similar to the TemplateNode concept ScriptNode rootNode = new ScriptNode(root, serviceRegistry, null); model.put("root", rootNode); // execute test scripts using the various entry points of the ScriptService // test executing a script file via classpath lookup Object result = scriptService.executeScript(TESTSCRIPT_CLASSPATH1, model); System.out.println("Result from TESTSCRIPT_CLASSPATH1: " + result.toString()); assertTrue((Boolean)result); // we know the result is a boolean // test executing a script embedded inside Node content ChildAssociationRef childRef = nodeService.createNode( root, BaseNodeServiceTest.ASSOC_TYPE_QNAME_TEST_CHILDREN, QName.createQName(BaseNodeServiceTest.NAMESPACE, "script_content"), BaseNodeServiceTest.TYPE_QNAME_TEST_CONTENT, null); NodeRef contentNodeRef = childRef.getChildRef(); ContentWriter writer = contentService.getWriter( contentNodeRef, BaseNodeServiceTest.PROP_QNAME_TEST_CONTENT, true); writer.setMimetype("application/x-javascript"); writer.putContent(TESTSCRIPT1); scriptService.executeScript(contentNodeRef, BaseNodeServiceTest.PROP_QNAME_TEST_CONTENT, model); // test executing a script directly as a String scriptService.executeScriptString("javascript", TESTSCRIPT1, model); } finally { } return null; } }); } public void testScriptActions() { transactionService.getRetryingTransactionHelper().doInTransaction( new RetryingTransactionCallback<Object>() { public Object execute() throws Exception { StoreRef store = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "rhino_" + System.currentTimeMillis()); NodeRef root = nodeService.getRootNode(store); try { // create a content object ChildAssociationRef childRef = nodeService.createNode( root, BaseNodeServiceTest.ASSOC_TYPE_QNAME_TEST_CHILDREN, QName.createQName(BaseNodeServiceTest.NAMESPACE, "script_content"), BaseNodeServiceTest.TYPE_QNAME_TEST_CONTENT, null); NodeRef contentNodeRef = childRef.getChildRef(); ContentWriter writer = contentService.getWriter( contentNodeRef, BaseNodeServiceTest.PROP_QNAME_TEST_CONTENT, true); writer.setMimetype("application/x-javascript"); writer.putContent(TESTSCRIPT1); // create an Alfresco scriptable Node object // the Node object is a wrapper similar to the TemplateNode concept Map<String, Object> model = new HashMap<String, Object>(); model.put("doc", new ScriptNode(childRef.getChildRef(), serviceRegistry, null)); model.put("root", new ScriptNode(root, serviceRegistry, null)); // execute to add aspect via action Object result = scriptService.executeScript(TESTSCRIPT_CLASSPATH2, model); System.out.println("Result from TESTSCRIPT_CLASSPATH2: " + result.toString()); assertTrue((Boolean)result); // we know the result is a boolean // ensure aspect has been added via script assertTrue(nodeService.hasAspect(childRef.getChildRef(), ContentModel.ASPECT_LOCKABLE)); } finally { } return null; } }); } public void xtestScriptActionsMail() { transactionService.getRetryingTransactionHelper().doInTransaction( new RetryingTransactionCallback<Object>() { public Object execute() throws Exception { StoreRef store = nodeService.createStore(StoreRef.PROTOCOL_WORKSPACE, "rhino_" + System.currentTimeMillis()); NodeRef root = nodeService.getRootNode(store); try { // create a content object ChildAssociationRef childRef = nodeService.createNode( root, BaseNodeServiceTest.ASSOC_TYPE_QNAME_TEST_CHILDREN, QName.createQName(BaseNodeServiceTest.NAMESPACE, "script_content"), BaseNodeServiceTest.TYPE_QNAME_TEST_CONTENT, null); NodeRef contentNodeRef = childRef.getChildRef(); ContentWriter writer = contentService.getWriter( contentNodeRef, BaseNodeServiceTest.PROP_QNAME_TEST_CONTENT, true); writer.setMimetype("application/x-javascript"); writer.putContent(TESTSCRIPT1); // create an Alfresco scriptable Node object // the Node object is a wrapper similar to the TemplateNode concept Map<String, Object> model = new HashMap<String, Object>(); model.put("doc", new ScriptNode(childRef.getChildRef(), serviceRegistry, null)); model.put("root", new ScriptNode(root, serviceRegistry, null)); // execute to add aspect via action Object result = scriptService.executeScript(TESTSCRIPT_CLASSPATH3, model); System.out.println("Result from TESTSCRIPT_CLASSPATH3: " + result.toString()); assertTrue((Boolean)result); // we know the result is a boolean } finally { } return null; } }); } private static final String TESTSCRIPT_CLASSPATH1 = "org/alfresco/repo/jscript/test_script1.js"; private static final String TESTSCRIPT_CLASSPATH2 = "org/alfresco/repo/jscript/test_script2.js"; private static final String TESTSCRIPT_CLASSPATH3 = "org/alfresco/repo/jscript/test_script3.js"; private static final String TESTSCRIPT1 = "var id = root.id;\r\n" + "logger.log(id);\r\n" + "var name = root.name;\r\n" + "logger.log(name);\r\n" + "var type = root.type;\r\n" + "logger.log(type);\r\n" + "var childList = root.children;\r\n" + "logger.log(\"zero index node name: \" + childList[0].name);\r\n" + "logger.log(\"name property access: \" + childList[0].properties.name);\r\n" + "var childByNameNode = root.childByNamePath(\"/\" + childList[0].name);\r\n" + "logger.log(\"child by name path: \" + childByNameNode.name);\r\n" + "var xpathResults = root.childrenByXPath(\"/*\");\r\n" + "logger.log(\"children of root from xpath: \" + xpathResults.length);\r\n"; }
lgpl-3.0
m133225/HubTurbo
src/test/java/unstable/BoardTests.java
11250
package unstable; import static junit.framework.TestCase.assertFalse; import static junit.framework.TestCase.assertTrue; import static org.junit.Assert.assertEquals; import static org.loadui.testfx.controls.Commons.hasText; import static ui.components.KeyboardShortcuts.*; import org.junit.Before; import org.junit.Test; import org.loadui.testfx.GuiTest; import guitests.UITest; import javafx.scene.control.TextField; import javafx.scene.input.KeyCode; import prefs.Preferences; import ui.IdGenerator; import ui.TestController; import ui.UI; import ui.issuepanel.PanelControl; import util.PlatformEx; public class BoardTests extends UITest { private static final String boardNameInputId = IdGenerator.getBoardNameInputFieldIdReference(); private static final String boardNameSaveButtonId = IdGenerator.getBoardNameSaveButtonIdReference(); /** * The initial state is one panel with no filter, and no saved boards */ private static void reset() { UI ui = TestController.getUI(); ui.getPanelControl().closeAllPanels(); ui.getPanelControl().createNewPanelAtStart(); UI.prefs.clearAllBoards(); ui.updateTitle(); } @Before public void before() { PlatformEx.runAndWait(BoardTests::reset); } @Test public void boards_panelCount_creatingAndClosingPanels() { UI ui = TestController.getUI(); PanelControl panelControl = ui.getPanelControl(); press(CLOSE_PANEL); waitAndAssertEquals(0, panelControl::getPanelCount); press(CREATE_RIGHT_PANEL); waitAndAssertEquals(1, panelControl::getPanelCount); press(CREATE_LEFT_PANEL); waitAndAssertEquals(2, panelControl::getPanelCount); traverseHubTurboMenu("Panels", "Create"); waitAndAssertEquals(3, panelControl::getPanelCount); traverseHubTurboMenu("Panels", "Create (Left)"); waitAndAssertEquals(4, panelControl::getPanelCount); traverseHubTurboMenu("Panels", "Close"); waitAndAssertEquals(3, panelControl::getPanelCount); traverseHubTurboMenu("Panels", "Close"); waitAndAssertEquals(2, panelControl::getPanelCount); } @Test public void boards_saveDialog_willSaveWhenNoBoardOpen() { UI ui = TestController.getUI(); PanelControl panelControl = ui.getPanelControl(); // No board is open assertEquals(0, panelControl.getNumberOfSavedBoards()); assertEquals(ui.getTitle(), getUiTitleWithOpenBoard("none")); // Saving when no board is open should prompt the user to save a new board traverseHubTurboMenu("Boards", "Save"); type("Board 1"); push(KeyCode.ESCAPE); } @Test public void boards_saveDialog_willNotSaveOnCancellation() { PanelControl panelControl = TestController.getUI().getPanelControl(); traverseHubTurboMenu("Boards", "Save"); type("Board 1"); push(KeyCode.ESCAPE); // No board is saved on cancellation waitAndAssertEquals(0, panelControl::getNumberOfSavedBoards); } @Test public void boards_lastOpenedBoard_switchingWhenNoBoardIsOpen() { // Switching when no board is open should do nothing pushKeys(SWITCH_BOARD); assertFalse(UI.prefs.getLastOpenBoard().isPresent()); } @Test public void boards_panelCount_boardsSaveSuccessfully() { UI ui = TestController.getUI(); PanelControl panelControl = ui.getPanelControl(); saveBoardWithName("Board 1"); waitAndAssertEquals(1, panelControl::getNumberOfSavedBoards); assertEquals(1, panelControl.getPanelCount()); assertEquals(ui.getTitle(), getUiTitleWithOpenBoard("Board 1")); } private void saveBoardWithName(String name) { traverseHubTurboMenu("Boards", "Save as"); waitUntilNodeAppears(boardNameInputId); ((TextField) GuiTest.find(boardNameInputId)).setText(name); clickOn("OK"); } @Test public void baords_lastOpenedBoard_cannotSwitchBoardWithOnlyOneSaved() { Preferences prefs = UI.prefs; saveBoardWithName("Board 1"); // Remain at the same board press(SWITCH_BOARD); assertTrue(prefs.getLastOpenBoard().isPresent()); assertEquals("Board 1", prefs.getLastOpenBoard().get()); } @Test public void boards_lastOpenedBoard_canSwitchBoardWithOnlyOneSaved() { Preferences prefs = UI.prefs; saveBoardWithName("Board 1"); saveBoardWithName("Board 2"); assertTrue(prefs.getLastOpenBoard().isPresent()); assertEquals("Board 2", prefs.getLastOpenBoard().get()); // Wraps around to the first board press(SWITCH_BOARD); assertTrue(prefs.getLastOpenBoard().isPresent()); assertEquals("Board 1", prefs.getLastOpenBoard().get()); // Back to the second board press(SWITCH_BOARD); assertTrue(prefs.getLastOpenBoard().isPresent()); assertEquals("Board 2", prefs.getLastOpenBoard().get()); } @Test public void boards_validation_displaysFeedbackOnFailingValidation() { tryBoardName(""); tryBoardName(" "); tryBoardName(" none "); } private void tryBoardName(String name) { traverseHubTurboMenu("Boards", "Save as"); waitUntilNodeAppears(boardNameInputId); ((TextField) GuiTest.find(boardNameInputId)).setText(name); assertTrue(GuiTest.find(boardNameSaveButtonId).isDisabled()); pushKeys(KeyCode.ESCAPE); waitUntilNodeDisappears(boardNameInputId); } @Test public void boards_panelCount_boardsCanBeOpenedSuccessfully() { UI ui = TestController.getUI(); PanelControl panelControl = ui.getPanelControl(); // Board 1 has 1 panel, Board 2 has 2 saveBoardWithName("Board 1"); pushKeys(CREATE_RIGHT_PANEL); saveBoardWithName("Board 2"); // We're at Board 2 now waitAndAssertEquals(2, panelControl::getPanelCount); assertEquals(ui.getTitle(), getUiTitleWithOpenBoard("Board 2")); traverseHubTurboMenu("Boards", "Open", "Board 1"); // We've switched to Board 1 waitAndAssertEquals(1, panelControl::getPanelCount); assertEquals(ui.getTitle(), getUiTitleWithOpenBoard("Board 1")); } @Test public void boards_panelCount_boardsCanBeSavedSuccessfully() { PanelControl panelControl = TestController.getUI().getPanelControl(); saveBoardWithName("Board 1"); pushKeys(CREATE_RIGHT_PANEL); awaitCondition(() -> 2 == panelControl.getPanelCount()); traverseHubTurboMenu("Boards", "Open", "Board 1"); // Abort saving changes to current board waitUntilNodeAppears("No"); clickOn("No"); // Without having saved, we lose the extra panel waitAndAssertEquals(1, panelControl::getPanelCount); pushKeys(CREATE_RIGHT_PANEL); traverseHubTurboMenu("Boards", "Save"); // After saving, the panel is there waitAndAssertEquals(2, panelControl::getPanelCount); } @Test public void boards_panelCount_boardsCanBeDeletedSuccessfully() { UI ui = TestController.getUI(); PanelControl panelControl = ui.getPanelControl(); saveBoardWithName("Board 1"); traverseHubTurboMenu("Boards", "Delete", "Board 1"); waitUntilNodeAppears(hasText("OK")); clickOn("OK"); // No board is open now assertEquals(0, panelControl.getNumberOfSavedBoards()); assertEquals(ui.getTitle(), getUiTitleWithOpenBoard("none")); } @Test public void boards_panelCount_switchToFirstBoardWhenNoBoardIsOpen() { saveBoardWithName("Board 1"); saveBoardWithName("Board 2"); saveBoardWithName("Board 3"); traverseHubTurboMenu("Boards", "Delete", "Board 3"); waitUntilNodeAppears(hasText("OK")); clickOn("OK"); // Switching board has no effect assertFalse(UI.prefs.getLastOpenBoard().isPresent()); pushKeys(SWITCH_BOARD); // Abort saving changes to current board waitUntilNodeAppears("No"); clickOn("No"); assertTrue(UI.prefs.getLastOpenBoard().isPresent()); assertEquals("Board 2", UI.prefs.getLastOpenBoard().get()); } @Test public void boards_panelCount_promptToSaveWhenCurrentBoardIsDirty() { UI ui = TestController.getUI(); PanelControl panelControl = ui.getPanelControl(); saveBoardWithName("Board 1"); saveBoardWithName("Board 2"); pushKeys(CREATE_RIGHT_PANEL); awaitCondition(() -> 2 == panelControl.getPanelCount()); pushKeys(SWITCH_BOARD); // Confirm saving changes to current board waitUntilNodeAppears("Yes"); clickOn("Yes"); traverseHubTurboMenu("Boards", "Open", "Board 2"); waitAndAssertEquals(2, panelControl::getPanelCount); } @Test public void boards_panelCount_askForBoardNameWhenCurrentBoardHasNeverBeenSaved() { UI ui = TestController.getUI(); PanelControl panelControl = ui.getPanelControl(); pushKeys(CREATE_RIGHT_PANEL); pushKeys(CREATE_RIGHT_PANEL); awaitCondition(() -> 3 == panelControl.getPanelCount()); traverseHubTurboMenu("Boards", "Save"); waitUntilNodeAppears(boardNameInputId); ((TextField) GuiTest.find(boardNameInputId)).setText("Board 1"); clickOn("OK"); assertEquals("Board 1", UI.prefs.getLastOpenBoard().get()); traverseHubTurboMenu("Boards", "Open", "Board 1"); waitAndAssertEquals(3, panelControl::getPanelCount); } private static String getUiTitleWithOpenBoard(String boardName) { return String.format(UI.WINDOW_TITLE, "dummy/dummy", boardName); } @Test public void boards_panelCount_nothingHappensWhenNewBoardIsCancelled() { UI ui = TestController.getUI(); PanelControl panelControl = ui.getPanelControl(); assertEquals(0, panelControl.getNumberOfSavedBoards()); assertEquals(1, panelControl.getPanelCount()); traverseHubTurboMenu("Boards", "New"); // Abort saving changes to current board waitUntilNodeAppears("No"); clickOn("No"); // Cancel new board action waitUntilNodeAppears("Cancel"); clickOn("Cancel"); assertEquals(0, panelControl.getNumberOfSavedBoards()); assertEquals(1, panelControl.getPanelCount()); } @Test public void boards_panelCount_newBoardCreated() { UI ui = TestController.getUI(); PanelControl panelControl = ui.getPanelControl(); traverseHubTurboMenu("Boards", "New"); // Abort saving changes to current board waitUntilNodeAppears("No"); clickOn("No"); waitUntilNodeAppears(boardNameInputId); ((TextField) GuiTest.find(boardNameInputId)).setText("empty"); waitUntilNodeAppears("OK"); clickOn("OK"); waitAndAssertEquals(1, panelControl::getPanelCount); waitAndAssertEquals(ui.getTitle(), () -> getUiTitleWithOpenBoard("empty")); } }
lgpl-3.0
legoboy0215/RedstoneLamp
src/main/java/net/redstonelamp/entity/EntityMotion.java
2085
/* * This file is part of RedstoneLamp. * * RedstoneLamp 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. * * RedstoneLamp 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 RedstoneLamp. If not, see <http://www.gnu.org/licenses/>. */ package net.redstonelamp.entity; public class EntityMotion{ private double dx; private double dy; private double dz; /** * Warning: this variable is in <em>radians</em>! */ private double yaw; private double pitch; private double speed; public EntityMotion(double dx, double dy, double dz, double yaw, double pitch, double speed){ this.dx = dx; this.dy = dy; this.dz = dz; this.yaw = yaw; this.pitch = pitch; this.speed = speed; } public static EntityMotion fromXYZ(double x, double y, double z){ double v = Math.sqrt(x * x + y * y + z * z); double pitch = Math.asin(-y / v); double yaw = Math.asin(z / v / Math.cos(pitch)); return new EntityMotion(x, y, z, yaw, pitch, v); } public static EntityMotion fromYPS(double yaw, double pitch, double speed){ return fromYPS(yaw, pitch, speed, false); } public static EntityMotion fromYPS(double yaw, double pitch, double v, boolean inRadians){ if(!inRadians){ yaw *= Math.PI / 180; pitch *= Math.PI / 180; } double y = -Math.sin(pitch) * v; double h = Math.cos(pitch) * v; double x = -h * Math.sin(yaw); double z = h * Math.cos(yaw); return new EntityMotion(x, y, z, yaw, pitch, v); } }
lgpl-3.0
AArhin/head
application/src/main/java/org/mifos/reports/struts/action/BirtReportsUploadAction.java
18259
/* * Copyright (c) 2005-2011 Grameen Foundation USA * 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. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.reports.struts.action; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.StringUtils; import org.apache.struts.Globals; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionServlet; import org.apache.struts.upload.FormFile; import org.mifos.application.util.helpers.ActionForwards; import org.mifos.config.Localization; import org.mifos.config.business.MifosConfigurationManager; import org.mifos.framework.business.service.BusinessService; import org.mifos.framework.exceptions.ApplicationException; import org.mifos.framework.exceptions.PersistenceException; import org.mifos.framework.exceptions.ServiceException; import org.mifos.framework.hibernate.helper.StaticHibernateUtil; import org.mifos.framework.struts.action.BaseAction; import org.mifos.framework.util.ConfigurationLocator; import org.mifos.framework.util.helpers.Constants; import org.mifos.reports.business.ReportsBO; import org.mifos.reports.business.ReportsCategoryBO; import org.mifos.reports.business.ReportsJasperMap; import org.mifos.reports.business.service.ReportsBusinessService; import org.mifos.reports.persistence.ReportsPersistence; import org.mifos.reports.struts.actionforms.BirtReportsUploadActionForm; import org.mifos.reports.util.helpers.ReportsConstants; import org.mifos.security.activity.ActivityGeneratorException; import org.mifos.security.util.ActivityMapper; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class BirtReportsUploadAction extends BaseAction { private static final Logger logger = LoggerFactory.getLogger(BirtReportsUploadAction.class); private ReportsBusinessService reportsBusinessService; public BirtReportsUploadAction() { reportsBusinessService = new ReportsBusinessService(); } public ActionForward getBirtReportsUploadPage(ActionMapping mapping, ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { logger.debug("In ReportsAction:getBirtReportPage Method: "); StaticHibernateUtil.flushAndCloseSession(); BirtReportsUploadActionForm uploadForm = (BirtReportsUploadActionForm) form; uploadForm.clear(); request.getSession().setAttribute(ReportsConstants.LISTOFREPORTS, new ReportsPersistence().getAllReportCategories()); return mapping.findForward(ActionForwards.load_success.toString()); } @Override protected BusinessService getService() throws ServiceException { return reportsBusinessService; } public ActionForward preview(ActionMapping mapping, ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { BirtReportsUploadActionForm uploadForm = (BirtReportsUploadActionForm) form; ReportsPersistence rp = new ReportsPersistence(); ReportsCategoryBO category = rp.getPersistentObject(ReportsCategoryBO.class, Short .valueOf(uploadForm.getReportCategoryId())); request.setAttribute("category", category); if (isReportAlreadyExist(request, uploadForm.getReportTitle(), category)) { return mapping.findForward(ActionForwards.preview_failure.toString()); } return mapping.findForward(ActionForwards.preview_success.toString()); } public ActionForward previous(ActionMapping mapping, @SuppressWarnings("unused") ActionForm form, @SuppressWarnings("unused") HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { return mapping.findForward(ActionForwards.load_success.toString()); } public ActionForward upload(ActionMapping mapping, ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { BirtReportsUploadActionForm uploadForm = (BirtReportsUploadActionForm) form; ReportsPersistence rp = new ReportsPersistence(); ReportsCategoryBO category = rp.getPersistentObject(ReportsCategoryBO.class, Short .valueOf(uploadForm.getReportCategoryId())); if (isReportAlreadyExist(request, uploadForm.getReportTitle(), category)) { return mapping.findForward(ActionForwards.preview_failure.toString()); } short parentActivity = category.getActivityId(); int newActivityId; String activityNameHead = "Can view "; try { newActivityId = legacyRolesPermissionsDao.calculateDynamicActivityId(); legacyRolesPermissionsDao.createActivityForReports(parentActivity, activityNameHead + uploadForm.getReportTitle()); } catch (ActivityGeneratorException ex) { ActionErrors errors = new ActionErrors(); errors.add(ex.getKey(), new ActionMessage(ex.getKey())); request.setAttribute(Globals.ERROR_KEY, errors); return mapping.findForward(ActionForwards.preview_failure.toString()); } FormFile formFile = uploadForm.getFile(); uploadFile(formFile); ReportsBO reportBO = createOrUpdateReport(category, newActivityId, uploadForm.getReportTitle(), Short .valueOf(uploadForm.getIsActive()), formFile.getFileName(), uploadForm.getIsDW()); allowActivityPermission(reportBO, newActivityId); request.setAttribute("report", reportBO); return mapping.findForward(ActionForwards.create_success.toString()); } private void allowActivityPermission(ReportsBO reportBO, int newActivityId) throws ApplicationException { ActivityMapper.getInstance().getActivityMap().put( "/reportsUserParamsAction-loadAddList-" + reportBO.getReportId(), (short) newActivityId); } private static String getServletRoot(ActionServlet servlet) { return servlet.getServletContext().getRealPath("/"); } public static String getUploadStorageDirectory() { ConfigurationLocator configurationLocator = new ConfigurationLocator(); String reportPath = configurationLocator.getConfigurationDirectory() + "/uploads"; String uploadsDir = reportPath; if (File.separatorChar == '\\') { // windows platform uploadsDir = uploadsDir.replaceAll("/", "\\\\"); } return uploadsDir; } public static String getCustomReportStorageDirectory() { return getUploadStorageDirectory().endsWith(File.separator) ? getUploadStorageDirectory() + "report" : getUploadStorageDirectory() + File.separator + "report"; } private void uploadFile(FormFile formFile) throws FileNotFoundException, IOException { File dir = new File(getCustomReportStorageDirectory()); dir.mkdirs(); File file = new File(dir, formFile.getFileName()); InputStream is = formFile.getInputStream(); OutputStream os; /* * for test purposes, if the real path does not exist (if we're * operating outside a deployed environment) the file is just written to * a ByteArrayOutputStream which is not actually stored. !! This does * not produce any sort of file that can be retirieved. !! it only * allows us to perform the upload action. */ if (getServletRoot(getServlet()) != null) { os = new FileOutputStream(file); } else { os = new ByteArrayOutputStream(); } byte[] buffer = new byte[4096]; int bytesRead = 0; while ((bytesRead = is.read(buffer, 0, 4096)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); is.close(); formFile.destroy(); } public ActionForward validate(ActionMapping mapping, @SuppressWarnings("unused") ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { String method = (String) request.getAttribute("methodCalled"); return mapping.findForward(method + "_failure"); } public ActionForward getViewReportPage(ActionMapping mapping, @SuppressWarnings("unused") ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { logger.debug("In ReportsAction:getViewReportsPage Method: "); StaticHibernateUtil.flushAndCloseSession(); request.getSession().setAttribute(ReportsConstants.LISTOFREPORTS, new ReportsPersistence().getAllReportCategories()); return mapping.findForward(ActionForwards.get_success.toString()); } public ActionForward edit(ActionMapping mapping, ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { BirtReportsUploadActionForm birtReportsUploadActionForm = (BirtReportsUploadActionForm) form; ReportsBO report = new ReportsPersistence().getReport(Short.valueOf(request.getParameter("reportId"))); request.setAttribute(Constants.BUSINESS_KEY, report); birtReportsUploadActionForm.setReportTitle(report.getReportName()); birtReportsUploadActionForm.setReportCategoryId(report.getReportsCategoryBO().getReportCategoryId().toString()); birtReportsUploadActionForm.setIsActive(report.getIsActive().toString()); request.getSession().setAttribute(ReportsConstants.LISTOFREPORTS, new ReportsPersistence().getAllReportCategories()); return mapping.findForward(ActionForwards.edit_success.toString()); } public ActionForward editpreview(ActionMapping mapping, ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { BirtReportsUploadActionForm uploadForm = (BirtReportsUploadActionForm) form; ReportsPersistence rp = new ReportsPersistence(); ReportsCategoryBO category = rp.getPersistentObject(ReportsCategoryBO.class, Short .valueOf(uploadForm.getReportCategoryId())); request.setAttribute("category", category); ReportsBO report = new ReportsPersistence().getReport(Short.valueOf(uploadForm.getReportId())); if (isReportInfoNotEdit(request, uploadForm, report)) { return mapping.findForward(ActionForwards.editpreview_failure.toString()); } else if (!isReportItsSelf(uploadForm, report) && isReportAlreadyExist(request, uploadForm.getReportTitle(), category)) { return mapping.findForward(ActionForwards.editpreview_failure.toString()); } return mapping.findForward(ActionForwards.editpreview_success.toString()); } private boolean isReportInfoNotEdit(HttpServletRequest request, BirtReportsUploadActionForm form, ReportsBO report) { if (isReportItsSelf(form, report)) { if (form.getIsActive().equals(report.getIsActive().toString()) && StringUtils.isBlank(form.getFile().getFileName())) { ActionErrors errors = new ActionErrors(); errors.add(ReportsConstants.ERROR_REPORTINFONOTEDIT, new ActionMessage( ReportsConstants.ERROR_REPORTINFONOTEDIT)); request.setAttribute(Globals.ERROR_KEY, errors); return true; } } return false; } private boolean isReportAlreadyExist(HttpServletRequest request, String reportName, ReportsCategoryBO categoryBO) throws Exception { for (ReportsBO report : new ReportsPersistence().getAllReports()) { if (reportName.equals(report.getReportName()) && categoryBO.getReportCategoryId().equals(report.getReportsCategoryBO().getReportCategoryId())) { ActionErrors errors = new ActionErrors(); errors.add(ReportsConstants.ERROR_REPORTALREADYEXIST, new ActionMessage( ReportsConstants.ERROR_REPORTALREADYEXIST)); request.setAttribute(Globals.ERROR_KEY, errors); return true; } } return false; } private boolean isReportItsSelf(BirtReportsUploadActionForm form, ReportsBO report) { if (form.getReportTitle().equals(report.getReportName()) && form.getReportCategoryId().equals(report.getReportsCategoryBO().getReportCategoryId().toString())) { return true; } return false; } public ActionForward editprevious(ActionMapping mapping, ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { BirtReportsUploadActionForm uploadForm = (BirtReportsUploadActionForm) form; ReportsPersistence rp = new ReportsPersistence(); ReportsCategoryBO category = rp.getPersistentObject(ReportsCategoryBO.class, Short .valueOf(uploadForm.getReportCategoryId())); request.setAttribute("category", category); return mapping.findForward(ActionForwards.editprevious_success.toString()); } public ActionForward editThenUpload(ActionMapping mapping, ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { BirtReportsUploadActionForm uploadForm = (BirtReportsUploadActionForm) form; ReportsPersistence rp = new ReportsPersistence(); ReportsCategoryBO category = rp.getPersistentObject(ReportsCategoryBO.class, Short .valueOf(uploadForm.getReportCategoryId())); ReportsBO reportBO = rp.getReport(Short.valueOf(uploadForm.getReportId())); ReportsJasperMap reportJasperMap = reportBO.getReportsJasperMap(); if (!isReportItsSelf(uploadForm, reportBO) && isReportAlreadyExist(request, uploadForm.getReportTitle(), category)) { return mapping.findForward(ActionForwards.editpreview_failure.toString()); } else if (isReportActivityIdNull(request, reportBO)) { return mapping.findForward(ActionForwards.create_failure.toString()); } reportBO.setReportName(uploadForm.getReportTitle()); reportBO.setIsActive(Short.valueOf(uploadForm.getIsActive())); reportBO.setReportsCategoryBO(category); rp.createOrUpdate(reportBO); // kim String activityNameHead = "Can view "; rp.updateLookUpValue(reportBO.getActivityId(), activityNameHead + uploadForm.getReportTitle()); legacyRolesPermissionsDao.reparentActivityUsingHibernate(reportBO.getActivityId(), category.getActivityId()); legacyRolesPermissionsDao.changeActivityMessage(reportBO.getActivityId(), Localization.ENGLISH_LOCALE_ID, "Can view " + reportBO.getReportName()); FormFile formFile = uploadForm.getFile(); if (StringUtils.isEmpty(formFile.getFileName())) { formFile.destroy(); } else { reportJasperMap.setReportJasper(formFile.getFileName()); rp.createOrUpdate(reportJasperMap); uploadFile(formFile); } return mapping.findForward(ActionForwards.create_success.toString()); } private boolean isReportActivityIdNull(HttpServletRequest request, ReportsBO reportBO) { if (null == reportBO.getActivityId()) { ActionErrors errors = new ActionErrors(); errors.add(ReportsConstants.ERROR_REPORTACTIVITYIDISNULL, new ActionMessage( ReportsConstants.ERROR_REPORTACTIVITYIDISNULL)); request.setAttribute(Globals.ERROR_KEY, errors); return true; } return false; } public ActionForward downloadBirtReport(ActionMapping mapping, @SuppressWarnings("unused") ActionForm form, HttpServletRequest request, @SuppressWarnings("unused") HttpServletResponse response) throws Exception { request.getSession().setAttribute("reportsBO", new ReportsPersistence().getReport(Short.valueOf(request.getParameter("reportId")))); return mapping.findForward(ActionForwards.download_success.toString()); } private ReportsBO createOrUpdateReport(ReportsCategoryBO category, int newActivityId, String reportTitle, Short isActive, String fileName, Boolean isDW) throws PersistenceException { ReportsBO reportBO = new ReportsBO(); reportBO.setReportName(reportTitle); reportBO.setReportsCategoryBO(category); reportBO.setActivityId((short) newActivityId); reportBO.setIsActive(isActive); reportBO.setIsDW(isDW); ReportsJasperMap reportsJasperMap = reportBO.getReportsJasperMap(); reportsJasperMap.setReportJasper(fileName); reportBO.setReportsJasperMap(reportsJasperMap); new ReportsPersistence().createOrUpdate(reportBO); return reportBO; } }
apache-2.0
ragerri/opennlp
opennlp-uima/src/main/java/opennlp/uima/dictionary/DictionaryResourceImpl.java
1293
/* * 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 opennlp.uima.dictionary; import java.io.IOException; import java.io.InputStream; import opennlp.tools.dictionary.Dictionary; import opennlp.uima.util.AbstractModelResource; public class DictionaryResourceImpl extends AbstractModelResource<Dictionary> implements DictionaryResource { @Override public Dictionary getDictionary() { return model; } @Override protected Dictionary loadModel(InputStream in) throws IOException { return new Dictionary(in); } }
apache-2.0
JerJohn15/concourse
concourse-driver-java/src/main/java/com/cinchapi/concourse/util/Version.java
3445
/* * Copyright (c) 2013-2016 Cinchapi 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.cinchapi.concourse.util; import java.util.Objects; import javax.annotation.concurrent.Immutable; import com.google.common.primitives.Longs; /** * A class that encapsulates the version information for a class contained in a * concourse jar. * * @author Jeff Nelson */ @Immutable public final class Version implements Comparable<Version> { /** * Return the Version for {@code clazz}. * * @param clazz * @return the class Version */ public static Version getVersion(Class<?> clazz) { return new Version(clazz); } private final long major; private final long minor; private final long patch; private final String build; /** * Construct a new instance. * * @param clazz */ private Version(Class<?> clazz) { String version = (version = clazz.getPackage() .getImplementationVersion()) == null ? "UNKNOWN" : version; String[] parts = version.split("\\."); if(parts.length == 4) { this.major = Long.parseLong(parts[0]); this.minor = Long.parseLong(parts[1]); this.patch = Long.parseLong(parts[2]); this.build = parts[3]; } else { this.major = 0; this.minor = 0; this.patch = 0; this.build = "0-SNAPSHOT"; } } @Override public int compareTo(Version o) { int comp; return (comp = Longs.compare(major, o.major)) == 0 ? (comp = Longs .compare(minor, o.minor)) == 0 ? (comp = Longs.compare(patch, o.patch)) == 0 ? (build.compareTo(o.build)) : comp : comp : comp; } @Override public boolean equals(Object obj) { if(obj instanceof Version) { return compareTo((Version) obj) == 0; } return false; } /** * Returns the build metadata for this Version. * * @return the build */ public String getBuild() { return build; } /** * Return the major component of this Version. * * @return the major */ public long getMajor() { return major; } /** * Return the minor component of this Version. * * @return the minor */ public long getMinor() { return minor; } /** * Return the patch component of this Version. * * @return the patch */ public long getPatch() { return patch; } @Override public int hashCode() { return Objects.hash(major, minor, patch, build); } @Override public String toString() { return new StringBuilder().append(major).append(".").append(minor) .append(".").append(patch).append(".").append(build).toString(); } }
apache-2.0
mmoayyed/pac4j
pac4j-kerberos/src/main/java/org/pac4j/kerberos/credentials/authenticator/SunJaasKerberosTicketValidator.java
10111
package org.pac4j.kerberos.credentials.authenticator; import org.ietf.jgss.*; import org.pac4j.core.exception.BadCredentialsException; import org.pac4j.core.exception.TechnicalException; import org.pac4j.core.util.CommonHelper; import org.pac4j.core.util.InitializableObject; import org.springframework.core.io.Resource; import javax.security.auth.Subject; import javax.security.auth.kerberos.KerberosPrincipal; import javax.security.auth.login.AppConfigurationEntry; import javax.security.auth.login.Configuration; import javax.security.auth.login.LoginContext; import javax.security.auth.login.LoginException; import java.io.IOException; import java.security.Principal; import java.security.PrivilegedActionException; import java.security.PrivilegedExceptionAction; import java.util.HashMap; import java.util.HashSet; import java.util.Set; /** * Implementation of {@link KerberosTicketValidator} which uses the SUN JAAS * login module, which is included in the SUN JRE, it will not work with an IBM JRE. * The whole configuration is done in this class, no additional JAAS configuration * is needed. * * @author Garry Boyce * @since 2.1.0 * <p> * originally from spring-kerberos project */ public class SunJaasKerberosTicketValidator extends InitializableObject implements KerberosTicketValidator { private String servicePrincipal; private Resource keyTabLocation; private Subject serviceSubject; private boolean holdOnToGSSContext; private boolean debug = false; @Override public KerberosTicketValidation validateTicket(byte[] token) { init(); try { return Subject.doAs(this.serviceSubject, new KerberosValidateAction(token)); } catch (PrivilegedActionException e) { throw new BadCredentialsException("Kerberos validation not successful", e); } } @Override protected void internalInit() { // P.S. this fn is called from init(), so if init() is not called explicitly, // then internalInit() runs lazily during the first validateTicket() call try { CommonHelper.assertNotNull("servicePrincipal must be specified", this.servicePrincipal); CommonHelper.assertNotNull("keyTab must be specified", this.keyTabLocation); String keyTabLocationAsString = this.keyTabLocation.getURL().toExternalForm(); // We need to remove the file prefix (if there is one), as it is not supported in Java 7 anymore. // As Java 6 accepts it with and without the prefix, we don't need to check for Java 7 if (keyTabLocationAsString.startsWith("file:")) { keyTabLocationAsString = keyTabLocationAsString.substring(5); } LoginConfig loginConfig = new LoginConfig(keyTabLocationAsString, this.servicePrincipal, this.debug); Set<Principal> princ = new HashSet<>(1); princ.add(new KerberosPrincipal(this.servicePrincipal)); Subject sub = new Subject(false, princ, new HashSet<>(), new HashSet<>()); LoginContext lc = new LoginContext("", sub, null, loginConfig); lc.login(); this.serviceSubject = lc.getSubject(); } catch (final LoginException | IOException e) { throw new TechnicalException(e); } } /** * The service principal of the application. * For web apps this is <code>HTTP/full-qualified-domain-name@DOMAIN</code>. * The keytab must contain the key for this principal. * * @param servicePrincipal service principal to use * @see #setKeyTabLocation(Resource) */ public void setServicePrincipal(String servicePrincipal) { this.servicePrincipal = servicePrincipal; } /** * <p>The location of the keytab. You can use the normal Resource * prefixes like <code>file:</code> or <code>classpath:</code>, but as the * file is later on read by JAAS, we cannot guarantee that <code>classpath</code> * works in every environment, esp. not in Java EE application servers. You * should use <code>file:</code> there. * <p> * This file also needs special protection, which is another reason to * not include it in the classpath but rather use <code>file:/etc/http.keytab</code> * for example. * * @param keyTabLocation The location where the keytab resides */ public void setKeyTabLocation(Resource keyTabLocation) { this.keyTabLocation = keyTabLocation; } /** * Enables the debug mode of the JAAS Kerberos login module. * * @param debug default is false */ public void setDebug(boolean debug) { this.debug = debug; } /** * Determines whether to hold on to the {@link GSSContext GSS security context} or * otherwise {@link GSSContext#dispose() dispose} of it immediately (the default behaviour). * <p>Holding on to the GSS context allows decrypt and encrypt operations for subsequent * interactions with the principal. * * @param holdOnToGSSContext true if should hold on to context */ public void setHoldOnToGSSContext(boolean holdOnToGSSContext) { this.holdOnToGSSContext = holdOnToGSSContext; } /** * This class is needed, because the validation must run with previously generated JAAS subject * which belongs to the service principal and was loaded out of the keytab during startup. */ private class KerberosValidateAction implements PrivilegedExceptionAction<KerberosTicketValidation> { byte[] kerberosTicket; public KerberosValidateAction(byte[] kerberosTicket) { this.kerberosTicket = kerberosTicket; } @Override public KerberosTicketValidation run() throws Exception { byte[] responseToken = new byte[0]; GSSName gssName = null; GSSContext context = GSSManager.getInstance().createContext((GSSCredential) null); boolean first = true; while (!context.isEstablished()) { if (first) { kerberosTicket = tweakJdkRegression(kerberosTicket); } responseToken = context.acceptSecContext(kerberosTicket, 0, kerberosTicket.length); gssName = context.getSrcName(); if (gssName == null) { throw new BadCredentialsException("GSSContext name of the context initiator is null"); } first = false; } if (!holdOnToGSSContext) { context.dispose(); } return new KerberosTicketValidation(gssName.toString(), servicePrincipal, responseToken, context); } } /** * Normally you need a JAAS config file in order to use the JAAS Kerberos Login Module, * with this class it is not needed and you can have different configurations in one JVM. */ private static class LoginConfig extends Configuration { private String keyTabLocation; private String servicePrincipalName; private boolean debug; public LoginConfig(String keyTabLocation, String servicePrincipalName, boolean debug) { this.keyTabLocation = keyTabLocation; this.servicePrincipalName = servicePrincipalName; this.debug = debug; } @Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) { HashMap<String, String> options = new HashMap<>(); options.put("useKeyTab", "true"); options.put("keyTab", this.keyTabLocation); options.put("principal", this.servicePrincipalName); options.put("storeKey", "true"); options.put("doNotPrompt", "true"); if (this.debug) { options.put("debug", "true"); } options.put("isInitiator", "false"); return new AppConfigurationEntry[]{new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule", AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options),}; } } private static byte[] tweakJdkRegression(byte[] token) throws GSSException { // Due to regression in 8u40/8u45 described in // https://bugs.openjdk.java.net/browse/JDK-8078439 // try to tweak token package if it looks like it has // OID's in wrong order // // 0000: 60 82 06 5C 06 06 2B 06 01 05 05 02 A0 82 06 50 // 0010: 30 82 06 4C A0 30 30 2E |06 09 2A 86 48 82 F7 12 // 0020: 01 02 02|06 09 2A 86 48 86 F7 12 01 02 02 06|0A // 0030: 2B 06 01 04 01 82 37 02 02 1E 06 0A 2B 06 01 04 // 0040: 01 82 37 02 02 0A A2 82 06 16 04 82 06 12 60 82 // // In above package first token is in position 24 and second // in 35 with both having size 11. // // We simple check if we have these two in this order and swap // // Below code would create two arrays, lets just create that // manually because it doesn't change // Oid GSS_KRB5_MECH_OID = new Oid("1.2.840.113554.1.2.2"); // Oid MS_KRB5_MECH_OID = new Oid("1.2.840.48018.1.2.2"); // byte[] der1 = GSS_KRB5_MECH_OID.getDER(); // byte[] der2 = MS_KRB5_MECH_OID.getDER(); // 0000: 06 09 2A 86 48 86 F7 12 01 02 02 // 0000: 06 09 2A 86 48 82 F7 12 01 02 02 if (token == null || token.length < 48) { return token; } int[] toCheck = new int[]{0x06, 0x09, 0x2A, 0x86, 0x48, 0x82, 0xF7, 0x12, 0x01, 0x02, 0x02, 0x06, 0x09, 0x2A, 0x86, 0x48, 0x86, 0xF7, 0x12, 0x01, 0x02, 0x02}; for (int i = 0; i < 22; i++) { if ((byte) toCheck[i] != token[i + 24]) { return token; } } byte[] nt = new byte[token.length]; System.arraycopy(token, 0, nt, 0, 24); System.arraycopy(token, 35, nt, 24, 11); System.arraycopy(token, 24, nt, 35, 11); System.arraycopy(token, 46, nt, 46, token.length - 24 - 11 - 11); return nt; } }
apache-2.0
googleapis/google-api-java-client-services
clients/google-api-services-videointelligence/v1beta2/1.31.0/com/google/api/services/videointelligence/v1beta2/model/GoogleCloudVideointelligenceV1p2beta1AnnotateVideoProgress.java
2892
/* * 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 code was generated by https://github.com/googleapis/google-api-java-client-services/ * Modify at your own risk. */ package com.google.api.services.videointelligence.v1beta2.model; /** * Video annotation progress. Included in the `metadata` field of the `Operation` returned by the * `GetOperation` call of the `google::longrunning::Operations` service. * * <p> This is the Java data model class that specifies how to parse/serialize into the JSON that is * transmitted over HTTP when working with the Cloud Video Intelligence API. For a detailed * explanation see: * <a href="https://developers.google.com/api-client-library/java/google-http-java-client/json">https://developers.google.com/api-client-library/java/google-http-java-client/json</a> * </p> * * @author Google, Inc. */ @SuppressWarnings("javadoc") public final class GoogleCloudVideointelligenceV1p2beta1AnnotateVideoProgress extends com.google.api.client.json.GenericJson { /** * Progress metadata for all videos specified in `AnnotateVideoRequest`. * The value may be {@code null}. */ @com.google.api.client.util.Key private java.util.List<GoogleCloudVideointelligenceV1p2beta1VideoAnnotationProgress> annotationProgress; /** * Progress metadata for all videos specified in `AnnotateVideoRequest`. * @return value or {@code null} for none */ public java.util.List<GoogleCloudVideointelligenceV1p2beta1VideoAnnotationProgress> getAnnotationProgress() { return annotationProgress; } /** * Progress metadata for all videos specified in `AnnotateVideoRequest`. * @param annotationProgress annotationProgress or {@code null} for none */ public GoogleCloudVideointelligenceV1p2beta1AnnotateVideoProgress setAnnotationProgress(java.util.List<GoogleCloudVideointelligenceV1p2beta1VideoAnnotationProgress> annotationProgress) { this.annotationProgress = annotationProgress; return this; } @Override public GoogleCloudVideointelligenceV1p2beta1AnnotateVideoProgress set(String fieldName, Object value) { return (GoogleCloudVideointelligenceV1p2beta1AnnotateVideoProgress) super.set(fieldName, value); } @Override public GoogleCloudVideointelligenceV1p2beta1AnnotateVideoProgress clone() { return (GoogleCloudVideointelligenceV1p2beta1AnnotateVideoProgress) super.clone(); } }
apache-2.0
themarkypantz/kafka
streams/src/test/java/org/apache/kafka/streams/kstream/internals/KStreamTransformTest.java
3850
/* * 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.kafka.streams.kstream.internals; import org.apache.kafka.common.serialization.Serde; import org.apache.kafka.common.serialization.Serdes; import org.apache.kafka.streams.Consumed; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.StreamsBuilder; import org.apache.kafka.streams.kstream.KStream; import org.apache.kafka.streams.kstream.Transformer; import org.apache.kafka.streams.kstream.TransformerSupplier; import org.apache.kafka.streams.processor.ProcessorContext; import org.apache.kafka.test.KStreamTestDriver; import org.apache.kafka.test.MockProcessorSupplier; import org.junit.Rule; import org.junit.Test; import static org.junit.Assert.assertEquals; public class KStreamTransformTest { private String topicName = "topic"; final private Serde<Integer> intSerde = Serdes.Integer(); @Rule public final KStreamTestDriver driver = new KStreamTestDriver(); @Test public void testTransform() { StreamsBuilder builder = new StreamsBuilder(); TransformerSupplier<Number, Number, KeyValue<Integer, Integer>> transformerSupplier = new TransformerSupplier<Number, Number, KeyValue<Integer, Integer>>() { public Transformer<Number, Number, KeyValue<Integer, Integer>> get() { return new Transformer<Number, Number, KeyValue<Integer, Integer>>() { private int total = 0; @Override public void init(ProcessorContext context) { } @Override public KeyValue<Integer, Integer> transform(Number key, Number value) { total += value.intValue(); return KeyValue.pair(key.intValue() * 2, total); } @Override public KeyValue<Integer, Integer> punctuate(long timestamp) { return KeyValue.pair(-1, (int) timestamp); } @Override public void close() { } }; } }; final int[] expectedKeys = {1, 10, 100, 1000}; MockProcessorSupplier<Integer, Integer> processor = new MockProcessorSupplier<>(); KStream<Integer, Integer> stream = builder.stream(topicName, Consumed.with(intSerde, intSerde)); stream.transform(transformerSupplier).process(processor); driver.setUp(builder); for (int expectedKey : expectedKeys) { driver.process(topicName, expectedKey, expectedKey * 10); } driver.punctuate(2); driver.punctuate(3); assertEquals(6, processor.processed.size()); String[] expected = {"2:10", "20:110", "200:1110", "2000:11110", "-1:2", "-1:3"}; for (int i = 0; i < expected.length; i++) { assertEquals(expected[i], processor.processed.get(i)); } } }
apache-2.0
kisskys/incubator-asterixdb
hyracks-fullstack/algebricks/algebricks-core/src/main/java/org/apache/hyracks/algebricks/core/algebra/operators/logical/LeftOuterUnnestMapOperator.java
3325
/* * 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.hyracks.algebricks.core.algebra.operators.logical; import java.util.List; import org.apache.commons.lang3.mutable.Mutable; import org.apache.hyracks.algebricks.common.exceptions.AlgebricksException; import org.apache.hyracks.algebricks.core.algebra.base.ILogicalExpression; import org.apache.hyracks.algebricks.core.algebra.base.LogicalOperatorTag; import org.apache.hyracks.algebricks.core.algebra.base.LogicalVariable; import org.apache.hyracks.algebricks.core.algebra.expressions.IVariableTypeEnvironment; import org.apache.hyracks.algebricks.core.algebra.typing.ITypingContext; import org.apache.hyracks.algebricks.core.algebra.typing.PropagatingTypeEnvironment; import org.apache.hyracks.algebricks.core.algebra.visitors.ILogicalOperatorVisitor; /** * Left-outer-unnest-map is similar to the unnest-map operator. The only * difference is that this operator represents left-outer semantics, meaning * that it generates null values for non-matching tuples. It also propagates all * input variables. This may be used only in a left-outer-join case. */ public class LeftOuterUnnestMapOperator extends AbstractUnnestMapOperator { public LeftOuterUnnestMapOperator(List<LogicalVariable> variables, Mutable<ILogicalExpression> expression, List<Object> variableTypes, boolean propagateInput) { super(variables, expression, variableTypes, propagateInput); // propagateInput is always set to true for this operator. this.propagateInput = true; } @Override public LogicalOperatorTag getOperatorTag() { return LogicalOperatorTag.LEFT_OUTER_UNNEST_MAP; } @Override public <R, T> R accept(ILogicalOperatorVisitor<R, T> visitor, T arg) throws AlgebricksException { return visitor.visitLeftOuterUnnestMapOperator(this, arg); } @Override public IVariableTypeEnvironment computeOutputTypeEnvironment(ITypingContext ctx) throws AlgebricksException { // Propagates all input variables that come from the outer branch. PropagatingTypeEnvironment env = createPropagatingAllInputsTypeEnvironment(ctx); env.getCorrelatedNullableVariableLists().add(variables); // For the variables from the inner branch, the output type is the union // of (original type + null). for (int i = 0; i < variables.size(); i++) { env.setVarType(variables.get(i), ctx.getNullableTypeComputer().makeNullableType(variableTypes.get(i))); } return env; } }
apache-2.0
ederign/uberfire
uberfire-extensions/uberfire-security/uberfire-security-management/uberfire-security-management-backend/src/main/java/org/uberfire/ext/security/management/service/GroupManagerServiceImpl.java
5565
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * 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.uberfire.ext.security.management.service; import java.util.Collection; import java.util.Set; import javax.annotation.PostConstruct; import javax.enterprise.context.ApplicationScoped; import javax.inject.Inject; import org.jboss.errai.bus.server.annotations.Service; import org.jboss.errai.security.shared.api.Group; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.uberfire.ext.security.management.BackendUserSystemManager; import org.uberfire.ext.security.management.api.GroupManager; import org.uberfire.ext.security.management.api.GroupManagerSettings; import org.uberfire.ext.security.management.api.exception.NoImplementationAvailableException; import org.uberfire.ext.security.management.api.exception.SecurityManagementException; import org.uberfire.ext.security.management.api.service.GroupManagerService; import org.uberfire.ext.security.management.util.SecurityManagementUtils; /** * <p>The UberFire service implementation for GroupsManager API.</p> */ @Service @ApplicationScoped public class GroupManagerServiceImpl implements GroupManagerService { private static final Logger LOG = LoggerFactory.getLogger(GroupManagerServiceImpl.class); @Inject private BackendUserSystemManager userSystemManager; private GroupManager service; @PostConstruct public void init() { service = userSystemManager.groups(); } private GroupManager getService() throws SecurityManagementException { if (service == null) { throw new NoImplementationAvailableException(); } return service; } @Override public SearchResponse<Group> search(SearchRequest request) throws SecurityManagementException { final GroupManager serviceImpl = getService(); if (request.getPage() == 0) { throw new IllegalArgumentException("First page must be 1."); } // Constraint registered UF roles as not allowed for searching. final Set<String> registeredRoleNames = SecurityManagementUtils.getRegisteredRoleNames(); if (request.getConstrainedIdentifiers() == null) { request.setConstrainedIdentifiers(registeredRoleNames); } else { request.getConstrainedIdentifiers().addAll(registeredRoleNames); } // Delegate the search to the specific provider. return serviceImpl.search(request); } @Override public Group get(String identifier) throws SecurityManagementException { final GroupManager serviceImpl = getService(); return serviceImpl.get(identifier); } @Override public Group create(Group group) throws SecurityManagementException { final String name = group.getName(); if (isConstrained(name)) { throw new IllegalArgumentException("Group with name '" + name + "' cannot be created, " + "as it is a constrained value (it is a role or the admin group"); } final GroupManager serviceImpl = getService(); return serviceImpl.create(group); } @Override public Group update(Group group) throws SecurityManagementException { final String name = group.getName(); if (isConstrained(name)) { throw new IllegalArgumentException("Group with name '" + name + "' cannot be updated, " + "as it is a constrained value (it is a role or the admin group"); } final GroupManager serviceImpl = getService(); return serviceImpl.update(group); } @Override public void delete(String... identifiers) throws SecurityManagementException { for (final String name : identifiers) { if (isConstrained(name)) { throw new IllegalArgumentException("Group with name '" + name + "' cannot be deleted, " + "as it is a constrained value (it is a role or the admin group"); } } final GroupManager serviceImpl = getService(); serviceImpl.delete(identifiers); } @Override public GroupManagerSettings getSettings() { final GroupManager serviceImpl = getService(); final GroupManagerSettings settings = serviceImpl.getSettings(); if (null != settings) { settings.setConstrainedGroups(SecurityManagementUtils.getRegisteredRoleNames()); } return settings; } @Override public void assignUsers(String name, Collection<String> users) throws SecurityManagementException { final GroupManager serviceImpl = getService(); serviceImpl.assignUsers(name, users); } protected boolean isConstrained(final String name) { return SecurityManagementUtils.getRegisteredRoleNames().contains(name); } }
apache-2.0
AlanJager/zstack
sdk/src/main/java/org/zstack/sdk/DeleteAutoScalingRuleTriggerAction.java
2882
package org.zstack.sdk; import java.util.HashMap; import java.util.Map; import org.zstack.sdk.*; public class DeleteAutoScalingRuleTriggerAction extends AbstractAction { private static final HashMap<String, Parameter> parameterMap = new HashMap<>(); private static final HashMap<String, Parameter> nonAPIParameterMap = new HashMap<>(); public static class Result { public ErrorCode error; public org.zstack.sdk.DeleteAutoScalingRuleTriggerResult value; public Result throwExceptionIfError() { if (error != null) { throw new ApiException( String.format("error[code: %s, description: %s, details: %s]", error.code, error.description, error.details) ); } return this; } } @Param(required = true, nonempty = false, nullElements = false, emptyString = true, noTrim = false) public java.lang.String uuid; @Param(required = false) public java.lang.String deleteMode = "Permissive"; @Param(required = false) public java.util.List systemTags; @Param(required = false) public java.util.List userTags; @Param(required = false) public String sessionId; @Param(required = false) public String accessKeyId; @Param(required = false) public String accessKeySecret; @Param(required = false) public String requestIp; @NonAPIParam public long timeout = -1; @NonAPIParam public long pollingInterval = -1; private Result makeResult(ApiResult res) { Result ret = new Result(); if (res.error != null) { ret.error = res.error; return ret; } org.zstack.sdk.DeleteAutoScalingRuleTriggerResult value = res.getResult(org.zstack.sdk.DeleteAutoScalingRuleTriggerResult.class); ret.value = value == null ? new org.zstack.sdk.DeleteAutoScalingRuleTriggerResult() : value; return ret; } public Result call() { ApiResult res = ZSClient.call(this); return makeResult(res); } public void call(final Completion<Result> completion) { ZSClient.call(this, new InternalCompletion() { @Override public void complete(ApiResult res) { completion.complete(makeResult(res)); } }); } protected Map<String, Parameter> getParameterMap() { return parameterMap; } protected Map<String, Parameter> getNonAPIParameterMap() { return nonAPIParameterMap; } protected RestInfo getRestInfo() { RestInfo info = new RestInfo(); info.httpMethod = "DELETE"; info.path = "/autoscaling/groups/rules/triggers/{uuid}"; info.needSession = true; info.needPoll = true; info.parameterName = ""; return info; } }
apache-2.0
OSUCartography/MapComposer
src/main/java/com/jhlabs/image/ErodeAlphaFilter.java
2219
/* Copyright 2006 Jerry Huxtable 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.jhlabs.image; import java.awt.image.*; public class ErodeAlphaFilter extends PointFilter { private float threshold; private float softness = 0; protected float radius = 5; private float lowerThreshold; private float upperThreshold; public ErodeAlphaFilter() { this( 3, 0.75f, 0 ); } public ErodeAlphaFilter( float radius, float threshold, float softness ) { this.radius = radius; this.threshold = threshold; this.softness = softness; } public void setRadius(float radius) { this.radius = radius; } public float getRadius() { return radius; } public void setThreshold(float threshold) { this.threshold = threshold; } public float getThreshold() { return threshold; } public void setSoftness(float softness) { this.softness = softness; } public float getSoftness() { return softness; } public BufferedImage filter( BufferedImage src, BufferedImage dst ) { dst = new GaussianFilter( (int)radius ).filter( src, null ); lowerThreshold = 255*(threshold - softness*0.5f); upperThreshold = 255*(threshold + softness*0.5f); return super.filter(dst, dst); } public int filterRGB(int x, int y, int rgb) { int a = (rgb >> 24) & 0xff; int r = (rgb >> 16) & 0xff; int g = (rgb >> 8) & 0xff; int b = rgb & 0xff; if ( a == 255 ) return 0xffffffff; float f = ImageMath.smoothStep(lowerThreshold, upperThreshold, (float)a); a = (int)(f * 255); if ( a < 0 ) a = 0; else if ( a > 255 ) a = 255; return (a << 24) | 0xffffff; } public String toString() { return "Alpha/Erode..."; } }
apache-2.0
NVolcz/zaproxy
src/org/zaproxy/zap/network/HttpResponseBody.java
4954
/* * Zed Attack Proxy (ZAP) and its related class files. * * ZAP is an HTTP/HTTPS proxy for assessing web application security. * * 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.zaproxy.zap.network; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.log4j.Logger; import org.parosproxy.paros.network.HttpBody; public class HttpResponseBody extends HttpBody { private static final Logger log = Logger.getLogger(HttpResponseBody.class); //private static Pattern patternCharset = Pattern.compile("<META +[^>]+charset=['\"]*([^>'\"])+['\"]*>", Pattern.CASE_INSENSITIVE| Pattern.MULTILINE); private static final Pattern patternCharset = Pattern.compile("<META +[^>]+charset *= *['\\x22]?([^>'\\x22;]+)['\\x22]? *[/]?>", Pattern.CASE_INSENSITIVE); /** * Constructs a {@code HttpResponseBody} with no contents (that is, zero length). */ public HttpResponseBody() { super(); } /** * Constructs a {@code HttpResponseBody} with the given initial capacity. * <p> * The initial capacity is limited to prevent allocating big arrays. * * @param capacity the initial capacity * @see HttpBody#LIMIT_INITIAL_CAPACITY */ public HttpResponseBody(int capacity) { super(capacity); } /** * Constructs a {@code HttpResponseBody} with the given {@code contents}, using default charset for {@code String} related * operations. * <p> * If the given {@code contents} are {@code null} the {@code HttpResponseBody} will have no content. * <p> * <strong>Note:</strong> If the contents are not representable with the default charset it might lead to data loss. * * @param contents the contents of the body, might be {@code null} * @see #HttpResponseBody(byte[]) * @see HttpBody#DEFAULT_CHARSET */ public HttpResponseBody(String contents) { super(contents); } /** * Constructs a {@code HttpResponseBody} with the given {@code contents}. * <p> * If the given {@code contents} are {@code null} the {@code HttpResponseBody} will have no content. * * @param contents the contents of the body, might be {@code null} * @since 2.5.0 */ public HttpResponseBody(byte[] contents) { super(contents); } @Override protected Charset determineCharset(String contents) { Matcher matcher = patternCharset.matcher(contents); if (matcher.find()) { try { return Charset.forName(matcher.group(1)); } catch (IllegalArgumentException e) { log.warn("Unable to determine (valid) charset with the (X)HTML meta charset: " + e.getMessage()); } } else if (isUtf8String(contents)) { return StandardCharsets.UTF_8; } return null; } private static boolean isUtf8String(String string) { return new String(string.getBytes(StandardCharsets.UTF_8), StandardCharsets.UTF_8).length() == string.length(); } @Override protected String createString(Charset currentCharset) { if (currentCharset != null) { return super.createString(currentCharset); } return createStringWithMetaCharset(); } private String createStringWithMetaCharset() { String result = null; String resultDefaultCharset = null; try{ resultDefaultCharset = new String(getBytes(), 0, getPos(), StandardCharsets.ISO_8859_1); Matcher matcher = patternCharset.matcher(resultDefaultCharset); if (matcher.find()) { final String charset = matcher.group(1); result = new String(getBytes(), 0, getPos(), charset); setCharset(charset); } else { String utf8 = toUTF8(); if (utf8 != null) { // assume to be UTF8 setCharset(StandardCharsets.UTF_8.name()); result = utf8; } else { result = resultDefaultCharset; } } } catch(UnsupportedEncodingException e) { log.error("Unable to encode with the (X)HTML meta charset: " + e.getMessage()); log.warn("Using default charset: " + DEFAULT_CHARSET); result = resultDefaultCharset; } return result; } private String toUTF8() { String utf8 = new String(getBytes(), 0, getPos(), StandardCharsets.UTF_8); int length2 = utf8.getBytes(StandardCharsets.UTF_8).length; if (getPos() != length2) { return null; } return utf8; } }
apache-2.0
ingokegel/intellij-community
platform/lang-impl/src/com/intellij/ide/hierarchy/ViewClassHierarchyAction.java
1497
/* * Copyright 2000-2009 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.ide.hierarchy; import com.intellij.icons.AllIcons; import com.intellij.ide.IdeBundle; import com.intellij.openapi.actionSystem.AnActionEvent; import org.jetbrains.annotations.NotNull; public final class ViewClassHierarchyAction extends ChangeViewTypeActionBase { public ViewClassHierarchyAction() { super(IdeBundle.messagePointer("action.view.class.hierarchy"), IdeBundle.messagePointer("action.description.view.class.hierarchy"), AllIcons.Hierarchy.Class); } @Override protected final String getTypeName() { return TypeHierarchyBrowserBase.getTypeHierarchyType(); } @Override public final void update(@NotNull final AnActionEvent event) { super.update(event); TypeHierarchyBrowserBase browser = getHierarchyBrowser(event.getDataContext()); event.getPresentation().setEnabled(browser != null && !browser.isInterface()); } }
apache-2.0
mariofusco/fuse-bxms-integ
switchyard/switchyard-component-common-knowledge/src/main/java/org/switchyard/component/common/knowledge/runtime/remote/RemoteRuntimeManager.java
2767
/* * Copyright 2014 Red Hat Inc. and/or its affiliates and other contributors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.switchyard.component.common.knowledge.runtime.remote; import java.util.Map; import java.util.WeakHashMap; import org.kie.api.runtime.manager.Context; import org.kie.api.runtime.manager.RuntimeEngine; import org.kie.api.runtime.manager.RuntimeManager; import org.kie.services.client.api.command.RemoteConfiguration; /** * RemoteRuntimeManager. * * @author David Ward &lt;<a href="mailto:dward@jboss.org">dward@jboss.org</a>&gt; &copy; 2014 Red Hat Inc. */ public class RemoteRuntimeManager implements RuntimeManager { private static final String NULL_CONTEXT_ID = "NullContext"; private final RemoteConfiguration _configuration; private final String _identifier; private final Map<Object, RuntimeEngine> _engines = new WeakHashMap<Object, RuntimeEngine>(); /** * Creates a new RemoteRuntimeManager. * @param configuration the RemoteConfiguration * @param identifier the identifier */ public RemoteRuntimeManager(RemoteConfiguration configuration, String identifier) { _configuration = configuration; _identifier = identifier; } /** * {@inheritDoc} */ @Override public synchronized RuntimeEngine getRuntimeEngine(Context<?> context) { Object contextId = context != null ? context.getContextId() : null; if (contextId == null) { contextId = NULL_CONTEXT_ID; } RuntimeEngine engine = _engines.get(contextId); if (engine == null) { engine = new ExtendedRemoteRuntimeEngine(_configuration, context); _engines.put(contextId, engine); } return engine; } /** * {@inheritDoc} */ @Override public String getIdentifier() { return _identifier; } /** * {@inheritDoc} */ @Override public void disposeRuntimeEngine(RuntimeEngine runtime) { // no-op } /** * {@inheritDoc} */ @Override public void close() { // no-op } @Override public void signalEvent(String arg0, Object arg1) { // TODO Auto-generated method stub } }
apache-2.0
clarkyzl/flink
flink-runtime/src/test/java/org/apache/flink/runtime/scheduler/TestingPhysicalSlotProvider.java
6964
/* * 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.flink.runtime.scheduler; import org.apache.flink.runtime.clusterframework.types.AllocationID; import org.apache.flink.runtime.clusterframework.types.ResourceProfile; import org.apache.flink.runtime.concurrent.FutureUtils; import org.apache.flink.runtime.executiongraph.utils.SimpleAckingTaskManagerGateway; import org.apache.flink.runtime.jobmanager.scheduler.NoResourceAvailableException; import org.apache.flink.runtime.jobmanager.slots.TaskManagerGateway; import org.apache.flink.runtime.jobmaster.SlotRequestId; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotProvider; import org.apache.flink.runtime.jobmaster.slotpool.PhysicalSlotRequest; import org.apache.flink.util.Preconditions; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Optional; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; /** A {@link PhysicalSlotProvider} implementation that can be used in tests. */ public class TestingPhysicalSlotProvider implements PhysicalSlotProvider { private final Map<SlotRequestId, PhysicalSlotRequest> requests; private final Map<SlotRequestId, CompletableFuture<TestingPhysicalSlot>> responses; private final Map<SlotRequestId, Throwable> cancellations; private final Function<ResourceProfile, CompletableFuture<TestingPhysicalSlot>> physicalSlotCreator; public static TestingPhysicalSlotProvider create( Function<ResourceProfile, CompletableFuture<TestingPhysicalSlot>> physicalSlotCreator) { return new TestingPhysicalSlotProvider(physicalSlotCreator); } public static TestingPhysicalSlotProvider createWithInfiniteSlotCreation() { return create( (resourceProfile) -> CompletableFuture.completedFuture( new TestingPhysicalSlot(resourceProfile, new AllocationID()))); } public static TestingPhysicalSlotProvider createWithoutImmediatePhysicalSlotCreation() { return create((ignored) -> new CompletableFuture<>()); } public static TestingPhysicalSlotProvider createWithFailingPhysicalSlotCreation(Throwable t) { return create((ignored) -> FutureUtils.completedExceptionally(t)); } public static TestingPhysicalSlotProvider createWithLimitedAmountOfPhysicalSlots( int slotCount) { return createWithLimitedAmountOfPhysicalSlots( slotCount, new SimpleAckingTaskManagerGateway()); } public static TestingPhysicalSlotProvider createWithLimitedAmountOfPhysicalSlots( int slotCount, TaskManagerGateway taskManagerGateway) { AtomicInteger availableSlotCount = new AtomicInteger(slotCount); return create( (resourceProfile) -> { int count = availableSlotCount.getAndDecrement(); if (count > 0) { return CompletableFuture.completedFuture( TestingPhysicalSlot.builder() .withResourceProfile(resourceProfile) .withTaskManagerGateway(taskManagerGateway) .build()); } else { return FutureUtils.completedExceptionally( new NoResourceAvailableException( String.format( "The limit of %d provided slots was reached. No available slots can be provided.", slotCount))); } }); } private TestingPhysicalSlotProvider( Function<ResourceProfile, CompletableFuture<TestingPhysicalSlot>> physicalSlotCreator) { this.physicalSlotCreator = physicalSlotCreator; this.requests = new HashMap<>(); this.responses = new HashMap<>(); this.cancellations = new HashMap<>(); } @Override public CompletableFuture<PhysicalSlotRequest.Result> allocatePhysicalSlot( PhysicalSlotRequest physicalSlotRequest) { SlotRequestId slotRequestId = physicalSlotRequest.getSlotRequestId(); requests.put(slotRequestId, physicalSlotRequest); final CompletableFuture<TestingPhysicalSlot> resultFuture = physicalSlotCreator.apply( physicalSlotRequest.getSlotProfile().getPhysicalSlotResourceProfile()); responses.put(slotRequestId, resultFuture); return resultFuture.thenApply( physicalSlot -> new PhysicalSlotRequest.Result(slotRequestId, physicalSlot)); } @Override public void cancelSlotRequest(SlotRequestId slotRequestId, Throwable cause) { cancellations.put(slotRequestId, cause); } public CompletableFuture<TestingPhysicalSlot> getResultForRequestId( SlotRequestId slotRequestId) { return getResponses().get(slotRequestId); } PhysicalSlotRequest getFirstRequestOrFail() { return getFirstElementOrFail(requests.values()); } public void awaitAllSlotRequests() { getResponses().values().forEach(CompletableFuture::join); } public Map<SlotRequestId, PhysicalSlotRequest> getRequests() { return Collections.unmodifiableMap(requests); } public CompletableFuture<TestingPhysicalSlot> getFirstResponseOrFail() { return getFirstElementOrFail(responses.values()); } public Map<SlotRequestId, CompletableFuture<TestingPhysicalSlot>> getResponses() { return Collections.unmodifiableMap(responses); } public Map<SlotRequestId, Throwable> getCancellations() { return Collections.unmodifiableMap(cancellations); } private static <T> T getFirstElementOrFail(Collection<T> collection) { Optional<T> element = collection.stream().findFirst(); Preconditions.checkState(element.isPresent()); return element.get(); } }
apache-2.0
ShailShah/alluxio
core/common/src/main/java/alluxio/resource/ResourcePool.java
6109
/* * 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.resource; import com.google.common.base.Preconditions; import java.io.IOException; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import javax.annotation.concurrent.ThreadSafe; /** * Class representing a pool of resources to be temporarily used and returned. Inheriting classes * must implement the close method as well as initialize the resources in the constructor. The * implemented methods are thread-safe and inheriting classes should also written in a thread-safe * manner. See {@code FileSystemMasterClientPool} as an example. * * @param <T> the type of resource this pool manages */ @ThreadSafe public abstract class ResourcePool<T> implements Pool<T> { private static final long WAIT_INDEFINITELY = -1; private final ReentrantLock mTakeLock; private final Condition mNotEmpty; protected final int mMaxCapacity; protected final ConcurrentLinkedQueue<T> mResources; /** It represents the total number of resources that have been created by this pool. */ protected final AtomicInteger mCurrentCapacity; /** * Creates a {@link ResourcePool} instance with the specified capacity. * * @param maxCapacity the maximum of resources in this pool */ public ResourcePool(int maxCapacity) { this(maxCapacity, new ConcurrentLinkedQueue<T>()); } /** * Internal constructor that can provide an object to be used for the internal queue. * * @param maxCapacity bhe maximum of resources in this pool * @param resources blocking queue to use */ protected ResourcePool(int maxCapacity, ConcurrentLinkedQueue<T> resources) { mTakeLock = new ReentrantLock(); mNotEmpty = mTakeLock.newCondition(); mMaxCapacity = maxCapacity; mCurrentCapacity = new AtomicInteger(); mResources = resources; } /** * Acquires an object of type {@code T} from the pool. This operation is blocking if no resource * is available. Each call of {@link #acquire()} should be paired with another call of * {@link #release(Object)}} after the use of this resource completes to return this resource to * the pool. * * @return a resource taken from the pool */ @Override public T acquire() { return acquire(WAIT_INDEFINITELY, null); } /** * Acquires an object of type {code T} from the pool. * * This method is like {@link #acquire()}, but it will time out if an object cannot be * acquired before the specified amount of time. * * @param time an amount of time to wait, <= 0 to wait indefinitely * @param unit the unit to use for time, null to wait indefinitely * @return a resource taken from the pool, or null if the operation times out */ @Override public T acquire(long time, TimeUnit unit) { // If either time or unit are null, the other should also be null. Preconditions.checkState((time <= 0) == (unit == null)); long endTimeMs = 0; if (time > 0) { endTimeMs = System.currentTimeMillis() + unit.toMillis(time); } // Try to take a resource without blocking T resource = mResources.poll(); if (resource != null) { return resource; } if (mCurrentCapacity.getAndIncrement() < mMaxCapacity) { // If the resource pool is empty but capacity is not yet full, create a new resource. return createNewResource(); } mCurrentCapacity.decrementAndGet(); // Otherwise, try to take a resource from the pool, blocking if none are available. try { mTakeLock.lockInterruptibly(); try { while (true) { resource = mResources.poll(); if (resource != null) { return resource; } if (time > 0) { long currTimeMs = System.currentTimeMillis(); if (currTimeMs >= endTimeMs) { return null; } if (!mNotEmpty.await(endTimeMs - currTimeMs, TimeUnit.MILLISECONDS)) { return null; } } else { mNotEmpty.await(); } } } finally { mTakeLock.unlock(); } } catch (InterruptedException e) { throw new RuntimeException(e); } } /** * Closes the resource pool. After this call, the object should be discarded. Inheriting classes * should clean up all their resources here. */ @Override public abstract void close() throws IOException; /** * Releases an object of type T, this must be called after the thread is done using a resource * obtained by acquire. * * @param resource the resource to be released, it should not be reused after calling this method */ @Override public void release(T resource) { if (resource != null) { mResources.add(resource); try (LockResource r = new LockResource(mTakeLock)) { mNotEmpty.signal(); } } } @Override public int size() { return mCurrentCapacity.get(); } /** * Creates a new resource which will be added to the resource pool after the user is done using * it. This method should only be called when the capacity of the pool has not been reached. If * creating the resource will take a significant amount of time, the inheriting class should * avoid calling this method and instead initialize all the resources in the constructor. * * @return a resource which will be added to the pool of resources */ protected abstract T createNewResource(); }
apache-2.0
vhalbert/modeshape
modeshape-jcr/src/main/java/org/modeshape/jcr/locking/AbstractLockingService.java
6998
/* * ModeShape (http://www.modeshape.org) * * 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.modeshape.jcr.locking; import java.util.Arrays; import java.util.LinkedHashSet; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.Lock; import org.modeshape.common.annotation.ThreadSafe; import org.modeshape.common.logging.Logger; import org.modeshape.common.util.CheckArg; /** * Base class for {@link LockingService} implementations. * * @author Horia Chiorean (hchiorea@redhat.com) * @since 5.0 */ @ThreadSafe public abstract class AbstractLockingService<T extends Lock> implements LockingService { protected final Logger logger = Logger.getLogger(getClass()); private final ConcurrentHashMap<String, T> locksByName = new ConcurrentHashMap<>(); private final ConcurrentHashMap<String, AtomicInteger> locksByWaiters = new ConcurrentHashMap<>(); private final AtomicBoolean running = new AtomicBoolean(false); private final long lockTimeoutMillis; protected AbstractLockingService() { this(0); } protected AbstractLockingService(long lockTimeoutMillis) { CheckArg.isNonNegative(lockTimeoutMillis, "lockTimeoutMillis"); this.lockTimeoutMillis = lockTimeoutMillis; this.running.compareAndSet(false, true); } @Override public boolean tryLock(String... names) throws InterruptedException { return tryLock(lockTimeoutMillis, TimeUnit.MILLISECONDS, names); } @Override public boolean tryLock(long time, TimeUnit unit, String... names) throws InterruptedException { if (!running.get()) { throw new IllegalStateException("Service has been shut down"); } Set<String> successfullyLocked = new LinkedHashSet<>(); for (String name : names) { logger.debug("attempting to lock {0}", name); locksByWaiters.computeIfAbsent(name, lockName -> new AtomicInteger(0)).incrementAndGet(); boolean success = false; T lock = null; try { lock = locksByName.computeIfAbsent(name, this::createLock); success = doLock(lock, time, unit); } catch (Exception e) { logger.debug(e, "unexpected exception while attempting to lock '{0}'", name); } // if lock acquisition was not successful (for whatever reason) revert the lock if (!success) { // decrement the waiter value for the lock we failed to get locksByWaiters.computeIfPresent(name, (lockName, atomicInteger) -> { if (atomicInteger.decrementAndGet() == 0) { // we couldn't get the lock, but no one is using it, meaning it just became unlocked so just remove it locksByName.computeIfPresent(name, (internalLockName, internalLock) -> null); return null; } return atomicInteger; }); if (!successfullyLocked.isEmpty()) { logger.debug("Unable to acquire lock on {0}. Reverting back the already obtained locks: {1}", name, successfullyLocked); // and unlock all the rest of the locks... unlock(successfullyLocked.toArray(new String[0])); } return false; } logger.debug("{0} locked successfully (ref {1})", name, lock); successfullyLocked.add(name); } return true; } @Override public boolean unlock(String... names) { if (!running.get()) { throw new IllegalStateException("Service has been shut down"); } return Arrays.stream(names) .map(this::unlock) .allMatch(Boolean::booleanValue); } protected boolean unlock(String name) { logger.debug("attempting to unlock {0}", name); AtomicBoolean unlocked = new AtomicBoolean(false); locksByName.computeIfPresent(name, (key, lock) -> { AtomicInteger waiters = locksByWaiters.computeIfPresent(name, (lockName, atomicInteger) -> { if (releaseLock(lock)) { logger.debug("{0} unlocked (ref {1})...", name, lock); unlocked.compareAndSet(false, true); if (atomicInteger.decrementAndGet() > 0) { // there are still threads waiting on this, so don't remove it... return atomicInteger; } else { // no one waiting on the this lock anymore return null; } } // the lock was not unlocked logger.debug("{0} failed to unlock (ref {1})...", name, lock); return atomicInteger; }); if (waiters != null) { logger.debug("lock '{0}' is not currently locked but will be", name); return lock; } else { // The lock is not used, and returning null will remove it from the map ... logger.debug("lock '{0}' not used anymore; removing it from map", name); return null; } }); return unlocked.get(); } @Override public synchronized boolean shutdown() { if (!running.get()) { return false; } logger.debug("Shutting down locking service..."); doShutdown(); locksByName.clear(); running.compareAndSet(true, false); return true; } protected void doShutdown() { locksByName.forEach((key, lock) -> { if (releaseLock(lock)) { logger.debug("{0} unlocked successfully ", key); } else { logger.debug("{0} cannot be released...", key); } }); } protected boolean doLock(T lock, long time, TimeUnit timeUnit) throws InterruptedException { return time > 0 ? lock.tryLock(time, timeUnit) : lock.tryLock(); } protected abstract T createLock(String name); protected abstract boolean releaseLock(T lock); }
apache-2.0
ingokegel/intellij-community
platform/analysis-impl/src/com/intellij/codeInsight/lookup/impl/ElementLookupRenderer.java
1278
/* * Copyright 2000-2009 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.codeInsight.lookup.impl; import com.intellij.codeInsight.lookup.LookupElementPresentation; import com.intellij.codeInsight.lookup.LookupItem; import com.intellij.openapi.extensions.ExtensionPointName; /** * @author yole * @deprecated use {@link com.intellij.codeInsight.lookup.LookupElement#renderElement(LookupElementPresentation)} */ @Deprecated public interface ElementLookupRenderer<T> { ExtensionPointName<ElementLookupRenderer> EP_NAME = ExtensionPointName.create("com.intellij.elementLookupRenderer"); boolean handlesItem(Object element); void renderElement(final LookupItem item, T element, LookupElementPresentation presentation); }
apache-2.0
jam2in/arcus-java-client
src/test/manual/net/spy/memcached/emptycollection/GetWithDropBTreeTest.java
3589
/* * arcus-java-client : Arcus Java client * Copyright 2010-2014 NAVER Corp. * * 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.spy.memcached.emptycollection; import java.util.Map; import junit.framework.Assert; import net.spy.memcached.collection.Element; import net.spy.memcached.collection.ElementFlagFilter; import net.spy.memcached.collection.BaseIntegrationTest; import net.spy.memcached.collection.CollectionAttributes; public class GetWithDropBTreeTest extends BaseIntegrationTest { private final String KEY = this.getClass().getSimpleName(); private final long BKEY = 10L; private final int VALUE = 1234567890; @Override protected void setUp() throws Exception { super.setUp(); mc.delete(KEY).get(); boolean insertResult = mc.asyncBopInsert(KEY, BKEY, null, VALUE, new CollectionAttributes()).get(); Assert.assertTrue(insertResult); } public void testGetWithoutDeleteAndDrop() { try { // check attr Assert.assertEquals(new Long(1), mc.asyncGetAttr(KEY).get() .getCount()); // get value delete=false, drop=true Assert.assertEquals( VALUE, mc.asyncBopGet(KEY, BKEY, ElementFlagFilter.DO_NOT_FILTER, false, false).get().get(BKEY).getValue()); // check exists Assert.assertEquals(new Long(1), mc.asyncGetAttr(KEY).get() .getCount()); // get value again Assert.assertEquals( VALUE, mc.asyncBopGet(KEY, BKEY, ElementFlagFilter.DO_NOT_FILTER, false, false).get().get(BKEY).getValue()); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } public void testGetWithtDeleteAndWithoutDrop() { try { // check attr Assert.assertEquals(new Long(1), mc.asyncGetAttr(KEY).get() .getCount()); // get value delete=true, drop=false Assert.assertEquals( VALUE, mc.asyncBopGet(KEY, BKEY, ElementFlagFilter.DO_NOT_FILTER, true, false).get().get(BKEY).getValue()); // check exists empty btree CollectionAttributes attr = mc.asyncGetAttr(KEY).get(); Assert.assertNotNull(attr); Assert.assertEquals(new Long(0), attr.getCount()); Map<Long, Element<Object>> map = mc.asyncBopGet(KEY, BKEY, ElementFlagFilter.DO_NOT_FILTER, false, false).get(); Assert.assertNotNull(map); Assert.assertTrue(map.isEmpty()); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } public void testGetWithtDeleteAndWithDrop() { try { // check attr Assert.assertEquals(new Long(1), mc.asyncGetAttr(KEY).get() .getCount()); // get value delete=true, drop=false Assert.assertEquals( VALUE, mc.asyncBopGet(KEY, BKEY, ElementFlagFilter.DO_NOT_FILTER, true, true).get().get(BKEY).getValue()); // check btree CollectionAttributes attr = mc.asyncGetAttr(KEY).get(); Assert.assertNull(attr); Map<Long, Element<Object>> map = mc.asyncBopGet(KEY, BKEY, ElementFlagFilter.DO_NOT_FILTER, false, false).get(); Assert.assertNull(map); } catch (Exception e) { e.printStackTrace(); Assert.fail(e.getMessage()); } } }
apache-2.0
XidongHuang/aws-sdk-for-java
src/main/java/com/amazonaws/services/cloudwatch/model/DescribeAlarmsForMetricRequest.java
17917
/* * Copyright 2010-2012 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.cloudwatch.model; import com.amazonaws.AmazonWebServiceRequest; /** * Container for the parameters to the {@link com.amazonaws.services.cloudwatch.AmazonCloudWatch#describeAlarmsForMetric(DescribeAlarmsForMetricRequest) DescribeAlarmsForMetric operation}. * <p> * Retrieves all alarms for a single metric. Specify a statistic, period, or unit to filter the set of alarms further. * </p> * * @see com.amazonaws.services.cloudwatch.AmazonCloudWatch#describeAlarmsForMetric(DescribeAlarmsForMetricRequest) */ public class DescribeAlarmsForMetricRequest extends AmazonWebServiceRequest { /** * The name of the metric. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 255<br/> */ private String metricName; /** * The namespace of the metric. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 255<br/> * <b>Pattern: </b>[^:].*<br/> */ private String namespace; /** * The statistic for the metric. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>SampleCount, Average, Sum, Minimum, Maximum */ private String statistic; /** * The list of dimensions associated with the metric. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>0 - 10<br/> */ private java.util.List<Dimension> dimensions; /** * The period in seconds over which the statistic is applied. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>60 - <br/> */ private Integer period; /** * The unit for the metric. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>Seconds, Microseconds, Milliseconds, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Bits, Kilobits, Megabits, Gigabits, Terabits, Percent, Count, Bytes/Second, Kilobytes/Second, Megabytes/Second, Gigabytes/Second, Terabytes/Second, Bits/Second, Kilobits/Second, Megabits/Second, Gigabits/Second, Terabits/Second, Count/Second, None */ private String unit; /** * The name of the metric. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 255<br/> * * @return The name of the metric. */ public String getMetricName() { return metricName; } /** * The name of the metric. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 255<br/> * * @param metricName The name of the metric. */ public void setMetricName(String metricName) { this.metricName = metricName; } /** * The name of the metric. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 255<br/> * * @param metricName The name of the metric. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeAlarmsForMetricRequest withMetricName(String metricName) { this.metricName = metricName; return this; } /** * The namespace of the metric. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 255<br/> * <b>Pattern: </b>[^:].*<br/> * * @return The namespace of the metric. */ public String getNamespace() { return namespace; } /** * The namespace of the metric. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 255<br/> * <b>Pattern: </b>[^:].*<br/> * * @param namespace The namespace of the metric. */ public void setNamespace(String namespace) { this.namespace = namespace; } /** * The namespace of the metric. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>1 - 255<br/> * <b>Pattern: </b>[^:].*<br/> * * @param namespace The namespace of the metric. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeAlarmsForMetricRequest withNamespace(String namespace) { this.namespace = namespace; return this; } /** * The statistic for the metric. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>SampleCount, Average, Sum, Minimum, Maximum * * @return The statistic for the metric. * * @see Statistic */ public String getStatistic() { return statistic; } /** * The statistic for the metric. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>SampleCount, Average, Sum, Minimum, Maximum * * @param statistic The statistic for the metric. * * @see Statistic */ public void setStatistic(String statistic) { this.statistic = statistic; } /** * The statistic for the metric. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>SampleCount, Average, Sum, Minimum, Maximum * * @param statistic The statistic for the metric. * * @return A reference to this updated object so that method calls can be chained * together. * * @see Statistic */ public DescribeAlarmsForMetricRequest withStatistic(String statistic) { this.statistic = statistic; return this; } /** * The statistic for the metric. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>SampleCount, Average, Sum, Minimum, Maximum * * @param statistic The statistic for the metric. * * @see Statistic */ public void setStatistic(Statistic statistic) { this.statistic = statistic.toString(); } /** * The statistic for the metric. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>SampleCount, Average, Sum, Minimum, Maximum * * @param statistic The statistic for the metric. * * @return A reference to this updated object so that method calls can be chained * together. * * @see Statistic */ public DescribeAlarmsForMetricRequest withStatistic(Statistic statistic) { this.statistic = statistic.toString(); return this; } /** * The list of dimensions associated with the metric. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>0 - 10<br/> * * @return The list of dimensions associated with the metric. */ public java.util.List<Dimension> getDimensions() { if (dimensions == null) { dimensions = new java.util.ArrayList<Dimension>(); } return dimensions; } /** * The list of dimensions associated with the metric. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>0 - 10<br/> * * @param dimensions The list of dimensions associated with the metric. */ public void setDimensions(java.util.Collection<Dimension> dimensions) { if (dimensions == null) { this.dimensions = null; return; } java.util.List<Dimension> dimensionsCopy = new java.util.ArrayList<Dimension>(dimensions.size()); dimensionsCopy.addAll(dimensions); this.dimensions = dimensionsCopy; } /** * The list of dimensions associated with the metric. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>0 - 10<br/> * * @param dimensions The list of dimensions associated with the metric. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeAlarmsForMetricRequest withDimensions(Dimension... dimensions) { if (getDimensions() == null) setDimensions(new java.util.ArrayList<Dimension>(dimensions.length)); for (Dimension value : dimensions) { getDimensions().add(value); } return this; } /** * The list of dimensions associated with the metric. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Length: </b>0 - 10<br/> * * @param dimensions The list of dimensions associated with the metric. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeAlarmsForMetricRequest withDimensions(java.util.Collection<Dimension> dimensions) { if (dimensions == null) { this.dimensions = null; } else { java.util.List<Dimension> dimensionsCopy = new java.util.ArrayList<Dimension>(dimensions.size()); dimensionsCopy.addAll(dimensions); this.dimensions = dimensionsCopy; } return this; } /** * The period in seconds over which the statistic is applied. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>60 - <br/> * * @return The period in seconds over which the statistic is applied. */ public Integer getPeriod() { return period; } /** * The period in seconds over which the statistic is applied. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>60 - <br/> * * @param period The period in seconds over which the statistic is applied. */ public void setPeriod(Integer period) { this.period = period; } /** * The period in seconds over which the statistic is applied. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Range: </b>60 - <br/> * * @param period The period in seconds over which the statistic is applied. * * @return A reference to this updated object so that method calls can be chained * together. */ public DescribeAlarmsForMetricRequest withPeriod(Integer period) { this.period = period; return this; } /** * The unit for the metric. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>Seconds, Microseconds, Milliseconds, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Bits, Kilobits, Megabits, Gigabits, Terabits, Percent, Count, Bytes/Second, Kilobytes/Second, Megabytes/Second, Gigabytes/Second, Terabytes/Second, Bits/Second, Kilobits/Second, Megabits/Second, Gigabits/Second, Terabits/Second, Count/Second, None * * @return The unit for the metric. * * @see StandardUnit */ public String getUnit() { return unit; } /** * The unit for the metric. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>Seconds, Microseconds, Milliseconds, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Bits, Kilobits, Megabits, Gigabits, Terabits, Percent, Count, Bytes/Second, Kilobytes/Second, Megabytes/Second, Gigabytes/Second, Terabytes/Second, Bits/Second, Kilobits/Second, Megabits/Second, Gigabits/Second, Terabits/Second, Count/Second, None * * @param unit The unit for the metric. * * @see StandardUnit */ public void setUnit(String unit) { this.unit = unit; } /** * The unit for the metric. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>Seconds, Microseconds, Milliseconds, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Bits, Kilobits, Megabits, Gigabits, Terabits, Percent, Count, Bytes/Second, Kilobytes/Second, Megabytes/Second, Gigabytes/Second, Terabytes/Second, Bits/Second, Kilobits/Second, Megabits/Second, Gigabits/Second, Terabits/Second, Count/Second, None * * @param unit The unit for the metric. * * @return A reference to this updated object so that method calls can be chained * together. * * @see StandardUnit */ public DescribeAlarmsForMetricRequest withUnit(String unit) { this.unit = unit; return this; } /** * The unit for the metric. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>Seconds, Microseconds, Milliseconds, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Bits, Kilobits, Megabits, Gigabits, Terabits, Percent, Count, Bytes/Second, Kilobytes/Second, Megabytes/Second, Gigabytes/Second, Terabytes/Second, Bits/Second, Kilobits/Second, Megabits/Second, Gigabits/Second, Terabits/Second, Count/Second, None * * @param unit The unit for the metric. * * @see StandardUnit */ public void setUnit(StandardUnit unit) { this.unit = unit.toString(); } /** * The unit for the metric. * <p> * Returns a reference to this object so that method calls can be chained together. * <p> * <b>Constraints:</b><br/> * <b>Allowed Values: </b>Seconds, Microseconds, Milliseconds, Bytes, Kilobytes, Megabytes, Gigabytes, Terabytes, Bits, Kilobits, Megabits, Gigabits, Terabits, Percent, Count, Bytes/Second, Kilobytes/Second, Megabytes/Second, Gigabytes/Second, Terabytes/Second, Bits/Second, Kilobits/Second, Megabits/Second, Gigabits/Second, Terabits/Second, Count/Second, None * * @param unit The unit for the metric. * * @return A reference to this updated object so that method calls can be chained * together. * * @see StandardUnit */ public DescribeAlarmsForMetricRequest withUnit(StandardUnit unit) { this.unit = unit.toString(); 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 (metricName != null) sb.append("MetricName: " + metricName + ", "); if (namespace != null) sb.append("Namespace: " + namespace + ", "); if (statistic != null) sb.append("Statistic: " + statistic + ", "); if (dimensions != null) sb.append("Dimensions: " + dimensions + ", "); if (period != null) sb.append("Period: " + period + ", "); if (unit != null) sb.append("Unit: " + unit + ", "); sb.append("}"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getMetricName() == null) ? 0 : getMetricName().hashCode()); hashCode = prime * hashCode + ((getNamespace() == null) ? 0 : getNamespace().hashCode()); hashCode = prime * hashCode + ((getStatistic() == null) ? 0 : getStatistic().hashCode()); hashCode = prime * hashCode + ((getDimensions() == null) ? 0 : getDimensions().hashCode()); hashCode = prime * hashCode + ((getPeriod() == null) ? 0 : getPeriod().hashCode()); hashCode = prime * hashCode + ((getUnit() == null) ? 0 : getUnit().hashCode()); return hashCode; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof DescribeAlarmsForMetricRequest == false) return false; DescribeAlarmsForMetricRequest other = (DescribeAlarmsForMetricRequest)obj; if (other.getMetricName() == null ^ this.getMetricName() == null) return false; if (other.getMetricName() != null && other.getMetricName().equals(this.getMetricName()) == false) return false; if (other.getNamespace() == null ^ this.getNamespace() == null) return false; if (other.getNamespace() != null && other.getNamespace().equals(this.getNamespace()) == false) return false; if (other.getStatistic() == null ^ this.getStatistic() == null) return false; if (other.getStatistic() != null && other.getStatistic().equals(this.getStatistic()) == false) return false; if (other.getDimensions() == null ^ this.getDimensions() == null) return false; if (other.getDimensions() != null && other.getDimensions().equals(this.getDimensions()) == false) return false; if (other.getPeriod() == null ^ this.getPeriod() == null) return false; if (other.getPeriod() != null && other.getPeriod().equals(this.getPeriod()) == false) return false; if (other.getUnit() == null ^ this.getUnit() == null) return false; if (other.getUnit() != null && other.getUnit().equals(this.getUnit()) == false) return false; return true; } }
apache-2.0
baldimir/optaplanner
optaplanner-examples/src/main/java/org/optaplanner/examples/coachshuttlegathering/domain/BusHub.java
2169
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * 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.optaplanner.examples.coachshuttlegathering.domain; import java.util.List; import com.thoughtworks.xstream.annotations.XStreamAlias; import org.optaplanner.examples.coachshuttlegathering.domain.location.RoadLocation; import org.optaplanner.examples.common.domain.AbstractPersistable; @XStreamAlias("CsgBusHub") public class BusHub extends AbstractPersistable implements StopOrHub { protected String name; protected RoadLocation location; // Shadow variables protected List<Shuttle> transferShuttleList; @Override public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public RoadLocation getLocation() { return location; } public void setLocation(RoadLocation location) { this.location = location; } @Override public List<Shuttle> getTransferShuttleList() { return transferShuttleList; } @Override public void setTransferShuttleList(List<Shuttle> transferShuttleList) { this.transferShuttleList = transferShuttleList; } @Override public Integer getTransportTimeToHub() { return 0; } // ************************************************************************ // Complex methods // ************************************************************************ @Override public boolean isVisitedByCoach() { return true; } @Override public String toString() { return name; } }
apache-2.0
Nachiket90/jmeter-sample
test/src/org/apache/jmeter/services/TestFileServer.java
4387
/* * 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 to test FileServer methods */ package org.apache.jmeter.services; import java.io.File; import java.io.IOException; import org.apache.jmeter.junit.JMeterTestCase; public class TestFileServer extends JMeterTestCase { private static final FileServer FS = FileServer.getFileServer(); public TestFileServer() { super(); } public TestFileServer(String arg0) { super(arg0); } @Override public void setUp() throws IOException { FS.resetBase(); } @Override public void tearDown() throws IOException{ FS.closeFiles(); } public void testopen() throws Exception { try { FS.readLine("test"); fail("Expected IOException"); } catch (IOException ignored){ } try { FS.write("test",""); fail("Expected IOException"); } catch (IOException ignored){ } assertFalse("Should not have any files open",FS.filesOpen()); FS.closeFile("xxx"); // Unrecognised files are ignored assertFalse("Should not have any files open",FS.filesOpen()); String infile=findTestPath("testfiles/test.csv"); FS.reserveFile(infile); // Does not open file assertFalse("Should not have any files open",FS.filesOpen()); assertEquals("a1,b1,c1,d1",FS.readLine(infile)); assertTrue("Should have some files open",FS.filesOpen()); assertNotNull(FS.readLine(infile)); assertNotNull(FS.readLine(infile)); assertNotNull(FS.readLine(infile)); assertEquals("a1,b1,c1,d1",FS.readLine(infile));// Re-read 1st line assertNotNull(FS.readLine(infile)); try { FS.write(infile,"");// should not be able to write to it ... fail("Expected IOException"); } catch (IOException ignored){ } FS.closeFile(infile); // does not remove the entry assertFalse("Should not have any files open",FS.filesOpen()); assertEquals("a1,b1,c1,d1",FS.readLine(infile));// Re-read 1st line assertTrue("Should have some files open",FS.filesOpen()); FS.closeFiles(); // removes all entries assertFalse("Should not have any files open",FS.filesOpen()); try { FS.readLine(infile); fail("Expected IOException"); } catch (IOException ignored){ } infile=findTestPath("testfiles/test.csv"); FS.reserveFile(infile); // Does not open file assertFalse("Should not have any files open",FS.filesOpen()); assertEquals("a1,b1,c1,d1",FS.readLine(infile)); try { FS.setBasedir("x"); fail("Expected IllegalStateException"); } catch (IllegalStateException ignored){ } FS.closeFile(infile); FS.setBasedir("y"); FS.closeFiles(); } public void testRelative() throws Exception { final String base = FileServer.getDefaultBase(); final File basefile = new File(base); FS.setBaseForScript(basefile); assertEquals(".",FS.getBaseDirRelative().toString()); FS.setBaseForScript(basefile.getParentFile()); assertEquals(".",FS.getBaseDirRelative().toString()); FS.setBaseForScript(new File(basefile.getParentFile(),"abcd/defg.jmx")); assertEquals(".",FS.getBaseDirRelative().toString()); File file = new File(basefile,"abcd/defg.jmx"); FS.setBaseForScript(file); assertEquals("abcd",FS.getBaseDirRelative().toString()); } }
apache-2.0
dbrimley/hazelcast
hazelcast/src/test/java/com/hazelcast/hotrestart/NoopHotRestartServicesTest.java
2778
/* * 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.hotrestart; import com.hazelcast.internal.management.dto.ClusterHotRestartStatusDTO; import com.hazelcast.test.HazelcastParallelClassRunner; import com.hazelcast.test.annotation.ParallelTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; @RunWith(HazelcastParallelClassRunner.class) @Category({QuickTest.class, ParallelTest.class}) public class NoopHotRestartServicesTest { @Test public void testNoOpHotRestartService() { final NoOpHotRestartService service = new NoOpHotRestartService(); service.backup(); service.backup(0); service.getBackupTaskStatus(); service.interruptBackupTask(); service.interruptLocalBackupTask(); assertFalse(service.isHotBackupEnabled()); assertEquals(new BackupTaskStatus(BackupTaskState.NO_TASK, 0, 0), service.getBackupTaskStatus()); } @Test public void testNoOpInternalHotRestartService() { final NoopInternalHotRestartService service = new NoopInternalHotRestartService(); service.notifyExcludedMember(null); service.handleExcludedMemberUuids(null, null); service.resetHotRestartData(); assertFalse(service.triggerForceStart()); assertFalse(service.triggerPartialStart()); assertFalse(service.isMemberExcluded(null, null)); assertEquals(0, service.getExcludedMemberUuids().size()); final ClusterHotRestartStatusDTO expected = new ClusterHotRestartStatusDTO(); final ClusterHotRestartStatusDTO dto = service.getCurrentClusterHotRestartStatus(); assertEquals(expected.getDataRecoveryPolicy(), dto.getDataRecoveryPolicy()); assertEquals(expected.getHotRestartStatus(), dto.getHotRestartStatus()); assertEquals(expected.getRemainingDataLoadTimeMillis(), dto.getRemainingDataLoadTimeMillis()); assertEquals(expected.getRemainingValidationTimeMillis(), dto.getRemainingValidationTimeMillis()); } }
apache-2.0
shun634501730/java_source_cn
src_en/java/awt/TextComponent.java
43134
/* * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ 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 &gt;= 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 &gt;= 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 &gt;= 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 &gt;= 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 &gt;= 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 &gt;= 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 &gt;= 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; }
apache-2.0
jerrinot/hazelcast
hazelcast/src/test/java/com/hazelcast/replicatedmap/ReplicatedMapWriteOrderTest.java
6781
/* * Copyright (c) 2008-2021, 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.replicatedmap; import com.hazelcast.config.Config; import com.hazelcast.core.HazelcastInstance; import com.hazelcast.instance.impl.HazelcastInstanceFactory; import com.hazelcast.test.AssertTask; import com.hazelcast.test.HazelcastParallelParametersRunnerFactory; import com.hazelcast.test.HazelcastParametrizedRunner; import com.hazelcast.test.TestHazelcastInstanceFactory; import com.hazelcast.test.annotation.ParallelJVMTest; import com.hazelcast.test.annotation.QuickTest; import org.junit.After; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.junit.runners.Parameterized.Parameters; import org.junit.runners.Parameterized.UseParametersRunnerFactory; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Random; import static java.util.Arrays.asList; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @RunWith(HazelcastParametrizedRunner.class) @UseParametersRunnerFactory(HazelcastParallelParametersRunnerFactory.class) @Category({QuickTest.class, ParallelJVMTest.class}) public class ReplicatedMapWriteOrderTest extends ReplicatedMapAbstractTest { @Parameters(name = "nodeCount:{0}, operations:{1}, keyCount:{2}") public static Collection<Object[]> data() { return asList(new Object[][]{ {2, 50, 1}, {2, 50, 10}, {2, 50, 50}, // {3, 50, 1}, {3, 50, 10}, {3, 50, 50}, // {3, 10, 10}, {3, 50, 50}, {3, 100, 100}, // {3, 150, 150}, {3, 200, 200}, {3, 250, 250}, // {3, 300, 300}, {3, 500, 500}, {3, 750, 750}, // {3, 500, 1}, {3, 500, 10}, {3, 500, 100}, {3, 500, 500}, // {3, 1000, 1}, {3, 1000, 10}, {3, 1000, 100}, {3, 1000, 1000}, // {3, 2000, 1}, {3, 2000, 10}, {3, 2000, 100}, {3, 2000, 1000}, // {5, 500, 1}, {5, 500, 10}, {5, 500, 100}, {5, 500, 500}, // {5, 1000, 1}, {5, 1000, 10}, {5, 1000, 100}, {5, 1000, 1000}, // {10, 1000, 1}, {10, 1000, 10}, {10, 1000, 100}, {10, 1000, 1000}, // {15, 2000, 1}, {15, 2000, 10}, {15, 2000, 100}, {15, 2000, 1000}, // {20, 2000, 1}, {20, 2000, 10}, {20, 2000, 100}, {20, 2000, 1000}, // {20, 5000, 1}, {20, 5000, 10}, {20, 5000, 1000}, {20, 5000, 3000}, }); } private int nodeCount; private int operations; private int keyCount; public ReplicatedMapWriteOrderTest(int nodeCount, int operations, int keyCount) { this.nodeCount = nodeCount; this.operations = operations; this.keyCount = keyCount; } @After public void setUp() { HazelcastInstanceFactory.terminateAll(); } @Test public void testDataIntegrity() { System.out.println("nodeCount = " + nodeCount); System.out.println("operations = " + operations); System.out.println("keyCount = " + keyCount); Config config = new Config(); config.getReplicatedMapConfig("test"); TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(nodeCount); final HazelcastInstance[] instances = factory.newInstances(config); String replicatedMapName = "test"; final List<ReplicatedMap<String, Object>> maps = createMapOnEachInstance(instances, replicatedMapName); ArrayList<Integer> keys = generateRandomIntegerList(keyCount); Thread[] threads = createThreads(nodeCount, maps, keys, operations); for (Thread thread : threads) { thread.start(); } assertJoinable(threads); for (int i = 0; i < keyCount; i++) { final String key = "foo-" + keys.get(i); assertTrueEventually(new AssertTask() { @Override public void run() throws Exception { System.out.println("---------------------"); System.out.println("key = " + key); printValues(); assertValuesAreEqual(); } private void printValues() throws Exception { for (int j = 0; j < maps.size(); j++) { ReplicatedMap map = maps.get(j); System.out.println("value[" + j + "] = " + map.get(key) + ", store version: " + getStore(map, key).getVersion()); } } private void assertValuesAreEqual() { for (int i = 0; i < maps.size() - 1; i++) { ReplicatedMap map1 = maps.get(i); ReplicatedMap map2 = maps.get(i + 1); Object v1 = map1.get(key); Object v2 = map2.get(key); assertNotNull(v1); assertNotNull(v2); assertEquals(v1, v2); } } }, 120); } } private Thread[] createThreads(int count, List<ReplicatedMap<String, Object>> maps, ArrayList<Integer> keys, int operations) { Thread[] threads = new Thread[count]; for (int i = 0; i < count; i++) { threads[i] = createPutOperationThread(maps.get(i), keys, operations); } return threads; } private Thread createPutOperationThread(final ReplicatedMap<String, Object> map, final ArrayList<Integer> keys, final int operations) { return new Thread(new Runnable() { @Override public void run() { Random random = new Random(); int size = keys.size(); for (int i = 0; i < operations; i++) { int index = i % size; String key = "foo-" + keys.get(index); map.put(key, random.nextLong()); boolean containsKey = map.containsKey(key); assert containsKey; } } }); } }
apache-2.0
andreagenso/java2scala
test/J2s/java/openjdk-6-src-b27/jdk/src/share/classes/com/sun/net/httpserver/Headers.java
6943
/* * Copyright (c) 2005, 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 com.sun.net.httpserver; import java.util.*; import java.io.*; /** * HTTP request and response headers are represented by this class which implements * the interface {@link java.util.Map}&lt; * {@link java.lang.String},{@link java.util.List}&lt;{@link java.lang.String}&gt;&gt;. * The keys are case-insensitive Strings representing the header names and * the value associated with each key is a {@link List}&lt;{@link String}&gt; with one * element for each occurence of the header name in the request or response. * <p> * For example, if a response header instance contains one key "HeaderName" with two values "value1 and value2" * then this object is output as two header lines: * <blockquote><pre> * HeaderName: value1 * HeaderName: value2 * </blockquote></pre> * <p> * All the normal {@link java.util.Map} methods are provided, but the following * additional convenience methods are most likely to be used: * <ul> * <li>{@link #getFirst(String)} returns a single valued header or the first value of * a multi-valued header.</li> * <li>{@link #add(String,String)} adds the given header value to the list for the given key</li> * <li>{@link #set(String,String)} sets the given header field to the single value given * overwriting any existing values in the value list. * </ul><p> * All methods in this class accept <code>null</code> values for keys and values. However, null * keys will never will be present in HTTP request headers, and will not be output/sent in response headers. * Null values can be represented as either a null entry for the key (i.e. the list is null) or * where the key has a list, but one (or more) of the list's values is null. Null values are output * as a header line containing the key but no associated value. * @since 1.6 */ public class Headers implements Map<String,List<String>> { HashMap<String,List<String>> map; public Headers () {map = new HashMap<String,List<String>>(32);} /* Normalize the key by converting to following form. * First char upper case, rest lower case. * key is presumed to be ASCII */ private String normalize (String key) { if (key == null) { return null; } int len = key.length(); if (len == 0) { return key; } char[] b = new char [len]; String s = null; b = key.toCharArray(); if (b[0] >= 'a' && b[0] <= 'z') { b[0] = (char)(b[0] - ('a' - 'A')); } for (int i=1; i<len; i++) { if (b[i] >= 'A' && b[i] <= 'Z') { b[i] = (char) (b[i] + ('a' - 'A')); } } s = new String (b); return s; } public int size() {return map.size();} public boolean isEmpty() {return map.isEmpty();} public boolean containsKey(Object key) { if (key == null) { return false; } if (!(key instanceof String)) { return false; } return map.containsKey (normalize((String)key)); } public boolean containsValue(Object value) { return map.containsValue(value); } public List<String> get(Object key) { return map.get(normalize((String)key)); } /** * returns the first value from the List of String values * for the given key (if at least one exists). * @param key the key to search for * @return the first string value associated with the key */ public String getFirst (String key) { List<String> l = map.get(normalize((String)key)); if (l == null) { return null; } return l.get(0); } public List<String> put(String key, List<String> value) { return map.put (normalize(key), value); } /** * adds the given value to the list of headers * for the given key. If the mapping does not * already exist, then it is created * @param key the header name * @param value the header value to add to the header */ public void add (String key, String value) { String k = normalize(key); List<String> l = map.get(k); if (l == null) { l = new LinkedList<String>(); map.put(k,l); } l.add (value); } /** * sets the given value as the sole header value * for the given key. If the mapping does not * already exist, then it is created * @param key the header name * @param value the header value to set. */ public void set (String key, String value) { LinkedList<String> l = new LinkedList<String>(); l.add (value); put (key, l); } public List<String> remove(Object key) { return map.remove(normalize((String)key)); } public void putAll(Map<? extends String,? extends List<String>> t) { map.putAll (t); } public void clear() {map.clear();} public Set<String> keySet() {return map.keySet();} public Collection<List<String>> values() {return map.values();} public Set<Map.Entry<String, List<String>>> entrySet() { return map.entrySet(); } public boolean equals(Object o) {return map.equals(o);} public int hashCode() {return map.hashCode();} }
apache-2.0
winstonewert/elasticsearch
modules/ingest-common/src/test/java/org/elasticsearch/ingest/common/SplitProcessorTests.java
5985
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.ingest.common; import org.elasticsearch.ingest.IngestDocument; import org.elasticsearch.ingest.Processor; import org.elasticsearch.ingest.RandomDocumentPicks; import org.elasticsearch.test.ESTestCase; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import static org.elasticsearch.ingest.IngestDocumentMatcher.assertIngestDocument; import static org.hamcrest.Matchers.containsString; import static org.hamcrest.Matchers.equalTo; public class SplitProcessorTests extends ESTestCase { public void testSplit() throws Exception { IngestDocument ingestDocument = RandomDocumentPicks.randomIngestDocument(random()); String fieldName = RandomDocumentPicks.addRandomField(random(), ingestDocument, "127.0.0.1"); Processor processor = new SplitProcessor(randomAlphaOfLength(10), fieldName, "\\.", false); processor.execute(ingestDocument); assertThat(ingestDocument.getFieldValue(fieldName, List.class), equalTo(Arrays.asList("127", "0", "0", "1"))); } public void testSplitFieldNotFound() throws Exception { IngestDocument ingestDocument = RandomDocumentPicks.randomIngestDocument(random(), new HashMap<>()); String fieldName = RandomDocumentPicks.randomFieldName(random()); Processor processor = new SplitProcessor(randomAlphaOfLength(10), fieldName, "\\.", false); try { processor.execute(ingestDocument); fail("split processor should have failed"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), containsString("not present as part of path [" + fieldName + "]")); } } public void testSplitNullValue() throws Exception { IngestDocument ingestDocument = RandomDocumentPicks.randomIngestDocument(random(), Collections.singletonMap("field", null)); Processor processor = new SplitProcessor(randomAlphaOfLength(10), "field", "\\.", false); try { processor.execute(ingestDocument); fail("split processor should have failed"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), equalTo("field [field] is null, cannot split.")); } } public void testSplitNullValueWithIgnoreMissing() throws Exception { String fieldName = RandomDocumentPicks.randomFieldName(random()); IngestDocument originalIngestDocument = RandomDocumentPicks.randomIngestDocument(random(), Collections.singletonMap(fieldName, null)); IngestDocument ingestDocument = new IngestDocument(originalIngestDocument); Processor processor = new SplitProcessor(randomAlphaOfLength(10), fieldName, "\\.", true); processor.execute(ingestDocument); assertIngestDocument(originalIngestDocument, ingestDocument); } public void testSplitNonExistentWithIgnoreMissing() throws Exception { IngestDocument originalIngestDocument = RandomDocumentPicks.randomIngestDocument(random(), Collections.emptyMap()); IngestDocument ingestDocument = new IngestDocument(originalIngestDocument); Processor processor = new SplitProcessor(randomAlphaOfLength(10), "field", "\\.", true); processor.execute(ingestDocument); assertIngestDocument(originalIngestDocument, ingestDocument); } public void testSplitNonStringValue() throws Exception { IngestDocument ingestDocument = RandomDocumentPicks.randomIngestDocument(random(), new HashMap<>()); String fieldName = RandomDocumentPicks.randomFieldName(random()); ingestDocument.setFieldValue(fieldName, randomInt()); Processor processor = new SplitProcessor(randomAlphaOfLength(10), fieldName, "\\.", false); try { processor.execute(ingestDocument); fail("split processor should have failed"); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), equalTo("field [" + fieldName + "] of type [java.lang.Integer] cannot be cast " + "to [java.lang.String]")); } } public void testSplitAppendable() throws Exception { Map<String, Object> splitConfig = new HashMap<>(); splitConfig.put("field", "flags"); splitConfig.put("separator", "\\|"); Processor splitProcessor = (new SplitProcessor.Factory()).create(null, null, splitConfig); Map<String, Object> source = new HashMap<>(); source.put("flags", "new|hot|super|fun|interesting"); IngestDocument ingestDocument = new IngestDocument(source, new HashMap<>()); splitProcessor.execute(ingestDocument); @SuppressWarnings("unchecked") List<String> flags = (List<String>)ingestDocument.getFieldValue("flags", List.class); assertThat(flags, equalTo(Arrays.asList("new", "hot", "super", "fun", "interesting"))); ingestDocument.appendFieldValue("flags", "additional_flag"); assertThat(ingestDocument.getFieldValue("flags", List.class), equalTo(Arrays.asList("new", "hot", "super", "fun", "interesting", "additional_flag"))); } }
apache-2.0
kevinearls/camel
components/camel-hl7/src/main/java/org/apache/camel/component/hl7/HL7GenericMessageConverter.java
6856
/** * 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.component.hl7; import java.io.IOException; import ca.uhn.hl7v2.DefaultHapiContext; import ca.uhn.hl7v2.HL7Exception; import ca.uhn.hl7v2.HapiContext; import ca.uhn.hl7v2.model.GenericMessage; import ca.uhn.hl7v2.model.Message; import ca.uhn.hl7v2.parser.GenericModelClassFactory; import ca.uhn.hl7v2.parser.Parser; import ca.uhn.hl7v2.parser.ParserConfiguration; import ca.uhn.hl7v2.parser.UnexpectedSegmentBehaviourEnum; import ca.uhn.hl7v2.validation.impl.ValidationContextFactory; import org.apache.camel.Converter; import org.apache.camel.Exchange; import org.apache.camel.TypeConversionException; import org.apache.camel.converter.IOConverter; /** * HL7 converters. */ @Converter public final class HL7GenericMessageConverter { private static final HapiContext GENERIC_MESSAGE_CONTEXT; static { ParserConfiguration parserConfiguration = new ParserConfiguration(); parserConfiguration.setDefaultObx2Type("ST"); parserConfiguration.setInvalidObx2Type("ST"); parserConfiguration.setUnexpectedSegmentBehaviour(UnexpectedSegmentBehaviourEnum.ADD_INLINE); GENERIC_MESSAGE_CONTEXT = new DefaultHapiContext(parserConfiguration, ValidationContextFactory.noValidation(), new GenericModelClassFactory()); } private HL7GenericMessageConverter() { // Helper class } @Converter public static GenericMessage toGenericMessage(String body) throws HL7Exception { return (GenericMessage) GENERIC_MESSAGE_CONTEXT.getGenericParser().parse(body); } @Converter public static GenericMessage toGenericMessage(byte[] body, Exchange exchange) throws HL7Exception, IOException { return (GenericMessage) GENERIC_MESSAGE_CONTEXT.getGenericParser().parse(IOConverter.toString(body, exchange)); } @Converter public static GenericMessage.V21 toV21GenericMessage(String hl7String) throws HL7Exception { return toGenericMessage(GenericMessage.V21.class, hl7String); } @Converter public static GenericMessage.V21 toV21GenericMessage(byte[] hl7Bytes, Exchange exchange) { return toGenericMessage(GenericMessage.V21.class, hl7Bytes, exchange); } @Converter public static GenericMessage.V22 toV22GenericMessage(String hl7String) throws HL7Exception { return toGenericMessage(GenericMessage.V22.class, hl7String); } @Converter public static GenericMessage.V22 toV22GenericMessage(byte[] hl7Bytes, Exchange exchange) { return toGenericMessage(GenericMessage.V22.class, hl7Bytes, exchange); } @Converter public static GenericMessage.V23 toV23GenericMessage(String hl7String) throws HL7Exception { return toGenericMessage(GenericMessage.V23.class, hl7String); } @Converter public static GenericMessage.V23 toV23GenericMessage(byte[] hl7Bytes, Exchange exchange) { return toGenericMessage(GenericMessage.V23.class, hl7Bytes, exchange); } @Converter public static GenericMessage.V231 toV231GenericMessage(String hl7String) throws HL7Exception { return toGenericMessage(GenericMessage.V231.class, hl7String); } @Converter public static GenericMessage.V231 toV231GenericMessage(byte[] hl7Bytes, Exchange exchange) { return toGenericMessage(GenericMessage.V231.class, hl7Bytes, exchange); } @Converter public static GenericMessage.V24 toV24GenericMessage(String hl7String) throws HL7Exception { return toGenericMessage(GenericMessage.V24.class, hl7String); } @Converter public static GenericMessage.V24 toV24GenericMessage(byte[] hl7Bytes, Exchange exchange) { return toGenericMessage(GenericMessage.V24.class, hl7Bytes, exchange); } @Converter public static GenericMessage.V25 toV25GenericMessage(String hl7String) throws HL7Exception { return toGenericMessage(GenericMessage.V25.class, hl7String); } @Converter public static GenericMessage.V25 toV25GenericMessage(byte[] hl7Bytes, Exchange exchange) { return toGenericMessage(GenericMessage.V25.class, hl7Bytes, exchange); } @Converter public static GenericMessage.V251 toV251GenericMessage(String hl7String) throws HL7Exception { return toGenericMessage(GenericMessage.V251.class, hl7String); } @Converter public static GenericMessage.V251 toV251GenericMessage(byte[] hl7Bytes, Exchange exchange) { return toGenericMessage(GenericMessage.V251.class, hl7Bytes, exchange); } @Converter public static GenericMessage.V26 toV26GenericMessage(String hl7String) throws HL7Exception { return toGenericMessage(GenericMessage.V26.class, hl7String); } @Converter public static GenericMessage.V26 toV26GenericMessage(byte[] hl7Bytes, Exchange exchange) { return toGenericMessage(GenericMessage.V26.class, hl7Bytes, exchange); } static Message parse(String body, Parser parser) throws HL7Exception { return parser.parse(body); } static String encode(Message message, Parser parser) throws HL7Exception { return parser.encode(message); } static <T extends Message> T toGenericMessage(Class<T> messageClass, String hl7String) { try { T genericMessage = GENERIC_MESSAGE_CONTEXT.newMessage(messageClass); genericMessage.parse(hl7String); return genericMessage; } catch (HL7Exception conversionEx) { throw new TypeConversionException(hl7String, String.class, conversionEx); } } static <T extends Message> T toGenericMessage(Class<T> messageClass, byte[] hl7Bytes, Exchange exchange) { try { T genericMessage = GENERIC_MESSAGE_CONTEXT.newMessage(messageClass); genericMessage.parse(IOConverter.toString(hl7Bytes, exchange)); return genericMessage; } catch (HL7Exception | IOException conversionEx) { throw new TypeConversionException(hl7Bytes, byte[].class, conversionEx); } } }
apache-2.0
ueshin/apache-flink
flink-runtime/src/test/java/org/apache/flink/runtime/taskexecutor/TaskManagerServicesTest.java
10102
/* * 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.flink.runtime.taskexecutor; import org.apache.flink.configuration.Configuration; import org.apache.flink.configuration.MemorySize; import org.apache.flink.configuration.TaskManagerOptions; import org.apache.flink.util.TestLogger; import org.junit.Test; import java.util.Random; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; /** * Unit test for {@link TaskManagerServices}. */ public class TaskManagerServicesTest extends TestLogger { /** * Test for {@link TaskManagerServices#calculateNetworkBufferMemory(long, Configuration)} using old * configurations via {@link TaskManagerOptions#NETWORK_NUM_BUFFERS}. */ @SuppressWarnings("deprecation") @Test public void calculateNetworkBufOld() { Configuration config = new Configuration(); config.setInteger(TaskManagerOptions.NETWORK_NUM_BUFFERS, 1); // note: actual network buffer memory size is independent of the totalJavaMemorySize assertEquals(MemorySize.parse(TaskManagerOptions.MEMORY_SEGMENT_SIZE.defaultValue()).getBytes(), TaskManagerServices.calculateNetworkBufferMemory(10L << 20, config)); assertEquals(MemorySize.parse(TaskManagerOptions.MEMORY_SEGMENT_SIZE.defaultValue()).getBytes(), TaskManagerServices.calculateNetworkBufferMemory(64L << 20, config)); // test integer overflow in the memory size int numBuffers = (int) ((2L << 32) / MemorySize.parse(TaskManagerOptions.MEMORY_SEGMENT_SIZE.defaultValue()).getBytes()); // 2^33 config.setInteger(TaskManagerOptions.NETWORK_NUM_BUFFERS, numBuffers); assertEquals(2L << 32, TaskManagerServices.calculateNetworkBufferMemory(2L << 33, config)); } /** * Test for {@link TaskManagerServices#calculateNetworkBufferMemory(long, Configuration)} using new * configurations via {@link TaskManagerOptions#NETWORK_BUFFERS_MEMORY_FRACTION}, * {@link TaskManagerOptions#NETWORK_BUFFERS_MEMORY_MIN} and * {@link TaskManagerOptions#NETWORK_BUFFERS_MEMORY_MAX}. */ @Test public void calculateNetworkBufNew() throws Exception { Configuration config = new Configuration(); // (1) defaults final Float defaultFrac = TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION.defaultValue(); final Long defaultMin = MemorySize.parse(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MIN.defaultValue()).getBytes(); final Long defaultMax = MemorySize.parse(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MAX.defaultValue()).getBytes(); assertEquals(enforceBounds((long) (defaultFrac * (10L << 20)), defaultMin, defaultMax), TaskManagerServices.calculateNetworkBufferMemory((64L << 20 + 1), config)); assertEquals(enforceBounds((long) (defaultFrac * (10L << 30)), defaultMin, defaultMax), TaskManagerServices.calculateNetworkBufferMemory((10L << 30), config)); calculateNetworkBufNew(config); } /** * Helper to test {@link TaskManagerServices#calculateNetworkBufferMemory(long, Configuration)} with the * new configuration parameters. * * @param config configuration object */ private static void calculateNetworkBufNew(final Configuration config) { // (2) fixed size memory config.setString(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MIN, String.valueOf(1L << 20)); // 1MB config.setString(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MAX, String.valueOf(1L << 20)); // 1MB // note: actual network buffer memory size is independent of the totalJavaMemorySize assertEquals(1 << 20, TaskManagerServices.calculateNetworkBufferMemory(10L << 20, config)); assertEquals(1 << 20, TaskManagerServices.calculateNetworkBufferMemory(64L << 20, config)); assertEquals(1 << 20, TaskManagerServices.calculateNetworkBufferMemory(1L << 30, config)); // (3) random fraction, min, and max values Random ran = new Random(); for (int i = 0; i < 1_000; ++i){ float frac = Math.max(ran.nextFloat(), Float.MIN_VALUE); config.setFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION, frac); long min = Math.max(MemorySize.parse(TaskManagerOptions.MEMORY_SEGMENT_SIZE.defaultValue()).getBytes(), ran.nextLong()); config.setString(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MIN, String.valueOf(min)); long max = Math.max(min, ran.nextLong()); config.setString(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MAX, String.valueOf(max)); long javaMem = Math.max(max + 1, ran.nextLong()); final long networkBufMem = TaskManagerServices.calculateNetworkBufferMemory(javaMem, config); if (networkBufMem < min) { fail("Lower bound not met with configuration: " + config.toString()); } if (networkBufMem > max) { fail("Upper bound not met with configuration: " + config.toString()); } if (networkBufMem > min && networkBufMem < max) { if ((javaMem * frac) != networkBufMem) { fail("Wrong network buffer memory size with configuration: " + config.toString() + ". Expected value: " + (javaMem * frac) + " actual value: " + networkBufMem + '.'); } } } } /** * Test for {@link TaskManagerServices#calculateNetworkBufferMemory(long, Configuration)} using mixed * old/new configurations. */ @SuppressWarnings("deprecation") @Test public void calculateNetworkBufMixed() throws Exception { Configuration config = new Configuration(); config.setInteger(TaskManagerOptions.NETWORK_NUM_BUFFERS, 1); final Float defaultFrac = TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION.defaultValue(); final Long defaultMin = MemorySize.parse(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MIN.defaultValue()).getBytes(); final Long defaultMax = MemorySize.parse(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MAX.defaultValue()).getBytes(); // old + 1 new parameter = new: Configuration config1 = config.clone(); config1.setFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION, 0.1f); assertEquals(enforceBounds((long) (0.1f * (10L << 20)), defaultMin, defaultMax), TaskManagerServices.calculateNetworkBufferMemory((64L << 20 + 1), config1)); assertEquals(enforceBounds((long) (0.1f * (10L << 30)), defaultMin, defaultMax), TaskManagerServices.calculateNetworkBufferMemory((10L << 30), config1)); config1 = config.clone(); long newMin = MemorySize.parse(TaskManagerOptions.MEMORY_SEGMENT_SIZE.defaultValue()).getBytes(); // smallest value possible config1.setString(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MIN, String.valueOf(newMin)); assertEquals(enforceBounds((long) (defaultFrac * (10L << 20)), newMin, defaultMax), TaskManagerServices.calculateNetworkBufferMemory((10L << 20), config1)); assertEquals(enforceBounds((long) (defaultFrac * (10L << 30)), newMin, defaultMax), TaskManagerServices.calculateNetworkBufferMemory((10L << 30), config1)); config1 = config.clone(); long newMax = Math.max(64L << 20 + 1, MemorySize.parse(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MIN.defaultValue()).getBytes()); config1.setString(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MAX, String.valueOf(newMax)); assertEquals(enforceBounds((long) (defaultFrac * (10L << 20)), defaultMin, newMax), TaskManagerServices.calculateNetworkBufferMemory((64L << 20 + 1), config1)); assertEquals(enforceBounds((long) (defaultFrac * (10L << 30)), defaultMin, newMax), TaskManagerServices.calculateNetworkBufferMemory((10L << 30), config1)); assertTrue(TaskManagerServicesConfiguration.hasNewNetworkBufConf(config1)); // old + any new parameter = new: calculateNetworkBufNew(config); } /** * Returns the value or the lower/upper bound in case the value is less/greater than the lower/upper bound, respectively. * * @param value value to inspect * @param lower lower bound * @param upper upper bound * * @return <tt>min(upper, max(lower, value))</tt> */ private static long enforceBounds(final long value, final long lower, final long upper) { return Math.min(upper, Math.max(lower, value)); } /** * Test for {@link TaskManagerServices#calculateHeapSizeMB(long, Configuration)} with some * manually calculated scenarios. */ @Test public void calculateHeapSizeMB() throws Exception { Configuration config = new Configuration(); config.setFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION, 0.1f); config.setString(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MIN, String.valueOf(64L << 20)); // 64MB config.setString(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_MAX, String.valueOf(1L << 30)); // 1GB config.setBoolean(TaskManagerOptions.MEMORY_OFF_HEAP, false); assertEquals(900, TaskManagerServices.calculateHeapSizeMB(1000, config)); config.setBoolean(TaskManagerOptions.MEMORY_OFF_HEAP, false); config.setFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION, 0.2f); assertEquals(800, TaskManagerServices.calculateHeapSizeMB(1000, config)); config.setBoolean(TaskManagerOptions.MEMORY_OFF_HEAP, true); config.setFloat(TaskManagerOptions.NETWORK_BUFFERS_MEMORY_FRACTION, 0.1f); config.setString(TaskManagerOptions.MANAGED_MEMORY_SIZE, "10m"); // 10MB assertEquals(890, TaskManagerServices.calculateHeapSizeMB(1000, config)); config.setString(TaskManagerOptions.MANAGED_MEMORY_SIZE, "0"); // use fraction of given memory config.setFloat(TaskManagerOptions.MANAGED_MEMORY_FRACTION, 0.1f); // 10% assertEquals(810, TaskManagerServices.calculateHeapSizeMB(1000, config)); } }
apache-2.0
lgrignon/eclipse-typescript
com.palantir.typescript/src/com/palantir/typescript/services/language/JsxEmit.java
963
/* * Copyright 2013 Palantir Technologies, 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.palantir.typescript.services.language; import com.fasterxml.jackson.annotation.JsonValue; /** * Corresponds to the enum with the same name in typescriptServices.d.ts. * * @author dcicerone */ public enum JsxEmit { NONE, PRESERVE, REACT; @JsonValue public int getValue() { return this.ordinal(); } }
apache-2.0
sesuncedu/elk-reasoner
elk-reasoner/src/main/java/org/semanticweb/elk/reasoner/indexing/factories/ModifiableIndexedPropertyChainFactory.java
1162
package org.semanticweb.elk.reasoner.indexing.factories; import org.semanticweb.elk.reasoner.indexing.modifiable.ModifiableIndexedPropertyChain; /* * #%L * ELK Reasoner * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2011 - 2012 Department of Computer Science, University of Oxford * %% * 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% */ /** * A factory for creating instances of {@link ModifiableIndexedPropertyChain} * * @author "Yevgeny Kazakov" * */ public interface ModifiableIndexedPropertyChainFactory extends ModifiableIndexedObjectPropertyFactory, ModifiableIndexedBinaryPropertyChainFactory { // combined interface }
apache-2.0
akomakom/ehcache3
core-spi-test/src/main/java/org/ehcache/internal/store/StoreValueHolderCreationTimeTest.java
1585
/* * Copyright Terracotta, 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.ehcache.internal.store; import org.ehcache.core.spi.store.Store; import org.ehcache.spi.test.SPITest; import java.util.concurrent.TimeUnit; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.notNullValue; import static org.hamcrest.core.Is.is; /** * Test the {@link Store.ValueHolder#creationTime(java.util.concurrent.TimeUnit)} contract of the * {@link Store.ValueHolder Store.ValueHolder} interface. * <p/> * * @author Aurelien Broszniowski */ public class StoreValueHolderCreationTimeTest<K, V> extends SPIStoreTester<K, V> { public StoreValueHolderCreationTimeTest(final StoreFactory<K, V> factory) { super(factory); } @SPITest public void creationTimeCanBeReturned() throws IllegalAccessException, InstantiationException { Store.ValueHolder<V> valueHolder = factory.newValueHolder(factory.createValue(1)); assertThat(valueHolder.creationTime(TimeUnit.MILLISECONDS), is(notNullValue())); } }
apache-2.0
kidaa/rave
rave-components/rave-jpa/src/main/java/org/apache/rave/portal/model/JpaRegion.java
7152
/* * 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.rave.portal.model; import com.fasterxml.jackson.annotation.JsonManagedReference; import com.google.common.collect.Maps; import org.apache.rave.model.Page; import org.apache.rave.model.Region; import org.apache.rave.model.RegionWidget; import org.apache.rave.portal.model.conversion.ConvertingListProxyFactory; import org.apache.rave.portal.model.conversion.JpaConverter; import com.fasterxml.jackson.annotation.JsonBackReference; import javax.persistence.*; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * A region of a page, which can contain widget instances {@link RegionWidget} */ @XmlAccessorType(XmlAccessType.NONE) @Entity @Table(name="region") @Access(AccessType.FIELD) @NamedQueries({ @NamedQuery(name = JpaRegion.FIND_BY_ENTITY_ID, query="select r from JpaRegion r where r.entityId = :entity_id"), @NamedQuery(name = JpaRegion.REGION_GET_ALL, query = JpaRegion.SELECT_R_FROM_REGION_R), @NamedQuery(name = JpaRegion.REGION_COUNT_ALL, query = JpaRegion.SELECT_COUNT_R_FROM_REGION_R) }) public class JpaRegion implements BasicEntity, Serializable, Region { private static final long serialVersionUID = 1L; public static final String FIND_BY_ENTITY_ID = "Region.findByEntityId"; public static final String REGION_GET_ALL = "Region.getAll"; public static final String REGION_COUNT_ALL = "Region.countAll"; public static final String ENTITY_ID_PARAM = "entity_id"; static final String SELECT_R_FROM_REGION_R = "SELECT r FROM JpaRegion r order by r.entityId"; static final String SELECT_COUNT_R_FROM_REGION_R = "SELECT count(r) FROM JpaRegion r "; @Id @Column(name="entity_id") @GeneratedValue(strategy = GenerationType.TABLE, generator = "regionIdGenerator") @TableGenerator(name = "regionIdGenerator", table = "RAVE_PORTAL_SEQUENCES", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "region", allocationSize = 1, initialValue = 1) private Long entityId; @ManyToOne @JoinColumn(name = "page_id") private JpaPage page; @Basic @Column(name = "render_order") private int renderOrder; @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true) @OrderBy("renderOrder") @JoinColumn(name = "region_id") private List<JpaRegionWidget> regionWidgets; @Basic(optional = false) @Column(name = "locked") private boolean locked; public JpaRegion() { } public JpaRegion(Long entityId) { this.entityId = entityId; } public JpaRegion(Long entityId, JpaPage page, int renderOrder) { this.entityId = entityId; this.page = page; this.renderOrder = renderOrder; } @SuppressWarnings("unused") @XmlElement(name="widget") /** * Only used for XML serialization, omitting regionwidget */ // private List<Widget> getWidgets(){ // ArrayList<Widget> widgets = new ArrayList<Widget>(); // for (RegionWidget rw: regionWidgets){ // widgets.add(rw.getWidget()); // } // return widgets; // } /** * Gets the persistence unique identifier * * @return id The ID of persisted object; null if not persisted */ @Override public Long getEntityId() { return entityId; } @Override public void setEntityId(Long entityId) { this.entityId = entityId; } @Override public String getId() { return this.getEntityId() == null ? null : this.getEntityId().toString(); } /** * Gets the associated page * * @return the associated page */ @Override @JsonBackReference public Page getPage() { return page; } @Override public void setPage(Page page) { this.page = JpaConverter.getInstance().convert(page, Page.class); } /** * Gets the order relative to regions on the page * * @return the order of the region */ @Override public int getRenderOrder() { return renderOrder; } @Override public void setRenderOrder(int renderOrder) { this.renderOrder = renderOrder; } /** * Gets the ordered list of widget instances for the region * * @return Valid list */ @Override @JsonManagedReference public List<RegionWidget> getRegionWidgets() { return ConvertingListProxyFactory.createProxyList(RegionWidget.class, regionWidgets); } @Override public void setRegionWidgets(List<RegionWidget> regionWidgets) { if(this.regionWidgets == null) { this.regionWidgets = new ArrayList<JpaRegionWidget>(); } this.getRegionWidgets().clear(); if(regionWidgets != null) { for(RegionWidget widget : regionWidgets) { widget.setRegion(this); this.getRegionWidgets().add(widget); } } } @Override public boolean isLocked() { return locked; } @Override public void setLocked(boolean locked) { this.locked = locked; } @Override public Map<String, Object> getProperties() { return Maps.newHashMap(); } @Override public void setProperties(Map<String, Object> properties) { // TODO: Implement this } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final JpaRegion other = (JpaRegion) obj; if (this.entityId != other.entityId && (this.entityId == null || !this.entityId.equals(other.entityId))) { return false; } return true; } @Override public int hashCode() { int hash = 3; hash = 67 * hash + (this.entityId != null ? this.entityId.hashCode() : 0); return hash; } @Override public String toString() { return "JpaRegion{" + "entityId=" + entityId + ", pageId=" + ((page == null) ? null : page.getEntityId()) + ", regionWidgets=" + regionWidgets + '}'; } }
apache-2.0
shun634501730/java_source_cn
src_en/com/sun/org/apache/xerces/internal/impl/xs/opti/DefaultText.java
10795
/* * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. */ /* * Copyright 2001-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.sun.org.apache.xerces.internal.impl.xs.opti; import org.w3c.dom.Text; import org.w3c.dom.DOMException; /* * @author Neil Graham, IBM */ /** * The <code>Text</code> interface inherits from <code>CharacterData</code> * and represents the textual content (termed character data in XML) of an * <code>Element</code> or <code>Attr</code>. If there is no markup inside * an element's content, the text is contained in a single object * implementing the <code>Text</code> interface that is the only child of * the element. If there is markup, it is parsed into the information items * (elements, comments, etc.) and <code>Text</code> nodes that form the list * of children of the element. * <p>When a document is first made available via the DOM, there is only one * <code>Text</code> node for each block of text. Users may create adjacent * <code>Text</code> nodes that represent the contents of a given element * without any intervening markup, but should be aware that there is no way * to represent the separations between these nodes in XML or HTML, so they * will not (in general) persist between DOM editing sessions. The * <code>normalize()</code> method on <code>Node</code> merges any such * adjacent <code>Text</code> objects into a single node for each block of * text. * <p>See also the <a href='http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113'>Document Object Model (DOM) Level 2 Core Specification</a>. * * This is an empty implementation. * * @xerces.internal */ public class DefaultText extends NodeImpl implements Text { // CharacterData methods /** * The character data of the node that implements this interface. The DOM * implementation may not put arbitrary limits on the amount of data * that may be stored in a <code>CharacterData</code> node. However, * implementation limits may mean that the entirety of a node's data may * not fit into a single <code>DOMString</code>. In such cases, the user * may call <code>substringData</code> to retrieve the data in * appropriately sized pieces. * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly. * @exception DOMException * DOMSTRING_SIZE_ERR: Raised when it would return more characters than * fit in a <code>DOMString</code> variable on the implementation * platform. */ public String getData() throws DOMException { return null; } /** * The character data of the node that implements this interface. The DOM * implementation may not put arbitrary limits on the amount of data * that may be stored in a <code>CharacterData</code> node. However, * implementation limits may mean that the entirety of a node's data may * not fit into a single <code>DOMString</code>. In such cases, the user * may call <code>substringData</code> to retrieve the data in * appropriately sized pieces. * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised when the node is readonly. * @exception DOMException * DOMSTRING_SIZE_ERR: Raised when it would return more characters than * fit in a <code>DOMString</code> variable on the implementation * platform. */ public void setData(String data) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported"); } /** * The number of 16-bit units that are available through <code>data</code> * and the <code>substringData</code> method below. This may have the * value zero, i.e., <code>CharacterData</code> nodes may be empty. */ public int getLength() { return 0; } /** * Extracts a range of data from the node. * @param offset Start offset of substring to extract. * @param count The number of 16-bit units to extract. * @return The specified substring. If the sum of <code>offset</code> and * <code>count</code> exceeds the <code>length</code>, then all 16-bit * units to the end of the data are returned. * @exception DOMException * INDEX_SIZE_ERR: Raised if the specified <code>offset</code> is * negative or greater than the number of 16-bit units in * <code>data</code>, or if the specified <code>count</code> is * negative. * <br>DOMSTRING_SIZE_ERR: Raised if the specified range of text does * not fit into a <code>DOMString</code>. */ public String substringData(int offset, int count) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported"); } /** * Append the string to the end of the character data of the node. Upon * success, <code>data</code> provides access to the concatenation of * <code>data</code> and the <code>DOMString</code> specified. * @param arg The <code>DOMString</code> to append. * @exception DOMException * NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly. */ public void appendData(String arg) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported"); } /** * Insert a string at the specified 16-bit unit offset. * @param offset The character offset at which to insert. * @param arg The <code>DOMString</code> to insert. * @exception DOMException * INDEX_SIZE_ERR: Raised if the specified <code>offset</code> is * negative or greater than the number of 16-bit units in * <code>data</code>. * <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly. */ public void insertData(int offset, String arg) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported"); } /** * Remove a range of 16-bit units from the node. Upon success, * <code>data</code> and <code>length</code> reflect the change. * @param offset The offset from which to start removing. * @param count The number of 16-bit units to delete. If the sum of * <code>offset</code> and <code>count</code> exceeds * <code>length</code> then all 16-bit units from <code>offset</code> * to the end of the data are deleted. * @exception DOMException * INDEX_SIZE_ERR: Raised if the specified <code>offset</code> is * negative or greater than the number of 16-bit units in * <code>data</code>, or if the specified <code>count</code> is * negative. * <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly. */ public void deleteData(int offset, int count) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported"); } /** * Replace the characters starting at the specified 16-bit unit offset * with the specified string. * @param offset The offset from which to start replacing. * @param count The number of 16-bit units to replace. If the sum of * <code>offset</code> and <code>count</code> exceeds * <code>length</code>, then all 16-bit units to the end of the data * are replaced; (i.e., the effect is the same as a <code>remove</code> * method call with the same range, followed by an <code>append</code> * method invocation). * @param arg The <code>DOMString</code> with which the range must be * replaced. * @exception DOMException * INDEX_SIZE_ERR: Raised if the specified <code>offset</code> is * negative or greater than the number of 16-bit units in * <code>data</code>, or if the specified <code>count</code> is * negative. * <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly. */ public void replaceData(int offset, int count, String arg) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported"); } // Text node methods /** * Breaks this node into two nodes at the specified <code>offset</code>, * keeping both in the tree as siblings. After being split, this node * will contain all the content up to the <code>offset</code> point. A * new node of the same type, which contains all the content at and * after the <code>offset</code> point, is returned. If the original * node had a parent node, the new node is inserted as the next sibling * of the original node. When the <code>offset</code> is equal to the * length of this node, the new node has no data. * @param offset The 16-bit unit offset at which to split, starting from * <code>0</code>. * @return The new node, of the same type as this node. * @exception DOMException * INDEX_SIZE_ERR: Raised if the specified offset is negative or greater * than the number of 16-bit units in <code>data</code>. * <br>NO_MODIFICATION_ALLOWED_ERR: Raised if this node is readonly. */ public Text splitText(int offset) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported"); } /** DOM Level 3 CR */ public boolean isElementContentWhitespace(){ throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported"); } public String getWholeText(){ throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported"); } public Text replaceWholeText(String content) throws DOMException { throw new DOMException(DOMException.NOT_SUPPORTED_ERR, "Method not supported"); } }
apache-2.0
ligi/bitcoinj
core/src/test/java/com/google/bitcoin/core/TestUtils.java
9326
/** * Copyright 2011 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.bitcoin.core; import com.google.bitcoin.store.BlockStore; import com.google.bitcoin.store.BlockStoreException; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.math.BigInteger; public class TestUtils { public static Transaction createFakeTxWithChangeAddress(NetworkParameters params, BigInteger nanocoins, Address to, Address changeOutput) throws IOException, ProtocolException { // Create a fake TX of sufficient realism to exercise the unit tests. Two outputs, one to us, one to somewhere // else to simulate change. Transaction t = new Transaction(params); TransactionOutput outputToMe = new TransactionOutput(params, t, nanocoins, to); t.addOutput(outputToMe); TransactionOutput change = new TransactionOutput(params, t, Utils.toNanoCoins(1, 11), changeOutput); t.addOutput(change); // Make a previous tx simply to send us sufficient coins. This prev tx is not really valid but it doesn't // matter for our purposes. Transaction prevTx = new Transaction(params); TransactionOutput prevOut = new TransactionOutput(params, prevTx, nanocoins, to); prevTx.addOutput(prevOut); // Connect it. t.addInput(prevOut); // Serialize/deserialize to ensure internal state is stripped, as if it had been read from the wire. return roundTripTransaction(params, t); } public static Transaction createFakeTx(NetworkParameters params, BigInteger nanocoins, Address to) throws IOException, ProtocolException { return createFakeTxWithChangeAddress(params, nanocoins, to, new ECKey().toAddress(params)); } public static Transaction createFakeTx(NetworkParameters params, BigInteger nanocoins, ECKey to) throws IOException, ProtocolException { // Create a fake TX of sufficient realism to exercise the unit tests. Two outputs, one to us, one to somewhere // else to simulate change. Transaction t = new Transaction(params); TransactionOutput outputToMe = new TransactionOutput(params, t, nanocoins, to); t.addOutput(outputToMe); TransactionOutput change = new TransactionOutput(params, t, Utils.toNanoCoins(1, 11), new ECKey()); t.addOutput(change); // Make a previous tx simply to send us sufficient coins. This prev tx is not really valid but it doesn't // matter for our purposes. Transaction prevTx = new Transaction(params); TransactionOutput prevOut = new TransactionOutput(params, prevTx, nanocoins, to); prevTx.addOutput(prevOut); // Connect it. t.addInput(prevOut); // Serialize/deserialize to ensure internal state is stripped, as if it had been read from the wire. return roundTripTransaction(params, t); } /** * @return Transaction[] Transaction[0] is a feeder transaction, supplying BTC to Transaction[1] */ public static Transaction[] createFakeTx(NetworkParameters params, BigInteger nanocoins, Address to, Address from) throws IOException, ProtocolException { // Create fake TXes of sufficient realism to exercise the unit tests. This transaction send BTC from the // from address, to the to address with to one to somewhere else to simulate change. Transaction t = new Transaction(params); TransactionOutput outputToMe = new TransactionOutput(params, t, nanocoins, to); t.addOutput(outputToMe); TransactionOutput change = new TransactionOutput(params, t, Utils.toNanoCoins(1, 11), new ECKey().toAddress(params)); t.addOutput(change); // Make a feeder tx that sends to the from address specified. This feeder tx is not really valid but it doesn't // matter for our purposes. Transaction feederTx = new Transaction(params); TransactionOutput feederOut = new TransactionOutput(params, feederTx, nanocoins, from); feederTx.addOutput(feederOut); // make a previous tx that sends from the feeder to the from address Transaction prevTx = new Transaction(params); TransactionOutput prevOut = new TransactionOutput(params, prevTx, nanocoins, to); prevTx.addOutput(prevOut); // Connect up the txes prevTx.addInput(feederOut); t.addInput(prevOut); // roundtrip the tx so that they are just like they would be from the wire return new Transaction[]{roundTripTransaction(params, prevTx), roundTripTransaction(params,t)}; } /** * Roundtrip a transaction so that it appears as if it has just come from the wire */ public static Transaction roundTripTransaction(NetworkParameters params, Transaction tx) throws IOException, ProtocolException { BitcoinSerializer bs = new BitcoinSerializer(params); ByteArrayOutputStream bos = new ByteArrayOutputStream(); bs.serialize(tx, bos); return (Transaction) bs.deserialize(new ByteArrayInputStream(bos.toByteArray())); } public static class DoubleSpends { public Transaction t1, t2, prevTx; } /** * Creates two transactions that spend the same (fake) output. t1 spends to "to". t2 spends somewhere else. * The fake output goes to the same address as t2. */ public static DoubleSpends createFakeDoubleSpendTxns(NetworkParameters params, Address to) { DoubleSpends doubleSpends = new DoubleSpends(); BigInteger value = Utils.toNanoCoins(1, 0); Address someBadGuy = new ECKey().toAddress(params); doubleSpends.t1 = new Transaction(params); TransactionOutput o1 = new TransactionOutput(params, doubleSpends.t1, value, to); doubleSpends.t1.addOutput(o1); doubleSpends.prevTx = new Transaction(params); TransactionOutput prevOut = new TransactionOutput(params, doubleSpends.prevTx, value, someBadGuy); doubleSpends.prevTx.addOutput(prevOut); doubleSpends.t1.addInput(prevOut); doubleSpends.t2 = new Transaction(params); doubleSpends.t2.addInput(prevOut); TransactionOutput o2 = new TransactionOutput(params, doubleSpends.t2, value, someBadGuy); doubleSpends.t2.addOutput(o2); try { doubleSpends.t1 = new Transaction(params, doubleSpends.t1.bitcoinSerialize()); doubleSpends.t2 = new Transaction(params, doubleSpends.t2.bitcoinSerialize()); } catch (ProtocolException e) { throw new RuntimeException(e); } return doubleSpends; } public static class BlockPair { StoredBlock storedBlock; Block block; } // Emulates receiving a valid block that builds on top of the chain. public static BlockPair createFakeBlock(BlockStore blockStore, long timeSeconds, Transaction... transactions) { try { Block chainHead = blockStore.getChainHead().getHeader(); Address to = new ECKey().toAddress(chainHead.params); Block b = chainHead.createNextBlock(to, timeSeconds); // Coinbase tx was already added. for (Transaction tx : transactions) { tx.getConfidence().setSource(TransactionConfidence.Source.NETWORK); b.addTransaction(tx); } b.solve(); BlockPair pair = new BlockPair(); pair.block = b; pair.storedBlock = blockStore.getChainHead().build(b); blockStore.put(pair.storedBlock); blockStore.setChainHead(pair.storedBlock); return pair; } catch (VerificationException e) { throw new RuntimeException(e); // Cannot happen. } catch (BlockStoreException e) { throw new RuntimeException(e); // Cannot happen. } } public static BlockPair createFakeBlock(BlockStore blockStore, Transaction... transactions) { return createFakeBlock(blockStore, Utils.now().getTime() / 1000, transactions); } public static Block makeSolvedTestBlock(BlockStore blockStore, Address coinsTo) throws BlockStoreException { Block b = blockStore.getChainHead().getHeader().createNextBlock(coinsTo); b.solve(); return b; } public static Block makeSolvedTestBlock(Block prev, Transaction... transactions) throws BlockStoreException { Address to = new ECKey().toAddress(prev.params); Block b = prev.createNextBlock(to); // Coinbase tx already exists. for (Transaction tx : transactions) { b.addTransaction(tx); } b.solve(); return b; } }
apache-2.0
Niranjan-K/siddhi
modules/siddhi-core/src/test/java/org/wso2/siddhi/test/standard/table/rdbms/RDBMSTableJoinTestCase.java
11695
/* * Copyright (c) 2005-2010, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.wso2.siddhi.test.standard.table.rdbms; import org.apache.log4j.Logger; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.wso2.siddhi.core.SiddhiManager; import org.wso2.siddhi.core.event.Event; import org.wso2.siddhi.core.query.output.callback.QueryCallback; import org.wso2.siddhi.core.stream.input.InputHandler; import org.wso2.siddhi.core.util.EventPrinter; import javax.sql.DataSource; public class RDBMSTableJoinTestCase { static final Logger log = Logger.getLogger(RDBMSTableJoinTestCase.class); private int eventCount; private boolean eventArrived; private static String dataSourceName = "cepDataSource"; private DataSource dataSource = new BasicDataSource(); @Before public void init() { eventCount = 0; eventArrived = false; } @Test public void testTableJoinQuery1() throws InterruptedException { log.info("Table Join test1"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.getSiddhiContext().addDataSource(dataSourceName, dataSource); siddhiManager.defineStream("define stream cseEventStream (symbol string, price float, volume long) "); siddhiManager.defineStream("define stream cseEventCheckStream (symbol string) "); siddhiManager.defineTable("define table cseEventTable (symbol string, price float, volume long) " + createFromClause("cepDataSource", "cepJoinEventTable", null)); siddhiManager.addQuery("from cseEventStream " + "insert into cseEventTable;"); String queryReference = siddhiManager.addQuery("from cseEventCheckStream#window.length(1) join cseEventTable " + "select cseEventCheckStream.symbol as checkSymbol, cseEventTable.symbol as symbol, cseEventTable.volume as volume " + "insert into joinOutputStream;"); siddhiManager.addCallback(queryReference, new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); eventArrived = true; if (inEvents != null) { eventCount += inEvents.length; } } }); InputHandler cseEventStreamHandler = siddhiManager.getInputHandler("cseEventStream"); InputHandler twitterStreamHandler = siddhiManager.getInputHandler("cseEventCheckStream"); cseEventStreamHandler.send(new Object[]{"WSO2", 55.6f, 100}); cseEventStreamHandler.send(new Object[]{"IBM", 75.6f, 100}); twitterStreamHandler.send(new Object[]{"WSO2"}); Thread.sleep(500); Assert.assertEquals("Number of success events", 2, eventCount); Assert.assertEquals("Event arrived", true, eventArrived); siddhiManager.shutdown(); } @Test public void testTableJoinQuery2() throws InterruptedException { log.info("Table Join test2"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.getSiddhiContext().addDataSource(dataSourceName, dataSource); siddhiManager.defineStream("define stream cseEventStream (symbol string, price float, volume long) "); siddhiManager.defineStream("define stream cseEventCheckStream (symbol string) "); siddhiManager.defineTable("define table cseEventTable (symbol string, price float, volume long) " + createFromClause("cepDataSource", "cepJoinEventTable2", null)); siddhiManager.addQuery("from cseEventStream " + "insert into cseEventTable;"); String queryReference = siddhiManager.addQuery("from cseEventCheckStream#window.length(1) join cseEventTable " + "on cseEventTable.symbol==cseEventCheckStream.symbol " + "select cseEventCheckStream.symbol as checkSymbol, cseEventTable.symbol as symbol, cseEventTable.volume as volume " + "insert into joinOutputStream;"); siddhiManager.addCallback(queryReference, new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); eventArrived = true; eventCount++; } }); InputHandler cseEventStreamHandler = siddhiManager.getInputHandler("cseEventStream"); InputHandler twitterStreamHandler = siddhiManager.getInputHandler("cseEventCheckStream"); cseEventStreamHandler.send(new Object[]{"WSO2", 55.6f, 100}); cseEventStreamHandler.send(new Object[]{"IBM", 75.6f, 100}); twitterStreamHandler.send(new Object[]{"WSO2"}); Thread.sleep(500); Assert.assertEquals("Number of success events", 1, eventCount); Assert.assertEquals("Event arrived", true, eventArrived); siddhiManager.shutdown(); } @Test public void testTableJoinQuery3() throws InterruptedException { log.info("Table Join test3"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.getSiddhiContext().addDataSource(dataSourceName, dataSource); siddhiManager.defineStream("define stream cseEventStream (symbol string, price float, volume long) "); siddhiManager.defineStream("define stream cseEventCheckStream (symbol string) "); siddhiManager.defineTable("define table cseEventTable (symbol string, price float, volume long) " + createFromClause("cepDataSource", "cepJoinEventTable3", null)); siddhiManager.addQuery("from cseEventStream " + "insert into cseEventTable;"); String queryReference = siddhiManager.addQuery("from cseEventCheckStream#window.length(1) as checkStream join cseEventTable " + "on checkStream.symbol != cseEventTable.symbol " + "select cseEventCheckStream.symbol as checkSymbol, cseEventTable.symbol as symbol, cseEventTable.volume as volume " + "insert into joinOutputStream;"); siddhiManager.addCallback(queryReference, new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); eventArrived = true; eventCount++; } }); InputHandler cseEventStreamHandler = siddhiManager.getInputHandler("cseEventStream"); InputHandler twitterStreamHandler = siddhiManager.getInputHandler("cseEventCheckStream"); cseEventStreamHandler.send(new Object[]{"WSO2", 55.6f, 100}); cseEventStreamHandler.send(new Object[]{"IBM", 75.6f, 100}); twitterStreamHandler.send(new Object[]{"WSO2"}); Thread.sleep(500); Assert.assertEquals("Number of success events", 1, eventCount); Assert.assertEquals("Event arrived", true, eventArrived); siddhiManager.shutdown(); } @Test public void testTableJoinQuery4() throws InterruptedException { log.info("Table Join test4"); SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.getSiddhiContext().addDataSource(dataSourceName, dataSource); siddhiManager.defineStream("define stream cseEventStream (symbol string, price float, volume long) "); siddhiManager.defineStream("define stream cseEventCheckStream (symbol string) "); siddhiManager.defineTable("define table cseEventTable (symbol string, price float, volume long) " + createFromClause("cepDataSource", "cepJoinEventTable4", null)); siddhiManager.addQuery("from cseEventStream " + "insert into cseEventTable;"); String queryReference = siddhiManager.addQuery("from cseEventCheckStream#window.time(1000) as checkStream join cseEventTable " + "on checkStream.symbol != cseEventTable.symbol " + "select cseEventCheckStream.symbol as checkSymbol, cseEventTable.symbol as symbol, cseEventTable.volume as volume " + "insert into joinOutputStream for all-events;"); siddhiManager.addCallback(queryReference, new QueryCallback() { @Override public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) { EventPrinter.print(timeStamp, inEvents, removeEvents); eventArrived = true; eventCount++; } }); InputHandler cseEventStreamHandler = siddhiManager.getInputHandler("cseEventStream"); InputHandler twitterStreamHandler = siddhiManager.getInputHandler("cseEventCheckStream"); cseEventStreamHandler.send(new Object[]{"WSO2", 55.6f, 100}); cseEventStreamHandler.send(new Object[]{"IBM", 75.6f, 100}); twitterStreamHandler.send(new Object[]{"WSO2"}); Thread.sleep(3000); Assert.assertEquals("Number of success events", 2, eventCount); Assert.assertEquals("Event arrived", true, eventArrived); siddhiManager.shutdown(); } private String createFromClause(String dataSourceName, String tableName, String createQuery) { String query = "from ( 'datasource.name'='" + dataSourceName + "','table.name'='" + tableName + "'"; if (createQuery != null) { query = query + ",'create.query'='" + createQuery + "'"; } query = query + ")"; return query; } @Test public void testConditions() throws InterruptedException { SiddhiManager siddhiManager = new SiddhiManager(); siddhiManager.getSiddhiContext().addDataSource(dataSourceName, dataSource); siddhiManager.defineStream("define stream siddhi_db_input (id int, value int) "); siddhiManager.defineTable("define table cepEventTable11 (id int, value int) from " + " ('datasource.name'='cepDataSource', 'table.name'='cepEventTable101')" ); siddhiManager.addQuery("from siddhi_db_input[not ((id == cepEventTable11.id ) in cepEventTable11)] " + "select id, value " + "insert into tempDataStream"); siddhiManager.addQuery("from tempDataStream insert into cepEventTable11"); siddhiManager.addQuery("from siddhi_db_input join cepEventTable11 on " + " siddhi_db_input.id == cepEventTable11.id " + " select siddhi_db_input.id as id, siddhi_db_input.value + cepEventTable11.value as value " + " insert into out_stream"); siddhiManager.addQuery("from out_stream select out_stream.id, out_stream.value " + " update cepEventTable11 " + " on siddhi_db_input.id == cepEventTable11.id"); InputHandler cseEventStreamHandler = siddhiManager.getInputHandler("siddhi_db_input"); cseEventStreamHandler.send(new Object[]{11, 123}); cseEventStreamHandler.send(new Object[]{11, 1213}); } }
apache-2.0
wisebaldone/incubator-wave
wave/src/main/java/org/waveprotocol/box/server/frontend/testing/FakeClientFrontend.java
4613
/** * 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.waveprotocol.box.server.frontend.testing; import org.waveprotocol.box.common.DeltaSequence; import org.waveprotocol.box.common.comms.WaveClientRpc; import org.waveprotocol.box.server.frontend.ClientFrontend; import org.waveprotocol.box.server.waveserver.WaveBus; import org.waveprotocol.box.server.waveserver.WaveletProvider.SubmitRequestListener; import org.waveprotocol.wave.federation.Proto.ProtocolWaveletDelta; import org.waveprotocol.wave.model.id.IdFilter; import org.waveprotocol.wave.model.id.WaveId; import org.waveprotocol.wave.model.id.WaveletName; import org.waveprotocol.wave.model.version.HashedVersion; import org.waveprotocol.wave.model.wave.ParticipantId; import org.waveprotocol.wave.model.wave.data.ReadableWaveletData; import java.util.Collection; import java.util.HashMap; import java.util.Map; /** * Implementation of a ClientFrontend which only records requests and will make callbacks when it * receives wavelet listener events. */ public class FakeClientFrontend implements ClientFrontend, WaveBus.Subscriber { private static class SubmitRecord { final SubmitRequestListener listener; final int operations; SubmitRecord(int operations, SubmitRequestListener listener) { this.operations = operations; this.listener = listener; } } private final Map<WaveId, OpenListener> openListeners = new HashMap<WaveId, OpenListener>(); private final Map<WaveletName, SubmitRecord> submitRecords = new HashMap<WaveletName, SubmitRecord>(); public void doSubmitFailed(WaveletName waveletName, String errorMessage) { SubmitRecord record = submitRecords.remove(waveletName); if (record != null) { record.listener.onFailure(errorMessage); } } /** Reports a submit success with resulting version 0 application timestamp 0 */ public void doSubmitSuccess(WaveletName waveletName) { HashedVersion fakeHashedVersion = HashedVersion.of(0, new byte[0]); doSubmitSuccess(waveletName, fakeHashedVersion, 0); } /** Reports a submit success with the specified resulting version and application timestamp */ public void doSubmitSuccess(WaveletName waveletName, HashedVersion resultingVersion, long applicationTimestamp) { SubmitRecord record = submitRecords.remove(waveletName); if (record != null) { record.listener.onSuccess(record.operations, resultingVersion, applicationTimestamp); } } public void doUpdateFailure(WaveId waveId, String errorMessage) { OpenListener listener = openListeners.get(waveId); if (listener != null) { listener.onFailure(errorMessage); } } @Override public void openRequest(ParticipantId participant, WaveId waveId, IdFilter waveletIdFilter, Collection<WaveClientRpc.WaveletVersion> knownWavelets, OpenListener openListener) { openListeners.put(waveId, openListener); } @Override public void submitRequest(ParticipantId loggedInUser, WaveletName waveletName, ProtocolWaveletDelta delta, String channelId, SubmitRequestListener listener) { submitRecords.put(waveletName, new SubmitRecord(delta.getOperationCount(), listener)); } @Override public void waveletCommitted(WaveletName waveletName, HashedVersion version) { OpenListener listener = openListeners.get(waveletName.waveId); if (listener != null) { listener.onUpdate(waveletName, null, DeltaSequence.empty(), version, null, null); } } @Override public void waveletUpdate(ReadableWaveletData wavelet, DeltaSequence newDeltas) { OpenListener listener = openListeners.get(wavelet.getWaveId()); if (listener != null) { WaveletName waveletName = WaveletName.of(wavelet.getWaveId(), wavelet.getWaveletId()); listener.onUpdate(waveletName, null, newDeltas, null, null, null); } } }
apache-2.0
mydevotion/elastic-job-source
elastic-job-common/elastic-job-common-core/src/test/java/com/dangdang/ddframe/job/fixture/context/TaskNode.java
1350
/* * Copyright 1999-2015 dangdang.com. * <p> * 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. * </p> */ package com.dangdang.ddframe.job.fixture.context; import com.dangdang.ddframe.job.context.ExecutionType; import com.google.common.base.Joiner; import lombok.Builder; @Builder public final class TaskNode { private String jobName; private int shardingItem; private ExecutionType type; private String slaveId; private String uuid; public String getTaskNodePath() { return Joiner.on("@-@").join(null == jobName ? "test_job" : jobName, shardingItem); } public String getTaskNodeValue() { return Joiner.on("@-@").join(getTaskNodePath(), null == type ? ExecutionType.READY : type, null == slaveId ? "slave-S0" : slaveId, null == uuid ? "0" : uuid); } }
apache-2.0
DariusX/camel
components/camel-smpp/src/generated/java/org/apache/camel/component/smpp/SmppEndpointConfigurer.java
14631
/* Generated by camel build tools - do NOT edit this file! */ package org.apache.camel.component.smpp; import java.util.Map; import org.apache.camel.CamelContext; import org.apache.camel.spi.GeneratedPropertyConfigurer; import org.apache.camel.spi.PropertyConfigurerGetter; import org.apache.camel.util.CaseInsensitiveMap; import org.apache.camel.support.component.PropertyConfigurerSupport; /** * Generated by camel build tools - do NOT edit this file! */ @SuppressWarnings("unchecked") public class SmppEndpointConfigurer extends PropertyConfigurerSupport implements GeneratedPropertyConfigurer, PropertyConfigurerGetter { @Override public boolean configure(CamelContext camelContext, Object obj, String name, Object value, boolean ignoreCase) { SmppEndpoint target = (SmppEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "addressrange": case "addressRange": target.getConfiguration().setAddressRange(property(camelContext, java.lang.String.class, value)); return true; case "alphabet": target.getConfiguration().setAlphabet(property(camelContext, byte.class, value)); return true; case "basicpropertybinding": case "basicPropertyBinding": target.setBasicPropertyBinding(property(camelContext, boolean.class, value)); return true; case "bridgeerrorhandler": case "bridgeErrorHandler": target.setBridgeErrorHandler(property(camelContext, boolean.class, value)); return true; case "datacoding": case "dataCoding": target.getConfiguration().setDataCoding(property(camelContext, byte.class, value)); return true; case "destaddr": case "destAddr": target.getConfiguration().setDestAddr(property(camelContext, java.lang.String.class, value)); return true; case "destaddrnpi": case "destAddrNpi": target.getConfiguration().setDestAddrNpi(property(camelContext, byte.class, value)); return true; case "destaddrton": case "destAddrTon": target.getConfiguration().setDestAddrTon(property(camelContext, byte.class, value)); return true; case "encoding": target.getConfiguration().setEncoding(property(camelContext, java.lang.String.class, value)); return true; case "enquirelinktimer": case "enquireLinkTimer": target.getConfiguration().setEnquireLinkTimer(property(camelContext, java.lang.Integer.class, value)); return true; case "exceptionhandler": case "exceptionHandler": target.setExceptionHandler(property(camelContext, org.apache.camel.spi.ExceptionHandler.class, value)); return true; case "exchangepattern": case "exchangePattern": target.setExchangePattern(property(camelContext, org.apache.camel.ExchangePattern.class, value)); return true; case "httpproxyhost": case "httpProxyHost": target.getConfiguration().setHttpProxyHost(property(camelContext, java.lang.String.class, value)); return true; case "httpproxypassword": case "httpProxyPassword": target.getConfiguration().setHttpProxyPassword(property(camelContext, java.lang.String.class, value)); return true; case "httpproxyport": case "httpProxyPort": target.getConfiguration().setHttpProxyPort(property(camelContext, java.lang.Integer.class, value)); return true; case "httpproxyusername": case "httpProxyUsername": target.getConfiguration().setHttpProxyUsername(property(camelContext, java.lang.String.class, value)); return true; case "initialreconnectdelay": case "initialReconnectDelay": target.getConfiguration().setInitialReconnectDelay(property(camelContext, long.class, value)); return true; case "lazysessioncreation": case "lazySessionCreation": target.getConfiguration().setLazySessionCreation(property(camelContext, boolean.class, value)); return true; case "lazystartproducer": case "lazyStartProducer": target.setLazyStartProducer(property(camelContext, boolean.class, value)); return true; case "maxreconnect": case "maxReconnect": target.getConfiguration().setMaxReconnect(property(camelContext, int.class, value)); return true; case "numberingplanindicator": case "numberingPlanIndicator": target.getConfiguration().setNumberingPlanIndicator(property(camelContext, byte.class, value)); return true; case "password": target.getConfiguration().setPassword(property(camelContext, java.lang.String.class, value)); return true; case "priorityflag": case "priorityFlag": target.getConfiguration().setPriorityFlag(property(camelContext, byte.class, value)); return true; case "protocolid": case "protocolId": target.getConfiguration().setProtocolId(property(camelContext, byte.class, value)); return true; case "proxyheaders": case "proxyHeaders": target.getConfiguration().setProxyHeaders(property(camelContext, java.util.Map.class, value)); return true; case "reconnectdelay": case "reconnectDelay": target.getConfiguration().setReconnectDelay(property(camelContext, long.class, value)); return true; case "registereddelivery": case "registeredDelivery": target.getConfiguration().setRegisteredDelivery(property(camelContext, byte.class, value)); return true; case "replaceifpresentflag": case "replaceIfPresentFlag": target.getConfiguration().setReplaceIfPresentFlag(property(camelContext, byte.class, value)); return true; case "servicetype": case "serviceType": target.getConfiguration().setServiceType(property(camelContext, java.lang.String.class, value)); return true; case "sessionstatelistener": case "sessionStateListener": target.getConfiguration().setSessionStateListener(property(camelContext, org.jsmpp.session.SessionStateListener.class, value)); return true; case "sourceaddr": case "sourceAddr": target.getConfiguration().setSourceAddr(property(camelContext, java.lang.String.class, value)); return true; case "sourceaddrnpi": case "sourceAddrNpi": target.getConfiguration().setSourceAddrNpi(property(camelContext, byte.class, value)); return true; case "sourceaddrton": case "sourceAddrTon": target.getConfiguration().setSourceAddrTon(property(camelContext, byte.class, value)); return true; case "splittingpolicy": case "splittingPolicy": target.getConfiguration().setSplittingPolicy(property(camelContext, org.apache.camel.component.smpp.SmppSplittingPolicy.class, value)); return true; case "synchronous": target.setSynchronous(property(camelContext, boolean.class, value)); return true; case "systemid": case "systemId": target.getConfiguration().setSystemId(property(camelContext, java.lang.String.class, value)); return true; case "systemtype": case "systemType": target.getConfiguration().setSystemType(property(camelContext, java.lang.String.class, value)); return true; case "transactiontimer": case "transactionTimer": target.getConfiguration().setTransactionTimer(property(camelContext, java.lang.Integer.class, value)); return true; case "typeofnumber": case "typeOfNumber": target.getConfiguration().setTypeOfNumber(property(camelContext, byte.class, value)); return true; case "usingssl": case "usingSSL": target.getConfiguration().setUsingSSL(property(camelContext, boolean.class, value)); return true; default: return false; } } @Override public Map<String, Object> getAllOptions(Object target) { Map<String, Object> answer = new CaseInsensitiveMap(); answer.put("addressRange", java.lang.String.class); answer.put("alphabet", byte.class); answer.put("basicPropertyBinding", boolean.class); answer.put("bridgeErrorHandler", boolean.class); answer.put("dataCoding", byte.class); answer.put("destAddr", java.lang.String.class); answer.put("destAddrNpi", byte.class); answer.put("destAddrTon", byte.class); answer.put("encoding", java.lang.String.class); answer.put("enquireLinkTimer", java.lang.Integer.class); answer.put("exceptionHandler", org.apache.camel.spi.ExceptionHandler.class); answer.put("exchangePattern", org.apache.camel.ExchangePattern.class); answer.put("httpProxyHost", java.lang.String.class); answer.put("httpProxyPassword", java.lang.String.class); answer.put("httpProxyPort", java.lang.Integer.class); answer.put("httpProxyUsername", java.lang.String.class); answer.put("initialReconnectDelay", long.class); answer.put("lazySessionCreation", boolean.class); answer.put("lazyStartProducer", boolean.class); answer.put("maxReconnect", int.class); answer.put("numberingPlanIndicator", byte.class); answer.put("password", java.lang.String.class); answer.put("priorityFlag", byte.class); answer.put("protocolId", byte.class); answer.put("proxyHeaders", java.util.Map.class); answer.put("reconnectDelay", long.class); answer.put("registeredDelivery", byte.class); answer.put("replaceIfPresentFlag", byte.class); answer.put("serviceType", java.lang.String.class); answer.put("sessionStateListener", org.jsmpp.session.SessionStateListener.class); answer.put("sourceAddr", java.lang.String.class); answer.put("sourceAddrNpi", byte.class); answer.put("sourceAddrTon", byte.class); answer.put("splittingPolicy", org.apache.camel.component.smpp.SmppSplittingPolicy.class); answer.put("synchronous", boolean.class); answer.put("systemId", java.lang.String.class); answer.put("systemType", java.lang.String.class); answer.put("transactionTimer", java.lang.Integer.class); answer.put("typeOfNumber", byte.class); answer.put("usingSSL", boolean.class); return answer; } @Override public Object getOptionValue(Object obj, String name, boolean ignoreCase) { SmppEndpoint target = (SmppEndpoint) obj; switch (ignoreCase ? name.toLowerCase() : name) { case "addressrange": case "addressRange": return target.getConfiguration().getAddressRange(); case "alphabet": return target.getConfiguration().getAlphabet(); case "basicpropertybinding": case "basicPropertyBinding": return target.isBasicPropertyBinding(); case "bridgeerrorhandler": case "bridgeErrorHandler": return target.isBridgeErrorHandler(); case "datacoding": case "dataCoding": return target.getConfiguration().getDataCoding(); case "destaddr": case "destAddr": return target.getConfiguration().getDestAddr(); case "destaddrnpi": case "destAddrNpi": return target.getConfiguration().getDestAddrNpi(); case "destaddrton": case "destAddrTon": return target.getConfiguration().getDestAddrTon(); case "encoding": return target.getConfiguration().getEncoding(); case "enquirelinktimer": case "enquireLinkTimer": return target.getConfiguration().getEnquireLinkTimer(); case "exceptionhandler": case "exceptionHandler": return target.getExceptionHandler(); case "exchangepattern": case "exchangePattern": return target.getExchangePattern(); case "httpproxyhost": case "httpProxyHost": return target.getConfiguration().getHttpProxyHost(); case "httpproxypassword": case "httpProxyPassword": return target.getConfiguration().getHttpProxyPassword(); case "httpproxyport": case "httpProxyPort": return target.getConfiguration().getHttpProxyPort(); case "httpproxyusername": case "httpProxyUsername": return target.getConfiguration().getHttpProxyUsername(); case "initialreconnectdelay": case "initialReconnectDelay": return target.getConfiguration().getInitialReconnectDelay(); case "lazysessioncreation": case "lazySessionCreation": return target.getConfiguration().isLazySessionCreation(); case "lazystartproducer": case "lazyStartProducer": return target.isLazyStartProducer(); case "maxreconnect": case "maxReconnect": return target.getConfiguration().getMaxReconnect(); case "numberingplanindicator": case "numberingPlanIndicator": return target.getConfiguration().getNumberingPlanIndicator(); case "password": return target.getConfiguration().getPassword(); case "priorityflag": case "priorityFlag": return target.getConfiguration().getPriorityFlag(); case "protocolid": case "protocolId": return target.getConfiguration().getProtocolId(); case "proxyheaders": case "proxyHeaders": return target.getConfiguration().getProxyHeaders(); case "reconnectdelay": case "reconnectDelay": return target.getConfiguration().getReconnectDelay(); case "registereddelivery": case "registeredDelivery": return target.getConfiguration().getRegisteredDelivery(); case "replaceifpresentflag": case "replaceIfPresentFlag": return target.getConfiguration().getReplaceIfPresentFlag(); case "servicetype": case "serviceType": return target.getConfiguration().getServiceType(); case "sessionstatelistener": case "sessionStateListener": return target.getConfiguration().getSessionStateListener(); case "sourceaddr": case "sourceAddr": return target.getConfiguration().getSourceAddr(); case "sourceaddrnpi": case "sourceAddrNpi": return target.getConfiguration().getSourceAddrNpi(); case "sourceaddrton": case "sourceAddrTon": return target.getConfiguration().getSourceAddrTon(); case "splittingpolicy": case "splittingPolicy": return target.getConfiguration().getSplittingPolicy(); case "synchronous": return target.isSynchronous(); case "systemid": case "systemId": return target.getConfiguration().getSystemId(); case "systemtype": case "systemType": return target.getConfiguration().getSystemType(); case "transactiontimer": case "transactionTimer": return target.getConfiguration().getTransactionTimer(); case "typeofnumber": case "typeOfNumber": return target.getConfiguration().getTypeOfNumber(); case "usingssl": case "usingSSL": return target.getConfiguration().isUsingSSL(); default: return null; } } }
apache-2.0
Phaneendra-Huawei/demo
providers/netcfglinks/src/test/java/org/onosproject/provider/netcfglinks/NetworkConfigLinksProviderTest.java
13332
/* * Copyright 2016-present Open Networking Laboratory * * 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.onosproject.provider.netcfglinks; import java.nio.ByteBuffer; import java.util.List; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.onlab.packet.ChassisId; import org.onlab.packet.Ethernet; import org.onlab.packet.ONOSLLDP; import org.onosproject.cluster.ClusterMetadataServiceAdapter; import org.onosproject.core.CoreServiceAdapter; import org.onosproject.mastership.MastershipServiceAdapter; import org.onosproject.net.ConnectPoint; import org.onosproject.net.DefaultPort; import org.onosproject.net.Device; import org.onosproject.net.DeviceId; import org.onosproject.net.LinkKey; import org.onosproject.net.NetTestTools; import org.onosproject.net.Port; import org.onosproject.net.PortNumber; import org.onosproject.net.config.NetworkConfigEvent; import org.onosproject.net.config.NetworkConfigListener; import org.onosproject.net.config.NetworkConfigRegistryAdapter; import org.onosproject.net.config.basics.BasicLinkConfig; import org.onosproject.net.device.DeviceEvent; import org.onosproject.net.device.DeviceListener; import org.onosproject.net.device.DeviceServiceAdapter; import org.onosproject.net.flow.TrafficTreatment; import org.onosproject.net.link.LinkDescription; import org.onosproject.net.link.LinkProviderRegistryAdapter; import org.onosproject.net.link.LinkProviderServiceAdapter; import org.onosproject.net.packet.DefaultInboundPacket; import org.onosproject.net.packet.InboundPacket; import org.onosproject.net.packet.OutboundPacket; import org.onosproject.net.packet.PacketContext; import org.onosproject.net.packet.PacketProcessor; import org.onosproject.net.packet.PacketServiceAdapter; import com.google.common.collect.ImmutableList; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.empty; import static org.hamcrest.Matchers.hasSize; import static org.hamcrest.Matchers.is; import static org.hamcrest.Matchers.notNullValue; /** * Unit tests for the network config links provider. */ public class NetworkConfigLinksProviderTest { private NetworkConfigLinksProvider provider; private PacketProcessor testProcessor; private LinkProviderServiceAdapter providerService; private NetworkConfigListener configListener; private final TestNetworkConfigRegistry configRegistry = new TestNetworkConfigRegistry(); static Device dev1 = NetTestTools.device("sw1"); static Device dev2 = NetTestTools.device("sw2"); static Device dev3 = NetTestTools.device("sw3"); static PortNumber portNumber1 = PortNumber.portNumber(1); static PortNumber portNumber2 = PortNumber.portNumber(2); static PortNumber portNumber3 = PortNumber.portNumber(3); static ConnectPoint src = new ConnectPoint(dev1.id(), portNumber2); static ConnectPoint dst = new ConnectPoint(dev2.id(), portNumber2); static DeviceListener deviceListener; /** * Test device manager. Returns a known set of devices and ports. */ static class TestDeviceManager extends DeviceServiceAdapter { @Override public Iterable<Device> getAvailableDevices() { return ImmutableList.of(dev1, dev2); } @Override public List<Port> getPorts(DeviceId deviceId) { return ImmutableList.of(new DefaultPort(dev1, portNumber1, true), new DefaultPort(dev2, portNumber2, true)); } @Override public void addListener(DeviceListener listener) { deviceListener = listener; } @Override public Device getDevice(DeviceId deviceId) { if (deviceId.equals(dev1.id())) { return dev1; } else { return dev2; } } } /** * Test mastership service. All devices owned by the local node for testing. */ static class TestMastershipService extends MastershipServiceAdapter { @Override public boolean isLocalMaster(DeviceId deviceId) { return true; } } /** * Test packet context for generation of LLDP packets. */ private class TestPacketContext implements PacketContext { protected ConnectPoint src; protected ConnectPoint dst; protected boolean blocked = false; public TestPacketContext(ConnectPoint src, ConnectPoint dst) { this.src = src; this.dst = dst; } @Override public long time() { return 0; } @Override public InboundPacket inPacket() { ONOSLLDP lldp = ONOSLLDP.onosLLDP(src.deviceId().toString(), new ChassisId(), (int) src.port().toLong()); Ethernet ethPacket = new Ethernet(); ethPacket.setEtherType(Ethernet.TYPE_LLDP); ethPacket.setDestinationMACAddress(ONOSLLDP.LLDP_NICIRA); ethPacket.setPayload(lldp); ethPacket.setPad(true); ethPacket.setSourceMACAddress("DE:AD:BE:EF:BA:11"); return new DefaultInboundPacket(dst, ethPacket, ByteBuffer.wrap(ethPacket.serialize())); } @Override public OutboundPacket outPacket() { return null; } @Override public TrafficTreatment.Builder treatmentBuilder() { return null; } @Override public void send() { } @Override public boolean block() { blocked = true; return true; } @Override public boolean isHandled() { return blocked; } } /** * Test packet service for capturing the packet processor from the service * under test. */ private class TestPacketService extends PacketServiceAdapter { @Override public void addProcessor(PacketProcessor processor, int priority) { testProcessor = processor; } } /** * Test network config registry. Captures the network config listener from * the service under test. */ private final class TestNetworkConfigRegistry extends NetworkConfigRegistryAdapter { @Override public void addListener(NetworkConfigListener listener) { configListener = listener; } } /** * Sets up a network config links provider under test and the services * required to run it. */ @Before public void setUp() { provider = new NetworkConfigLinksProvider(); provider.coreService = new CoreServiceAdapter(); provider.packetService = new PacketServiceAdapter(); LinkProviderRegistryAdapter linkRegistry = new LinkProviderRegistryAdapter(); provider.providerRegistry = linkRegistry; provider.deviceService = new TestDeviceManager(); provider.masterService = new TestMastershipService(); provider.packetService = new TestPacketService(); provider.metadataService = new ClusterMetadataServiceAdapter(); provider.netCfgService = configRegistry; provider.activate(); providerService = linkRegistry.registeredProvider(); } /** * Tears down the provider under test. */ @After public void tearDown() { provider.deactivate(); } /** * Tests that a network config links provider object can be created. * The actual creation is done in the setUp() method. */ @Test public void testCreation() { assertThat(provider, notNullValue()); assertThat(provider.configuredLinks, empty()); } /** * Tests loading of devices from the device manager. */ @Test public void testDeviceLoad() { assertThat(provider, notNullValue()); assertThat(provider.discoverers.entrySet(), hasSize(2)); } /** * Tests discovery of a link that is not expected in the configuration. */ @Test public void testNotConfiguredLink() { PacketContext pktCtx = new TestPacketContext(src, dst); testProcessor.process(pktCtx); assertThat(providerService.discoveredLinks().entrySet(), hasSize(1)); DeviceId destination = providerService.discoveredLinks().get(dev1.id()); assertThat(destination, notNullValue()); LinkKey key = LinkKey.linkKey(src, dst); LinkDescription linkDescription = providerService .discoveredLinkDescriptions().get(key); assertThat(linkDescription, notNullValue()); assertThat(linkDescription.isExpected(), is(false)); } /** * Tests discovery of an expected link. */ @Test public void testConfiguredLink() { LinkKey key = LinkKey.linkKey(src, dst); configListener.event(new NetworkConfigEvent(NetworkConfigEvent.Type.CONFIG_ADDED, key, BasicLinkConfig.class)); PacketContext pktCtx = new TestPacketContext(src, dst); testProcessor.process(pktCtx); assertThat(providerService.discoveredLinks().entrySet(), hasSize(1)); DeviceId destination = providerService.discoveredLinks().get(dev1.id()); assertThat(destination, notNullValue()); LinkDescription linkDescription = providerService .discoveredLinkDescriptions().get(key); assertThat(linkDescription, notNullValue()); assertThat(linkDescription.isExpected(), is(true)); } /** * Tests removal of a link from the configuration. */ @Test public void testRemoveLink() { LinkKey key = LinkKey.linkKey(src, dst); configListener.event(new NetworkConfigEvent(NetworkConfigEvent.Type.CONFIG_ADDED, key, BasicLinkConfig.class)); assertThat(provider.configuredLinks, hasSize(1)); configListener.event(new NetworkConfigEvent(NetworkConfigEvent.Type.CONFIG_REMOVED, key, BasicLinkConfig.class)); assertThat(provider.configuredLinks, hasSize(0)); } /** * Tests adding a new device via an event. */ @Test public void testAddDevice() { deviceListener.event(new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, dev3)); assertThat(provider.discoverers.entrySet(), hasSize(3)); } /** * Tests adding a new port via an event. */ @Test public void testAddPort() { deviceListener.event(new DeviceEvent(DeviceEvent.Type.PORT_ADDED, dev3, new DefaultPort(dev3, portNumber3, true))); assertThat(provider.discoverers.entrySet(), hasSize(3)); } /** * Tests removing a device via an event. */ @Test public void testRemoveDevice() { assertThat(provider.discoverers.entrySet(), hasSize(2)); deviceListener.event(new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, dev3)); assertThat(provider.discoverers.entrySet(), hasSize(3)); deviceListener.event(new DeviceEvent(DeviceEvent.Type.DEVICE_REMOVED, dev3)); assertThat(provider.discoverers.entrySet(), hasSize(2)); } /** * Tests removing a port via an event. */ @Test public void testRemovePort() { assertThat(provider.discoverers.entrySet(), hasSize(2)); deviceListener.event(new DeviceEvent(DeviceEvent.Type.PORT_ADDED, dev3, new DefaultPort(dev3, portNumber3, true))); assertThat(provider.discoverers.entrySet(), hasSize(3)); deviceListener.event(new DeviceEvent(DeviceEvent.Type.PORT_REMOVED, dev3, new DefaultPort(dev3, portNumber3, true))); assertThat(provider.discoverers.entrySet(), hasSize(3)); } /** * Tests changing device availability via an event. */ @Test public void testDeviceAvailabilityChanged() { assertThat(providerService.vanishedDpid(), hasSize(0)); deviceListener.event( new DeviceEvent(DeviceEvent.Type.DEVICE_ADDED, dev3)); assertThat(providerService.vanishedDpid(), hasSize(0)); deviceListener.event( new DeviceEvent(DeviceEvent.Type.DEVICE_AVAILABILITY_CHANGED, dev3)); assertThat(providerService.vanishedDpid(), hasSize(1)); } }
apache-2.0
shun634501730/java_source_cn
src_en/com/sun/corba/se/spi/logging/LogWrapperFactory.java
424
/* * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */ package com.sun.corba.se.spi.logging ; import java.util.logging.Logger ; import com.sun.corba.se.spi.logging.LogWrapperBase ; public interface LogWrapperFactory { LogWrapperBase create( Logger logger ) ; }
apache-2.0
avthart/mina-sshd
sshd-core/src/main/java/org/apache/sshd/client/scp/CloseableScpClient.java
1141
/* * 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.sshd.client.scp; import java.nio.channels.Channel; /** * An {@link ScpClient} wrapper that also closes the underlying session * when closed * * @author <a href="mailto:dev@mina.apache.org">Apache MINA SSHD Project</a> */ public interface CloseableScpClient extends ScpClient, Channel { // Marker interface }
apache-2.0
sijie/bookkeeper
stream/api/src/main/java/org/apache/bookkeeper/api/kv/PTableBase.java
2754
/* * 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.bookkeeper.api.kv; import org.apache.bookkeeper.api.kv.op.CompareOp; import org.apache.bookkeeper.api.kv.op.CompareResult; import org.apache.bookkeeper.api.kv.op.DeleteOp; import org.apache.bookkeeper.api.kv.op.IncrementOp; import org.apache.bookkeeper.api.kv.op.OpFactory; import org.apache.bookkeeper.api.kv.op.PutOp; import org.apache.bookkeeper.api.kv.op.RangeOp; import org.apache.bookkeeper.api.kv.options.Options; /** * A base class for {@link PTable}. */ public interface PTableBase<K, V> extends AutoCloseable { OpFactory<K, V> opFactory(); default CompareOp<K, V> compareCreateRevision(CompareResult result, K key, long revision) { return opFactory().compareCreateRevision(result, key, revision); } default CompareOp<K, V> compareModRevision(CompareResult result, K key, long revision) { return opFactory().compareModRevision(result, key, revision); } default CompareOp<K, V> compareVersion(CompareResult result, K key, long version) { return opFactory().compareVersion(result, key, version); } default CompareOp<K, V> compareValue(CompareResult result, K key, V value) { return opFactory().compareValue(result, key, value); } default PutOp<K, V> newPut(K key, V value) { return opFactory().newPut(key, value, Options.blindPut()); } default DeleteOp<K, V> newDelete(K key) { return opFactory().newDelete(key, Options.delete()); } default IncrementOp<K, V> newIncrement(K key, long amount) { return opFactory().newIncrement(key, amount, Options.blindIncrement()); } default IncrementOp<K, V> newIncrementAndGet(K key, long amount) { return opFactory().newIncrement(key, amount, Options.incrementAndGet()); } default RangeOp<K, V> newGet(K key) { return opFactory().newRange( key, Options.get()); } @Override void close(); }
apache-2.0
spring-projects/spring-loaded
testdata/src/main/java/invokespecial/C.java
313
package invokespecial; public class C extends B { public int getInt() { return super.getInt(); } public String toString(boolean b, String s) { return super.toString(b, s); } public String run1() { return Integer.toString(getInt()); } public String run2() { return toString(false, "abc"); } }
apache-2.0
trekawek/jackrabbit-oak
oak-core/src/test/java/org/apache/jackrabbit/oak/security/authorization/restriction/ItemNameRestrictionTest.java
10926
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.jackrabbit.oak.security.authorization.restriction; import java.security.Principal; import java.util.Collections; import java.util.List; import java.util.UUID; import javax.jcr.PropertyType; import javax.jcr.Value; import javax.jcr.ValueFactory; import javax.jcr.security.AccessControlManager; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import org.apache.jackrabbit.JcrConstants; import org.apache.jackrabbit.api.security.JackrabbitAccessControlList; import org.apache.jackrabbit.api.security.user.Group; import org.apache.jackrabbit.api.security.user.User; import org.apache.jackrabbit.api.security.user.UserManager; import org.apache.jackrabbit.commons.jackrabbit.authorization.AccessControlUtils; import org.apache.jackrabbit.oak.AbstractSecurityTest; import org.apache.jackrabbit.oak.api.CommitFailedException; import org.apache.jackrabbit.oak.api.ContentSession; import org.apache.jackrabbit.oak.api.Root; import org.apache.jackrabbit.oak.api.Tree; import org.apache.jackrabbit.oak.commons.PathUtils; import org.apache.jackrabbit.oak.namepath.NamePathMapper; import org.apache.jackrabbit.oak.plugins.tree.TreeUtil; import org.apache.jackrabbit.oak.spi.nodetype.NodeTypeConstants; import org.apache.jackrabbit.oak.plugins.value.jcr.ValueFactoryImpl; import org.apache.jackrabbit.oak.spi.security.authorization.accesscontrol.AccessControlConstants; import org.apache.jackrabbit.oak.spi.security.privilege.PrivilegeConstants; import org.apache.jackrabbit.oak.spi.security.user.UserConstants; import org.junit.Test; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import static org.junit.Assert.fail; public class ItemNameRestrictionTest extends AbstractSecurityTest { private ValueFactory vf; private ContentSession testSession; private Principal testPrincipal; private Group testGroup; @Override public void before() throws Exception { super.before(); Tree rootTree = root.getTree("/"); // "/a/d/b/e/c/f" Tree a = TreeUtil.addChild(rootTree, "a", NodeTypeConstants.NT_OAK_UNSTRUCTURED); Tree d = TreeUtil.addChild(a, "d", NodeTypeConstants.NT_OAK_UNSTRUCTURED); Tree b = TreeUtil.addChild(d, "b", NodeTypeConstants.NT_OAK_UNSTRUCTURED); Tree e = TreeUtil.addChild(b, "e", NodeTypeConstants.NT_OAK_UNSTRUCTURED); Tree c = TreeUtil.addChild(e, "c", NodeTypeConstants.NT_OAK_UNSTRUCTURED); Tree f = TreeUtil.addChild(c, "f", NodeTypeConstants.NT_OAK_UNSTRUCTURED); c.setProperty("prop", "value"); c.setProperty("a", "value"); testPrincipal = getTestUser().getPrincipal(); AccessControlManager acMgr = getAccessControlManager(root); JackrabbitAccessControlList acl = AccessControlUtils.getAccessControlList(acMgr, "/a"); vf = new ValueFactoryImpl(root, NamePathMapper.DEFAULT); acl.addEntry(testPrincipal, privilegesFromNames( PrivilegeConstants.JCR_READ, PrivilegeConstants.REP_ADD_PROPERTIES, PrivilegeConstants.JCR_ADD_CHILD_NODES, PrivilegeConstants.JCR_REMOVE_NODE), true, Collections.<String, Value>emptyMap(), ImmutableMap.of(AccessControlConstants.REP_ITEM_NAMES, new Value[] { vf.createValue("a", PropertyType.NAME), vf.createValue("b", PropertyType.NAME), vf.createValue("c", PropertyType.NAME)})); acMgr.setPolicy(acl.getPath(), acl); UserManager uMgr = getUserManager(root); testGroup = uMgr.createGroup("testGroup" + UUID.randomUUID()); root.commit(); testSession = createTestSession(); } @Override public void after() throws Exception { try { testSession.close(); root.refresh(); Tree a = root.getTree("/a"); if (a.exists()) { a.remove(); root.commit(); } } finally { super.after(); } } @Test public void testRead() { Root testRoot = testSession.getLatestRoot(); List<String> visible = ImmutableList.of("/a", "/a/d/b", "/a/d/b/e/c"); for (String p : visible) { assertTrue(testRoot.getTree(p).exists()); } List<String> invisible = ImmutableList.of("/", "/a/d", "/a/d/b/e", "/a/d/b/e/c/f"); for (String p : invisible) { assertFalse(testRoot.getTree(p).exists()); } Tree c = testRoot.getTree("/a/d/b/e/c"); assertNull(c.getProperty(JcrConstants.JCR_PRIMARYTYPE)); assertNull(c.getProperty("prop")); assertNotNull(c.getProperty("a")); } @Test public void testAddProperty() throws Exception { Root testRoot = testSession.getLatestRoot(); List<String> paths = ImmutableList.of("/a", "/a/d/b", "/a/d/b/e/c"); for (String p : paths) { Tree t = testRoot.getTree(p); t.setProperty("b", "anyvalue"); testRoot.commit(); } for (String p : paths) { Tree t = testRoot.getTree(p); try { t.setProperty("notAllowed", "anyvalue"); testRoot.commit(); fail(); } catch (CommitFailedException e) { // success assertTrue(e.isAccessViolation()); } finally { testRoot.refresh(); } } } @Test(expected = CommitFailedException.class) public void testModifyProperty() throws Exception { Root testRoot = testSession.getLatestRoot(); Tree c = testRoot.getTree("/a/d/b/e/c"); try { c.setProperty("a", "anyvalue"); testRoot.commit(); } catch (CommitFailedException e) { // success assertTrue(e.isAccessViolation()); throw e; } } @Test public void testAddChild() throws Exception { Root testRoot = testSession.getLatestRoot(); List<String> paths = ImmutableList.of("/a", "/a/d/b", "/a/d/b/e/c"); for (String p : paths) { Tree t = testRoot.getTree(p); TreeUtil.addChild(t, "c", NodeTypeConstants.NT_OAK_UNSTRUCTURED); testRoot.commit(); } } @Test public void testRemoveTree() { Root testRoot = testSession.getLatestRoot(); List<String> paths = ImmutableList.of("/a/d/b/e/c", "/a/d/b", "/a"); for (String p : paths) { try { testRoot.getTree(p).remove(); testRoot.commit(); fail(); } catch (CommitFailedException e) { // success assertTrue(e.isAccessViolation()); } finally { testRoot.refresh(); } } } @Test(expected = CommitFailedException.class) public void testRemoveTree2() throws Exception { AccessControlManager acMgr = getAccessControlManager(root); JackrabbitAccessControlList acl = AccessControlUtils.getAccessControlList(acMgr, "/a"); acl.addEntry(testPrincipal, privilegesFromNames(PrivilegeConstants.JCR_READ, PrivilegeConstants.JCR_REMOVE_CHILD_NODES), true); acMgr.setPolicy(acl.getPath(), acl); root.commit(); Root testRoot = testSession.getLatestRoot(); List<String> paths = ImmutableList.of("/a/d/b/e/c", "/a/d/b"); for (String p : paths) { testRoot.getTree(p).remove(); testRoot.commit(); } try { testRoot.getTree("/a").remove(); testRoot.commit(); } catch (CommitFailedException e) { // success assertTrue(e.isAccessViolation()); throw e; } } @Test public void testModifyMembersOnly() throws Exception { AccessControlManager acMgr = getAccessControlManager(root); String path = PathUtils.getAncestorPath(UserConstants.DEFAULT_USER_PATH, 1); try { JackrabbitAccessControlList acl = AccessControlUtils.getAccessControlList(acMgr, path); acl.addEntry(testPrincipal, privilegesFromNames(PrivilegeConstants.JCR_READ), true); acl.addEntry(testPrincipal, privilegesFromNames(PrivilegeConstants.REP_USER_MANAGEMENT), true, Collections.<String,Value>emptyMap(), ImmutableMap.<String,Value[]>of (AccessControlConstants.REP_ITEM_NAMES, new Value[] { vf.createValue(UserConstants.REP_MEMBERS, PropertyType.NAME)})); acMgr.setPolicy(acl.getPath(), acl); root.commit(); Root testRoot = testSession.getLatestRoot(); UserManager uMgr = getUserManager(testRoot); // adding a group member must succeed Group gr = uMgr.getAuthorizable(testGroup.getID(), Group.class); User u = uMgr.getAuthorizable(getTestUser().getID(), User.class); gr.addMember(u); testRoot.commit(); // changing the pw property of the test user must fail try { u.changePassword("blub"); testRoot.commit(); fail(); } catch (CommitFailedException e) { // success assertTrue(e.isAccessViolation()); } finally { testRoot.refresh(); } } catch (CommitFailedException e) { // success assertTrue(e.isAccessViolation()); } finally { JackrabbitAccessControlList acl = AccessControlUtils.getAccessControlList(acMgr, path); if (acl != null) { acMgr.removePolicy(acl.getPath(), acl); root.commit(); } } } }
apache-2.0
sauravvishal8797/hawkular-android-client
mobile/src/androidTest/java/org/hawkular/client/android/adapter/PersonasAdapterTester.java
2383
/* * Copyright 2015-2017 Red Hat, Inc. and/or its affiliates * and other contributors as indicated by the @author tags. * * 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.hawkular.client.android.adapter; import java.util.ArrayList; import java.util.List; import org.assertj.android.api.Assertions; import org.hawkular.client.android.backend.model.Persona; import org.hawkular.client.android.util.Randomizer; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import android.content.Context; import android.support.test.InstrumentationRegistry; import android.support.test.runner.AndroidJUnit4; @RunWith(AndroidJUnit4.class) public final class PersonasAdapterTester { private Context context; @Before public void setUp() { context = InstrumentationRegistry.getTargetContext(); } @Test public void count() { List<Persona> personas = generatePersonas(); PersonasAdapter personasAdapter = new PersonasAdapter(context, personas); Assertions.assertThat(personasAdapter).hasCount(personas.size()); } @Test public void item() { Persona persona = generatePersona(); List<Persona> personas = new ArrayList<>(); personas.add(persona); personas.addAll(generatePersonas()); PersonasAdapter personasAdapter = new PersonasAdapter(context, personas); Assertions.assertThat(personasAdapter).hasItem(persona, 0); } private List<Persona> generatePersonas() { List<Persona> personas = new ArrayList<>(); for (int personaPosition = 0; personaPosition < Randomizer.generateNumber(); personaPosition++) { personas.add(generatePersona()); } return personas; } private Persona generatePersona() { return new Persona(Randomizer.generateString()); } }
apache-2.0
ingokegel/intellij-community
plugins/git4idea/src/git4idea/GitReference.java
1806
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package git4idea; import com.intellij.openapi.util.NlsSafe; import com.intellij.openapi.util.SystemInfo; import com.intellij.openapi.util.text.StringUtil; import com.intellij.util.text.FilePathHashingStrategy; import gnu.trove.TObjectHashingStrategy; import org.jetbrains.annotations.NotNull; /** * The base class for named git references, like branches and tags. */ public abstract class GitReference implements Comparable<GitReference> { public static final TObjectHashingStrategy<String> BRANCH_NAME_HASHING_STRATEGY = FilePathHashingStrategy.create(); @NotNull protected final String myName; public GitReference(@NotNull String name) { myName = name; } /** * @return the name of the reference, e.g. "origin/master" or "feature". * @see #getFullName() */ @NlsSafe @NotNull public String getName() { return myName; } /** * @return the full name of the reference, e.g. "refs/remotes/origin/master" or "refs/heads/master". */ @NlsSafe @NotNull public abstract String getFullName(); @Override public String toString() { return getFullName(); } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; GitReference reference = (GitReference)o; return BRANCH_NAME_HASHING_STRATEGY.equals(myName, reference.myName); } @Override public int hashCode() { return BRANCH_NAME_HASHING_STRATEGY.computeHashCode(myName); } @Override public int compareTo(GitReference o) { return o == null ? 1 : StringUtil.compare(getFullName(), o.getFullName(), SystemInfo.isFileSystemCaseSensitive); } }
apache-2.0
ctripcorp/hermes
hermes-kafka/src/test/java/com/ctrip/hermes/kafka/producer/ProducerTest.java
3770
package com.ctrip.hermes.kafka.producer; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ExecutionException; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import com.ctrip.hermes.core.result.CompletionCallback; import com.ctrip.hermes.core.result.SendResult; import com.ctrip.hermes.core.utils.PlexusComponentLocator; import com.ctrip.hermes.kafka.server.MockKafkaCluster; import com.ctrip.hermes.kafka.server.MockZookeeper; import com.ctrip.hermes.meta.entity.Endpoint; import com.ctrip.hermes.producer.api.Producer; import com.ctrip.hermes.producer.api.Producer.MessageHolder; import com.ctrip.hermes.producer.sender.MessageSender; public class ProducerTest { private static MockZookeeper zk; private static MockKafkaCluster kafkaCluster; private static String topic = "kafka.SimpleTextTopic5"; @BeforeClass public static void beforeClass() { zk = new MockZookeeper(); kafkaCluster = new MockKafkaCluster(zk, 3); kafkaCluster.createTopic(topic, 3, 1); } @AfterClass public static void afterClass() { KafkaMessageSender kafkaSender = (KafkaMessageSender) PlexusComponentLocator.lookup(MessageSender.class, Endpoint.KAFKA); kafkaSender.close(); kafkaCluster.stop(); zk.stop(); } @Test public void producerSyncTest() throws InterruptedException, ExecutionException { List<String> expected = new ArrayList<String>(); expected.add("msg1"); expected.add("msg2"); expected.add("msg3"); expected.add("msg4"); expected.add("msg5"); expected.add("msg6"); List<SendResult> sendResults = new ArrayList<SendResult>(); Producer producer = Producer.getInstance(); for (int i = 0; i < expected.size(); i++) { String proMsg = expected.get(i); MessageHolder holder = producer.message(topic, String.valueOf(i), proMsg); if (System.currentTimeMillis() % 2 == 0) { holder = holder.withPriority(); } holder = holder.withRefKey(String.valueOf(i)); KafkaFuture future = (KafkaFuture) holder.send(); KafkaSendResult result = future.get(); Assert.assertTrue(future.isDone()); sendResults.add(result); System.out.println(String.format("Sent:%s, Topic:%s, Partition:%s, Offset:%s", proMsg, result.getTopic(), result.getPartition(), result.getOffset())); } Assert.assertEquals(expected.size(), sendResults.size()); } @Test public void producerWithCallbackTest() throws InterruptedException, ExecutionException { List<String> expected = new ArrayList<String>(); expected.add("msg1"); expected.add("msg2"); expected.add("msg3"); expected.add("msg4"); expected.add("msg5"); expected.add("msg6"); final List<SendResult> sendResults = new ArrayList<SendResult>(); Producer producer = Producer.getInstance(); for (int i = 0; i < expected.size(); i++) { String proMsg = expected.get(i); MessageHolder holder = producer.message(topic, String.valueOf(i), proMsg); holder.setCallback(new CompletionCallback<SendResult>() { @Override public void onSuccess(SendResult sendResult) { if (sendResult instanceof KafkaSendResult) { KafkaSendResult result = (KafkaSendResult) sendResult; sendResults.add(result); } } @Override public void onFailure(Throwable t) { } }); if (System.currentTimeMillis() % 2 == 0) { holder = holder.withPriority(); } holder = holder.withRefKey(String.valueOf(i)); KafkaFuture future = (KafkaFuture) holder.send(); KafkaSendResult result = future.get(); Assert.assertTrue(future.isDone()); System.out.println(String.format("Sent:%s, Topic:%s, Partition:%s, Offset:%s", proMsg, result.getTopic(), result.getPartition(), result.getOffset())); } } }
apache-2.0
struberg/deltaspike
deltaspike/modules/test-control/impl/src/test/java/org/apache/deltaspike/test/testcontrol/uc015/GlobalAlternativeTestService.java
1146
/* * 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.deltaspike.test.testcontrol.uc015; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.inject.Alternative; @Alternative @ApplicationScoped public class GlobalAlternativeTestService implements TestService { @Override public String getValue() { return "alternative-result"; } }
apache-2.0
alexksikes/elasticsearch
src/main/java/org/elasticsearch/index/mapper/geo/GeoShapeFieldMapper.java
12604
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.index.mapper.geo; import org.apache.lucene.document.Field; import org.apache.lucene.document.FieldType; import org.apache.lucene.index.FieldInfo; import org.apache.lucene.spatial.prefix.PrefixTreeStrategy; import org.apache.lucene.spatial.prefix.RecursivePrefixTreeStrategy; import org.apache.lucene.spatial.prefix.TermQueryPrefixTreeStrategy; import org.apache.lucene.spatial.prefix.tree.GeohashPrefixTree; import org.apache.lucene.spatial.prefix.tree.QuadPrefixTree; import org.apache.lucene.spatial.prefix.tree.SpatialPrefixTree; import org.elasticsearch.ElasticsearchIllegalArgumentException; import org.elasticsearch.common.Strings; import org.elasticsearch.common.geo.GeoUtils; import org.elasticsearch.common.geo.SpatialStrategy; import org.elasticsearch.common.geo.builders.ShapeBuilder; import org.elasticsearch.common.unit.DistanceUnit; import org.elasticsearch.common.xcontent.XContentBuilder; import org.elasticsearch.index.codec.docvaluesformat.DocValuesFormatProvider; import org.elasticsearch.index.codec.postingsformat.PostingsFormatProvider; import org.elasticsearch.index.fielddata.FieldDataType; import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.index.mapper.Mapper; import org.elasticsearch.index.mapper.MapperParsingException; import org.elasticsearch.index.mapper.ParseContext; import org.elasticsearch.index.mapper.core.AbstractFieldMapper; import java.io.IOException; import java.util.List; import java.util.Map; import static org.elasticsearch.index.mapper.MapperBuilders.geoShapeField; /** * FieldMapper for indexing {@link com.spatial4j.core.shape.Shape}s. * <p/> * Currently Shapes can only be indexed and can only be queried using * {@link org.elasticsearch.index.query.GeoShapeFilterParser}, consequently * a lot of behavior in this Mapper is disabled. * <p/> * Format supported: * <p/> * "field" : { * "type" : "polygon", * "coordinates" : [ * [ [100.0, 0.0], [101.0, 0.0], [101.0, 1.0], [100.0, 1.0], [100.0, 0.0] ] * ] * } */ public class GeoShapeFieldMapper extends AbstractFieldMapper<String> { public static final String CONTENT_TYPE = "geo_shape"; public static class Names { public static final String TREE = "tree"; public static final String TREE_GEOHASH = "geohash"; public static final String TREE_QUADTREE = "quadtree"; public static final String TREE_LEVELS = "tree_levels"; public static final String TREE_PRESISION = "precision"; public static final String DISTANCE_ERROR_PCT = "distance_error_pct"; public static final String STRATEGY = "strategy"; } public static class Defaults { public static final String TREE = Names.TREE_GEOHASH; public static final String STRATEGY = SpatialStrategy.RECURSIVE.getStrategyName(); public static final int GEOHASH_LEVELS = GeoUtils.geoHashLevelsForPrecision("50m"); public static final int QUADTREE_LEVELS = GeoUtils.quadTreeLevelsForPrecision("50m"); public static final double DISTANCE_ERROR_PCT = 0.025d; public static final FieldType FIELD_TYPE = new FieldType(); static { FIELD_TYPE.setIndexed(true); FIELD_TYPE.setTokenized(false); FIELD_TYPE.setStored(false); FIELD_TYPE.setStoreTermVectors(false); FIELD_TYPE.setOmitNorms(true); FIELD_TYPE.setIndexOptions(FieldInfo.IndexOptions.DOCS_ONLY); FIELD_TYPE.freeze(); } } public static class Builder extends AbstractFieldMapper.Builder<Builder, GeoShapeFieldMapper> { private String tree = Defaults.TREE; private String strategyName = Defaults.STRATEGY; private int treeLevels = 0; private double precisionInMeters = -1; private double distanceErrorPct = Defaults.DISTANCE_ERROR_PCT; private SpatialPrefixTree prefixTree; public Builder(String name) { super(name, new FieldType(Defaults.FIELD_TYPE)); } public Builder tree(String tree) { this.tree = tree; return this; } public Builder strategy(String strategy) { this.strategyName = strategy; return this; } public Builder treeLevelsByDistance(double meters) { this.precisionInMeters = meters; return this; } public Builder treeLevels(int treeLevels) { this.treeLevels = treeLevels; return this; } public Builder distanceErrorPct(double distanceErrorPct) { this.distanceErrorPct = distanceErrorPct; return this; } @Override public GeoShapeFieldMapper build(BuilderContext context) { final FieldMapper.Names names = buildNames(context); if (Names.TREE_GEOHASH.equals(tree)) { prefixTree = new GeohashPrefixTree(ShapeBuilder.SPATIAL_CONTEXT, getLevels(treeLevels, precisionInMeters, Defaults.GEOHASH_LEVELS, true)); } else if (Names.TREE_QUADTREE.equals(tree)) { prefixTree = new QuadPrefixTree(ShapeBuilder.SPATIAL_CONTEXT, getLevels(treeLevels, precisionInMeters, Defaults.QUADTREE_LEVELS, false)); } else { throw new ElasticsearchIllegalArgumentException("Unknown prefix tree type [" + tree + "]"); } return new GeoShapeFieldMapper(names, prefixTree, strategyName, distanceErrorPct, fieldType, postingsProvider, docValuesProvider, multiFieldsBuilder.build(this, context), copyTo); } } private static final int getLevels(int treeLevels, double precisionInMeters, int defaultLevels, boolean geoHash) { if (treeLevels > 0 || precisionInMeters >= 0) { return Math.max(treeLevels, precisionInMeters >= 0 ? (geoHash ? GeoUtils.geoHashLevelsForPrecision(precisionInMeters) : GeoUtils.quadTreeLevelsForPrecision(precisionInMeters)) : 0); } return defaultLevels; } public static class TypeParser implements Mapper.TypeParser { @Override public Mapper.Builder parse(String name, Map<String, Object> node, ParserContext parserContext) throws MapperParsingException { Builder builder = geoShapeField(name); for (Map.Entry<String, Object> entry : node.entrySet()) { String fieldName = Strings.toUnderscoreCase(entry.getKey()); Object fieldNode = entry.getValue(); if (Names.TREE.equals(fieldName)) { builder.tree(fieldNode.toString()); } else if (Names.TREE_LEVELS.equals(fieldName)) { builder.treeLevels(Integer.parseInt(fieldNode.toString())); } else if (Names.TREE_PRESISION.equals(fieldName)) { builder.treeLevelsByDistance(DistanceUnit.parse(fieldNode.toString(), DistanceUnit.DEFAULT, DistanceUnit.DEFAULT)); } else if (Names.DISTANCE_ERROR_PCT.equals(fieldName)) { builder.distanceErrorPct(Double.parseDouble(fieldNode.toString())); } else if (Names.STRATEGY.equals(fieldName)) { builder.strategy(fieldNode.toString()); } } return builder; } } private final PrefixTreeStrategy defaultStrategy; private final RecursivePrefixTreeStrategy recursiveStrategy; private final TermQueryPrefixTreeStrategy termStrategy; public GeoShapeFieldMapper(FieldMapper.Names names, SpatialPrefixTree tree, String defaultStrategyName, double distanceErrorPct, FieldType fieldType, PostingsFormatProvider postingsProvider, DocValuesFormatProvider docValuesProvider, MultiFields multiFields, CopyTo copyTo) { super(names, 1, fieldType, null, null, null, postingsProvider, docValuesProvider, null, null, null, null, multiFields, copyTo); this.recursiveStrategy = new RecursivePrefixTreeStrategy(tree, names.indexName()); this.recursiveStrategy.setDistErrPct(distanceErrorPct); this.termStrategy = new TermQueryPrefixTreeStrategy(tree, names.indexName()); this.termStrategy.setDistErrPct(distanceErrorPct); this.defaultStrategy = resolveStrategy(defaultStrategyName); } @Override public FieldType defaultFieldType() { return Defaults.FIELD_TYPE; } @Override public FieldDataType defaultFieldDataType() { return null; } @Override public boolean hasDocValues() { return false; } @Override public void parse(ParseContext context) throws IOException { try { ShapeBuilder shape = ShapeBuilder.parse(context.parser()); if (shape == null) { return; } Field[] fields = defaultStrategy.createIndexableFields(shape.build()); if (fields == null || fields.length == 0) { return; } for (Field field : fields) { if (!customBoost()) { field.setBoost(boost); } if (context.listener().beforeFieldAdded(this, field, context)) { context.doc().add(field); } } } catch (Exception e) { throw new MapperParsingException("failed to parse [" + names.fullName() + "]", e); } } @Override protected void parseCreateField(ParseContext context, List<Field> fields) throws IOException { } @Override protected void doXContentBody(XContentBuilder builder, boolean includeDefaults, Params params) throws IOException { builder.field("type", contentType()); // TODO: Come up with a better way to get the name, maybe pass it from builder if (defaultStrategy.getGrid() instanceof GeohashPrefixTree) { // Don't emit the tree name since GeohashPrefixTree is the default // Only emit the tree levels if it isn't the default value if (includeDefaults || defaultStrategy.getGrid().getMaxLevels() != Defaults.GEOHASH_LEVELS) { builder.field(Names.TREE_LEVELS, defaultStrategy.getGrid().getMaxLevels()); } } else { builder.field(Names.TREE, Names.TREE_QUADTREE); if (includeDefaults || defaultStrategy.getGrid().getMaxLevels() != Defaults.QUADTREE_LEVELS) { builder.field(Names.TREE_LEVELS, defaultStrategy.getGrid().getMaxLevels()); } } if (includeDefaults || defaultStrategy.getDistErrPct() != Defaults.DISTANCE_ERROR_PCT) { builder.field(Names.DISTANCE_ERROR_PCT, defaultStrategy.getDistErrPct()); } } @Override protected String contentType() { return CONTENT_TYPE; } @Override public String value(Object value) { throw new UnsupportedOperationException("GeoShape fields cannot be converted to String values"); } public PrefixTreeStrategy defaultStrategy() { return this.defaultStrategy; } public PrefixTreeStrategy recursiveStrategy() { return this.recursiveStrategy; } public PrefixTreeStrategy termStrategy() { return this.termStrategy; } public PrefixTreeStrategy resolveStrategy(String strategyName) { if (SpatialStrategy.RECURSIVE.getStrategyName().equals(strategyName)) { return recursiveStrategy; } if (SpatialStrategy.TERM.getStrategyName().equals(strategyName)) { return termStrategy; } throw new ElasticsearchIllegalArgumentException("Unknown prefix tree strategy [" + strategyName + "]"); } }
apache-2.0
SaiNadh001/aws-sdk-for-java
src/main/java/com/amazonaws/services/cloudwatch/model/transform/EnableAlarmActionsRequestMarshaller.java
2123
/* * Copyright 2010-2012 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.cloudwatch.model.transform; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.services.cloudwatch.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * Enable Alarm Actions Request Marshaller */ public class EnableAlarmActionsRequestMarshaller implements Marshaller<Request<EnableAlarmActionsRequest>, EnableAlarmActionsRequest> { public Request<EnableAlarmActionsRequest> marshall(EnableAlarmActionsRequest enableAlarmActionsRequest) { if (enableAlarmActionsRequest == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } Request<EnableAlarmActionsRequest> request = new DefaultRequest<EnableAlarmActionsRequest>(enableAlarmActionsRequest, "AmazonCloudWatch"); request.addParameter("Action", "EnableAlarmActions"); request.addParameter("Version", "2010-08-01"); java.util.List<String> alarmNamesList = enableAlarmActionsRequest.getAlarmNames(); int alarmNamesListIndex = 1; for (String alarmNamesListValue : alarmNamesList) { if (alarmNamesListValue != null) { request.addParameter("AlarmNames.member." + alarmNamesListIndex, StringUtils.fromString(alarmNamesListValue)); } alarmNamesListIndex++; } return request; } }
apache-2.0
SaiNadh001/aws-sdk-for-java
src/main/java/com/amazonaws/services/simpleemail/model/transform/GetIdentityDkimAttributesRequestMarshaller.java
2225
/* * Copyright 2010-2012 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.simpleemail.model.transform; import java.util.HashMap; import java.util.List; import java.util.Map; import com.amazonaws.AmazonClientException; import com.amazonaws.Request; import com.amazonaws.DefaultRequest; import com.amazonaws.services.simpleemail.model.*; import com.amazonaws.transform.Marshaller; import com.amazonaws.util.StringUtils; /** * Get Identity Dkim Attributes Request Marshaller */ public class GetIdentityDkimAttributesRequestMarshaller implements Marshaller<Request<GetIdentityDkimAttributesRequest>, GetIdentityDkimAttributesRequest> { public Request<GetIdentityDkimAttributesRequest> marshall(GetIdentityDkimAttributesRequest getIdentityDkimAttributesRequest) { if (getIdentityDkimAttributesRequest == null) { throw new AmazonClientException("Invalid argument passed to marshall(...)"); } Request<GetIdentityDkimAttributesRequest> request = new DefaultRequest<GetIdentityDkimAttributesRequest>(getIdentityDkimAttributesRequest, "AmazonSimpleEmailService"); request.addParameter("Action", "GetIdentityDkimAttributes"); request.addParameter("Version", "2010-12-01"); java.util.List<String> identitiesList = getIdentityDkimAttributesRequest.getIdentities(); int identitiesListIndex = 1; for (String identitiesListValue : identitiesList) { if (identitiesListValue != null) { request.addParameter("Identities.member." + identitiesListIndex, StringUtils.fromString(identitiesListValue)); } identitiesListIndex++; } return request; } }
apache-2.0
ricepanda/rice-git2
rice-framework/krad-web-framework/src/main/java/org/kuali/rice/krad/web/controller/UifControllerBase.java
19041
/** * 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.krad.web.controller; import org.kuali.rice.krad.uif.UifConstants; import org.kuali.rice.krad.uif.field.AttributeQueryResult; import org.kuali.rice.krad.util.GlobalVariables; import org.kuali.rice.krad.web.form.UifFormBase; import org.kuali.rice.krad.web.service.CollectionControllerService; import org.kuali.rice.krad.web.service.ControllerService; import org.kuali.rice.krad.web.service.FileControllerService; import org.kuali.rice.krad.web.service.ModelAndViewService; import org.kuali.rice.krad.web.service.NavigationControllerService; import org.kuali.rice.krad.web.service.QueryControllerService; import org.kuali.rice.krad.web.service.RefreshControllerService; import org.kuali.rice.krad.web.service.SaveControllerService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.Map; import java.util.Properties; /** * Base controller class for views within the KRAD User Interface Framework. * * <p>Provides common methods such as navigation, collection handling, queries, and refresh calls. * * All subclass controller methods after processing should call one of the #getModelAndView methods to * setup the {@link org.kuali.rice.krad.uif.view.View} and return the {@link org.springframework.web.servlet.ModelAndView} * instance.</p> * * @author Kuali Rice Team (rice.collab@kuali.org) */ public abstract class UifControllerBase { @Autowired private ControllerService controllerService; @Autowired private NavigationControllerService navigationControllerService; @Autowired private CollectionControllerService collectionControllerService; @Autowired private SaveControllerService saveControllerService; @Autowired private RefreshControllerService refreshControllerService; @Autowired private QueryControllerService queryControllerService; @Autowired private FileControllerService fileControllerService; @Autowired private ModelAndViewService modelAndViewService; /** * Creates form instance the will be used for the default model. * * @return UifFormBase form instance for holding model data */ @ModelAttribute(value = UifConstants.DEFAULT_MODEL_NAME) protected UifFormBase initForm() { return createInitialForm(); } /** * Invoked to create a new form instance for the request before it is passed to the Binder/BeanWrapper. * * @return UifFormBase instance that will be used for data binding and backing the view. */ protected abstract UifFormBase createInitialForm(); /** * Default method mapping for cases where the method to call is not passed, calls the start method. */ @RequestMapping() public ModelAndView defaultMapping(UifFormBase form) { return start(form); } /** * @see org.kuali.rice.krad.web.service.ControllerService#start(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.GET, params = "methodToCall=start") public ModelAndView start(UifFormBase form) { return getControllerService().start(form); } /** * @see org.kuali.rice.krad.web.service.ControllerService#sessionTimeout(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(params = "methodToCall=sessionTimeout") public ModelAndView sessionTimeout(UifFormBase form) { return getControllerService().sessionTimeout(form); } /** * @see org.kuali.rice.krad.web.service.ControllerService#cancel(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(params = "methodToCall=cancel") public ModelAndView cancel(UifFormBase form) { return getControllerService().cancel(form); } /** * @see org.kuali.rice.krad.web.service.NavigationControllerService#back(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(params = "methodToCall=back") public ModelAndView back(UifFormBase form) { return getNavigationControllerService().back(form); } /** * @see org.kuali.rice.krad.web.service.NavigationControllerService#returnToPrevious(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(params = "methodToCall=returnToPrevious") public ModelAndView returnToPrevious(UifFormBase form) { return getNavigationControllerService().returnToPrevious(form); } /** * @see org.kuali.rice.krad.web.service.SaveControllerService#save(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=save") public ModelAndView save(UifFormBase form) throws Exception{ // Hook method for saving the form return getSaveControllerService().save(form); } /** * @see org.kuali.rice.krad.web.service.SaveControllerService#saveField(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=saveField") public ModelAndView saveField(UifFormBase form) throws Exception{ // Hook method for saving individual fields return getSaveControllerService().saveField(form); } /** * @see org.kuali.rice.krad.web.service.NavigationControllerService#returnToHub(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(params = "methodToCall=returnToHub") public ModelAndView returnToHub(UifFormBase form) { return getNavigationControllerService().returnToHub(form); } /** * @see org.kuali.rice.krad.web.service.FileControllerService#addFileUploadLine(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=addFileUploadLine") public ModelAndView addFileUploadLine(UifFormBase form) { return getFileControllerService().addFileUploadLine(form); } /** * @see org.kuali.rice.krad.web.service.FileControllerService#deleteFileUploadLine(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=deleteFileUploadLine") public ModelAndView deleteFileUploadLine(UifFormBase form) { return getFileControllerService().deleteFileUploadLine(form); } /** * @see org.kuali.rice.krad.web.service.FileControllerService#getFileFromLine(org.kuali.rice.krad.web.form.UifFormBase, * javax.servlet.http.HttpServletResponse) */ @RequestMapping(method = RequestMethod.GET, params = "methodToCall=getFileFromLine") public void getFileFromLine(UifFormBase form, HttpServletResponse response) { getFileControllerService().getFileFromLine(form, response); } /** * @see org.kuali.rice.krad.web.service.NavigationControllerService#navigate(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=navigate") public ModelAndView navigate(UifFormBase form) { return getNavigationControllerService().navigate(form); } /** * @see org.kuali.rice.krad.web.service.CollectionControllerService#addLine(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=addLine") public ModelAndView addLine(UifFormBase form) { return getCollectionControllerService().addLine(form); } /** * @see org.kuali.rice.krad.web.service.CollectionControllerService#addBlankLine(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=addBlankLine") public ModelAndView addBlankLine(UifFormBase form) { return getCollectionControllerService().addBlankLine(form); } /** * @see org.kuali.rice.krad.web.service.CollectionControllerService#retrieveEditLineDialog(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=retrieveEditLineDialog") public ModelAndView retrieveEditLineDialog(UifFormBase form) { return getCollectionControllerService().retrieveEditLineDialog(form); } /** * @see org.kuali.rice.krad.web.service.CollectionControllerService#editLine(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=editLine") public ModelAndView editLine(UifFormBase form) { return getCollectionControllerService().editLine(form); } /** * @see org.kuali.rice.krad.web.service.CollectionControllerService#closeEditLineDialog(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=closeEditLineDialog") public ModelAndView closeEditLineDialog(UifFormBase form) { return getCollectionControllerService().closeEditLineDialog(form); } /** * @see org.kuali.rice.krad.web.service.CollectionControllerService#saveLine(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=saveLine") public ModelAndView saveLine(UifFormBase form) { return getCollectionControllerService().saveLine(form); } /** * @see org.kuali.rice.krad.web.service.CollectionControllerService#deleteLine(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=deleteLine") public ModelAndView deleteLine(final UifFormBase form) { return getCollectionControllerService().deleteLine(form); } /** * @see org.kuali.rice.krad.web.service.CollectionControllerService#retrieveCollectionPage(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(params = "methodToCall=retrieveCollectionPage") public ModelAndView retrieveCollectionPage(UifFormBase form) { return getCollectionControllerService().retrieveCollectionPage(form); } /** * @see org.kuali.rice.krad.web.service.CollectionControllerService#tableJsonRetrieval(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.GET, params = "methodToCall=tableJsonRetrieval") public ModelAndView tableJsonRetrieval(UifFormBase form) { return getCollectionControllerService().tableJsonRetrieval(form); } /** * @see org.kuali.rice.krad.web.service.RefreshControllerService#refresh(org.kuali.rice.krad.web.form.UifFormBase) */ @MethodAccessible @RequestMapping(params = "methodToCall=refresh") public ModelAndView refresh(UifFormBase form) { return getRefreshControllerService().refresh(form); } /** * @see org.kuali.rice.krad.web.service.QueryControllerService#performLookup(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=performLookup") public ModelAndView performLookup(UifFormBase form) { return getQueryControllerService().performLookup(form); } /** * @see org.kuali.rice.krad.web.service.QueryControllerService#performFieldSuggest(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.GET, params = "methodToCall=performFieldSuggest") @ResponseBody public AttributeQueryResult performFieldSuggest(UifFormBase form) { return getQueryControllerService().performFieldSuggest(form); } /** * @see org.kuali.rice.krad.web.service.QueryControllerService#performFieldQuery(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.GET, params = "methodToCall=performFieldQuery") @ResponseBody public AttributeQueryResult performFieldQuery(UifFormBase form) { return getQueryControllerService().performFieldQuery(form); } /** * @see org.kuali.rice.krad.web.service.ModelAndViewService#checkForm(org.kuali.rice.krad.web.form.UifFormBase) */ @RequestMapping(method = RequestMethod.POST, params = "methodToCall=checkForm") public ModelAndView checkForm(UifFormBase form) { return getModelAndViewService().checkForm(form); } /** * @see org.kuali.rice.krad.web.service.ModelAndViewService#showDialog(java.lang.String, boolean, * org.kuali.rice.krad.web.form.UifFormBase) */ protected ModelAndView showDialog(String dialogId, boolean confirmation, UifFormBase form) { return getModelAndViewService().showDialog(dialogId, confirmation, form); } /** * @see org.kuali.rice.krad.web.service.ModelAndViewService#performRedirect(org.kuali.rice.krad.web.form.UifFormBase, * java.lang.String, java.util.Properties) */ protected ModelAndView performRedirect(UifFormBase form, String baseUrl, Properties urlParameters) { return getModelAndViewService().performRedirect(form, baseUrl, urlParameters); } /** * @see org.kuali.rice.krad.web.service.ModelAndViewService#performRedirect(org.kuali.rice.krad.web.form.UifFormBase, * java.lang.String) */ protected ModelAndView performRedirect(UifFormBase form, String redirectUrl) { return getModelAndViewService().performRedirect(form, redirectUrl); } /** * @see org.kuali.rice.krad.web.service.ModelAndViewService#getMessageView(org.kuali.rice.krad.web.form.UifFormBase, * java.lang.String, java.lang.String) */ protected ModelAndView getMessageView(UifFormBase form, String headerText, String messageText) { return getModelAndViewService().getMessageView(form, headerText, messageText); } /** * @see org.kuali.rice.krad.web.service.ModelAndViewService#getModelAndView(org.kuali.rice.krad.web.form.UifFormBase) */ protected ModelAndView getModelAndView(UifFormBase form) { return getModelAndViewService().getModelAndView(form); } /** * @see org.kuali.rice.krad.web.service.ModelAndViewService#getModelAndView(org.kuali.rice.krad.web.form.UifFormBase, * java.lang.String) */ protected ModelAndView getModelAndView(UifFormBase form, String pageId) { return getModelAndViewService().getModelAndView(form, pageId); } /** * @see org.kuali.rice.krad.web.service.ModelAndViewService#getModelAndView(org.kuali.rice.krad.web.form.UifFormBase, * java.util.Map<java.lang.String,java.lang.Object>) */ protected ModelAndView getModelAndView(UifFormBase form, Map<String, Object> additionalViewAttributes) { return getModelAndViewService().getModelAndView(form, additionalViewAttributes); } /** * @see org.kuali.rice.krad.web.service.ModelAndViewService#getModelAndViewWithInit(org.kuali.rice.krad.web.form.UifFormBase, * java.lang.String) */ protected ModelAndView getModelAndViewWithInit(UifFormBase form, String viewId) { return getModelAndViewService().getModelAndViewWithInit(form, viewId); } /** * @see org.kuali.rice.krad.web.service.ModelAndViewService#getModelAndViewWithInit(org.kuali.rice.krad.web.form.UifFormBase, * java.lang.String, java.lang.String) */ protected ModelAndView getModelAndViewWithInit(UifFormBase form, String viewId, String pageId) { return getModelAndViewService().getModelAndViewWithInit(form, viewId, pageId); } protected ControllerService getControllerService() { return controllerService; } public void setControllerService(ControllerService controllerService) { this.controllerService = controllerService; } protected NavigationControllerService getNavigationControllerService() { return navigationControllerService; } public void setNavigationControllerService(NavigationControllerService navigationControllerService) { this.navigationControllerService = navigationControllerService; } protected CollectionControllerService getCollectionControllerService() { return collectionControllerService; } public void setCollectionControllerService(CollectionControllerService collectionControllerService) { this.collectionControllerService = collectionControllerService; } protected RefreshControllerService getRefreshControllerService() { return refreshControllerService; } public void setRefreshControllerService(RefreshControllerService refreshControllerService) { this.refreshControllerService = refreshControllerService; } public SaveControllerService getSaveControllerService() { return saveControllerService; } public void setSaveControllerService(SaveControllerService saveControllerService) { this.saveControllerService = saveControllerService; } protected QueryControllerService getQueryControllerService() { return queryControllerService; } public void setQueryControllerService(QueryControllerService queryControllerService) { this.queryControllerService = queryControllerService; } protected FileControllerService getFileControllerService() { return fileControllerService; } public void setFileControllerService(FileControllerService fileControllerService) { this.fileControllerService = fileControllerService; } protected ModelAndViewService getModelAndViewService() { return modelAndViewService; } public void setModelAndViewService(ModelAndViewService modelAndViewService) { this.modelAndViewService = modelAndViewService; } }
apache-2.0
VivianLuwenHuangfu/processors
src/main/java/org/maltparserx/core/io/dataformat/DataFormatEntry.java
3925
package org.maltparserx.core.io.dataformat; /** * DataFormatEntry is used for storing information about one column in a data format. * * @author Johan Hall * @since 1.0 **/ public class DataFormatEntry { /** Column name */ private String dataFormatEntryName; /** Column category (INPUT, HEAD, DEPENDENCY_EDGE_LABEL, PHRASE_STRUCTURE_EDGE_LABEL, PHRASE_STRUCTURE_NODE_LABEL, SECONDARY_EDGE_LABEL, IGNORE and INTERNAL) */ private String category; /** Column type (STRING, INTEGER, BOOLEAN, REAL) */ private String type; /** Default output for a ignore column */ private String defaultOutput; /** Cache the hash code for the data format entry */ private int cachedHash; /** * Creates a data format entry * * @param dataFormatEntryName column name * @param category column category * @param type column type * @param defaultOutput default output for a ignore column */ public DataFormatEntry(String dataFormatEntryName, String category, String type, String defaultOutput) { setDataFormatEntryName(dataFormatEntryName); setCategory(category); setType(type); setDefaultOutput(defaultOutput); } /** * Returns the column name * @return the column name */ public String getDataFormatEntryName() { return dataFormatEntryName; } /** * Sets the column name * @param dataFormatEntryName column name */ public void setDataFormatEntryName(String dataFormatEntryName) { this.dataFormatEntryName = dataFormatEntryName.toUpperCase(); } /** * Returns the column category * * @return the column category */ public String getCategory() { return category; } /** * Sets the column category * * @param category the column category */ public void setCategory(String category) { this.category = category.toUpperCase(); } /** * Return the column type * * @return the column type */ public String getType() { return type; } /** * Sets the column type * * @param type the column type */ public void setType(String type) { this.type = type.toUpperCase(); } /** * Returns the default output of an ignore column * * @return the default output of an ignore column */ public String getDefaultOutput() { return defaultOutput; } /** * Sets the default output of an ignore column * * @param defaultOutput the default output of an ignore column */ public void setDefaultOutput(String defaultOutput) { this.defaultOutput = defaultOutput; } public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; DataFormatEntry objC = (DataFormatEntry)obj; return ((dataFormatEntryName == null) ? objC.dataFormatEntryName == null : dataFormatEntryName.equals(objC.dataFormatEntryName)) && ((type == null) ? objC.type == null : type.equals(objC.type)) && ((category == null) ? objC.category == null : category.equals(objC.category)) && ((defaultOutput == null) ? objC.defaultOutput == null : defaultOutput.equals(objC.defaultOutput)); } public int hashCode() { if (cachedHash == 0) { int hash = 7; hash = 31 * hash + (null == dataFormatEntryName ? 0 : dataFormatEntryName.hashCode()); hash = 31 * hash + (null == type ? 0 : type.hashCode()); hash = 31 * hash + (null == category ? 0 : category.hashCode()); hash = 31 * hash + (null == defaultOutput ? 0 : defaultOutput.hashCode()); cachedHash = hash; } return cachedHash; } public String toString() { final StringBuilder sb = new StringBuilder(); sb.append(dataFormatEntryName); sb.append("\t"); sb.append(category); sb.append("\t"); sb.append(type); if (defaultOutput != null) { sb.append("\t"); sb.append(defaultOutput); } return sb.toString(); } }
apache-2.0
emacarron/mybatis-3-no-local-cache
src/main/java/org/apache/ibatis/annotations/Lang.java
957
/* * 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.apache.ibatis.annotations; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Lang { Class<?> value(); }
apache-2.0
trangvh/elasticsearch
test/framework/src/main/java/org/elasticsearch/ingest/RandomDocumentPicks.java
9375
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.ingest; import com.carrotsearch.randomizedtesting.generators.RandomInts; import com.carrotsearch.randomizedtesting.generators.RandomPicks; import com.carrotsearch.randomizedtesting.generators.RandomStrings; import org.elasticsearch.ingest.core.IngestDocument; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Random; import java.util.TreeMap; public final class RandomDocumentPicks { private RandomDocumentPicks() { } /** * Returns a random field name. Can be a leaf field name or the * path to refer to a field name using the dot notation. */ public static String randomFieldName(Random random) { int numLevels = RandomInts.randomIntBetween(random, 1, 5); String fieldName = ""; for (int i = 0; i < numLevels; i++) { if (i > 0) { fieldName += "."; } fieldName += randomString(random); } return fieldName; } /** * Returns a random leaf field name. */ public static String randomLeafFieldName(Random random) { String fieldName; do { fieldName = randomString(random); } while (fieldName.contains(".")); return fieldName; } /** * Returns a randomly selected existing field name out of the fields that are contained * in the document provided as an argument. */ public static String randomExistingFieldName(Random random, IngestDocument ingestDocument) { Map<String, Object> source = new TreeMap<>(ingestDocument.getSourceAndMetadata()); Map.Entry<String, Object> randomEntry = RandomPicks.randomFrom(random, source.entrySet()); String key = randomEntry.getKey(); while (randomEntry.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) randomEntry.getValue(); Map<String, Object> treeMap = new TreeMap<>(map); randomEntry = RandomPicks.randomFrom(random, treeMap.entrySet()); key += "." + randomEntry.getKey(); } assert ingestDocument.getFieldValue(key, Object.class) != null; return key; } /** * Adds a random non existing field to the provided document and associates it * with the provided value. The field will be added at a random position within the document, * not necessarily at the top level using a leaf field name. */ public static String addRandomField(Random random, IngestDocument ingestDocument, Object value) { String fieldName; do { fieldName = randomFieldName(random); } while (canAddField(fieldName, ingestDocument) == false); ingestDocument.setFieldValue(fieldName, value); return fieldName; } /** * Checks whether the provided field name can be safely added to the provided document. * When the provided field name holds the path using the dot notation, we have to make sure * that each node of the tree either doesn't exist or is a map, otherwise new fields cannot be added. */ public static boolean canAddField(String path, IngestDocument ingestDocument) { String[] pathElements = path.split("\\."); Map<String, Object> innerMap = ingestDocument.getSourceAndMetadata(); if (pathElements.length > 1) { for (int i = 0; i < pathElements.length - 1; i++) { Object currentLevel = innerMap.get(pathElements[i]); if (currentLevel == null) { return true; } if (currentLevel instanceof Map == false) { return false; } @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) currentLevel; innerMap = map; } } String leafKey = pathElements[pathElements.length - 1]; return innerMap.containsKey(leafKey) == false; } /** * Generates a random document and random metadata */ public static IngestDocument randomIngestDocument(Random random) { return randomIngestDocument(random, randomSource(random)); } /** * Generates a document that holds random metadata and the document provided as a map argument */ public static IngestDocument randomIngestDocument(Random random, Map<String, Object> source) { String index = randomString(random); String type = randomString(random); String id = randomString(random); String routing = null; if (random.nextBoolean()) { routing = randomString(random); } String parent = null; if (random.nextBoolean()) { parent = randomString(random); } String timestamp = null; if (random.nextBoolean()) { timestamp = randomString(random); } String ttl = null; if (random.nextBoolean()) { ttl = randomString(random); } return new IngestDocument(index, type, id, routing, parent, timestamp, ttl, source); } public static Map<String, Object> randomSource(Random random) { Map<String, Object> document = new HashMap<>(); addRandomFields(random, document, 0); return document; } /** * Generates a random field value, can be a string, a number, a list of an object itself. */ public static Object randomFieldValue(Random random) { return randomFieldValue(random, 0); } private static Object randomFieldValue(Random random, int currentDepth) { switch(RandomInts.randomIntBetween(random, 0, 9)) { case 0: return randomString(random); case 1: return random.nextInt(); case 2: return random.nextBoolean(); case 3: return random.nextDouble(); case 4: List<String> stringList = new ArrayList<>(); int numStringItems = RandomInts.randomIntBetween(random, 1, 10); for (int j = 0; j < numStringItems; j++) { stringList.add(randomString(random)); } return stringList; case 5: List<Integer> intList = new ArrayList<>(); int numIntItems = RandomInts.randomIntBetween(random, 1, 10); for (int j = 0; j < numIntItems; j++) { intList.add(random.nextInt()); } return intList; case 6: List<Boolean> booleanList = new ArrayList<>(); int numBooleanItems = RandomInts.randomIntBetween(random, 1, 10); for (int j = 0; j < numBooleanItems; j++) { booleanList.add(random.nextBoolean()); } return booleanList; case 7: List<Double> doubleList = new ArrayList<>(); int numDoubleItems = RandomInts.randomIntBetween(random, 1, 10); for (int j = 0; j < numDoubleItems; j++) { doubleList.add(random.nextDouble()); } return doubleList; case 8: Map<String, Object> newNode = new HashMap<>(); addRandomFields(random, newNode, ++currentDepth); return newNode; case 9: byte[] byteArray = new byte[RandomInts.randomIntBetween(random, 1, 1024)]; random.nextBytes(byteArray); return byteArray; default: throw new UnsupportedOperationException(); } } public static String randomString(Random random) { if (random.nextBoolean()) { return RandomStrings.randomAsciiOfLengthBetween(random, 1, 10); } return RandomStrings.randomUnicodeOfCodepointLengthBetween(random, 1, 10); } private static void addRandomFields(Random random, Map<String, Object> parentNode, int currentDepth) { if (currentDepth > 5) { return; } int numFields = RandomInts.randomIntBetween(random, 1, 10); for (int i = 0; i < numFields; i++) { String fieldName = randomLeafFieldName(random); Object fieldValue = randomFieldValue(random, currentDepth); parentNode.put(fieldName, fieldValue); } } }
apache-2.0
zwets/flowable-engine
modules/flowable-rest/src/main/java/org/flowable/rest/service/api/history/HistoricDetailResponse.java
4426
/* 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.flowable.rest.service.api.history; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import io.swagger.annotations.ApiModelProperty; import org.flowable.rest.service.api.engine.variable.RestVariable; import org.flowable.rest.util.DateToStringSerializer; import java.util.Date; /** * @author Tijs Rademakers */ public class HistoricDetailResponse { public static String FORM_PROPERTY = "formProperty"; public static String VARIABLE_UPDATE = "variableUpdate"; protected String id; protected String processInstanceId; protected String processInstanceUrl; protected String executionId; protected String activityInstanceId; protected String taskId; protected String taskUrl; @JsonSerialize(using = DateToStringSerializer.class, as = Date.class) protected Date time; protected String detailType; // Historic variable update properties protected Integer revision; protected RestVariable variable; // Form properties protected String propertyId; protected String propertyValue; @ApiModelProperty(example = "26") public String getId() { return id; } public void setId(String id) { this.id = id; } @ApiModelProperty(example = "5") public String getProcessInstanceId() { return processInstanceId; } public void setProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; } @ApiModelProperty(example = "http://localhost:8182/history/historic-process-instances/5") public String getProcessInstanceUrl() { return processInstanceUrl; } public void setProcessInstanceUrl(String processInstanceUrl) { this.processInstanceUrl = processInstanceUrl; } @ApiModelProperty(example = "6") public String getExecutionId() { return executionId; } public void setExecutionId(String executionId) { this.executionId = executionId; } @ApiModelProperty(example = "10") public String getActivityInstanceId() { return activityInstanceId; } public void setActivityInstanceId(String activityInstanceId) { this.activityInstanceId = activityInstanceId; } @ApiModelProperty(example = "6") public String getTaskId() { return taskId; } public void setTaskId(String taskId) { this.taskId = taskId; } @ApiModelProperty(example = "http://localhost:8182/history/historic-task-instances/6") public String getTaskUrl() { return taskUrl; } public void setTaskUrl(String taskUrl) { this.taskUrl = taskUrl; } @ApiModelProperty(example = "2013-04-17T10:17:43.902+0000") public Date getTime() { return time; } public void setTime(Date time) { this.time = time; } @ApiModelProperty(example = "variableUpdate") public String getDetailType() { return detailType; } public void setDetailType(String detailType) { this.detailType = detailType; } @ApiModelProperty(example = "2") public Integer getRevision() { return revision; } public void setRevision(Integer revision) { this.revision = revision; } public RestVariable getVariable() { return variable; } public void setVariable(RestVariable variable) { this.variable = variable; } @ApiModelProperty(example = "null") public String getPropertyId() { return propertyId; } public void setPropertyId(String propertyId) { this.propertyId = propertyId; } @ApiModelProperty(example = "null") public String getPropertyValue() { return propertyValue; } public void setPropertyValue(String propertyValue) { this.propertyValue = propertyValue; } }
apache-2.0
jensim/astrix
doc-snippets/src/main/java/tutorial/p3/provider/LunchServiceProvider.java
879
/* * Copyright 2014 Avanza Bank AB * * 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 tutorial.p3.provider; import tutorial.p3.api.LunchService; import com.avanza.astrix.provider.core.AstrixApiProvider; import com.avanza.astrix.provider.core.Service; @AstrixApiProvider public interface LunchServiceProvider { @Service LunchService lunchService(); }
apache-2.0
karreiro/uberfire
uberfire-extensions/uberfire-security/uberfire-security-management/uberfire-security-management-api/src/test/java/org/uberfire/ext/security/management/api/validation/GroupValidatorTest.java
2013
/* * Copyright 2016 Red Hat, Inc. and/or its affiliates. * * 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.uberfire.ext.security.management.api.validation; import java.util.Set; import javax.validation.ConstraintViolation; import org.jboss.errai.security.shared.api.Group; import org.junit.Test; import static org.junit.Assert.*; import static org.mockito.Mockito.*; public class GroupValidatorTest { @Test public void testValid() { final Group group = mock(Group.class); when(group.getName()).thenReturn("group1"); Set<ConstraintViolation<Group>> violations = new GroupValidatorTestImpl().validate(group); assertTrue(violations.isEmpty()); } @Test public void testBlankGroupName() { final Group blankGroup = mock(Group.class); when(blankGroup.getName()).thenReturn(""); final Set<ConstraintViolation<Group>> violations1 = new GroupValidatorTestImpl().validate(blankGroup); assertTrue(violations1.size() == 1); final ConstraintViolation<Group> violation = violations1.iterator().next(); assertEquals(violation.getPropertyPath().iterator().next().getName(), "name"); assertEquals(violation.getMessage(), GroupValidator.KEY_NAME_NOT_EMPTY); } public static class GroupValidatorTestImpl extends GroupValidator { @Override public String getMessage(String key) { return key; } } }
apache-2.0
q474818917/solr-5.2.0
lucene/core/src/java/org/apache/lucene/search/SortedSetSortField.java
4766
package org.apache.lucene.search; /* * 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.io.IOException; import org.apache.lucene.index.LeafReaderContext; import org.apache.lucene.index.DocValues; import org.apache.lucene.index.SortedDocValues; import org.apache.lucene.index.SortedSetDocValues; /** * SortField for {@link SortedSetDocValues}. * <p> * A SortedSetDocValues contains multiple values for a field, so sorting with * this technique "selects" a value as the representative sort value for the document. * <p> * By default, the minimum value in the set is selected as the sort value, but * this can be customized. Selectors other than the default do have some limitations * to ensure that all selections happen in constant-time for performance. * <p> * Like sorting by string, this also supports sorting missing values as first or last, * via {@link #setMissingValue(Object)}. * @see SortedSetSelector */ public class SortedSetSortField extends SortField { private final SortedSetSelector.Type selector; /** * Creates a sort, possibly in reverse, by the minimum value in the set * for the document. * @param field Name of field to sort by. Must not be null. * @param reverse True if natural order should be reversed. */ public SortedSetSortField(String field, boolean reverse) { this(field, reverse, SortedSetSelector.Type.MIN); } /** * Creates a sort, possibly in reverse, specifying how the sort value from * the document's set is selected. * @param field Name of field to sort by. Must not be null. * @param reverse True if natural order should be reversed. * @param selector custom selector type for choosing the sort value from the set. * <p> * NOTE: selectors other than {@link SortedSetSelector.Type#MIN} require optional codec support. */ public SortedSetSortField(String field, boolean reverse, SortedSetSelector.Type selector) { super(field, SortField.Type.CUSTOM, reverse); if (selector == null) { throw new NullPointerException(); } this.selector = selector; } /** Returns the selector in use for this sort */ public SortedSetSelector.Type getSelector() { return selector; } @Override public int hashCode() { return 31 * super.hashCode() + selector.hashCode(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (!super.equals(obj)) return false; if (getClass() != obj.getClass()) return false; SortedSetSortField other = (SortedSetSortField) obj; if (selector != other.selector) return false; return true; } @Override public String toString() { StringBuilder buffer = new StringBuilder(); buffer.append("<sortedset" + ": \"").append(getField()).append("\">"); if (getReverse()) buffer.append('!'); if (missingValue != null) { buffer.append(" missingValue="); buffer.append(missingValue); } buffer.append(" selector="); buffer.append(selector); return buffer.toString(); } /** * Set how missing values (the empty set) are sorted. * <p> * Note that this must be {@link #STRING_FIRST} or {@link #STRING_LAST}. */ @Override public void setMissingValue(Object missingValue) { if (missingValue != STRING_FIRST && missingValue != STRING_LAST) { throw new IllegalArgumentException("For SORTED_SET type, missing value must be either STRING_FIRST or STRING_LAST"); } this.missingValue = missingValue; } @Override public FieldComparator<?> getComparator(int numHits, int sortPos) throws IOException { return new FieldComparator.TermOrdValComparator(numHits, getField(), missingValue == STRING_LAST) { @Override protected SortedDocValues getSortedDocValues(LeafReaderContext context, String field) throws IOException { SortedSetDocValues sortedSet = DocValues.getSortedSet(context.reader(), field); return SortedSetSelector.wrap(sortedSet, selector); } }; } }
apache-2.0
mbiarnes/uberfire
uberfire-extensions/uberfire-social-activities/uberfire-social-activities-backend/src/main/java/org/ext/uberfire/social/activities/persistence/SocialTimelineCacheClusterPersistence.java
12001
/* * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * * 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.ext.uberfire.social.activities.persistence; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.List; import com.google.gson.Gson; import org.ext.uberfire.social.activities.model.SocialActivitiesEvent; import org.ext.uberfire.social.activities.model.SocialEventType; import org.ext.uberfire.social.activities.model.SocialUser; import org.ext.uberfire.social.activities.security.SocialSecurityConstraintsManager; import org.ext.uberfire.social.activities.server.SocialUserServicesExtendedBackEndImpl; import org.ext.uberfire.social.activities.service.SocialEventTypeRepositoryAPI; import org.ext.uberfire.social.activities.service.SocialTimelinePersistenceAPI; import org.ext.uberfire.social.activities.service.SocialUserPersistenceAPI; import org.uberfire.commons.lifecycle.PriorityDisposableRegistry; import org.uberfire.io.IOService; import org.uberfire.java.nio.file.FileSystem; import org.uberfire.java.nio.file.Path; public class SocialTimelineCacheClusterPersistence extends SocialTimelineCachePersistence implements SocialTimelinePersistenceAPI { private SocialClusterMessaging socialClusterMessaging; public SocialTimelineCacheClusterPersistence(final Gson gson, final Type gsonCollectionType, final IOService ioService, final SocialEventTypeRepositoryAPI socialEventTypeRepository, final SocialUserPersistenceAPI socialUserPersistenceAPI, final SocialClusterMessaging socialClusterMessaging, final SocialUserServicesExtendedBackEndImpl userServicesBackend, final FileSystem fileSystem, final SocialSecurityConstraintsManager socialSecurityConstraintsManager) { this.gson = gson; this.gsonCollectionType = gsonCollectionType; this.ioService = ioService; this.socialEventTypeRepository = socialEventTypeRepository; this.socialUserPersistenceAPI = socialUserPersistenceAPI; this.socialClusterMessaging = socialClusterMessaging; this.userServicesBackend = userServicesBackend; this.fileSystem = fileSystem; this.socialSecurityConstraintsManager = socialSecurityConstraintsManager; PriorityDisposableRegistry.register(this); } @Override public void persist(SocialActivitiesEvent event) { SocialEventType type = socialEventTypeRepository.findType(event.getType()); persistEvent(event, type, true); } @Override public void persist(SocialUser user, SocialActivitiesEvent event) { if (!clusterSyncEvent(event)) { registerNewEvent(user, event); } else { syncCluster(user); } } @Override public void saveAllEvents() { if (!typeEventsTimelineCache.keySet().isEmpty()) { try { final SocialEventType sampleType = typeEventsTimelineCache.keySet().iterator().next(); Path timeLineDir = userServicesBackend.buildPath(SOCIAL_FILES, sampleType.name()); ioService.startBatch(timeLineDir.getFileSystem()); socialClusterMessaging.notifySomeInstanceisOnShutdown(); saveAllTypeEvents(); saveAllUserTimelines(); } catch (Exception e) { System.out.println(); } finally { ioService.endBatch(); } } } private void registerNewEvent(SocialUser user, SocialActivitiesEvent event) { List<SocialActivitiesEvent> userEvents = userEventsTimelineFreshEvents.get(user.getUserName()); if (userEvents == null) { userEvents = new ArrayList<SocialActivitiesEvent>(); } userEvents.add(event); userEventsTimelineFreshEvents.put(user.getUserName(), userEvents); cacheControl(user); } private void syncCluster(SocialUser user) { List<SocialActivitiesEvent> myFreshEvents = userEventsTimelineFreshEvents.get(user.getUserName()); SocialCacheControl socialCacheControl = userEventsCacheControl.get(user.getUserName()); socialCacheControl.reset(); List<SocialActivitiesEvent> actualTypeTimeline = createOrGetUserTimeline(user.getUserName()); refreshCache(user.getUserName(), actualTypeTimeline); syncMyStaleItems(myFreshEvents, actualTypeTimeline, user); } private void syncCluster(SocialEventType eventType) { List<SocialActivitiesEvent> myFreshEvents = typeEventsFreshEvents.get(eventType); SocialCacheControl socialCacheControl = typeEventsCacheControl.get(eventType); socialCacheControl.reset(); List<SocialActivitiesEvent> actualTypeTimeline = createOrGetTypeTimeline(eventType); refreshCache(eventType, actualTypeTimeline); syncMyStaleItems(myFreshEvents, actualTypeTimeline, eventType); } void persist(SocialActivitiesEvent event, SocialEventType type, boolean sendClusterMsg) { persistEvent(event, type, sendClusterMsg); } private void persistEvent(SocialActivitiesEvent event, SocialEventType eventType, boolean sendClusterMsg) { if (!clusterSyncEvent(event)) { registerNewEvent(event, eventType, sendClusterMsg); } else { syncCluster(eventType); } } private void registerNewEvent(SocialActivitiesEvent event, SocialEventType eventType, boolean sendClusterMsg) { List<SocialActivitiesEvent> typeEvents = typeEventsFreshEvents.get(eventType); typeEvents.add(event); typeEventsFreshEvents.put(eventType, typeEvents); cacheControl(event, eventType); if (sendClusterMsg) { socialClusterMessaging.notify(event); } } private boolean clusterSyncEvent(SocialActivitiesEvent event) { return event.isDummyEvent(); } private void syncMyStaleItems(List<SocialActivitiesEvent> myFreshEvents, List<SocialActivitiesEvent> storedTimeline, SocialEventType eventType) { List<SocialActivitiesEvent> unsavedEvents = findStaleEvents(myFreshEvents, storedTimeline); if (!unsavedEvents.isEmpty()) { List<SocialActivitiesEvent> cacheEvents = typeEventsFreshEvents.get(eventType); cacheEvents.addAll(unsavedEvents); typeEventsFreshEvents.put(eventType, cacheEvents); } } private void syncMyStaleItems(List<SocialActivitiesEvent> myFreshEvents, List<SocialActivitiesEvent> storedTimeline, SocialUser user) { List<SocialActivitiesEvent> unsavedEvents = findStaleEvents(myFreshEvents, storedTimeline); if (!unsavedEvents.isEmpty()) { List<SocialActivitiesEvent> cacheEvents = userEventsTimelineFreshEvents.get(user.getUserName()); cacheEvents.addAll(unsavedEvents); userEventsTimelineFreshEvents.put(user.getUserName(), cacheEvents); } } private List<SocialActivitiesEvent> findStaleEvents(List<SocialActivitiesEvent> myFreshEvents, List<SocialActivitiesEvent> storedTimeline ) { List<SocialActivitiesEvent> unsavedEvents = new ArrayList<SocialActivitiesEvent>(); for (SocialActivitiesEvent myEvent : myFreshEvents) { boolean hasEvent = false; for (SocialActivitiesEvent storedEvents : storedTimeline) { if (storedEvents.equals(myEvent)) { hasEvent = true; break; } } if (!hasEvent) { unsavedEvents.add(myEvent); } } return unsavedEvents; } private void cacheControl(SocialUser user) { SocialCacheControl socialCacheControl = userEventsCacheControl.get(user.getUserName()); if (socialCacheControl == null) { socialCacheControl = new SocialCacheControl(); userEventsCacheControl.put(user.getUserName(), socialCacheControl); } socialCacheControl.registerNewEvent(); if (socialCacheControl.needToPersist()) { Path userDir = getUserDirectory(user.getUserName()); try { ioService.startBatch(userDir.getFileSystem()); List<SocialActivitiesEvent> storedEvents = storeTimeLineInFile(user); socialClusterMessaging.notifyTimeLineUpdate(user, storedEvents); socialCacheControl.reset(); } finally { ioService.endBatch(); } } } private void cacheControl(SocialActivitiesEvent event, SocialEventType eventType) { SocialEventType type = socialEventTypeRepository.findType(event.getType()); SocialCacheControl socialCacheControl = typeEventsCacheControl.get(type); socialCacheControl.registerNewEvent(); if (socialCacheControl.needToPersist()) { Path timeLineDir = userServicesBackend.buildPath(SOCIAL_FILES, type.name()); try { ioService.startBatch(timeLineDir.getFileSystem()); socialClusterMessaging.notifyTimeLineUpdate(event); storeTimeLineInFile(eventType); socialCacheControl.reset(); } finally { ioService.endBatch(); } } } public void someNodeShutdownAndPersistEvents() { for (SocialEventType socialEventType : typeEventsFreshEvents.keySet()) { final List<SocialActivitiesEvent> freshEvents = typeEventsFreshEvents.get(socialEventType); refreshCache(socialEventType, freshEvents); } for (String user : userEventsTimelineFreshEvents.keySet()) { final List<SocialActivitiesEvent> userEvents = userEventsTimelineFreshEvents.get(user); refreshCache(user, userEvents); } } }
apache-2.0
0359xiaodong/ChatSecureAndroid
src/info/guardianproject/otr/app/im/engine/ImConnection.java
9238
/* * Copyright (C) 2007-2008 Esmertec AG. Copyright (C) 2007-2008 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 info.guardianproject.otr.app.im.engine; import java.util.Map; import java.util.concurrent.CopyOnWriteArrayList; import android.content.Context; /** * An <code>ImConnection</code> is an abstract representation of a connection to * the IM server. */ public abstract class ImConnection { /** Connection state that indicates the connection is not connected yet. */ public static final int DISCONNECTED = 0; /** Connection state that indicates the user is logging into the server. */ public static final int LOGGING_IN = 1; /** Connection state that indicates the user has logged into the server. */ public static final int LOGGED_IN = 2; /** Connection state that indicates the user is logging out the server. */ public static final int LOGGING_OUT = 3; /** Connection state that indicate the connection is suspending. */ public static final int SUSPENDING = 4; /** Connection state that indicate the connection has been suspended. */ public static final int SUSPENDED = 5; /** The capability of supporting group chat. */ public static final int CAPABILITY_GROUP_CHAT = 1; /** The capability of supporting session re-establishment. */ public static final int CAPABILITY_SESSION_REESTABLISHMENT = 2; /** The current state of the connection. */ protected int mState; protected CopyOnWriteArrayList<ConnectionListener> mConnectionListeners; protected Presence mUserPresence; protected Context mContext; protected ImConnection(Context context) { mConnectionListeners = new CopyOnWriteArrayList<ConnectionListener>(); mState = DISCONNECTED; mContext = context; } public void addConnectionListener(ConnectionListener listener) { if (listener != null) { mConnectionListeners.add(listener); } } public void removeConnectionListener(ConnectionListener listener) { mConnectionListeners.remove(listener); } public abstract Contact getLoginUser(); public String getLoginUserName() { Contact loginUser = getLoginUser(); return loginUser == null ? null : loginUser.getName(); } public abstract int[] getSupportedPresenceStatus(); public Presence getUserPresence() { if (mState == SUSPENDING || mState == SUSPENDED) { return new Presence(); } if (mState != LOGGED_IN) { // In most cases we have a valid mUserPresence instance also // in the LOGGING_OUT state. However there is one exception: // if logout() is called before login finishes, the state may // jump from LOGGING_IN directly to LOGGING_OUT, skipping the // LOGGED_IN state. In this case we won't have a valid Presence // in the LOGGING_OUT state. return null; } return new Presence(mUserPresence); } public abstract void initUser (long providerId, long accountId) throws ImException; public void updateUserPresenceAsync(Presence newPresence) throws ImException { if (mState != LOGGED_IN) { throw new ImException(ImErrorInfo.NOT_LOGGED_IN, "NOT logged in"); } doUpdateUserPresenceAsync(newPresence); } /** * Tells the engine that the network type has changed, e.g. switch from gprs * to wifi. The engine should drop all the network connections created * before because they are not available anymore. * * The engine might also need to redo authentication on the new network * depending on the underlying protocol. */ public void networkTypeChanged() { } /** Tells the current state of the connection. */ public int getState() { return mState; } /** * Sets the state of the connection. * * @param state the new state of the connection. * @param error the error information which caused the state change or null. */ protected void setState(int state, ImErrorInfo error) { if (state < DISCONNECTED || state > SUSPENDED) { throw new IllegalArgumentException("Invalid state: " + state); } if (mState != state) { mState = state; for (ConnectionListener listener : mConnectionListeners) { listener.onStateChanged(state, error); } } } protected void notifyUserPresenceUpdated() { for (ConnectionListener listener : mConnectionListeners) { listener.onUserPresenceUpdated(); } } protected void notifyUpdateUserPresenceError(ImErrorInfo error) { for (ConnectionListener listener : mConnectionListeners) { listener.onUpdatePresenceError(error); } } /** * Gets bit-or of capabilities supported by the underlying protocol. Valid * capability bits are: {@value #CAPABILITY_GROUP_CHAT}, * {@value #CAPABILITY_SESSION_REESTABLISHMENT} * * @return bit-or of capabilities supported by the underlying protocol */ public abstract int getCapability(); /** * Log in to the IM server, using the settings stored in Imps. * * @param accountId the ID to get the Account record * @param passwordTemp a one time use password, not to be saved * @param providerId the ID to get the ProviderSettings record * @param retry whether or not to retry the connection upon failure */ public abstract void loginAsync(long accountId, String passwordTemp, long providerId, boolean retry); /** * Re-establish previous session using the session context persisted by the * client. Only sessions that were dropped unexpectedly(e.g. power loss, * crash, etc) can be re-established using the stored session context. If * the session was terminated normally by either user logging out or server * initiated disconnection, it can't be re-established again therefore the * stored context should be removed by the client. <p> The client can query * if session re-establishment is supported through {@link #getCapability()} * . * * @param sessionContext the session context which was fetched from previous * session by {@link #getSessionContext()} and persisted by the * client. * @throws UnsupportedOperationException if session re-establishment is not * supported by the underlying protocol. */ public abstract void reestablishSessionAsync(Map<String, String> sessionContext); /** Log out from the IM server. */ public abstract void logoutAsync(); /** Immediate logout */ public abstract void logout(); /** Suspend connection with the IM server. */ public abstract void suspend(); /** * Gets the cookie of the current session. The client could store the * context and use it to re-establish the session by * {@link #reestablishSessionAsync(Map)} . The stored context MUST be * removed upon the connection logout/disconnect. * * @return the context of the current session or <code>null</code> if the * user has not logged in yet. * @throws UnsupportedOperationException if session re-establishment is not * supported by the underlying protocol. */ public abstract Map<String, String> getSessionContext(); /** * Gets the instance of ChatSessionManager for the connection. * * @return the instance of ChatSessionManager for the connection. */ public abstract ChatSessionManager getChatSessionManager(); /** * Gets the instance of ContactListManager for the connection. * * @return the instance of ContactListManager for the connection. */ public abstract ContactListManager getContactListManager(); /** * Gets the instance of ChatGroupManager for the connection. * * @return the instance of ChatGroupManager for the connection. * @throws UnsupportedOperationException if group chat is not supported by * the underlying protocol. */ public abstract ChatGroupManager getChatGroupManager(); protected abstract void doUpdateUserPresenceAsync(Presence presence); /** * Handle a heartbeat. * * @param heartbeatInterval the number of heartbeats before a ping should be sent. */ public abstract void sendHeartbeat(long heartbeatInterval); public abstract void setProxy(String type, String host, int port); }
apache-2.0
peterl1084/framework
server/src/test/java/com/vaadin/tests/data/converter/ConverterTest.java
1153
package com.vaadin.tests.data.converter; import org.junit.Assert; import org.junit.Test; import com.vaadin.data.Converter; import com.vaadin.data.Result; import com.vaadin.data.ValueContext; import com.vaadin.server.SerializableFunction; public class ConverterTest { SerializableFunction<String, Result<String>> toModel = presentation -> { if (presentation.startsWith("presentation-")) { return Result.ok(presentation.substring("presentation-".length())); } else { return Result.error("invalid prefix: " + presentation); } }; SerializableFunction<String, String> toPresentation = model -> "presentation-" + model; Converter<String, String> converter = Converter.from(toModel, toPresentation); @Test public void basicConversion() { Assert.assertEquals("presentation-123", converter.convertToPresentation("123", new ValueContext())); Assert.assertEquals("123", converter.convertToModel("presentation-123", new ValueContext()) .getOrThrow(msg -> new AssertionError(msg))); } }
apache-2.0
milleruntime/accumulo
core/src/test/java/org/apache/accumulo/core/client/mapreduce/AccumuloMultiTableInputFormatTest.java
2448
/* * 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.accumulo.core.client.mapreduce; import static org.junit.jupiter.api.Assertions.assertEquals; import java.io.IOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import org.apache.accumulo.core.WithTestNames; import org.apache.accumulo.core.client.IteratorSetting; import org.apache.accumulo.core.data.Range; import org.apache.accumulo.core.util.Pair; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.Job; import org.junit.jupiter.api.Test; @Deprecated(since = "2.0.0") public class AccumuloMultiTableInputFormatTest extends WithTestNames { /** * Verify {@link InputTableConfig} objects get correctly serialized in the JobContext. */ @Test public void testInputTableConfigSerialization() throws IOException { String table1 = testName() + "1"; String table2 = testName() + "2"; Job job = Job.getInstance(); InputTableConfig tableConfig = new InputTableConfig() .setRanges(Collections.singletonList(new Range("a", "b"))) .fetchColumns(Collections.singleton(new Pair<>(new Text("CF1"), new Text("CQ1")))) .setIterators(Collections.singletonList(new IteratorSetting(50, "iter1", "iterclass1"))); Map<String,InputTableConfig> configMap = new HashMap<>(); configMap.put(table1, tableConfig); configMap.put(table2, tableConfig); AccumuloMultiTableInputFormat.setInputTableConfigs(job, configMap); assertEquals(tableConfig, AccumuloMultiTableInputFormat.getInputTableConfig(job, table1)); assertEquals(tableConfig, AccumuloMultiTableInputFormat.getInputTableConfig(job, table2)); } }
apache-2.0
kuali/ojb-1.0.4
src/xdoclet/test/xdoclet/modules/ojb/tests/ModifyInheritedTagColumnDocumentationAttributeTests.java
15502
package xdoclet.modules.ojb.tests; /* Copyright 2003-2005 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Tests for the ojb.modify-inherited tag with the column-documentation attribute. * * @author <a href="mailto:tomdz@apache.org">Thomas Dudziak</a> */ public class ModifyInheritedTagColumnDocumentationAttributeTests extends OjbTestBase { public ModifyInheritedTagColumnDocumentationAttributeTests(String name) { super(name); } // Test: modifying the column-documentation attribute of a field in a direct base class public void testDocumentation1() { addClass( "test.A", "package test;\n"+ "/** @ojb.class */\n" + "public class A {\n"+ " /** @ojb.field */\n"+ " private int attr;\n"+ "}"); addClass( "test.B", "package test;\n"+ "/** @ojb.class\n" + " * @ojb.modify-inherited name=\"attr\"\n"+ " * column-documentation=\"Some documentation\"\n"+ " */\n"+ "public class B extends A {}\n"); assertEqualsOjbDescriptorFile( "<class-descriptor\n"+ " class=\"test.A\"\n"+ " table=\"A\"\n"+ ">\n"+ " <extent-class class-ref=\"test.B\"/>\n"+ " <field-descriptor\n"+ " name=\"attr\"\n"+ " column=\"attr\"\n"+ " jdbc-type=\"INTEGER\"\n"+ " >\n"+ " </field-descriptor>\n"+ "</class-descriptor>\n"+ "<class-descriptor\n"+ " class=\"test.B\"\n"+ " table=\"B\"\n"+ ">\n"+ " <field-descriptor\n"+ " name=\"attr\"\n"+ " column=\"attr\"\n"+ " jdbc-type=\"INTEGER\"\n"+ " >\n"+ " </field-descriptor>\n"+ "</class-descriptor>", runOjbXDoclet(OJB_DEST_FILE)); assertEqualsTorqueSchemaFile( "<database name=\"ojbtest\">\n"+ " <table name=\"A\">\n"+ " <column name=\"attr\"\n"+ " javaName=\"attr\"\n"+ " type=\"INTEGER\"\n"+ " />\n"+ " </table>\n"+ " <table name=\"B\">\n"+ " <column name=\"attr\"\n"+ " javaName=\"attr\"\n"+ " type=\"INTEGER\"\n"+ " description=\"Some documentation\"\n"+ " />\n"+ " </table>\n"+ "</database>", runTorqueXDoclet(TORQUE_DEST_FILE, "ojbtest")); } // Test: modifying the column-documentation attribute of an anonymous field in an indirect base class public void testDocumentation2() { addClass( "test.A", "package test;\n"+ "/** @ojb.class\n"+ " * @ojb.field name=\"attr\"\n"+ " * jdbc-type=\"INTEGER\"\n"+ " * column-documentation=\"Some documentation\"\n"+ " */\n" + "public class A {}"); addClass( "test.B", "package test;\n"+ "public class B extends A {}"); addClass( "test.C", "package test;\n"+ "/** @ojb.class */\n" + "public class C extends B {}"); addClass( "test.D", "package test;\n"+ "/** @ojb.class\n" + " * @ojb.modify-inherited name=\"attr\"\n"+ " * column-documentation=\"Some other documentation\"\n"+ " */\n"+ "public class D extends C {}\n"); assertEqualsOjbDescriptorFile( "<class-descriptor\n"+ " class=\"test.A\"\n"+ " table=\"A\"\n"+ ">\n"+ " <extent-class class-ref=\"test.C\"/>\n"+ " <field-descriptor\n"+ " name=\"attr\"\n"+ " column=\"attr\"\n"+ " jdbc-type=\"INTEGER\"\n"+ " access=\"anonymous\"\n"+ " >\n"+ " </field-descriptor>\n"+ "</class-descriptor>\n"+ "<class-descriptor\n"+ " class=\"test.C\"\n"+ " table=\"C\"\n"+ ">\n"+ " <extent-class class-ref=\"test.D\"/>\n"+ " <field-descriptor\n"+ " name=\"attr\"\n"+ " column=\"attr\"\n"+ " jdbc-type=\"INTEGER\"\n"+ " access=\"anonymous\"\n"+ " >\n"+ " </field-descriptor>\n"+ "</class-descriptor>\n"+ "<class-descriptor\n"+ " class=\"test.D\"\n"+ " table=\"D\"\n"+ ">\n"+ " <field-descriptor\n"+ " name=\"attr\"\n"+ " column=\"attr\"\n"+ " jdbc-type=\"INTEGER\"\n"+ " access=\"anonymous\"\n"+ " >\n"+ " </field-descriptor>\n"+ "</class-descriptor>", runOjbXDoclet(OJB_DEST_FILE)); assertEqualsTorqueSchemaFile( "<database name=\"ojbtest\">\n"+ " <table name=\"A\">\n"+ " <column name=\"attr\"\n"+ " javaName=\"attr\"\n"+ " type=\"INTEGER\"\n"+ " description=\"Some documentation\"\n"+ " />\n"+ " </table>\n"+ " <table name=\"C\">\n"+ " <column name=\"attr\"\n"+ " javaName=\"attr\"\n"+ " type=\"INTEGER\"\n"+ " description=\"Some documentation\"\n"+ " />\n"+ " </table>\n"+ " <table name=\"D\">\n"+ " <column name=\"attr\"\n"+ " javaName=\"attr\"\n"+ " type=\"INTEGER\"\n"+ " description=\"Some other documentation\"\n"+ " />\n"+ " </table>\n"+ "</database>", runTorqueXDoclet(TORQUE_DEST_FILE, "ojbtest")); } // Test: unsetting the column-documentation attribute of an anonymous field in a direct base class public void testDocumentation3() { addClass( "test.A", "package test;\n"+ "/** @ojb.class\n"+ " * @ojb.field name=\"attr\"\n"+ " * jdbc-type=\"INTEGER\"\n"+ " * documentation=\"Some field documentation\"\n"+ " * column-documentation=\"Some column documentation\"\n"+ " */\n" + "public class A {}"); addClass( "test.B", "package test;\n"+ "/** @ojb.class\n" + " * @ojb.modify-inherited name=\"attr\"\n"+ " * column-documentation=\"\"\n"+ " */\n"+ "public class B extends A {}\n"); assertEqualsOjbDescriptorFile( "<class-descriptor\n"+ " class=\"test.A\"\n"+ " table=\"A\"\n"+ ">\n"+ " <extent-class class-ref=\"test.B\"/>\n"+ " <field-descriptor\n"+ " name=\"attr\"\n"+ " column=\"attr\"\n"+ " jdbc-type=\"INTEGER\"\n"+ " access=\"anonymous\"\n"+ " >\n"+ " <documentation>Some field documentation</documentation>\n"+ " </field-descriptor>\n"+ "</class-descriptor>\n"+ "<class-descriptor\n"+ " class=\"test.B\"\n"+ " table=\"B\"\n"+ ">\n"+ " <field-descriptor\n"+ " name=\"attr\"\n"+ " column=\"attr\"\n"+ " jdbc-type=\"INTEGER\"\n"+ " access=\"anonymous\"\n"+ " >\n"+ " <documentation>Some field documentation</documentation>\n"+ " </field-descriptor>\n"+ "</class-descriptor>", runOjbXDoclet(OJB_DEST_FILE)); assertEqualsTorqueSchemaFile( "<database name=\"ojbtest\">\n"+ " <table name=\"A\">\n"+ " <column name=\"attr\"\n"+ " javaName=\"attr\"\n"+ " type=\"INTEGER\"\n"+ " description=\"Some column documentation\"\n"+ " />\n"+ " </table>\n"+ " <table name=\"B\">\n"+ " <column name=\"attr\"\n"+ " javaName=\"attr\"\n"+ " type=\"INTEGER\"\n"+ " description=\"Some field documentation\"\n"+ " />\n"+ " </table>\n"+ "</database>", runTorqueXDoclet(TORQUE_DEST_FILE, "ojbtest")); } // Test: setting the column-documentation attribute of an inherited field which has a documentation attribute public void testDocumentation4() { addClass( "test.A", "package test;\n"+ "/** @ojb.class */\n" + "public class A {\n"+ " /** @ojb.field documentation=\"Some documentation\"*/\n"+ " private int attr;\n"+ "}"); addClass( "test.B", "package test;\n"+ "/** @ojb.class\n" + " * @ojb.modify-inherited name=\"attr\"\n"+ " * column-documentation=\"Some other documentation\"\n"+ " */\n"+ "public class B extends A {}\n"); assertEqualsOjbDescriptorFile( "<class-descriptor\n"+ " class=\"test.A\"\n"+ " table=\"A\"\n"+ ">\n"+ " <extent-class class-ref=\"test.B\"/>\n"+ " <field-descriptor\n"+ " name=\"attr\"\n"+ " column=\"attr\"\n"+ " jdbc-type=\"INTEGER\"\n"+ " >\n"+ " <documentation>Some documentation</documentation>\n"+ " </field-descriptor>\n"+ "</class-descriptor>\n"+ "<class-descriptor\n"+ " class=\"test.B\"\n"+ " table=\"B\"\n"+ ">\n"+ " <field-descriptor\n"+ " name=\"attr\"\n"+ " column=\"attr\"\n"+ " jdbc-type=\"INTEGER\"\n"+ " >\n"+ " <documentation>Some documentation</documentation>\n"+ " </field-descriptor>\n"+ "</class-descriptor>", runOjbXDoclet(OJB_DEST_FILE)); assertEqualsTorqueSchemaFile( "<database name=\"ojbtest\">\n"+ " <table name=\"A\">\n"+ " <column name=\"attr\"\n"+ " javaName=\"attr\"\n"+ " type=\"INTEGER\"\n"+ " description=\"Some documentation\"\n"+ " />\n"+ " </table>\n"+ " <table name=\"B\">\n"+ " <column name=\"attr\"\n"+ " javaName=\"attr\"\n"+ " type=\"INTEGER\"\n"+ " description=\"Some other documentation\"\n"+ " />\n"+ " </table>\n"+ "</database>", runTorqueXDoclet(TORQUE_DEST_FILE, "ojbtest")); } // Test: setting the documentation attribute of an inherited field which has a column-documentation attribute public void testDocumentation5() { addClass( "test.A", "package test;\n"+ "/** @ojb.class */\n" + "public class A {\n"+ " /** @ojb.field column-documentation=\"Some documentation\"*/\n"+ " private int attr;\n"+ "}"); addClass( "test.B", "package test;\n"+ "/** @ojb.class\n" + " * @ojb.modify-inherited name=\"attr\"\n"+ " * documentation=\"Some other documentation\"\n"+ " */\n"+ "public class B extends A {}\n"); assertEqualsOjbDescriptorFile( "<class-descriptor\n"+ " class=\"test.A\"\n"+ " table=\"A\"\n"+ ">\n"+ " <extent-class class-ref=\"test.B\"/>\n"+ " <field-descriptor\n"+ " name=\"attr\"\n"+ " column=\"attr\"\n"+ " jdbc-type=\"INTEGER\"\n"+ " >\n"+ " </field-descriptor>\n"+ "</class-descriptor>\n"+ "<class-descriptor\n"+ " class=\"test.B\"\n"+ " table=\"B\"\n"+ ">\n"+ " <field-descriptor\n"+ " name=\"attr\"\n"+ " column=\"attr\"\n"+ " jdbc-type=\"INTEGER\"\n"+ " >\n"+ " <documentation>Some other documentation</documentation>\n"+ " </field-descriptor>\n"+ "</class-descriptor>", runOjbXDoclet(OJB_DEST_FILE)); assertEqualsTorqueSchemaFile( "<database name=\"ojbtest\">\n"+ " <table name=\"A\">\n"+ " <column name=\"attr\"\n"+ " javaName=\"attr\"\n"+ " type=\"INTEGER\"\n"+ " description=\"Some documentation\"\n"+ " />\n"+ " </table>\n"+ " <table name=\"B\">\n"+ " <column name=\"attr\"\n"+ " javaName=\"attr\"\n"+ " type=\"INTEGER\"\n"+ " description=\"Some documentation\"\n"+ " />\n"+ " </table>\n"+ "</database>", runTorqueXDoclet(TORQUE_DEST_FILE, "ojbtest")); } }
apache-2.0
gkatsikas/onos
apps/cfm/api/src/main/java/org/onosproject/incubator/net/l2monitoring/soam/loss/LossMeasurementEntry.java
5994
/* * Copyright 2017-present Open Networking Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onosproject.incubator.net.l2monitoring.soam.loss; import java.time.Instant; import java.util.Collection; import org.onosproject.incubator.net.l2monitoring.soam.MilliPct; import org.onosproject.incubator.net.l2monitoring.soam.SoamId; /** * A model of Loss Measurement from ITU Y.1731 Chapter 8.2, MEF 17, MEF 36.1 and MEF 39. * * In this model Loss Measurements entries are returned as a collection in the * MepEntry. In this way Loss Measurements are created by calling on the * Create Loss Measurement function, passing in any arguments needed to * configure it. The Loss Measurement is a result and not configured or * persisted in ONOS, but instead is is passed on to some analytics system. */ public interface LossMeasurementEntry extends LossMeasurementCreate { /** * Ian id that uniquely identifies a scheduled measurement. * It is automatically generated by the server on creation of a new measurement * @return An LM id */ SoamId lmId(); /** * Contains the Frame Loss Ratio in the forward direction calculated by this MEP. * from the last received SOAM PDU. * The FLR value is a ratio that is expressed as a percent with a value of * 0 (ratio 0.00) through 100000 (ratio 1.00). * @return Units are in milli-percent, where 1 indicates 0.001 per-cent */ MilliPct measuredForwardFlr(); /** * Contains the Frame Loss Ratio in the backward direction calculated by this MEP. * from the last received SOAM PDU. * The FLR value is a ratio that is expressed as a percent with a value of * 0 (ratio 0.00) through 100000 (ratio 1.00). * @return Units are in milli-percent, where 1 indicates 0.001 per-cent */ MilliPct measuredBackwardFlr(); /** * The availability status (the outcome of the last availability indicator) in the forward direction. * based upon the last received SOAM PDU * @return enumerated availability value */ AvailabilityType measuredAvailabilityForwardStatus(); /** * The availability status (the outcome of the last availability indicator) in the backward direction. * based upon the last received SOAM PDU * @return enumerated availability value */ AvailabilityType measuredAvailabilityBackwardStatus(); /** * The time of the last transition between available and unavailable in the forward direction. * If there have been no transitions since the Loss Measurement Session was * started, this is set to 0 * @return The transition time */ Instant measuredForwardLastTransitionTime(); /** * The time of the last transition between available and unavailable in the backward direction. * If there have been no transitions since the Loss Measurement Session was * started, this is set to 0 * @return The transition time */ Instant measuredBackwardLastTransitionTime(); /** * The results for the current Measurement Interval in a SOAM Loss Measurement session. * gathered during the interval indicated by measurement-interval * @return An object with current measurements */ LossMeasurementStatCurrent measurementCurrent(); /** * The results for history Measurement Intervals in a SOAM Loss Measurement session. * @return An object with historic measurements */ Collection<LossMeasurementStatHistory> measurementHistories(); /** * The current results for a SOAM Loss Measurement session for availability statistics. * gathered during the interval indicated by availability-measurement-interval * @return An object with current availability */ LossAvailabilityStatCurrent availabilityCurrent(); /** * The results for availability history Measurement Intervals in a SOAM Loss Measurement session. * @return An object with historic availability */ Collection<LossAvailabilityStatHistory> availabilityHistories(); /** * Builder for {@link LossMeasurementEntry}. */ public interface LmEntryBuilder extends LmCreateBuilder { LmEntryBuilder measuredForwardFlr(MilliPct measuredForwardFlr); LmEntryBuilder measuredBackwardFlr(MilliPct measuredBackwardFlr); LmEntryBuilder measuredAvailabilityForwardStatus( AvailabilityType measuredAvailabilityForwardStatus); LmEntryBuilder measuredAvailabilityBackwardStatus( AvailabilityType measuredAvailabilityBackwardStatus); LmEntryBuilder measuredForwardLastTransitionTime( Instant measuredForwardLastTransitionTime); LmEntryBuilder measuredBackwardLastTransitionTime( Instant measuredBackwardLastTransitionTime); LmEntryBuilder measurementCurrent( LossMeasurementStatCurrent measurementCurrent); LmEntryBuilder addToMeasurementHistories( LossMeasurementStatHistory history); LmEntryBuilder availabilityCurrent( LossAvailabilityStatCurrent availabilityCurrent); LmEntryBuilder addToAvailabilityHistories(LossAvailabilityStatHistory history); LossMeasurementEntry build(); } /** * Options for Availability test types. */ public enum AvailabilityType { AVAILABLE, UNAVAILABLE, UNKNOWN; } }
apache-2.0
q474818917/solr-5.2.0
solr/solrj/src/java/org/apache/solr/client/solrj/io/stream/expr/StreamExpressionValue.java
1822
package org.apache.solr.client.solrj.io.stream.expr; /* * 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. */ /** * Basic string stream expression */ public class StreamExpressionValue implements StreamExpressionParameter { private String value; public StreamExpressionValue(String value){ this.value = value; } public String getValue(){ return this.value; } public void setValue(String value){ this.value = value; } public StreamExpressionValue withValue(String value){ this.value = value; return this; } @Override public String toString(){ return this.value; } @Override public boolean equals(Object other){ if(other.getClass() != StreamExpressionValue.class){ return false; } StreamExpressionValue check = (StreamExpressionValue)other; if(null == this.value && null == check.value){ return true; } if(null == this.value || null == check.value){ return false; } return this.value.equals(((StreamExpressionValue)other).value); } }
apache-2.0
ern/elasticsearch
client/rest-high-level/src/main/java/org/elasticsearch/client/ml/GetJobResponse.java
2542
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.client.ml; import org.elasticsearch.client.ml.job.config.Job; import org.elasticsearch.common.xcontent.ParseField; import org.elasticsearch.common.Strings; import org.elasticsearch.common.xcontent.ConstructingObjectParser; import org.elasticsearch.common.xcontent.XContentParser; import java.io.IOException; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; import static org.elasticsearch.common.xcontent.ConstructingObjectParser.constructorArg; /** * Contains a {@link List} of the found {@link Job} objects and the total count found */ public class GetJobResponse extends AbstractResultResponse<Job> { public static final ParseField RESULTS_FIELD = new ParseField("jobs"); @SuppressWarnings("unchecked") public static final ConstructingObjectParser<GetJobResponse, Void> PARSER = new ConstructingObjectParser<>("jobs_response", true, a -> new GetJobResponse((List<Job.Builder>) a[0], (long) a[1])); static { PARSER.declareObjectArray(constructorArg(), Job.PARSER, RESULTS_FIELD); PARSER.declareLong(constructorArg(), AbstractResultResponse.COUNT); } GetJobResponse(List<Job.Builder> jobBuilders, long count) { super(RESULTS_FIELD, jobBuilders.stream().map(Job.Builder::build).collect(Collectors.toList()), count); } /** * The collection of {@link Job} objects found in the query */ public List<Job> jobs() { return results; } public static GetJobResponse fromXContent(XContentParser parser) throws IOException { return PARSER.parse(parser, null); } @Override public int hashCode() { return Objects.hash(results, count); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null || getClass() != obj.getClass()) { return false; } GetJobResponse other = (GetJobResponse) obj; return Objects.equals(results, other.results) && count == other.count; } @Override public final String toString() { return Strings.toString(this); } }
apache-2.0
flofreud/aws-sdk-java
aws-java-sdk-ec2/src/main/java/com/amazonaws/services/ec2/model/AvailableCapacity.java
7571
/* * Copyright 2010-2016 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.ec2.model; import java.io.Serializable; /** * <p> * The capacity information for instances launched onto the Dedicated host. * </p> */ public class AvailableCapacity implements Serializable, Cloneable { /** * <p> * The total number of instances that the Dedicated host supports. * </p> */ private com.amazonaws.internal.SdkInternalList<InstanceCapacity> availableInstanceCapacity; /** * <p> * The number of vCPUs available on the Dedicated host. * </p> */ private Integer availableVCpus; /** * <p> * The total number of instances that the Dedicated host supports. * </p> * * @return The total number of instances that the Dedicated host supports. */ public java.util.List<InstanceCapacity> getAvailableInstanceCapacity() { if (availableInstanceCapacity == null) { availableInstanceCapacity = new com.amazonaws.internal.SdkInternalList<InstanceCapacity>(); } return availableInstanceCapacity; } /** * <p> * The total number of instances that the Dedicated host supports. * </p> * * @param availableInstanceCapacity * The total number of instances that the Dedicated host supports. */ public void setAvailableInstanceCapacity( java.util.Collection<InstanceCapacity> availableInstanceCapacity) { if (availableInstanceCapacity == null) { this.availableInstanceCapacity = null; return; } this.availableInstanceCapacity = new com.amazonaws.internal.SdkInternalList<InstanceCapacity>( availableInstanceCapacity); } /** * <p> * The total number of instances that the Dedicated host supports. * </p> * <p> * <b>NOTE:</b> This method appends the values to the existing list (if * any). Use {@link #setAvailableInstanceCapacity(java.util.Collection)} or * {@link #withAvailableInstanceCapacity(java.util.Collection)} if you want * to override the existing values. * </p> * * @param availableInstanceCapacity * The total number of instances that the Dedicated host supports. * @return Returns a reference to this object so that method calls can be * chained together. */ public AvailableCapacity withAvailableInstanceCapacity( InstanceCapacity... availableInstanceCapacity) { if (this.availableInstanceCapacity == null) { setAvailableInstanceCapacity(new com.amazonaws.internal.SdkInternalList<InstanceCapacity>( availableInstanceCapacity.length)); } for (InstanceCapacity ele : availableInstanceCapacity) { this.availableInstanceCapacity.add(ele); } return this; } /** * <p> * The total number of instances that the Dedicated host supports. * </p> * * @param availableInstanceCapacity * The total number of instances that the Dedicated host supports. * @return Returns a reference to this object so that method calls can be * chained together. */ public AvailableCapacity withAvailableInstanceCapacity( java.util.Collection<InstanceCapacity> availableInstanceCapacity) { setAvailableInstanceCapacity(availableInstanceCapacity); return this; } /** * <p> * The number of vCPUs available on the Dedicated host. * </p> * * @param availableVCpus * The number of vCPUs available on the Dedicated host. */ public void setAvailableVCpus(Integer availableVCpus) { this.availableVCpus = availableVCpus; } /** * <p> * The number of vCPUs available on the Dedicated host. * </p> * * @return The number of vCPUs available on the Dedicated host. */ public Integer getAvailableVCpus() { return this.availableVCpus; } /** * <p> * The number of vCPUs available on the Dedicated host. * </p> * * @param availableVCpus * The number of vCPUs available on the Dedicated host. * @return Returns a reference to this object so that method calls can be * chained together. */ public AvailableCapacity withAvailableVCpus(Integer availableVCpus) { setAvailableVCpus(availableVCpus); 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 (getAvailableInstanceCapacity() != null) sb.append("AvailableInstanceCapacity: " + getAvailableInstanceCapacity() + ","); if (getAvailableVCpus() != null) sb.append("AvailableVCpus: " + getAvailableVCpus()); sb.append("}"); return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (obj instanceof AvailableCapacity == false) return false; AvailableCapacity other = (AvailableCapacity) obj; if (other.getAvailableInstanceCapacity() == null ^ this.getAvailableInstanceCapacity() == null) return false; if (other.getAvailableInstanceCapacity() != null && other.getAvailableInstanceCapacity().equals( this.getAvailableInstanceCapacity()) == false) return false; if (other.getAvailableVCpus() == null ^ this.getAvailableVCpus() == null) return false; if (other.getAvailableVCpus() != null && other.getAvailableVCpus().equals(this.getAvailableVCpus()) == false) return false; return true; } @Override public int hashCode() { final int prime = 31; int hashCode = 1; hashCode = prime * hashCode + ((getAvailableInstanceCapacity() == null) ? 0 : getAvailableInstanceCapacity().hashCode()); hashCode = prime * hashCode + ((getAvailableVCpus() == null) ? 0 : getAvailableVCpus() .hashCode()); return hashCode; } @Override public AvailableCapacity clone() { try { return (AvailableCapacity) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException( "Got a CloneNotSupportedException from Object.clone() " + "even though we're Cloneable!", e); } } }
apache-2.0
ravisund/Kundera
src/kundera-hbase/kundera-hbase/src/test/java/com/impetus/client/hbase/generatedId/entites/HBaseGeneratedIdStrategySequence.java
1113
package com.impetus.client.hbase.generatedId.entites; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.SequenceGenerator; import javax.persistence.Table; @Entity @Table(name = "HBaseGeneratedIdStrategySequence", schema = "kundera@hbase_generated_id") public class HBaseGeneratedIdStrategySequence { @Id @SequenceGenerator(name = "seq_gen") @GeneratedValue(generator = "seq_gen", strategy = GenerationType.SEQUENCE) private int id; @Column private String name; /** * @return the id */ public int getId() { return id; } /** * @param id * the id to set */ public void setId(int id) { this.id = id; } /** * @return the name */ public String getName() { return name; } /** * @param name * the name to set */ public void setName(String name) { this.name = name; } }
apache-2.0
smgoller/geode
geode-core/src/main/java/org/apache/geode/management/internal/beans/stats/MBeanStatsMonitor.java
3508
/* * 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.management.internal.beans.stats; import java.util.HashMap; import java.util.Map; import org.apache.logging.log4j.Logger; import org.apache.geode.StatisticDescriptor; import org.apache.geode.Statistics; import org.apache.geode.StatisticsType; import org.apache.geode.internal.statistics.StatisticId; import org.apache.geode.internal.statistics.StatisticNotFoundException; import org.apache.geode.internal.statistics.StatisticsListener; import org.apache.geode.internal.statistics.StatisticsNotification; import org.apache.geode.internal.statistics.ValueMonitor; import org.apache.geode.logging.internal.log4j.api.LogService; /** * Class to get mappings of stats name to their values */ public class MBeanStatsMonitor implements StatisticsListener { private static final Logger logger = LogService.getLogger(); protected ValueMonitor monitor; /** * Map which contains statistics with their name and value */ protected Map<String, Number> statsMap; private String monitorName; public MBeanStatsMonitor(final String name) { this(name, new ValueMonitor()); } MBeanStatsMonitor(final String name, final ValueMonitor monitor) { this.monitorName = name; this.monitor = monitor; this.statsMap = new HashMap<>(); } public void addStatisticsToMonitor(final Statistics stats) { monitor.addListener(this);// if already listener is added this will be a no-op // Initialize the stats with the current values. StatisticsType type = stats.getType(); StatisticDescriptor[] descriptors = type.getStatistics(); for (StatisticDescriptor d : descriptors) { statsMap.put(d.getName(), stats.get(d)); } monitor.addStatistics(stats); } public void removeStatisticsFromMonitor(final Statistics stats) { statsMap.clear(); } public void stopListener() { monitor.removeListener(this); } public Number getStatistic(final String statName) { Number value = statsMap.getOrDefault(statName, 0); return value != null ? value : 0; } @Override public void handleNotification(final StatisticsNotification notification) { for (StatisticId statId : notification) { StatisticDescriptor descriptor = statId.getStatisticDescriptor(); String name = descriptor.getName(); Number value; try { value = notification.getValue(statId); } catch (StatisticNotFoundException e) { value = 0; } log(name, value); statsMap.put(name, value); } } protected void log(final String name, final Number value) { if (logger.isTraceEnabled()) { logger.trace("Monitor = {} descriptor = {} And value = {}", monitorName, name, value); } } }
apache-2.0
tempbottle/idea-rust
src/java/main/vektah/rust/formatter/RustFormattingModelBuilder.java
3632
/* * Copyright 2012-2013 Sergey Ignatov * * 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 vektah.rust.formatter; import com.intellij.formatting.FormattingModel; import com.intellij.formatting.FormattingModelBuilder; import com.intellij.formatting.FormattingModelProvider; import com.intellij.formatting.SpacingBuilder; import com.intellij.lang.ASTNode; import com.intellij.openapi.util.TextRange; import com.intellij.psi.PsiElement; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.psi.tree.TokenSet; import org.jetbrains.annotations.NotNull; import vektah.rust.RustLanguage; import static vektah.rust.psi.RustTokens.*; public class RustFormattingModelBuilder implements FormattingModelBuilder { @NotNull @Override public FormattingModel createModel(PsiElement element, CodeStyleSettings settings) { CommonCodeStyleSettings commonSettings = settings.getCommonSettings(RustLanguage.INSTANCE); SpacingBuilder spacingBuilder = createSpacingBuilder(commonSettings); RustFormattingBlock block = new RustFormattingBlock(element.getNode(), null, null, null, commonSettings, spacingBuilder, -1); return FormattingModelProvider.createFormattingModelForPsiFile(element.getContainingFile(), block, settings); } private static SpacingBuilder createSpacingBuilder(@NotNull CommonCodeStyleSettings settings) { TokenSet keywords = TokenSet.create( KW_AS, KW_BREAK, KW_CRATE, KW_ELSE, KW_ENUM, KW_EXTERN, KW_FALSE, KW_FN, KW_FOR, KW_IF, KW_IMPL, KW_IN, KW_LET, KW_LOOP, KW_MATCH, KW_MOD, KW_PRIV, KW_PROC, KW_PUB, KW_RETURN, KW_CONTINUE, KW_MACRO_RULES, KW_SELF, KW_STATIC, KW_STRUCT, KW_SUPER, KW_TRUE, KW_TRAIT, KW_TYPE, KW_UNSAFE, KW_USE, KW_WHILE ); CodeStyleSettings codeStyleSettings = new CodeStyleSettings(); return new SpacingBuilder(codeStyleSettings, RustLanguage.INSTANCE) .before(COMMA).spaceIf(settings.SPACE_BEFORE_COMMA) .after(COMMA).spaceIf(settings.SPACE_AFTER_COMMA) .before(SEMICOLON).none() .after(OPEN_SQUARE_BRACKET).none() .before(CLOSE_SQUARE_BRACKET).none() .afterInside(OPEN_BRACE, USE_GROUP).none() .beforeInside(CLOSE_BRACE, USE_GROUP).none() .after(OPEN_BRACE).spaces(1) .before(CLOSE_BRACE).spaces(1) .withinPair(OPEN_PAREN, CLOSE_PAREN).spaceIf(settings.SPACE_WITHIN_METHOD_CALL_PARENTHESES) .between(REF, KW_SELF).spacing(0, 1, 0, false, 0) // &self .between(REF, KW_MUT).spacing(0, 1, 0, false, 0) // &mut .between(MULTIPLY, KW_MUT).none() // *mut .between(KW_IMPL, GENERIC_PARAMS).none() // impl< .between(SINGLE_QUOTE, KW_STATIC).none() // 'static .between(KW_SELF, DOT).none() // self. .between(KW_SELF, DOUBLE_COLON).none() // self:: .between(KW_SUPER, DOUBLE_COLON).none() // super:: .between(DOUBLE_COLON, KW_SUPER).none() // ::super .around(keywords).spaces(1) ; } @Override public TextRange getRangeAffectingIndent(PsiFile psiFile, int i, ASTNode astNode) { return null; } }
bsd-2-clause
erwin1/MyDevoxxGluon
DevoxxClientWearable/src/main/java/com/devoxx/views/AmbientView.java
2746
/** * Copyright (c) 2017, Gluon Software * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation and/or other materials provided * with the distribution. * * 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package com.devoxx.views; import com.gluonhq.charm.glisten.animation.FadeInTransition; import com.gluonhq.charm.glisten.control.AppBar; import com.gluonhq.charm.glisten.mvc.View; import java.text.SimpleDateFormat; import java.util.Date; import javafx.geometry.Insets; import javafx.scene.control.Label; public class AmbientView extends View { private static final SimpleDateFormat AMBIENT_DATE_FORMAT = new SimpleDateFormat("HH:mm"); private final Label date; public AmbientView(String name) { super(name); setShowTransitionFactory(FadeInTransition::new); setPadding(new Insets(40)); final Label label = new Label("GluonWatch App"); label.getStyleClass().add("white"); setTop(label); date = new Label(AMBIENT_DATE_FORMAT.format(new Date())); date.setStyle("-fx-font-size: 3em;"); date.getStyleClass().add("white"); setBottom(date); } @Override protected void updateAppBar(AppBar appBar) { appBar.setVisible(false); } public void updateView() { date.setText(AMBIENT_DATE_FORMAT.format(new Date())); } }
bsd-3-clause
tuxbox/simple-pgp
simple-pgp-java/src/test/java/me/sniggle/pgp/crypt/PGPMessageSignerVerifyTest.java
1891
package me.sniggle.pgp.crypt; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.Parameterized; import java.io.FileNotFoundException; import java.util.Arrays; import java.util.Collection; import static org.junit.Assert.assertEquals; /** * Created by iulius on 19/09/15. */ @RunWith(Parameterized.class) public class PGPMessageSignerVerifyTest { private final boolean expectedResult; private MessageSigner messageSigner; private String publicKeyFilename; private String plainMessageFilename; private String signatureFilename; public PGPMessageSignerVerifyTest(String publicKeyFilename, String plainMessageFilename, String signatureFilename, boolean expectedResult) { this.publicKeyFilename = publicKeyFilename; this.plainMessageFilename = plainMessageFilename; this.signatureFilename = signatureFilename; this.expectedResult = expectedResult; } @Parameterized.Parameters public static Collection<Object[]> data() { return Arrays.asList(new Object[][]{ {"testcase-1-pub.asc", "test-message.txt", "test-message.txt.tc1.sig", true}, {"testcase-2-pub.asc", "test-message.txt", "test-message.txt.tc2.sig", true}, {"testcase-1-pub.asc", "test-message.txt", "test-message.txt.tc2.sig", false}, {"testcase-2-pub.asc", "test-message.txt", "test-message.txt.tc1.sig", false} }); } @Before public void setup() { messageSigner = PGPWrapperFactory.getSigner(); } @Test public void testVerifyMessage() throws FileNotFoundException { assertEquals(expectedResult, messageSigner.verifyMessage(getClass().getResourceAsStream(publicKeyFilename), getClass().getResourceAsStream(plainMessageFilename), getClass().getResourceAsStream(signatureFilename))); } @After public void cleanUp() { messageSigner = null; } }
bsd-3-clause
Just-D/chromium-1
chrome/test/android/javatests/src/org/chromium/chrome/test/util/browser/sync/SyncTestUtil.java
22536
// 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.test.util.browser.sync; import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout; import android.accounts.Account; import android.content.Context; import android.util.Log; import android.util.Pair; import junit.framework.Assert; import org.chromium.base.CommandLine; import org.chromium.base.ThreadUtils; import org.chromium.base.test.util.AdvancedMockContext; import org.chromium.chrome.browser.invalidation.InvalidationServiceFactory; import org.chromium.chrome.browser.profiles.Profile; import org.chromium.chrome.browser.sync.ProfileSyncService; import org.chromium.chrome.test.util.TestHttpServerClient; import org.chromium.content.browser.test.util.Criteria; import org.chromium.content.browser.test.util.CriteriaHelper; import org.chromium.sync.signin.AccountManagerHelper; import org.chromium.sync.signin.ChromeSigninController; import org.chromium.sync.test.util.AccountHolder; import org.chromium.sync.test.util.MockAccountManager; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.concurrent.Callable; import java.util.concurrent.Semaphore; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicLong; /** * Utility class for shared sync test functionality. */ public final class SyncTestUtil { public static final String DEFAULT_TEST_ACCOUNT = "test@gmail.com"; public static final String DEFAULT_PASSWORD = "myPassword"; private static final String TAG = "SyncTestUtil"; public static final long UI_TIMEOUT_MS = scaleTimeout(20000); public static final int CHECK_INTERVAL_MS = 250; private static final long SYNC_WAIT_TIMEOUT_MS = scaleTimeout(30 * 1000); private static final int SYNC_CHECK_INTERVAL_MS = 250; public static final Pair<String, String> SYNC_SUMMARY_STATUS = newPair("Summary", "Summary"); protected static final String UNINITIALIZED = "Uninitialized"; protected static final Pair<String, String> USERNAME_STAT = newPair("Identity", "Username"); // Override the default server used for profile sync. // Native switch - chrome_switches::kSyncServiceURL private static final String SYNC_URL = "sync-url"; private SyncTestUtil() { } /** * Creates a Pair of lowercased and trimmed Strings. Makes it easier to avoid running afoul of * case-sensitive comparison since getAboutInfoStats(), et al, use Pair<String, String> as map * keys. */ private static Pair<String, String> newPair(String first, String second) { return Pair.create(first.toLowerCase(Locale.US).trim(), second.toLowerCase(Locale.US).trim()); } /** * Parses raw JSON into a map with keys Pair<String, String>. The first string in each Pair * corresponds to the title under which a given stat_name/stat_value is situated, and the second * contains the name of the actual stat. For example, a stat named "Syncing" which falls under * "Local State" would be a Pair of newPair("Local State", "Syncing"). * * @param rawJson the JSON to parse into a map * @return a map containing a mapping of titles and stat names to stat values * @throws org.json.JSONException */ public static Map<Pair<String, String>, String> getAboutInfoStats(String rawJson) throws JSONException { // What we get back is what you'd get from chrome.sync.aboutInfo at chrome://sync. This is // a JSON object, and we care about the "details" field in that object. "details" itself has // objects with two fields: data and title. The data field itself contains an array of // objects. These objects contains two fields: stat_name and stat_value. Ultimately these // are the values displayed on the page and the values we care about in this method. Map<Pair<String, String>, String> statLookup = new HashMap<Pair<String, String>, String>(); JSONObject aboutInfo = new JSONObject(rawJson); JSONArray detailsArray = aboutInfo.getJSONArray("details"); for (int i = 0; i < detailsArray.length(); i++) { JSONObject dataObj = detailsArray.getJSONObject(i); String dataTitle = dataObj.getString("title"); JSONArray dataArray = dataObj.getJSONArray("data"); for (int j = 0; j < dataArray.length(); j++) { JSONObject statObj = dataArray.getJSONObject(j); String statName = statObj.getString("stat_name"); Pair<String, String> key = newPair(dataTitle, statName); statLookup.put(key, statObj.getString("stat_value")); } } return statLookup; } /** * Verifies that sync is signed out and its status is "Syncing not enabled". * TODO(mmontgomery): check whether or not this method is necessary. It queries * syncSummaryStatus(), which is a slightly more direct route than via JSON. */ public static void verifySyncIsSignedOut(Context context) { Map<Pair<String, String>, String> expectedStats = new HashMap<Pair<String, String>, String>(); expectedStats.put(SYNC_SUMMARY_STATUS, UNINITIALIZED); expectedStats.put(USERNAME_STAT, ""); // Expect an empty username when sync is signed out. Assert.assertTrue("Expected sync to be disabled.", pollAboutSyncStats(context, expectedStats)); } /** * Polls the stats on about:sync until timeout or all expected stats match actual stats. The * comparison is case insensitive. *All* stats must match those passed in via expectedStats. * * * @param expectedStats a map of stat names to their expected values * @return whether the stats matched up before the timeout */ public static boolean pollAboutSyncStats( Context context, final Map<Pair<String, String>, String> expectedStats) { final AboutSyncInfoGetter aboutInfoGetter = new AboutSyncInfoGetter(context); Criteria statChecker = new Criteria() { @Override public boolean isSatisfied() { try { ThreadUtils.runOnUiThreadBlocking(aboutInfoGetter); Map<Pair<String, String>, String> actualStats = aboutInfoGetter.getAboutInfo(); return areExpectedStatsAmongActual(expectedStats, actualStats); } catch (Throwable e) { Log.w(TAG, "Interrupted while attempting to fetch sync internals info.", e); } return false; } }; boolean matched = false; try { matched = CriteriaHelper.pollForCriteria(statChecker, UI_TIMEOUT_MS, CHECK_INTERVAL_MS); } catch (InterruptedException e) { Log.w(TAG, "Interrupted while polling sync internals info.", e); Assert.fail("Interrupted while polling sync internals info."); } return matched; } /** * Checks whether the expected map's keys and values are a subset of those in another map. Both * keys and values are compared in a case-insensitive fashion. * * @param expectedStats a map which may be a subset of actualSet * @param actualStats a map which may be a superset of expectedSet * @return true if all key/value pairs in expectedSet are in actualSet; false otherwise */ private static boolean areExpectedStatsAmongActual( Map<Pair<String, String>, String> expectedStats, Map<Pair<String, String>, String> actualStats) { for (Map.Entry<Pair<String, String>, String> statEntry : expectedStats.entrySet()) { // Make stuff lowercase here, at the site of comparison. String expectedValue = statEntry.getValue().toLowerCase(Locale.US).trim(); String actualValue = actualStats.get(statEntry.getKey()); if (actualValue == null) { return false; } actualValue = actualValue.toLowerCase(Locale.US).trim(); if (!expectedValue.contentEquals(actualValue)) { return false; } } return true; } /** * Triggers a sync and waits till it is complete. */ public static void triggerSyncAndWaitForCompletion(final Context context) throws InterruptedException { final long oldSyncTime = getCurrentSyncTime(context); // Request sync. ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { InvalidationServiceFactory.getForProfile(Profile.getLastUsedProfile()) .requestSyncFromNativeChromeForAllTypes(); } }); // Wait till lastSyncedTime > oldSyncTime. Assert.assertTrue("Timed out waiting for syncing to complete.", CriteriaHelper.pollForCriteria(new Criteria() { @Override public boolean isSatisfied() { long currentSyncTime = 0; try { currentSyncTime = getCurrentSyncTime(context); } catch (InterruptedException e) { Log.w(TAG, "Interrupted while getting sync time.", e); } return currentSyncTime > oldSyncTime; } }, SYNC_WAIT_TIMEOUT_MS, SYNC_CHECK_INTERVAL_MS)); } private static long getCurrentSyncTime(final Context context) throws InterruptedException { final Semaphore s = new Semaphore(0); final AtomicLong result = new AtomicLong(); ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { result.set(ProfileSyncService.get(context).getLastSyncedTimeForTest()); s.release(); } }); Assert.assertTrue(s.tryAcquire(SYNC_WAIT_TIMEOUT_MS, TimeUnit.MILLISECONDS)); return result.get(); } /** * Waits for sync to become active. */ public static void waitForSyncActive(final Context context) throws InterruptedException { Assert.assertTrue("Timed out waiting for sync to become active.", CriteriaHelper.pollForCriteria(new Criteria() { @Override public boolean isSatisfied() { return ThreadUtils.runOnUiThreadBlockingNoException( new Callable<Boolean>() { @Override public Boolean call() throws Exception { return ProfileSyncService.get(context).isSyncActive(); } }); } }, SYNC_WAIT_TIMEOUT_MS, SYNC_CHECK_INTERVAL_MS)); } /** * Verifies that the sync is active and signed in with the given account. */ public static void verifySyncIsActiveForAccount(Context context, Account account) throws InterruptedException { waitForSyncActive(context); triggerSyncAndWaitForCompletion(context); verifySignedInWithAccount(context, account); } /** * Makes sure that sync is enabled with the correct account. */ public static void verifySignedInWithAccount(Context context, Account account) { if (account == null) return; Assert.assertEquals( account.name, ChromeSigninController.get(context).getSignedInAccountName()); } /** * Makes sure that the Python sync server was successfully started by checking for a well known * response to a request for the server time. The command line argument for the sync server must * be present in order for this check to be valid. */ public static void verifySyncServerIsRunning() { boolean hasSwitch = CommandLine.getInstance().hasSwitch(SYNC_URL); Assert.assertTrue(SYNC_URL + " is a required parameter for the sync tests.", hasSwitch); String syncTimeUrl = CommandLine.getInstance().getSwitchValue(SYNC_URL) + "/time"; TestHttpServerClient.checkServerIsUp(syncTimeUrl, "0123456789"); } /** * Sets up a test Google account on the device with specified auth token types. */ public static Account setupTestAccount(MockAccountManager accountManager, String accountName, String password, String... allowedAuthTokenTypes) { Account account = AccountManagerHelper.createAccountFromName(accountName); AccountHolder.Builder accountHolder = AccountHolder.create().account(account).password(password); if (allowedAuthTokenTypes != null) { // Auto-allowing provided auth token types for (String authTokenType : allowedAuthTokenTypes) { accountHolder.hasBeenAccepted(authTokenType, true); } } accountManager.addAccountHolderExplicitly(accountHolder.build()); return account; } /** * Sets up a test Google account on the device, that accepts all auth tokens. */ public static Account setupTestAccountThatAcceptsAllAuthTokens( MockAccountManager accountManager, String accountName, String password) { Account account = AccountManagerHelper.createAccountFromName(accountName); AccountHolder.Builder accountHolder = AccountHolder.create().account(account).password(password).alwaysAccept(true); accountManager.addAccountHolderExplicitly(accountHolder.build()); return account; } /** * Returns whether the sync engine has keep everything synced set to true. */ public static boolean isSyncEverythingEnabled(final Context context) { final AtomicBoolean result = new AtomicBoolean(); ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { result.set(ProfileSyncService.get(context).hasKeepEverythingSynced()); } }); return result.get(); } /** * Verifies that the sync status is "Syncing not enabled" and that sync is signed in with the * account. */ public static void verifySyncIsDisabled(Context context, Account account) { Map<Pair<String, String>, String> expectedStats = new HashMap<Pair<String, String>, String>(); expectedStats.put(SYNC_SUMMARY_STATUS, UNINITIALIZED); Assert.assertTrue( "Expected sync to be disabled.", pollAboutSyncStats(context, expectedStats)); verifySignedInWithAccount(context, account); } /** * Retrieves the local Sync data as a JSONArray via ProfileSyncService. * * This method blocks until the data is available or until it times out. */ private static JSONArray getAllNodesAsJsonArray(final Context context) throws JSONException { final Semaphore semaphore = new Semaphore(0); final ProfileSyncService.GetAllNodesCallback callback = new ProfileSyncService.GetAllNodesCallback() { @Override public void onResult(String nodesString) { super.onResult(nodesString); semaphore.release(); } }; ThreadUtils.runOnUiThreadBlocking(new Runnable() { @Override public void run() { ProfileSyncService.get(context).getAllNodes(callback); } }); try { Assert.assertTrue("Semaphore should have been released.", semaphore.tryAcquire(UI_TIMEOUT_MS, TimeUnit.MILLISECONDS)); } catch (InterruptedException e) { throw new RuntimeException(e); } return callback.getNodesAsJsonArray(); } /** * Extracts datatype-specific information from the given JSONObject. The returned JSONObject * contains the same data as a specifics protocol buffer (e.g., TypedUrlSpecifics). */ private static JSONObject extractSpecifics(JSONObject node) throws JSONException { JSONObject specifics = node.getJSONObject("SPECIFICS"); // The key name here is type-specific (e.g., "typed_url" for Typed URLs), so we // can't hard code a value. Iterator<String> keysIterator = specifics.keys(); String key = null; if (!keysIterator.hasNext()) { throw new JSONException("Specifics object has 0 keys."); } key = keysIterator.next(); if (keysIterator.hasNext()) { throw new JSONException("Specifics object has more than 1 key."); } if (key.equals("bookmark")) { JSONObject bookmarkSpecifics = specifics.getJSONObject(key); bookmarkSpecifics.put("parent_id", node.getString("PARENT_ID")); return bookmarkSpecifics; } return specifics.getJSONObject(key); } /** * Converts the given ID to the format stored by the server. * * See the SyncableId (C++) class for more information about ID encoding. To paraphrase, * the client prepends "s" or "c" to the server's ID depending on the commit state of the data. * IDs can also be "r" to indicate the root node, but that entity is not supported here. * * @param clientId the ID to be converted * @return the converted ID */ private static String convertToServerId(String clientId) { if (clientId == null) { throw new IllegalArgumentException("Client entity ID cannot be null."); } else if (clientId.isEmpty()) { throw new IllegalArgumentException("Client ID cannot be empty."); } else if (!clientId.startsWith("s") && !clientId.startsWith("c")) { throw new IllegalArgumentException(String.format( "Client ID (%s) must start with c or s.", clientId)); } return clientId.substring(1); } /** * Returns the local Sync data present for a single datatype. * * For each data entity, a Pair is returned. The first piece of data is the entity's server ID. * This is useful for activities like deleting an entity on the server. The second piece of data * is a JSONObject representing the datatype-specific information for the entity. This data is * the same as the data stored in a specifics protocol buffer (e.g., TypedUrlSpecifics). * * @param context the Context used to retreive the correct ProfileSyncService * @param typeString a String representing a specific datatype. * * TODO(pvalenzuela): Replace typeString with the native ModelType enum or something else * that will avoid callers needing to specify the native string version. * * @return a List of Pair<String, JSONObject> representing the local Sync data */ public static List<Pair<String, JSONObject>> getLocalData( Context context, String typeString) throws JSONException { JSONArray localData = getAllNodesAsJsonArray(context); JSONArray datatypeNodes = new JSONArray(); for (int i = 0; i < localData.length(); i++) { JSONObject datatypeObject = localData.getJSONObject(i); if (datatypeObject.getString("type").equals(typeString)) { datatypeNodes = datatypeObject.getJSONArray("nodes"); break; } } List<Pair<String, JSONObject>> localDataForDatatype = new ArrayList<Pair<String, JSONObject>>(datatypeNodes.length()); for (int i = 0; i < datatypeNodes.length(); i++) { JSONObject entity = datatypeNodes.getJSONObject(i); if (!entity.getString("UNIQUE_SERVER_TAG").isEmpty()) { // Ignore permanent items (e.g., root datatype folders). continue; } String id = convertToServerId(entity.getString("ID")); localDataForDatatype.add(Pair.create(id, extractSpecifics(entity))); } return localDataForDatatype; } /** * Retrieves the sync internals information which is the basis for chrome://sync-internals and * makes the result available in {@link AboutSyncInfoGetter#getAboutInfo()}. * * This class has to be run on the main thread, as it accesses the ProfileSyncService. */ public static class AboutSyncInfoGetter implements Runnable { private static final String TAG = "AboutSyncInfoGetter"; final Context mContext; Map<Pair<String, String>, String> mAboutInfo; public AboutSyncInfoGetter(Context context) { mContext = context.getApplicationContext(); mAboutInfo = new HashMap<Pair<String, String>, String>(); } @Override public void run() { String info = ProfileSyncService.get(mContext).getSyncInternalsInfoForTest(); try { mAboutInfo = getAboutInfoStats(info); } catch (JSONException e) { Log.w(TAG, "Unable to parse JSON message: " + info, e); } } public Map<Pair<String, String>, String> getAboutInfo() { return mAboutInfo; } } /** * Helper class used to create a mock account on the device. */ public static class SyncTestContext extends AdvancedMockContext { public SyncTestContext(Context context) { super(context); } @Override public Object getSystemService(String name) { if (Context.ACCOUNT_SERVICE.equals(name)) { throw new UnsupportedOperationException( "Sync tests should not use system Account Manager."); } return super.getSystemService(name); } } }
bsd-3-clause
kbc-developers/android_packages_inputmethods_Mozc
src/com/google/android/inputmethod/japanese/keyboard/Key.java
8278
// Copyright 2010-2015, Google Inc. // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package org.mozc.android.inputmethod.japanese.keyboard; import org.mozc.android.inputmethod.japanese.keyboard.BackgroundDrawableFactory.DrawableType; import com.google.common.base.Objects; import com.google.common.base.Objects.ToStringHelper; import com.google.common.base.Optional; import com.google.common.base.Preconditions; import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; /** * This is a model class of a key, corresponding to a {@code &lt;Key&gt;} element * in a xml resource file. * * Here is a list this class supports. * <ul> * <li> {@code keyBackground}: an background image for the key. * <li> {@code width}: key width. * <li> {@code height}: key height. * <li> {@code horizontalGap}: the gap between the (both) next keys and this key. * Note that the width should includes horizontalGap. HorizontalGap will be evenly * divided into each side. * <li> {@code edgeFlags}: flags whether the key should stick to keyboard's boundary. * <li> {@code isRepeatable}: whether the key long press cause a repeated key tapping. * <li> {@code isModifier}: whether the key is modifier (e.g. shift key). * </ul> * * The {@code &lt;Key&gt;} element can have (at most) two {@code &lt;KeyState&gt;} elements. * See also KeyState class for details. * */ public class Key { /** * This enum is only for spacers, not actual keys, to specify clicking behavior. * If this is set to: * - {@code EVEN}, then the spacer will be split into two regions, left and right. * If a user touches left half, it is considered a part of the key on the spacer's immediate * left. If a user touches right half, it is considered a part of the right one. * - {@code LEFT}, then the corresponding key is the left one. * - {@code RIGHT}, then the corresponding key is the right one. */ public enum Stick { EVEN, LEFT, RIGHT, } private final int x; private final int y; private final int width; private final int height; private final int horizontalGap; private final int edgeFlags; private final boolean isRepeatable; private final boolean isModifier; private final Stick stick; // Default KeyState. // Absent if this is a spacer. private final Optional<KeyState> defaultKeyState; private final DrawableType keyBackgroundDrawableType; private final List<KeyState> keyStateList; public Key(int x, int y, int width, int height, int horizontalGap, int edgeFlags, boolean isRepeatable, boolean isModifier, Stick stick, DrawableType keyBackgroundDrawableType, List<? extends KeyState> keyStateList) { Preconditions.checkNotNull(stick); Preconditions.checkNotNull(keyBackgroundDrawableType); Preconditions.checkNotNull(keyStateList); Preconditions.checkArgument(width >= 0); Preconditions.checkArgument(height >= 0); this.x = x; this.y = y; this.width = width; this.height = height; this.horizontalGap = horizontalGap; this.edgeFlags = edgeFlags; this.isRepeatable = isRepeatable; this.isModifier = isModifier; this.stick = stick; this.keyBackgroundDrawableType = keyBackgroundDrawableType; List<KeyState> tmpKeyStateList = null; // Lazy creation. Optional<KeyState> defaultKeyState = Optional.absent(); for (KeyState keyState : keyStateList) { Set<KeyState.MetaState> metaStateSet = keyState.getMetaStateSet(); if (metaStateSet.isEmpty() || metaStateSet.contains(KeyState.MetaState.FALLBACK)) { if (defaultKeyState.isPresent()) { throw new IllegalArgumentException("Found duplicate default meta state"); } defaultKeyState = Optional.of(keyState); if (metaStateSet.size() <= 1) { // metaStateSet contains only FALLBACK continue; } } if (tmpKeyStateList == null) { tmpKeyStateList = new ArrayList<KeyState>(); } tmpKeyStateList.add(keyState); } Preconditions.checkArgument(defaultKeyState.isPresent() || tmpKeyStateList == null, "Default KeyState is mandatory for non-spacer."); this.defaultKeyState = defaultKeyState; this.keyStateList = tmpKeyStateList == null ? Collections.<KeyState>emptyList() : Collections.unmodifiableList(tmpKeyStateList); } public int getX() { return x; } public int getY() { return y; } public int getWidth() { return width; } public int getHeight() { return height; } public int getHorizontalGap() { return horizontalGap; } public int getEdgeFlags() { return edgeFlags; } public boolean isRepeatable() { return isRepeatable; } public boolean isModifier() { return isModifier; } public Stick getStick() { return stick; } public DrawableType getKeyBackgroundDrawableType() { return keyBackgroundDrawableType; } /** * Returns {@code KeyState} at least one of which the metaState is in given {@code metaStates}. * <p> * For example, if there are following {@code KeyState}s (registered in this order); * <ul> * <li>KeyState1 : metaStates=A|B * <li>KeyState2 : metaStates=C * <li>KeyState3 : metaStates=null (default) * </ul> * <ul> * <li>metaStates=A gets KeyState1 * <li>metaStates=A|B gets KeyState1 * <li>metaStates=D gets KeyState3 as default * <li>metaStates=A|C gets KeyState1 as it is registered earlier than KeyState2. * </ul> */ public Optional<KeyState> getKeyState(Set<KeyState.MetaState> metaStates) { Preconditions.checkNotNull(metaStates); for (KeyState state : keyStateList) { if (!Sets.intersection(state.getMetaStateSet(), metaStates).isEmpty()) { return Optional.of(state); } } return defaultKeyState; } public boolean isSpacer() { return !defaultKeyState.isPresent(); } @Override public String toString() { ToStringHelper helper = Objects.toStringHelper(this); helper.add("defaultKeyState", defaultKeyState.isPresent() ? defaultKeyState.get().toString() : "empty"); for (KeyState entry : keyStateList) { helper.addValue(entry.toString()); } return helper.toString(); } /** * Gets all the {@code KeyState}s, including default one. */ public Iterable<KeyState> getKeyStates() { if (defaultKeyState.isPresent()) { return Iterables.concat(keyStateList, Collections.singletonList(defaultKeyState.get())); } else { // Spacer return Collections.emptySet(); } } }
bsd-3-clause
arshadalisoomro/pebble
src/main/java/net/sourceforge/pebble/permalink/Latin1SeoPermalinkProvider.java
7277
/* * Copyright (c) 2003-2011, Simon Brown * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * - Neither the name of Pebble nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ package net.sourceforge.pebble.permalink; import java.text.SimpleDateFormat; import java.util.Iterator; import java.util.List; import net.sourceforge.pebble.domain.Blog; import net.sourceforge.pebble.domain.BlogEntry; import net.sourceforge.pebble.domain.BlogService; import net.sourceforge.pebble.domain.BlogServiceException; import net.sourceforge.pebble.domain.Day; import net.sourceforge.pebble.domain.Month; /** * Generates permalinks based upon the blog entry title. This implementation * retains characters from the latin1 character by converting * them to suitable "url-friendly" counterparts. * <p/> * It also uses dashes instead of underscores for whitespace as this is * what Google recommends. * <p/> * For titles without characters from the latin1 character set * the blog entry ID is used for the permalink instead. * * @author Mattias Reichel */ public class Latin1SeoPermalinkProvider extends PermalinkProviderSupport { /** * the regex used to check for a day request */ private static final String DAY_PERMALINK_REGEX = "/\\d\\d\\d\\d/\\d\\d/\\d\\d"; /** * the regex used to check for a monthly blog request */ private static final String MONTH_PERMALINK_REGEX = "/\\d\\d\\d\\d/\\d\\d"; /** * the regex used to check for a blog entry permalink */ private static final String BLOG_ENTRY_PERMALINK_REGEX = "/[\\w-]*"; /** * the Blog associated with this provider instance */ private Blog blog; /** * Gets the blog associated with this provider instance. * * @return a Blog instance */ public Blog getBlog() { return this.blog; } /** * Sets the blog associated with this provider instance. * * @param blog a Blog instance */ public void setBlog(Blog blog) { this.blog = blog; } /** * Gets the permalink for a blog entry. * * @return a URI as a String */ public synchronized String getPermalink(BlogEntry blogEntry) { if (blogEntry.getTitle() == null || blogEntry.getTitle().length() == 0) { return buildPermalink(blogEntry); } else { List<BlogEntry> entries = getBlog().getBlogEntries(); int count = 0; for (int i = entries.size() - 1; i >= 0 && !entries.get(i).getId().equals(blogEntry.getId()); i--) { if (entries.get(i).getTitle().equals(blogEntry.getTitle())) { count++; } } if (count == 0) { return buildPermalink(blogEntry); } else { return buildPermalink(blogEntry) + "_" + blogEntry.getId(); } } } private String buildPermalink(BlogEntry blogEntry) { String title = getCuratedPermalinkTitle(blogEntry, "-"); return "/" + title; } public boolean isBlogEntryPermalink(String uri) { if (uri != null) { return uri.matches(BLOG_ENTRY_PERMALINK_REGEX); } else { return false; } } public BlogEntry getBlogEntry(String uri) { BlogService service = new BlogService(); Iterator it = getBlog().getBlogEntries().iterator(); while (it.hasNext()) { try { BlogEntry blogEntry = service.getBlogEntry(getBlog(), "" + ((BlogEntry) it.next()).getId()); // use the local permalink, just in case the entry has been aggregated // and an original permalink assigned if (blogEntry.getLocalPermalink().endsWith(uri)) { return blogEntry; } } catch (BlogServiceException e) { // do nothing } } return null; } /** * Gets the permalink for a monthly blog. * * @param month a Month instance * @return a URI as a String */ public String getPermalink(Month month) { SimpleDateFormat format = new SimpleDateFormat("'/'yyyy'/'MM"); format.setTimeZone(blog.getTimeZone()); return format.format(month.getDate()); } /** * Determines whether the specified URI is a monthly blog permalink. * * @param uri a relative URI * @return true if the URI represents a permalink to a monthly blog, * false otherwise */ public boolean isMonthPermalink(String uri) { if (uri != null) { return uri.matches(MONTH_PERMALINK_REGEX); } else { return false; } } /** * Gets the monthly blog referred to by the specified URI. * * @param uri a relative URI * @return a Month instance, or null if one can't be found */ public Month getMonth(String uri) { String year = uri.substring(1, 5); String month = uri.substring(6, 8); return getBlog().getBlogForMonth(Integer.parseInt(year), Integer.parseInt(month)); } /** * Gets the permalink for a day. * * @param day a Day instance * @return a URI as a String */ public String getPermalink(Day day) { SimpleDateFormat format = new SimpleDateFormat("'/'yyyy'/'MM'/'dd"); format.setTimeZone(blog.getTimeZone()); return format.format(day.getDate()); } /** * Determines whether the specified URI is a day permalink. * * @param uri a relative URI * @return true if the URI represents a permalink to a day, * false otherwise */ public boolean isDayPermalink(String uri) { if (uri != null) { return uri.matches(DAY_PERMALINK_REGEX); } else { return false; } } /** * Gets the day referred to by the specified URI. * * @param uri a relative URI * @return a Day instance, or null if one can't be found */ public Day getDay(String uri) { String year = uri.substring(1, 5); String month = uri.substring(6, 8); String day = uri.substring(9, 11); return getBlog().getBlogForDay(Integer.parseInt(year), Integer.parseInt(month), Integer.parseInt(day)); } }
bsd-3-clause
vincentml/basex
basex-core/src/main/java/org/basex/gui/view/folder/FolderView.java
12545
package org.basex.gui.view.folder; import static org.basex.gui.GUIConstants.*; import static org.basex.gui.layout.BaseXKeys.*; import java.awt.*; import java.awt.event.*; import java.awt.image.*; import java.util.*; import javax.swing.*; import org.basex.data.*; import org.basex.gui.*; import org.basex.gui.layout.*; import org.basex.gui.view.*; import org.basex.query.value.seq.*; /** * This view offers a folder visualization of the database contents. * * @author BaseX Team 2005-16, BSD License * @author Christian Gruen */ public final class FolderView extends View { /** Horizontal offset. */ private static final int OFFX = 8; /** References closed nodes. */ boolean[] opened; /** Line Height. */ int lineH; /** Focused folder position. */ int focusedPos; /** Closed marker. */ private BufferedImage closedMarker; /** Opened marker. */ private BufferedImage openedMarker; /** Scroll Bar. */ private final BaseXScrollBar scroll; /** Vertical mouse position. */ private int totalW; /** Start y value. */ private int startY; /** Total height. */ private int treeH; /** Box Size. */ private int boxW; /** Box Margin. */ private int boxMargin; /** * Default constructor. * @param man view manager */ public FolderView(final ViewNotifier man) { super(FOLDERVIEW, man); createBoxes(); layout(new BorderLayout()); scroll = new BaseXScrollBar(this); add(scroll, BorderLayout.EAST); new BaseXPopup(this, POPUP); } @Override public void refreshInit() { scroll.pos(0); if(gui.context.data() == null) { opened = null; } else if(visible()) { refreshOpenedNodes(); refreshHeight(); repaint(); } } /** * Refreshes opened nodes. */ private void refreshOpenedNodes() { final Data data = gui.context.data(); opened = new boolean[data.meta.size]; final int is = data.meta.size; for(int pre = 0; pre < is; ++pre) { opened[pre] = data.parent(pre, data.kind(pre)) <= 0; } } @Override public void refreshFocus() { repaint(); } @Override public void refreshMark() { final int pre = gui.context.focused; if(pre == -1) return; // jump to the currently marked node final Data data = gui.context.data(); final int par = data.parent(pre, data.kind(pre)); // open node if it's not visible jumpTo(pre, par != -1 && !opened[par]); repaint(); } @Override public void refreshContext(final boolean more, final boolean quick) { startY = 0; scroll.pos(0); final DBNodes curr = gui.context.current(); if(more && curr.size() != 0) jumpTo(curr.pre(0), true); refreshHeight(); repaint(); } @Override public void refreshLayout() { scroll.refreshLayout(); createBoxes(); if(opened == null) return; refreshOpenedNodes(); refreshHeight(); revalidate(); repaint(); } @Override public void refreshUpdate() { if(opened == null) return; final Data data = gui.context.data(); if(opened.length < data.meta.size) opened = Arrays.copyOf(opened, data.meta.size); startY = 0; scroll.pos(0); final DBNodes marked = gui.context.marked; if(marked.size() != 0) jumpTo(marked.pre(0), true); refreshHeight(); repaint(); } @Override public boolean visible() { return gui.gopts.get(GUIOptions.SHOWFOLDER); } @Override public void visible(final boolean v) { gui.gopts.set(GUIOptions.SHOWFOLDER, v); } @Override protected boolean db() { return true; } /** * Refreshes tree height. */ private void refreshHeight() { if(opened == null) return; treeH = new FolderIterator(this).height(); scroll.height(treeH + 5); } @Override public void paintComponent(final Graphics g) { if(opened == null) { refreshInit(); return; } super.paintComponent(g); if(opened == null) return; gui.painting = true; startY = -scroll.pos(); totalW = getWidth() - (treeH > getHeight() ? scroll.getWidth() : 0); final FolderIterator it = new FolderIterator(this, startY + 5, getHeight()); final Data data = gui.context.data(); while(it.more()) { final int kind = data.kind(it.pre); final boolean elem = kind == Data.ELEM || kind == Data.DOC; final int x = OFFX + it.level * (lineH >> 1) + (elem ? lineH : boxW); drawEntry(g, it.pre, x, it.y + boxW); } gui.painting = false; } /** * Draws a string and checks mouse position. * @param g graphics reference * @param pre pre value * @param x horizontal coordinate * @param y vertical coordinate */ private void drawEntry(final Graphics g, final int pre, final int x, final int y) { final Data data = gui.context.data(); final DBNodes marked = gui.context.marked; final int kind = data.kind(pre); final boolean elem = kind == Data.ELEM || kind == Data.DOC; Color col = TEXT; Font fnt = font; if(marked.find(pre) >= 0) { // mark node col = colormark3; fnt = bfont; } if(y < -lineH) return; g.setColor(color1); g.drawLine(2, y + boxMargin - 1, totalW - 5, y + boxMargin - 1); final byte[] name = ViewData.content(data, pre, false); int p = gui.context.focused; while(p > pre) p = ViewData.parent(data, p); if(pre == p) { g.setColor(color2); g.fillRect(0, y - boxW - boxMargin, totalW, lineH + 1); } if(elem) { final int yy = y - boxW; final Image marker = opened[pre] ? openedMarker : closedMarker; g.drawImage(marker, x - lineH, yy, this); } g.setFont(fnt); g.setColor(col); final int tw = totalW + 6; BaseXLayout.chopString(g, name, x, y - fontSize, tw - x - 10, fontSize); if(gui.context.focused == pre) { g.setColor(color4); g.drawRect(1, y - boxW - boxMargin, totalW - 3, lineH + 1); g.drawRect(2, y - boxW - boxMargin + 1, totalW - 5, lineH - 1); } } /** * Focuses the current pre value. * @param x x mouse position * @param y y mouse position * @return currently focused id */ private boolean focus(final int x, final int y) { if(opened == null) return false; final int fsz = fontSize; final FolderIterator it = new FolderIterator(this, startY + 3, getHeight()); final Data data = gui.context.data(); while(it.more()) { if(y > it.y && y <= it.y + lineH) { Cursor c = CURSORARROW; final int kind = data.kind(it.pre); if(kind == Data.ELEM || kind == Data.DOC) { // set cursor when moving over tree boxes final int xx = OFFX + it.level * (lineH >> 1) + lineH - 6; if(x > xx - fsz && x < xx) c = CURSORHAND; } gui.cursor(c); gui.notify.focus(it.pre, this); repaint(); return true; } } return false; } /** * Jumps to the specified pre value. * @param pre pre value to be found * @param open opened folder */ private void jumpTo(final int pre, final boolean open) { if(getWidth() == 0 || !visible()) return; if(open) { int p = pre; while(p > 0) { opened[p] = true; p = ViewData.parent(gui.context.data(), p); } refreshHeight(); } // find specified pre value final FolderIterator it = new FolderIterator(this); while(it.more() && pre != it.pre); // set new vertical position final int y = -it.y; final int h = getHeight(); if(y > startY || y + h < startY + lineH) { startY = Math.min(0, Math.max(-treeH + h - 5, y + lineH)); scroll.pos(-startY); } } /** * Creates click boxes. */ private void createBoxes() { final int s = fontSize; boxMargin = s >> 2; lineH = s + boxMargin; boxW = s - boxMargin; final int sp = Math.max(1, s >> 4); /* Empty Box. */ final BufferedImage emptyBox = new BufferedImage(boxW + 1, boxW + 1, BufferedImage.TYPE_INT_ARGB); Graphics2D g = BaseXLayout.antiAlias(emptyBox.createGraphics()); g.setColor(color4); g.fillOval((boxW >> 2) - 1, (boxW >> 2) + 1, boxW >> 1, boxW >> 1); g.setColor(color3); g.fillOval((boxW >> 2) - 2, boxW >> 2, boxW >> 1, boxW >> 1); openedMarker = new BufferedImage(boxW + 1, boxW + 1, BufferedImage.TYPE_INT_ARGB); g = BaseXLayout.antiAlias(openedMarker.createGraphics()); Polygon p = new Polygon(new int[] { 0, boxW, boxW >> 1 }, new int[] { boxW - sp >> 1, boxW - sp >> 1, boxW }, 3); p.translate(0, -1); g.setColor(color4); g.fillPolygon(p); p.translate(-1, -1); g.setColor(color3); g.fillPolygon(p); closedMarker = new BufferedImage(boxW + 1, boxW + 1, BufferedImage.TYPE_INT_ARGB); g = BaseXLayout.antiAlias(closedMarker.createGraphics()); p = new Polygon(new int[] { boxW - sp >> 1, boxW, boxW - sp >> 1 }, new int[] { 0, boxW >> 1, boxW }, 3); p.translate(-1, 1); g.setColor(color4); g.fillPolygon(p); p.translate(-1, -1); g.setColor(color3); g.fillPolygon(p); } @Override public void mouseMoved(final MouseEvent e) { if(gui.updating) return; super.mouseMoved(e); // set new focus focus(e.getX(), e.getY()); } @Override public void mousePressed(final MouseEvent e) { if(gui.updating || opened == null) return; super.mousePressed(e); if(!focus(e.getX(), e.getY())) return; // add or remove marked node final DBNodes marked = gui.context.marked; if(e.getClickCount() == 2) { gui.notify.context(marked, false, null); } else if(e.isShiftDown()) { gui.notify.mark(1, null); } else if(sc(e) && SwingUtilities.isLeftMouseButton(e)) { gui.notify.mark(2, null); } else if(getCursor() != CURSORHAND) { if(!marked.contains(gui.context.focused)) gui.notify.mark(0, null); } else { // open/close entry opened[gui.context.focused] ^= true; refreshHeight(); repaint(); } } @Override public void mouseDragged(final MouseEvent e) { final boolean left = SwingUtilities.isLeftMouseButton(e); if(!left || gui.updating || opened == null) return; super.mouseDragged(e); // marks currently focused node if(focus(e.getX(), e.getY())) gui.notify.mark(1, null); } @Override public void mouseWheelMoved(final MouseWheelEvent e) { if(gui.updating) return; scroll.pos(scroll.pos() + e.getUnitsToScroll() * 20); repaint(); } @Override public void keyPressed(final KeyEvent e) { if(gui.updating || opened == null) return; super.keyPressed(e); int focus = focusedPos == -1 ? 0 : focusedPos; if(gui.context.focused == -1) gui.context.focused = 0; final int focusPre = gui.context.focused; final Data data = gui.context.data(); final int kind = data.kind(focusPre); final boolean right = NEXTCHAR.is(e); boolean down = NEXTLINE.is(e); boolean up = PREVLINE.is(e); if(right || PREVCHAR.is(e)) { // open/close subtree if(e.isShiftDown()) { opened[focusPre] = right; final int s = data.meta.size; for(int pre = focusPre + 1; pre != s && data.parent(pre, data.kind(pre)) >= focusPre; pre++) { opened[pre] = right; } refreshHeight(); repaint(); return; } if(right ^ opened[focusPre] && (!ViewData.leaf(gui.gopts, data, focusPre) || data.attSize(focusPre, kind) > 1)) { opened[focusPre] = right; refreshHeight(); repaint(); } else if(right) { down = true; } else { up = true; } } if(down) { focus = Math.min(data.meta.size - 1, focus + 1); } else if(up) { focus = Math.max(0, focus - 1); } else if(NEXTPAGE.is(e)) { focus = Math.min(data.meta.size - 1, focus + getHeight() / lineH); } else if(PREVPAGE.is(e)) { focus = Math.max(0, focus - getHeight() / lineH); } else if(TEXTSTART.is(e)) { focus = 0; } else if(TEXTEND.is(e)) { focus = data.meta.size - 1; } if(focus == focusedPos) return; // calculate new tree position gui.context.focused = -1; final DBNodes curr = gui.context.current(); int pre = curr.pre(0); final FolderIterator it = new FolderIterator(this); while(it.more() && focus-- != 0) pre = it.pre; if(pre == curr.pre(0) && down) ++pre; gui.notify.focus(pre, this); jumpTo(pre, false); repaint(); } }
bsd-3-clause
smesdaghi/geogig
src/core/src/main/java/org/locationtech/geogig/di/PluginDefaults.java
1697
/* Copyright (c) 2014 Boundless and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Distribution License v1.0 * which accompanies this distribution, and is available at * https://www.eclipse.org/org/documents/edl-v10.html * * Contributors: * David Winslow (Boundless) - initial implementation */ package org.locationtech.geogig.di; import com.google.common.base.Optional; public final class PluginDefaults { private VersionedFormat refs; private VersionedFormat objects; private VersionedFormat graph; PluginDefaults() { // } public PluginDefaults(VersionedFormat objects, VersionedFormat refs, VersionedFormat graph) { this.refs = refs; this.objects = objects; this.graph = graph; } public PluginDefaults(StorageProvider provider) { refs = provider.getRefsDatabaseFormat(); objects = provider.getObjectDatabaseFormat(); graph = provider.getGraphDatabaseFormat(); } public Optional<VersionedFormat> getRefs() { return Optional.fromNullable(refs); } public Optional<VersionedFormat> getObjects() { return Optional.fromNullable(objects); } public Optional<VersionedFormat> getGraph() { return Optional.fromNullable(graph); } public void setObjects(VersionedFormat objects) { this.objects = objects; } public void setRefs(VersionedFormat refs) { this.refs = refs; } public void setGraph(VersionedFormat graph) { this.graph = graph; } public static final PluginDefaults NO_PLUGINS = new PluginDefaults(); }
bsd-3-clause
StexX/KiWi-OSE
src/action/kiwi/service/render/RenderingServiceImpl.java
19667
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright (c) 2008-2009, The KiWi Project (http://www.kiwi-project.eu) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of the KiWi Project nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * Contributor(s): * * */ package kiwi.service.render; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.security.PrivateKey; import java.util.Collection; import java.util.LinkedList; import java.util.List; import javax.ejb.Remove; import javax.ejb.Stateless; import kiwi.api.config.ConfigurationService; import kiwi.api.event.KiWiEvents; import kiwi.api.render.RenderingServiceLocal; import kiwi.api.render.RenderingServiceRemote; import kiwi.api.security.CryptoService; import kiwi.config.Configuration; import kiwi.config.UserConfiguration; import kiwi.model.Constants; import kiwi.model.content.ContentItem; import kiwi.model.content.TextContent; import kiwi.model.user.User; import kiwi.service.render.renderlet.MediaContentRenderlet; import kiwi.service.render.renderlet.SourceRenderlet; import kiwi.service.render.renderlet.XOMRenderlet; import kiwi.util.KiWiStringUtils; import nu.xom.Document; import nu.xom.Node; import nu.xom.Nodes; import nu.xom.ParsingException; import nu.xom.XPathContext; import nu.xom.canonical.Canonicalizer; import org.jboss.seam.Component; import org.jboss.seam.ScopeType; import org.jboss.seam.annotations.AutoCreate; import org.jboss.seam.annotations.In; import org.jboss.seam.annotations.Install; import org.jboss.seam.annotations.Logger; import org.jboss.seam.annotations.Name; import org.jboss.seam.annotations.Observer; import org.jboss.seam.annotations.Out; import org.jboss.seam.annotations.Scope; import org.jboss.seam.cache.CacheProvider; import org.jboss.seam.log.Log; /** * The RenderingPipeline contains methods that transform the content item content contained in the database * into the HTML (or other presentation) that is sent to the browser. Typical tasks are rendering wiki links as * internal links, adding RDF/A annotations, and so on. * * RenderingPipeline is implemented as a stateless bean and shared among all users; the rendering for each user * takes place in ContentRenderService, which calls the renderer methods with the current context item * * @see StoringServiceImpl for the transformation process from the edited XHTML to the internal XHTML representation * * TODO: need a renderlet that extracts the content of the HTML body so that we don't get nested <html> and <body> tags * * @author sschaffe * */ @Stateless @Name("renderingPipeline") @Scope(ScopeType.STATELESS) @AutoCreate @Install(dependencies="configurationService") public class RenderingServiceImpl implements RenderingServiceLocal, RenderingServiceRemote { @In(value="renderingService.htmlSourceRenderlets",scope=ScopeType.APPLICATION, required=false) @Out(value="renderingService.htmlSourceRenderlets",scope=ScopeType.APPLICATION) private List<SourceRenderlet> htmlSourceRenderlets; @In(value="renderingService.htmlXOMRenderlets",scope=ScopeType.APPLICATION, required=false) @Out(value="renderingService.htmlXOMRenderlets",scope=ScopeType.APPLICATION) private List<XOMRenderlet> htmlXOMRenderlets; @In(value="renderingService.annotationSourceRenderlets",scope=ScopeType.APPLICATION, required=false) @Out(value="renderingService.annotationSourceRenderlets",scope=ScopeType.APPLICATION) private List<SourceRenderlet> annotationSourceRenderlets; @In(value="renderingService.annotationXOMRenderlets",scope=ScopeType.APPLICATION, required=false) @Out(value="renderingService.annotationXOMRenderlets",scope=ScopeType.APPLICATION) private List<XOMRenderlet> annotationXOMRenderlets; @In(value="renderingService.editorSourceRenderlets",scope=ScopeType.APPLICATION, required=false) @Out(value="renderingService.editorSourceRenderlets",scope=ScopeType.APPLICATION) private List<SourceRenderlet> editorSourceRenderlets; @In(value="renderingService.editorXOMRenderlets",scope=ScopeType.APPLICATION, required=false) @Out(value="renderingService.editorXOMRenderlets",scope=ScopeType.APPLICATION) private List<XOMRenderlet> editorXOMRenderlets; @In(value="renderingService.mediaRenderlets",scope=ScopeType.APPLICATION, required=false) @Out(value="renderingService.mediaRenderlets",scope=ScopeType.APPLICATION) private List<MediaContentRenderlet> mediaRenderlets; @In private CacheProvider cacheProvider; // @In // private FacesMessages facesMessages; @Logger private static Log log; @In(value="configurationService", create=true) ConfigurationService configurationService; @Observer(KiWiEvents.CONFIGURATIONSERVICE_INIT) public void initialise(String dummyString) { log.info("RenderingPipeline starting up ..."); htmlSourceRenderlets = new LinkedList<SourceRenderlet>(); htmlXOMRenderlets = new LinkedList<XOMRenderlet>(); annotationSourceRenderlets = new LinkedList<SourceRenderlet>(); annotationXOMRenderlets = new LinkedList<XOMRenderlet>(); editorSourceRenderlets = new LinkedList<SourceRenderlet>(); editorXOMRenderlets = new LinkedList<XOMRenderlet>(); mediaRenderlets = new LinkedList<MediaContentRenderlet>(); // initialise renderlets from configuration in kspace // renderlets.html.source -> htmlSourceRenderlets // renderlets.html.xom -> htmlXOMRenderlets // renderlets.editor.source -> editorSourceRenderlets // renderlets.editor.xom -> editorXOMRenderlets // renderlets.media -> mediaRenderlets for(String cls : configurationService.getConfiguration("renderlets.html.source").getListValue()) { initRenderlet(htmlSourceRenderlets,cls); } log.info("rendering pipeline: #0 source renderlets for HTML rendering", htmlSourceRenderlets.size()); for(String cls : configurationService.getConfiguration("renderlets.html.xom").getListValue()) { initRenderlet(htmlXOMRenderlets,cls); } log.info("rendering pipeline: #0 XOM renderlets for HTML rendering", htmlXOMRenderlets.size()); for(String cls : configurationService.getConfiguration("renderlets.annotation.source").getListValue()) { initRenderlet(annotationSourceRenderlets,cls); } log.info("rendering pipeline: #0 source renderlets for Annotation View rendering", htmlSourceRenderlets.size()); for(String cls : configurationService.getConfiguration("renderlets.annotation.xom").getListValue()) { initRenderlet(annotationXOMRenderlets,cls); } log.info("rendering pipeline: #0 XOM renderlets for Annotation View rendering", htmlXOMRenderlets.size()); for(String cls : configurationService.getConfiguration("renderlets.editor.source").getListValue()) { initRenderlet(editorSourceRenderlets,cls); } log.info("rendering pipeline: #0 source renderlets for editor rendering", htmlSourceRenderlets.size()); for(String cls : configurationService.getConfiguration("renderlets.editor.xom").getListValue()) { initRenderlet(editorXOMRenderlets,cls); } log.info("rendering pipeline: #0 XOM renderlets for editor rendering", htmlXOMRenderlets.size()); for(String cls : configurationService.getConfiguration("renderlets.media").getListValue()) { initRenderlet(mediaRenderlets,cls); } log.info("rendering pipeline: #0 renderlets for media rendering", mediaRenderlets.size()); } private <T> void initRenderlet(List<T> list, String cls) { try { //T savelet = (T)Class.forName(cls).newInstance(); T renderlet = (T) Component.getInstance(cls); if(renderlet != null) list.add(renderlet); else log.warn("warning: renderlet #0 was null after initialisation", cls); } catch (Exception e) { log.error("error while instantiating renderlet #0: #1",cls,e.getMessage()); } } @Remove public void shutdown() { } /* (non-Javadoc) * @see kiwi.api.render.RenderingService#renderHTML(java.lang.String, kiwi.model.content.ContentItem) */ public String renderHTML(String text, ContentItem ci) { log.debug("rendering: " + text); Document xom = string2xom(text); log.debug(xom.getBaseURI()); // perform rendering: XOM renderlets for(XOMRenderlet renderlet : htmlXOMRenderlets) { xom = renderlet.apply(ci.getResource(), xom); } // select the element marked as kiwi:type="page" and take all elements below it String result; XPathContext namespaces = new XPathContext(); namespaces.addNamespace("kiwi", Constants.NS_KIWI_HTML); Nodes nl = xom.query("//*[@kiwi:type='page']/*",namespaces); if(nl.size() > 0) { result = ""; for(int i = 0; i < nl.size(); i++) { result += xom2string(nl.get(i),true); } } else { result = xom2string(xom,true); } // perform rendering: source renderlets for(SourceRenderlet renderlet : htmlSourceRenderlets) { result = renderlet.apply(ci.getResource(), result); } return result; } public String renderHTML(ContentItem ci) { TextContent content = ci.getTextContent(); if(content != null) { String html = content.getId() == null ? null : (String)cacheProvider.get("rendered.html", content.getId()+""); // cached rendering; text content is immutable, so the id is a good key for the renderer if(html == null) { html = renderGeneric(ci, htmlXOMRenderlets, htmlSourceRenderlets); if(content.getId() != null) { cacheProvider.put("rendered.html", content.getId()+"", html); } } return html; } else { return ""; } } @Override public String renderHTML(ContentItem ci, User user) { TextContent content = ci.getTextContent(); if(content != null) { String html = content.getId() == null ? null : (String)cacheProvider.get("rendered.html", content.getId()+""); // String html = null; if(html == null) { PrivateKey priv = null; if(user != null && (priv = user.getPrivateKey()) != null) { UserConfiguration encryption = configurationService.getUserConfiguration(user,user.getLogin() + "-key:" + ci.getResource()); String key = encryption.getEncryptedKey(); if(ci != null && encryption != null && key != null) { byte[] encKeyBytes = KiWiStringUtils.fromHex(key, key.length()); if(encKeyBytes != null) { // TODO: decrypt AES key from RSA private key CryptoService cryptoService = (CryptoService) Component.getInstance("cryptoService"); byte[] keyBytes = cryptoService.decryptAsymmetric(encKeyBytes, priv); String cipher = KiWiStringUtils.extractAESCipher(content.getHtmlContent()); if(cipher != null) { byte[] plainBytes = cryptoService.decryptSymmetric( KiWiStringUtils.fromHex(cipher,cipher.length()), keyBytes, "AES"); html = content.getHtmlContent().replaceAll( "-----BEGIN AES ENCRYPTED MESSAGE-----<br></br><br></br>" + ".*" + "<br></br><br></br>------END AES ENCRYPTED MESSAGE------", new String(plainBytes)); } } } } } // cached rendering; text content is immutable, so the id is a good key for the renderer if(html == null) { html = renderGeneric(ci, htmlXOMRenderlets, htmlSourceRenderlets); if(content.getId() != null) { cacheProvider.put("rendered.html", content.getId()+"", html); } } return html; } else { return ""; } } // KIWI-766, rendering is a function of textcontent AND metadata, so just clear cache if metadata changes. @Observer(KiWiEvents.METADATA_UPDATED) public void listenMetadataUpdate(ContentItem item) { log.info("onMetadataUpdate"); if (item != null && item.getTextContent() != null) { cacheProvider.remove("rendered.html", item.getTextContent().getId()+""); } } @Override public String renderEditor(ContentItem ci, User user) { TextContent content = ci.getTextContent(); if(content != null) { TextContent text = (TextContent)content; String html = text.getXmlString(); PrivateKey priv = null; if(user != null && (priv = user.getPrivateKey()) != null) { UserConfiguration encryption = configurationService.getUserConfiguration(user,user.getLogin() + "-key:" + ci.getResource()); String key = encryption.getEncryptedKey(); if(ci != null && encryption != null && key != null) { byte[] encKeyBytes = KiWiStringUtils.fromHex(key, key.length()); if(encKeyBytes != null) { // TODO: decrypt AES key from RSA private key CryptoService cryptoService = (CryptoService) Component.getInstance("cryptoService"); byte[] keyBytes = cryptoService.decryptAsymmetric(encKeyBytes, priv); String cipher = KiWiStringUtils.extractAESCipher(html); if(cipher != null) { byte[] plainBytes = cryptoService.decryptSymmetric( KiWiStringUtils.fromHex(cipher,cipher.length()), keyBytes, "AES"); html = content.getHtmlContent().replaceAll( "-----BEGIN AES ENCRYPTED MESSAGE-----<br></br><br></br>" + ".*" + "<br></br><br></br>------END AES ENCRYPTED MESSAGE------", new String(plainBytes)); } } html = KiWiStringUtils.extractWithoutRSASignature(html); text.setXmlString(html); } } Document xom = text.copyXmlDocument(); if(xom != null) { // perform rendering: XOM renderlets for(XOMRenderlet renderlet : editorXOMRenderlets) { xom = renderlet.apply(ci.getResource(), xom); } // select the element marked as kiwi:type="page" and take all elements below it String result = extractPage(xom); // perform rendering: source renderlets for(SourceRenderlet renderlet : editorSourceRenderlets) { result = renderlet.apply(ci.getResource(), result); } // workaround for tinyMCE bug which doubles all br tags. result=result.replaceAll("<br></br>", "<br/>"); return result; } else { // facesMessages.add("text content was null - displaying empty page"); return ""; } } else { return ""; } } public String renderPreview(ContentItem ci) { TextContent content = ci.getTextContent(); if(content==null) { return ""; } else { TextContent text = (TextContent)content; // perform rendering return text.getHtmlContent(); } } public String renderAnnotation(ContentItem ci) { return renderGeneric(ci, annotationXOMRenderlets, annotationSourceRenderlets); } private String renderGeneric(ContentItem ci, Collection<XOMRenderlet> xomRenderlets, Collection<SourceRenderlet> sourceRenderlets) { TextContent content = ci.getTextContent(); if(content == null) { log.error("error rendering null content"); return ""; } log.info("rendering content (content item: #0)",ci.getTitle()); long start = System.currentTimeMillis(); if(content != null) { TextContent text = (TextContent)content; Document xom = text.copyXmlDocument(); if(xom != null) { // perform rendering: XOM renderlets for(XOMRenderlet renderlet : xomRenderlets) { xom = renderlet.apply(ci.getResource(), xom); } // select the element marked as kiwi:type="page" and take all elements below it String result = extractPage(xom); // perform rendering: source renderlets // TODO: change to UIComponent instead of string for(SourceRenderlet renderlet : sourceRenderlets) { result = renderlet.apply(ci.getResource(), result); } log.info("rendering text content took #0ms",System.currentTimeMillis()-start); return result; } else { // facesMessages.add("text content was null - displaying empty page"); return ""; } } else { // currently no active content item, return empty string return ""; } } public static String extractPage(Document xom) { String result; XPathContext namespaces = new XPathContext(); namespaces.addNamespace("kiwi", Constants.NS_KIWI_HTML); Nodes nl = xom.query("//*[@kiwi:type='page']/*",namespaces); if(nl.size() > 0) { result = ""; for(int i = 0; i < nl.size(); i++) { result += xom2string(nl.get(i),true); } } else { result = xom2string(xom,true); } return result; } public static String xom2string(Node xom, boolean canonical) { if(xom != null) { if(canonical) { // use a canonicalizer from XOM to create a canonical representation of the document ByteArrayOutputStream out = new ByteArrayOutputStream(); Canonicalizer c14n = new Canonicalizer(out,Canonicalizer.CANONICAL_XML); try { c14n.write(xom); } catch(IOException ex) { throw new RuntimeException("I/O Exception while serialising XML document; this should never happen!",ex); } String result = ""; try { result = new String(out.toByteArray(), "UTF-8"); } catch (UnsupportedEncodingException exc) {} return result; } else { // use the XOM serializer to create a String representation return xom.toXML(); } } else { return null; } } /** * Converts a string into a nu.xom.Document * @param xml * @return */ public static nu.xom.Document string2xom( String xml ) { if(xml != null) { // Seam/JPA seems to need this nu.xom.Builder builder = new nu.xom.Builder(); try { nu.xom.Document doc = builder.build(xml, "kiwi://"); return doc; } catch(ParsingException ex) { log.error("string to xom converter could not parse string: #0", xml); return null; } catch(IOException ex) { log.error("string to xom run into an IOException. String: #0", xml); return null; } } else { return null; } } }
bsd-3-clause
joansmith/rultor
src/test/java/com/rultor/dynamo/package-info.java
1697
/** * Copyright (c) 2009-2015, rultor.com * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: 1) Redistributions of source code must retain the above * copyright notice, this list of conditions and the following * disclaimer. 2) Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. 3) Neither the name of the rultor.com nor * the names of its contributors may be used to endorse or promote * products derived from this software without specific prior written * permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Dynamo, tests. * * @author Yegor Bugayenko (yegor@teamed.io) * @version $Id$ * @since 1.0 */ package com.rultor.dynamo;
bsd-3-clause
Pursuit92/antlr4
runtime/Java/src/org/antlr/v4/runtime/atn/DecisionInfo.java
8587
/* * Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. * Use of this file is governed by the BSD 3-clause license that * can be found in the LICENSE.txt file in the project root. */ package org.antlr.v4.runtime.atn; import java.util.ArrayList; import java.util.List; /** * This class contains profiling gathered for a particular decision. * * <p> * Parsing performance in ANTLR 4 is heavily influenced by both static factors * (e.g. the form of the rules in the grammar) and dynamic factors (e.g. the * choice of input and the state of the DFA cache at the time profiling * operations are started). For best results, gather and use aggregate * statistics from a large sample of inputs representing the inputs expected in * production before using the results to make changes in the grammar.</p> * * @since 4.3 */ public class DecisionInfo { /** * The decision number, which is an index into {@link ATN#decisionToState}. */ public final int decision; /** * The total number of times {@link ParserATNSimulator#adaptivePredict} was * invoked for this decision. */ public long invocations; /** * The total time spent in {@link ParserATNSimulator#adaptivePredict} for * this decision, in nanoseconds. * * <p> * The value of this field contains the sum of differential results obtained * by {@link System#nanoTime()}, and is not adjusted to compensate for JIT * and/or garbage collection overhead. For best accuracy, use a modern JVM * implementation that provides precise results from * {@link System#nanoTime()}, and perform profiling in a separate process * which is warmed up by parsing the input prior to profiling. If desired, * call {@link ATNSimulator#clearDFA} to reset the DFA cache to its initial * state before starting the profiling measurement pass.</p> */ public long timeInPrediction; /** * The sum of the lookahead required for SLL prediction for this decision. * Note that SLL prediction is used before LL prediction for performance * reasons even when {@link PredictionMode#LL} or * {@link PredictionMode#LL_EXACT_AMBIG_DETECTION} is used. */ public long SLL_TotalLook; /** * Gets the minimum lookahead required for any single SLL prediction to * complete for this decision, by reaching a unique prediction, reaching an * SLL conflict state, or encountering a syntax error. */ public long SLL_MinLook; /** * Gets the maximum lookahead required for any single SLL prediction to * complete for this decision, by reaching a unique prediction, reaching an * SLL conflict state, or encountering a syntax error. */ public long SLL_MaxLook; /** * Gets the {@link LookaheadEventInfo} associated with the event where the * {@link #SLL_MaxLook} value was set. */ public LookaheadEventInfo SLL_MaxLookEvent; /** * The sum of the lookahead required for LL prediction for this decision. * Note that LL prediction is only used when SLL prediction reaches a * conflict state. */ public long LL_TotalLook; /** * Gets the minimum lookahead required for any single LL prediction to * complete for this decision. An LL prediction completes when the algorithm * reaches a unique prediction, a conflict state (for * {@link PredictionMode#LL}, an ambiguity state (for * {@link PredictionMode#LL_EXACT_AMBIG_DETECTION}, or a syntax error. */ public long LL_MinLook; /** * Gets the maximum lookahead required for any single LL prediction to * complete for this decision. An LL prediction completes when the algorithm * reaches a unique prediction, a conflict state (for * {@link PredictionMode#LL}, an ambiguity state (for * {@link PredictionMode#LL_EXACT_AMBIG_DETECTION}, or a syntax error. */ public long LL_MaxLook; /** * Gets the {@link LookaheadEventInfo} associated with the event where the * {@link #LL_MaxLook} value was set. */ public LookaheadEventInfo LL_MaxLookEvent; /** * A collection of {@link ContextSensitivityInfo} instances describing the * context sensitivities encountered during LL prediction for this decision. * * @see ContextSensitivityInfo */ public final List<ContextSensitivityInfo> contextSensitivities = new ArrayList<ContextSensitivityInfo>(); /** * A collection of {@link ErrorInfo} instances describing the parse errors * identified during calls to {@link ParserATNSimulator#adaptivePredict} for * this decision. * * @see ErrorInfo */ public final List<ErrorInfo> errors = new ArrayList<ErrorInfo>(); /** * A collection of {@link AmbiguityInfo} instances describing the * ambiguities encountered during LL prediction for this decision. * * @see AmbiguityInfo */ public final List<AmbiguityInfo> ambiguities = new ArrayList<AmbiguityInfo>(); /** * A collection of {@link PredicateEvalInfo} instances describing the * results of evaluating individual predicates during prediction for this * decision. * * @see PredicateEvalInfo */ public final List<PredicateEvalInfo> predicateEvals = new ArrayList<PredicateEvalInfo>(); /** * The total number of ATN transitions required during SLL prediction for * this decision. An ATN transition is determined by the number of times the * DFA does not contain an edge that is required for prediction, resulting * in on-the-fly computation of that edge. * * <p> * If DFA caching of SLL transitions is employed by the implementation, ATN * computation may cache the computed edge for efficient lookup during * future parsing of this decision. Otherwise, the SLL parsing algorithm * will use ATN transitions exclusively.</p> * * @see #SLL_ATNTransitions * @see ParserATNSimulator#computeTargetState * @see LexerATNSimulator#computeTargetState */ public long SLL_ATNTransitions; /** * The total number of DFA transitions required during SLL prediction for * this decision. * * <p>If the ATN simulator implementation does not use DFA caching for SLL * transitions, this value will be 0.</p> * * @see ParserATNSimulator#getExistingTargetState * @see LexerATNSimulator#getExistingTargetState */ public long SLL_DFATransitions; /** * Gets the total number of times SLL prediction completed in a conflict * state, resulting in fallback to LL prediction. * * <p>Note that this value is not related to whether or not * {@link PredictionMode#SLL} may be used successfully with a particular * grammar. If the ambiguity resolution algorithm applied to the SLL * conflicts for this decision produce the same result as LL prediction for * this decision, {@link PredictionMode#SLL} would produce the same overall * parsing result as {@link PredictionMode#LL}.</p> */ public long LL_Fallback; /** * The total number of ATN transitions required during LL prediction for * this decision. An ATN transition is determined by the number of times the * DFA does not contain an edge that is required for prediction, resulting * in on-the-fly computation of that edge. * * <p> * If DFA caching of LL transitions is employed by the implementation, ATN * computation may cache the computed edge for efficient lookup during * future parsing of this decision. Otherwise, the LL parsing algorithm will * use ATN transitions exclusively.</p> * * @see #LL_DFATransitions * @see ParserATNSimulator#computeTargetState * @see LexerATNSimulator#computeTargetState */ public long LL_ATNTransitions; /** * The total number of DFA transitions required during LL prediction for * this decision. * * <p>If the ATN simulator implementation does not use DFA caching for LL * transitions, this value will be 0.</p> * * @see ParserATNSimulator#getExistingTargetState * @see LexerATNSimulator#getExistingTargetState */ public long LL_DFATransitions; /** * Constructs a new instance of the {@link DecisionInfo} class to contain * statistics for a particular decision. * * @param decision The decision number */ public DecisionInfo(int decision) { this.decision = decision; } @Override public String toString() { return "{" + "decision=" + decision + ", contextSensitivities=" + contextSensitivities.size() + ", errors=" + errors.size() + ", ambiguities=" + ambiguities.size() + ", SLL_lookahead=" + SLL_TotalLook + ", SLL_ATNTransitions=" + SLL_ATNTransitions + ", SLL_DFATransitions=" + SLL_DFATransitions + ", LL_Fallback=" + LL_Fallback + ", LL_lookahead=" + LL_TotalLook + ", LL_ATNTransitions=" + LL_ATNTransitions + '}'; } }
bsd-3-clause
AdamLuptak/Time_MNA
library/src/test/java/com/orm/util/NumberComparatorTest.java
1085
package com.orm.util; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.assertEquals; /** * @author jonatan.salas */ public final class NumberComparatorTest { private NumberComparator comparator; @Before public void setUp() { comparator = new NumberComparator(); } @Test public void testNumberComparatorWithoutNumbers() { int result = comparator.compare("hola", "hola"); assertEquals(0, result); } @Test public void testNumberComparatorWithNumbers() { int result = comparator.compare("1", "2"); assertEquals(-1, result); } @Test public void testComparatorWithNumbers() { int result = comparator.compare("4", "2"); assertEquals(1, result); } @Test public void testCompareRight() { int result = comparator.compareRight("hola", "hola"); assertEquals(0, result); } @Test public void testCharAt() { Character c = NumberComparator.charAt("Hola", 0); assertEquals("H", c.toString()); } }
mit