code
stringlengths
3
1.04M
repo_name
stringlengths
5
109
path
stringlengths
6
306
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
3
1.04M
/* * Package : org.ludo.codegenerator.core.gen.bean * Source : IStereotype.java */ package org.ludo.codegenerator.core.gen.bean; import java.io.Serializable; import java.util.Date; import java.util.ArrayList; import java.util.List; import org.ludo.codegenerator.core.gen.bean.impl.AttributBean; import org.ludo.codegenerator.core.gen.bean.impl.ClasseBean; import org.ludo.codegenerator.core.gen.bean.abst.IStereotypeAbstract; /** * <b>Description :</b> * IStereotype * */ public interface IStereotype extends IStereotypeAbstract, Serializable { }
ludo1026/tuto
generator-uml-to-config-xml/save/_3/src/org/ludo/codegenerator/core/gen/bean/IStereotype.java
Java
artistic-2.0
562
package org.glob3.mobile.specific; import java.util.Map; import org.glob3.mobile.generated.IByteBuffer; import org.glob3.mobile.generated.IJSONParser; import org.glob3.mobile.generated.JSONArray; import org.glob3.mobile.generated.JSONBaseObject; import org.glob3.mobile.generated.JSONBoolean; import org.glob3.mobile.generated.JSONDouble; import org.glob3.mobile.generated.JSONFloat; import org.glob3.mobile.generated.JSONInteger; import org.glob3.mobile.generated.JSONLong; import org.glob3.mobile.generated.JSONNull; import org.glob3.mobile.generated.JSONObject; import org.glob3.mobile.generated.JSONString; import com.google.gson.JsonArray; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParser; import com.google.gson.JsonPrimitive; public class JSONParser_JavaDesktop extends IJSONParser { @Override public JSONBaseObject parse(final IByteBuffer buffer, final boolean nullAsObject) { return parse(buffer.getAsString(), nullAsObject); } @Override public JSONBaseObject parse(final String string, final boolean nullAsObject) { final JsonParser parser = new JsonParser(); final JsonElement element = parser.parse(string); return convert(element, nullAsObject); } private JSONBaseObject convert(final JsonElement element, final boolean nullAsObject) { if (element.isJsonNull()) { return nullAsObject ? new JSONNull() : null; } else if (element.isJsonObject()) { final JsonObject jsonObject = (JsonObject) element; final JSONObject result = new JSONObject(); for (final Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) { result.put(entry.getKey(), convert(entry.getValue(), nullAsObject)); } return result; } else if (element.isJsonPrimitive()) { final JsonPrimitive jsonPrimitive = (JsonPrimitive) element; if (jsonPrimitive.isBoolean()) { return new JSONBoolean(jsonPrimitive.getAsBoolean()); } else if (jsonPrimitive.isNumber()) { final double doubleValue = jsonPrimitive.getAsDouble(); final long longValue = (long) doubleValue; if (doubleValue == longValue) { final int intValue = (int) longValue; return (intValue == longValue) ? new JSONInteger(intValue) : new JSONLong(longValue); } final float floatValue = (float) doubleValue; return (floatValue == doubleValue) ? new JSONFloat(floatValue) : new JSONDouble(doubleValue); } else if (jsonPrimitive.isString()) { return new JSONString(jsonPrimitive.getAsString()); } else { throw new RuntimeException("JSON unsopoerted" + element.getClass()); } } else if (element.isJsonArray()) { final JsonArray jsonArray = (JsonArray) element; final JSONArray result = new JSONArray(); for (final JsonElement child : jsonArray) { result.add(convert(child, nullAsObject)); } return result; } else { throw new RuntimeException("JSON unsopoerted" + element.getClass()); } } }
AeroGlass/g3m
JavaDesktop/G3MJavaDesktopSDK/src/org/glob3/mobile/specific/JSONParser_JavaDesktop.java
Java
bsd-2-clause
3,373
/* * Copyright (c) 2008-2011, Matthias Mann * * 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 Matthias Mann nor the names of its contributors may * be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package de.matthiasmann.twl; import de.matthiasmann.twl.model.IntegerModel; import de.matthiasmann.twl.model.ListModel; import de.matthiasmann.twl.renderer.Image; import de.matthiasmann.twl.utils.TypeMapping; /** * A wheel widget. * * @param <T> The data type for the wheel items * * @author Matthias Mann */ public class WheelWidget<T> extends Widget { public interface ItemRenderer { public Widget getRenderWidget(Object data); } private final TypeMapping<ItemRenderer> itemRenderer; private final L listener; private final R renderer; private final Runnable timerCB; protected int itemHeight; protected int numVisibleItems; protected Image selectedOverlay; private static final int TIMER_INTERVAL = 30; private static final int MIN_SPEED = 3; private static final int MAX_SPEED = 100; protected Timer timer; protected int dragStartY; protected long lastDragTime; protected long lastDragDelta; protected int lastDragDist; protected boolean hasDragStart; protected boolean dragActive; protected int scrollOffset; protected int scrollAmount; protected ListModel<T> model; protected IntegerModel selectedModel; protected int selected; protected boolean cyclic; public WheelWidget() { this.itemRenderer = new TypeMapping<ItemRenderer>(); this.listener = new L(); this.renderer = new R(); this.timerCB = new Runnable() { public void run() { onTimer(); } }; itemRenderer.put(String.class, new StringItemRenderer()); super.insertChild(renderer, 0); setCanAcceptKeyboardFocus(true); } public WheelWidget(ListModel<T> model) { this(); this.model = model; } public ListModel<T> getModel() { return model; } public void setModel(ListModel<T> model) { removeListener(); this.model = model; addListener(); invalidateLayout(); } public IntegerModel getSelectedModel() { return selectedModel; } public void setSelectedModel(IntegerModel selectedModel) { removeSelectedListener(); this.selectedModel = selectedModel; addSelectedListener(); } public int getSelected() { return selected; } public void setSelected(int selected) { int oldSelected = this.selected; if(oldSelected != selected) { this.selected = selected; if(selectedModel != null) { selectedModel.setValue(selected); } firePropertyChange("selected", oldSelected, selected); } } public boolean isCyclic() { return cyclic; } public void setCyclic(boolean cyclic) { this.cyclic = cyclic; } public int getItemHeight() { return itemHeight; } public int getNumVisibleItems() { return numVisibleItems; } public boolean removeItemRenderer(Class<? extends T> clazz) { if(itemRenderer.remove(clazz)) { super.removeAllChildren(); invalidateLayout(); return true; } return false; } public void registerItemRenderer(Class<? extends T> clazz, ItemRenderer value) { itemRenderer.put(clazz, value); invalidateLayout(); } public void scroll(int amount) { scrollInt(amount); scrollAmount = 0; } protected void scrollInt(int amount) { int pos = selected; int half = itemHeight / 2; scrollOffset += amount; while(scrollOffset >= half) { scrollOffset -= itemHeight; pos++; } while(scrollOffset <= -half) { scrollOffset += itemHeight; pos--; } if(!cyclic) { int n = getNumEntries(); if(n > 0) { while(pos >= n) { pos--; scrollOffset += itemHeight; } } while(pos < 0) { pos++; scrollOffset -= itemHeight; } scrollOffset = Math.max(-itemHeight, Math.min(itemHeight, scrollOffset)); } setSelected(pos); if(scrollOffset == 0 && scrollAmount == 0) { stopTimer(); } else { startTimer(); } } public void autoScroll(int dir) { if(dir != 0) { if(scrollAmount != 0 && Integer.signum(scrollAmount) != Integer.signum(dir)) { scrollAmount = dir; } else { scrollAmount += dir; } startTimer(); } } @Override public int getPreferredInnerHeight() { return numVisibleItems * itemHeight; } @Override public int getPreferredInnerWidth() { int width = 0; for(int i=0,n=getNumEntries() ; i<n ; i++) { Widget w = getItemRenderer(i); if(w != null) { width = Math.max(width, w.getPreferredWidth()); } } return width; } @Override protected void paintOverlay(GUI gui) { super.paintOverlay(gui); if(selectedOverlay != null) { int y = getInnerY() + itemHeight * (numVisibleItems/2); if((numVisibleItems & 1) == 0) { y -= itemHeight/2; } selectedOverlay.draw(getAnimationState(), getX(), y, getWidth(), itemHeight); } } @Override protected boolean handleEvent(Event evt) { if(evt.isMouseDragEnd() && dragActive) { int absDist = Math.abs(lastDragDist); if(absDist > 3 && lastDragDelta > 0) { int amount = (int)Math.min(1000, absDist * 100 / lastDragDelta); autoScroll(amount * Integer.signum(lastDragDist)); } hasDragStart = false; dragActive = false; return true; } if(evt.isMouseDragEvent()) { if(hasDragStart) { long time = getTime(); dragActive = true; lastDragDist = dragStartY - evt.getMouseY(); lastDragDelta = Math.max(1, time - lastDragTime); scroll(lastDragDist); dragStartY = evt.getMouseY(); lastDragTime = time; } return true; } if(super.handleEvent(evt)) { return true; } switch(evt.getType()) { case MOUSE_WHEEL: autoScroll(itemHeight * evt.getMouseWheelDelta()); return true; case MOUSE_BTNDOWN: if(evt.getMouseButton() == Event.MOUSE_LBUTTON) { dragStartY = evt.getMouseY(); lastDragTime = getTime(); hasDragStart = true; } return true; case KEY_PRESSED: switch(evt.getKeyCode()) { case Event.KEY_UP: autoScroll(-itemHeight); return true; case Event.KEY_DOWN: autoScroll(+itemHeight); return true; } return false; } return evt.isMouseEvent(); } protected long getTime() { GUI gui = getGUI(); return (gui != null) ? gui.getCurrentTime() : 0; } protected int getNumEntries() { return (model == null) ? 0 : model.getNumEntries(); } protected Widget getItemRenderer(int i) { T item = model.getEntry(i); if(item != null) { ItemRenderer ir = itemRenderer.get(item.getClass()); if(ir != null) { Widget w = ir.getRenderWidget(item); if(w != null) { if(w.getParent() != renderer) { w.setVisible(false); renderer.add(w); } return w; } } } return null; } protected void startTimer() { if(timer != null && !timer.isRunning()) { timer.start(); } } protected void stopTimer() { if(timer != null) { timer.stop(); } } protected void onTimer() { int amount = scrollAmount; int newAmount = amount; if(amount == 0 && !dragActive) { amount = -scrollOffset; } if(amount != 0) { int absAmount = Math.abs(amount); int speed = absAmount * TIMER_INTERVAL / 200; int dir = Integer.signum(amount) * Math.min(absAmount, Math.max(MIN_SPEED, Math.min(MAX_SPEED, speed))); if(newAmount != 0) { newAmount -= dir; } scrollAmount = newAmount; scrollInt(dir); } } @Override protected void layout() { layoutChildFullInnerArea(renderer); } @Override protected void applyTheme(ThemeInfo themeInfo) { super.applyTheme(themeInfo); applyThemeWheel(themeInfo); } protected void applyThemeWheel(ThemeInfo themeInfo) { itemHeight = themeInfo.getParameter("itemHeight", 10); numVisibleItems = themeInfo.getParameter("visibleItems", 5); selectedOverlay = themeInfo.getImage("selectedOverlay"); invalidateLayout(); } @Override protected void afterAddToGUI(GUI gui) { super.afterAddToGUI(gui); addListener(); addSelectedListener(); timer = gui.createTimer(); timer.setCallback(timerCB); timer.setDelay(TIMER_INTERVAL); timer.setContinuous(true); } @Override protected void beforeRemoveFromGUI(GUI gui) { timer.stop(); timer = null; removeListener(); removeSelectedListener(); super.beforeRemoveFromGUI(gui); } @Override public void insertChild(Widget child, int index) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public void removeAllChildren() throws UnsupportedOperationException { throw new UnsupportedOperationException(); } @Override public Widget removeChild(int index) throws UnsupportedOperationException { throw new UnsupportedOperationException(); } private void addListener() { if(model != null) { model.addChangeListener(listener); } } private void removeListener() { if(model != null) { model.removeChangeListener(listener); } } private void addSelectedListener() { if(selectedModel != null) { selectedModel.addCallback(listener); syncSelected(); } } private void removeSelectedListener() { if(selectedModel != null) { selectedModel.removeCallback(listener); } } void syncSelected() { setSelected(selectedModel.getValue()); } void entriesDeleted(int first, int last) { if(selected > first) { if(selected > last) { setSelected(selected - (last-first+1)); } else { setSelected(first); } } invalidateLayout(); } void entriesInserted(int first, int last) { if(selected >= first) { setSelected(selected + (last-first+1)); } invalidateLayout(); } class L implements ListModel.ChangeListener, Runnable { public void allChanged() { invalidateLayout(); } public void entriesChanged(int first, int last) { invalidateLayout(); } public void entriesDeleted(int first, int last) { WheelWidget.this.entriesDeleted(first, last); } public void entriesInserted(int first, int last) { WheelWidget.this.entriesInserted(first, last); } public void run() { syncSelected(); } } class R extends Widget { public R() { setTheme(""); setClip(true); } @Override protected void paintWidget(GUI gui) { if(model == null) { return; } int width = getInnerWidth(); int x = getInnerX(); int y = getInnerY(); int numItems = model.getNumEntries(); int numDraw = numVisibleItems; int startIdx = selected - numVisibleItems/2; if((numDraw & 1) == 0) { y -= itemHeight / 2; numDraw++; } if(scrollOffset > 0) { y -= scrollOffset; numDraw++; } if(scrollOffset < 0) { y -= itemHeight + scrollOffset; numDraw++; startIdx--; } main: for(int i=0 ; i<numDraw ; i++) { int idx = startIdx + i; while(idx < 0) { if(!cyclic) { continue main; } idx += numItems; } while(idx >= numItems) { if(!cyclic) { continue main; } idx -= numItems; } Widget w = getItemRenderer(idx); if(w != null) { w.setSize(width, itemHeight); w.setPosition(x, y + i*itemHeight); w.validateLayout(); paintChild(gui, w); } } } @Override public void invalidateLayout() { } @Override protected void sizeChanged() { } } public static class StringItemRenderer extends Label implements WheelWidget.ItemRenderer { public StringItemRenderer() { setCache(false); } public Widget getRenderWidget(Object data) { setText(String.valueOf(data)); return this; } @Override protected void sizeChanged() { } } }
ColaMachine/MyBlock
src/main/java/de/matthiasmann/twl/WheelWidget.java
Java
bsd-2-clause
16,353
/* * $Id$ */ /* Copyright (c) 2000-2004 Board of Trustees of Leland Stanford Jr. University, all rights reserved. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Except as contained in this notice, the name of Stanford University shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from Stanford University. */ package org.lockss.mail; import java.io.*; import java.util.*; import java.net.*; import org.apache.oro.text.regex.*; import javax.mail.*; import javax.mail.internet.*; // import javax.activation.*; import org.lockss.test.*; import org.lockss.mail.*; import org.lockss.util.*; import org.lockss.daemon.*; import org.lockss.plugin.*; public class TestMimeMessage extends LockssTestCase { // The generated message is checked against these patterns, in a way that // is too brittle (order dependent, etc.). If the format of the message // changes innocuously the patterns and/or tests may have to be changed static final String PAT_MESSAGE_ID = "^Message-ID: "; static final String PAT_MIME_VERSION = "^MIME-Version: 1.0"; static final String PAT_CONTENT_TYPE = "^Content-Type: "; static final String PAT_FROM = "^From: "; static final String PAT_TO = "^To: "; static final String PAT_BOUNDARY = "^------=_Part"; static final String PAT_CONTENT_TRANSFER_ENCODING = "^Content-Transfer-Encoding: "; static final String PAT_CONTENT_DISPOSITION = "^Content-Disposition: "; String toString(MailMessage msg) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); BufferedOutputStream out = new BufferedOutputStream(baos); msg.writeData(out); out.flush(); return baos.toString(); } catch (IOException e) { throw new RuntimeException("Error converting MimeMessage to string", e); } } /** Return the header part (lines preceding first blank line) */ String getHeader(String body) { List lst = StringUtil.breakAt(body, "\r\n\r\n"); if (lst.size() < 1) return null; return (String)lst.get(0); } /** Return the header part (lines preceding first blank line) */ String getHeader(MimeMessage msg) { return getHeader(toString(msg)); } /** Return the body part (lines following first blank line) */ String getBody(String body) { int pos = body.indexOf("\r\n\r\n"); if (pos < 0) return null; return body.substring(pos+4); } /** Return the body part (lines following first blank line) */ String getBody(MimeMessage msg) { return getBody(toString(msg)); } /** Break a string at <crlf>s into an array of lines */ String[] getLines(String body) { List lst = StringUtil.breakAt(body, "\r\n"); return (String[])lst.toArray(new String[0]); } String[] getHeaderLines(MimeMessage msg) { return getLines(getHeader(msg)); } String[] getBodyLines(MimeMessage msg) { return getLines(getBody(msg)); } /** assert that the pattern exists in the string, interpreting the string * as having multiple lines */ void assertHeaderLine(String expPat, String hdr) { Pattern pat = RegexpUtil.uncheckedCompile(expPat, Perl5Compiler.MULTILINE_MASK); assertMatchesRE(pat, hdr); } /** assert that the message starts with the expected header */ void assertHeader(MimeMessage msg) { assertHeader(null, null, msg); } /** assert that the message starts with the expected header */ void assertHeader(String expFrom, String expTo, MimeMessage msg) { String hdr = getHeader(msg); assertHeaderLine(PAT_MESSAGE_ID, hdr); assertHeaderLine(PAT_MIME_VERSION, hdr); assertHeaderLine(PAT_CONTENT_TYPE, hdr); if (expFrom != null) { assertHeaderLine(PAT_FROM + expFrom, hdr); } if (expTo != null) { assertHeaderLine(PAT_TO + expTo, hdr); } } /** assert that the array of lines is a MIME text-part with the expected * text */ void assertTextPart(String expText, String[]lines, int idx) { assertMatchesRE(PAT_BOUNDARY, lines[idx + 0]); assertMatchesRE(PAT_CONTENT_TYPE + "text/plain; charset=us-ascii", lines[idx + 1]); assertMatchesRE(PAT_CONTENT_TRANSFER_ENCODING + "7bit", lines[idx + 2]); assertEquals("", lines[idx + 3]); assertEquals(expText, lines[idx + 4]); assertMatchesRE(PAT_BOUNDARY, lines[idx + 5]); } public void testNull() throws IOException { MimeMessage msg = new MimeMessage(); assertHeader(msg); assertEquals(2, getBodyLines(msg).length); assertMatchesRE(PAT_BOUNDARY, getBody(msg)); assertEquals("", getBodyLines(msg)[1]); } public void testGetHeader() throws IOException { MimeMessage msg = new MimeMessage(); msg.addHeader("From", "me"); msg.addHeader("To", "you"); msg.addHeader("To", "and you"); assertEquals("me", msg.getHeader("From")); assertEquals("you, and you", msg.getHeader("To")); assertEquals(null, msg.getHeader("xxxx")); } public void testText() throws IOException { MimeMessage msg = new MimeMessage(); msg.addHeader("From", "me"); msg.addHeader("To", "you"); msg.addHeader("Subject", "topic"); msg.addTextPart("Message\ntext"); assertHeader("me", "you", msg); String[] blines = getBodyLines(msg); log.debug2("msg: " + StringUtil.separatedString(blines, ", ")); assertTextPart("Message\ntext", blines, 0); } public void testDot() throws IOException { MimeMessage msg = new MimeMessage(); msg.addHeader("From", "me"); msg.addHeader("To", "you"); msg.addTextPart("one\n.\ntwo\n"); assertHeader("me", "you", msg); String[] blines = getBodyLines(msg); log.debug2("msg: " + StringUtil.separatedString(blines, ", ")); assertTextPart("one\n.\ntwo\n", blines, 0); } public void testTextAndFile() throws IOException { File file = FileTestUtil.writeTempFile("XXX", "\000\001\254\255this is a test"); MimeMessage msg = new MimeMessage(); msg.addHeader("From", "us"); msg.addHeader("To", "them"); msg.addHeader("Subject", "object"); msg.addTextPart("Explanatory text"); msg.addFile(file, "file.foo"); assertHeader("us", "them", msg); String[] blines = getBodyLines(msg); log.debug2("msg: " + StringUtil.separatedString(blines, ", ")); assertTextPart("Explanatory text", blines, 0); assertMatchesRE(PAT_CONTENT_TYPE + "application/octet-stream; name=file.foo", blines[6]); assertMatchesRE(PAT_CONTENT_TRANSFER_ENCODING + "base64", blines[7]); assertMatchesRE(PAT_CONTENT_DISPOSITION, blines[8]); assertEquals("", blines[9]); assertEquals("AAGsrXRoaXMgaXMgYSB0ZXN0", blines[10]); assertMatchesRE(PAT_BOUNDARY, blines[11]); assertTrue(file.exists()); msg.delete(true); assertTrue(file.exists()); } public void testGetParts() throws Exception { File file = FileTestUtil.writeTempFile("XXX", "\000\001\254\255this is a test"); MimeMessage msg = new MimeMessage(); msg.addTextPart("foo text"); msg.addFile(file, "file.foo"); MimeBodyPart[] parts = msg.getParts(); assertEquals(2, parts.length); assertEquals("foo text", parts[0].getContent()); assertEquals("file.foo", parts[1].getFileName()); } public void testTmpFile() throws IOException { File file = FileTestUtil.writeTempFile("XXX", "\000\001\254\255this is a test"); MimeMessage msg = new MimeMessage(); msg.addTmpFile(file, "file.foo"); assertTrue(file.exists()); msg.delete(true); assertFalse(file.exists()); } }
edina/lockss-daemon
test/src/org/lockss/mail/TestMimeMessage.java
Java
bsd-3-clause
8,543
package org.lemurproject.galago.core.util; import org.lemurproject.galago.core.retrieval.iterator.BaseIterator; import org.lemurproject.galago.core.retrieval.traversal.Traversal; import org.lemurproject.galago.utility.Parameters; import java.util.ArrayList; import java.util.List; /** * @author jfoley. */ public class IterUtils { /** * Adds an operator into a Retrieval's parameters for usage. * @param p the parameters object * @param name the name of the operator, e.g. "combine" for #combine * @param iterClass the operator to register */ public static void addToParameters(Parameters p, String name, Class<? extends BaseIterator> iterClass) { if(!p.containsKey("operators")) { p.put("operators", Parameters.create()); } p.getMap("operators").put(name, iterClass.getName()); } /** * Adds a traversal into a Retrieval's parameters for usage. * @param argp the parameters object * @param traversalClass the traversal to register */ public static void addToParameters(Parameters argp, Class<? extends Traversal> traversalClass) { if(!argp.isList("traversals")) { argp.put("traversals", new ArrayList<>()); } List<Parameters> traversals = argp.getList("traversals", Parameters.class); traversals.add(Parameters.parseArray( "name", traversalClass.getName(), "order", "before" )); argp.put("traversals", traversals); } }
hzhao/galago-git
core/src/main/java/org/lemurproject/galago/core/util/IterUtils.java
Java
bsd-3-clause
1,424
/*L * Copyright RTI International * * Distributed under the OSI-approved BSD 3-Clause License. * See http://ncip.github.com/webgenome/LICENSE.txt for details. */ /* $Revision: 1.1 $ $Date: 2007-08-22 20:03:57 $ */ package org.rti.webgenome.webui.struts.upload; import javax.servlet.http.HttpServletRequest; import org.apache.struts.action.ActionError; import org.apache.struts.action.ActionErrors; import org.apache.struts.action.ActionMapping; import org.rti.webgenome.util.SystemUtils; import org.rti.webgenome.webui.struts.BaseForm; /** * Form for inputting the name of a rectangular file * column that contains reporter names. * @author dhall * */ public class ReporterColumnNameForm extends BaseForm { /** Serialized version ID. */ private static final long serialVersionUID = SystemUtils.getLongApplicationProperty("serial.version.uid"); /** Name of column containing reporter names. */ private String reporterColumnName = null; /** * Get name of column containing reporter names. * @return Column heading. */ public String getReporterColumnName() { return reporterColumnName; } /** * Set name of column containing reporter names. * @param reporterColumnName Column heading. */ public void setReporterColumnName(final String reporterColumnName) { this.reporterColumnName = reporterColumnName; } /** * {@inheritDoc} */ @Override public ActionErrors validate(final ActionMapping mapping, final HttpServletRequest request) { ActionErrors errors = new ActionErrors(); if (this.reporterColumnName == null || this.reporterColumnName.length() < 1) { errors.add("reporterColumnName", new ActionError("invalid.field")); } if (errors.size() > 0) { errors.add("global", new ActionError("invalid.fields")); } return errors; } }
NCIP/webgenome
tags/WEBGENOME_R3.2_6MAR2009_BUILD1/java/webui/src/org/rti/webgenome/webui/struts/upload/ReporterColumnNameForm.java
Java
bsd-3-clause
1,844
package org.hisp.dhis.sms.listener; /* * Copyright (c) 2004-2018, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import java.util.*; import org.apache.commons.lang3.StringUtils; import org.hisp.dhis.organisationunit.OrganisationUnit; import org.hisp.dhis.program.Program; import org.hisp.dhis.program.ProgramInstanceService; import org.hisp.dhis.sms.command.SMSCommand; import org.hisp.dhis.sms.command.SMSCommandService; import org.hisp.dhis.sms.command.code.SMSCode; import org.hisp.dhis.sms.incoming.IncomingSms; import org.hisp.dhis.sms.incoming.SmsMessageStatus; import org.hisp.dhis.sms.parse.ParserType; import org.hisp.dhis.sms.parse.SMSParserException; import org.hisp.dhis.system.util.SmsUtils; import org.hisp.dhis.trackedentity.TrackedEntityAttribute; import org.hisp.dhis.trackedentity.TrackedEntityInstance; import org.hisp.dhis.trackedentity.TrackedEntityInstanceService; import org.hisp.dhis.trackedentity.TrackedEntityTypeService; import org.hisp.dhis.trackedentityattributevalue.TrackedEntityAttributeValue; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.transaction.annotation.Transactional; @Transactional public class TrackedEntityRegistrationSMSListener extends BaseSMSListener { private static final String SUCCESS_MESSAGE = "Tracked Entity Registered Successfully with uid. "; // ------------------------------------------------------------------------- // Dependencies // ------------------------------------------------------------------------- @Autowired private SMSCommandService smsCommandService; @Autowired private TrackedEntityTypeService trackedEntityTypeService; @Autowired private TrackedEntityInstanceService trackedEntityInstanceService; @Autowired private ProgramInstanceService programInstanceService; // ------------------------------------------------------------------------- // IncomingSmsListener implementation // ------------------------------------------------------------------------- @Override protected void postProcess( IncomingSms sms, SMSCommand smsCommand, Map<String, String> parsedMessage ) { String message = sms.getText(); Date date = SmsUtils.lookForDate( message ); String senderPhoneNumber = StringUtils.replace( sms.getOriginator(), "+", "" ); Collection<OrganisationUnit> orgUnits = getOrganisationUnits( sms ); Program program = smsCommand.getProgram(); OrganisationUnit orgUnit = SmsUtils.selectOrganisationUnit( orgUnits, parsedMessage, smsCommand ); if ( !program.hasOrganisationUnit( orgUnit ) ) { sendFeedback( SMSCommand.NO_OU_FOR_PROGRAM, senderPhoneNumber, WARNING ); throw new SMSParserException( SMSCommand.NO_OU_FOR_PROGRAM ); } TrackedEntityInstance trackedEntityInstance = new TrackedEntityInstance(); trackedEntityInstance.setOrganisationUnit( orgUnit ); trackedEntityInstance.setTrackedEntityType( trackedEntityTypeService.getTrackedEntityByName( smsCommand.getProgram().getTrackedEntityType().getName() ) ); Set<TrackedEntityAttributeValue> patientAttributeValues = new HashSet<>(); smsCommand.getCodes().stream() .filter( code -> parsedMessage.containsKey( code.getCode() ) ) .forEach( code -> { TrackedEntityAttributeValue trackedEntityAttributeValue = this.createTrackedEntityAttributeValue( parsedMessage, code, trackedEntityInstance) ; patientAttributeValues.add( trackedEntityAttributeValue ); }); int trackedEntityInstanceId = 0; if ( patientAttributeValues.size() > 0 ) { trackedEntityInstanceId = trackedEntityInstanceService.createTrackedEntityInstance( trackedEntityInstance, null, null, patientAttributeValues ); } else { sendFeedback( "No TrackedEntityAttribute found", senderPhoneNumber, WARNING ); } TrackedEntityInstance tei = trackedEntityInstanceService.getTrackedEntityInstance( trackedEntityInstanceId ); programInstanceService.enrollTrackedEntityInstance( tei, smsCommand.getProgram(), new Date(), date, orgUnit ); sendFeedback( StringUtils.defaultIfBlank( smsCommand.getSuccessMessage(), SUCCESS_MESSAGE + tei.getUid() ), senderPhoneNumber, INFO ); update( sms, SmsMessageStatus.PROCESSED, true ); } @Override protected SMSCommand getSMSCommand( IncomingSms sms ) { return smsCommandService.getSMSCommand( SmsUtils.getCommandString( sms ), ParserType.TRACKED_ENTITY_REGISTRATION_PARSER ); } private TrackedEntityAttributeValue createTrackedEntityAttributeValue( Map<String, String> parsedMessage, SMSCode code, TrackedEntityInstance trackedEntityInstance ) { String value = parsedMessage.get( code.getCode() ); TrackedEntityAttribute trackedEntityAttribute = code.getTrackedEntityAttribute(); TrackedEntityAttributeValue trackedEntityAttributeValue = new TrackedEntityAttributeValue(); trackedEntityAttributeValue.setAttribute( trackedEntityAttribute ); trackedEntityAttributeValue.setEntityInstance( trackedEntityInstance ); trackedEntityAttributeValue.setValue( value ); return trackedEntityAttributeValue; } }
msf-oca-his/dhis-core
dhis-2/dhis-services/dhis-service-core/src/main/java/org/hisp/dhis/sms/listener/TrackedEntityRegistrationSMSListener.java
Java
bsd-3-clause
7,054
package org.hisp.dhis.email; /* * Copyright (c) 2004-2018, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * @author Zubair <rajazubair.asghar@gmail.com> */ public enum EmailResponse { SENT( "success" ), FAILED( "failed" ), ABORTED( "aborted" ), NOT_CONFIGURED( "no configuration found" ); private String responseMessage; EmailResponse( String responseMessage ) { this.responseMessage = responseMessage; } public String getResponseMessage() { return responseMessage; } public void setResponseMessage( String responseMessage ) { this.responseMessage = responseMessage; } }
vietnguyen/dhis2-core
dhis-2/dhis-api/src/main/java/org/hisp/dhis/email/EmailResponse.java
Java
bsd-3-clause
2,144
/** * SAHARA Scheduling Server * * Schedules and assigns local laboratory rigs. * * @license See LICENSE in the top level directory for complete license terms. * * Copyright (c) 2009, University of Technology, Sydney * 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 University of Technology, Sydney 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. * * @author Tania Machet (tmachet) * @date 13 December 2010 */ package au.edu.uts.eng.remotelabs.schedserver.reports.intf.types; import java.io.Serializable; import java.util.ArrayList; import java.util.Calendar; import javax.xml.namespace.QName; import javax.xml.stream.XMLStreamException; import javax.xml.stream.XMLStreamReader; import javax.xml.stream.XMLStreamWriter; import org.apache.axiom.om.OMConstants; import org.apache.axiom.om.OMDataSource; import org.apache.axiom.om.OMElement; import org.apache.axiom.om.OMFactory; import org.apache.axiom.om.impl.llom.OMSourcedElementImpl; import org.apache.axis2.databinding.ADBBean; import org.apache.axis2.databinding.ADBDataSource; import org.apache.axis2.databinding.ADBException; import org.apache.axis2.databinding.utils.BeanUtil; import org.apache.axis2.databinding.utils.ConverterUtil; import org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl; import org.apache.axis2.databinding.utils.writer.MTOMAwareXMLStreamWriter; /** * QuerySessionReportType bean class. */ public class QuerySessionReportType implements ADBBean { /* * This type was generated from the piece of schema that had * name = QuerySessionReportType * Namespace URI = http://remotelabs.eng.uts.edu.au/schedserver/reports * Namespace Prefix = ns1 */ private static final long serialVersionUID = -5121246029757741056L; private static String generatePrefix(final String namespace) { if (namespace.equals("http://remotelabs.eng.uts.edu.au/schedserver/reports")) { return "ns1"; } return BeanUtil.getUniquePrefix(); } protected RequestorType requestor; public RequestorType getRequestor() { return this.requestor; } public void setRequestor(final RequestorType param) { this.requestor = param; } protected QueryFilterType querySelect; public QueryFilterType getQuerySelect() { return this.querySelect; } public void setQuerySelect(final QueryFilterType param) { this.querySelect = param; } protected QueryFilterType queryConstraints; protected boolean queryConstraintsTracker = false; public QueryFilterType getQueryConstraints() { return this.queryConstraints; } public void setQueryConstraints(final QueryFilterType param) { this.queryConstraints = param; this.queryConstraintsTracker = param != null; } protected Calendar startTime; protected boolean startTimeTracker = false; public Calendar getStartTime() { return this.startTime; } public void setStartTime(final Calendar param) { this.startTime = param; this.startTimeTracker = param != null; } protected Calendar endTime; protected boolean endTimeTracker = false; public Calendar getEndTime() { return this.endTime; } public void setEndTime(final Calendar param) { this.endTime = param; this.endTimeTracker = param != null; } protected PaginationType pagination; protected boolean paginationTracker = false; public PaginationType getPagination() { return this.pagination; } public void setPagination(final PaginationType param) { this.pagination = param; this.paginationTracker = param != null; } public static boolean isReaderMTOMAware(final XMLStreamReader reader) { boolean isReaderMTOMAware = false; try { isReaderMTOMAware = Boolean.TRUE.equals(reader.getProperty(OMConstants.IS_DATA_HANDLERS_AWARE)); } catch (final IllegalArgumentException e) { isReaderMTOMAware = false; } return isReaderMTOMAware; } public OMElement getOMElement(final QName parentQName, final OMFactory factory) throws ADBException { final OMDataSource dataSource = new ADBDataSource(this, parentQName) { @Override public void serialize(final MTOMAwareXMLStreamWriter xmlWriter) throws XMLStreamException { QuerySessionReportType.this.serialize(this.parentQName, factory, xmlWriter); } }; return new OMSourcedElementImpl(parentQName, factory, dataSource); } @Override public void serialize(final QName parentQName, final OMFactory factory, final MTOMAwareXMLStreamWriter xmlWriter) throws XMLStreamException, ADBException { this.serialize(parentQName, factory, xmlWriter, false); } @Override public void serialize(final QName parentQName, final OMFactory factory, final MTOMAwareXMLStreamWriter xmlWriter, final boolean serializeType) throws XMLStreamException, ADBException { String prefix = parentQName.getPrefix(); String namespace = parentQName.getNamespaceURI(); if ((namespace != null) && (namespace.trim().length() > 0)) { final String writerPrefix = xmlWriter.getPrefix(namespace); if (writerPrefix != null) { xmlWriter.writeStartElement(namespace, parentQName.getLocalPart()); } else { if (prefix == null) { prefix = QuerySessionReportType.generatePrefix(namespace); } xmlWriter.writeStartElement(prefix, parentQName.getLocalPart(), namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } } else { xmlWriter.writeStartElement(parentQName.getLocalPart()); } if (serializeType) { final String namespacePrefix = this.registerPrefix(xmlWriter, "http://remotelabs.eng.uts.edu.au/schedserver/reports"); if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)) { this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", namespacePrefix + ":QuerySessionReportType", xmlWriter); } else { this.writeAttribute("xsi", "http://www.w3.org/2001/XMLSchema-instance", "type", "QuerySessionReportType", xmlWriter); } } if (this.requestor == null) { throw new ADBException("requestor cannot be null!!"); } this.requestor.serialize(new QName("", "requestor"), factory, xmlWriter); if (this.querySelect == null) { throw new ADBException("querySelect cannot be null!!"); } this.querySelect.serialize(new QName("", "querySelect"), factory, xmlWriter); if (this.queryConstraintsTracker) { if (this.queryConstraints == null) { throw new ADBException("queryConstraints cannot be null!!"); } this.queryConstraints.serialize(new QName("", "queryConstraints"), factory, xmlWriter); } if (this.startTimeTracker) { namespace = ""; if (!namespace.equals("")) { prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = QuerySessionReportType.generatePrefix(namespace); xmlWriter.writeStartElement(prefix, "startTime", namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } else { xmlWriter.writeStartElement(namespace, "startTime"); } } else { xmlWriter.writeStartElement("startTime"); } if (this.startTime == null) { throw new ADBException("startTime cannot be null!!"); } else { xmlWriter.writeCharacters(ConverterUtil.convertToString(this.startTime)); } xmlWriter.writeEndElement(); } if (this.endTimeTracker) { namespace = ""; if (!namespace.equals("")) { prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = QuerySessionReportType.generatePrefix(namespace); xmlWriter.writeStartElement(prefix, "endTime", namespace); xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } else { xmlWriter.writeStartElement(namespace, "endTime"); } } else { xmlWriter.writeStartElement("endTime"); } if (this.endTime == null) { throw new ADBException("endTime cannot be null!!"); } else { xmlWriter.writeCharacters(ConverterUtil.convertToString(this.endTime)); } xmlWriter.writeEndElement(); } if (this.paginationTracker) { if (this.pagination == null) { throw new ADBException("pagination cannot be null!!"); } this.pagination.serialize(new QName("", "pagination"), factory, xmlWriter); } xmlWriter.writeEndElement(); } private void writeAttribute(final String prefix, final String namespace, final String attName, final String attValue, final XMLStreamWriter xmlWriter) throws XMLStreamException { if (xmlWriter.getPrefix(namespace) == null) { xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } xmlWriter.writeAttribute(namespace, attName, attValue); } private String registerPrefix(final XMLStreamWriter xmlWriter, final String namespace) throws XMLStreamException { String prefix = xmlWriter.getPrefix(namespace); if (prefix == null) { prefix = QuerySessionReportType.generatePrefix(namespace); while (xmlWriter.getNamespaceContext().getNamespaceURI(prefix) != null) { prefix = BeanUtil.getUniquePrefix(); } xmlWriter.writeNamespace(prefix, namespace); xmlWriter.setPrefix(prefix, namespace); } return prefix; } @Override public XMLStreamReader getPullParser(final QName qName) throws ADBException { final ArrayList<Serializable> elementList = new ArrayList<Serializable>(); elementList.add(new QName("", "requestor")); if (this.requestor == null) { throw new ADBException("requestor cannot be null!!"); } elementList.add(this.requestor); elementList.add(new QName("", "querySelect")); if (this.querySelect == null) { throw new ADBException("querySelect cannot be null!!"); } elementList.add(this.querySelect); if (this.queryConstraintsTracker) { elementList.add(new QName("", "queryConstraints")); if (this.queryConstraints == null) { throw new ADBException("queryConstraints cannot be null!!"); } elementList.add(this.queryConstraints); } if (this.startTimeTracker) { elementList.add(new QName("", "startTime")); if (this.startTime != null) { elementList.add(ConverterUtil.convertToString(this.startTime)); } else { throw new ADBException("startTime cannot be null!!"); } } if (this.endTimeTracker) { elementList.add(new QName("", "endTime")); if (this.endTime != null) { elementList.add(ConverterUtil.convertToString(this.endTime)); } else { throw new ADBException("endTime cannot be null!!"); } } if (this.paginationTracker) { elementList.add(new QName("", "pagination")); if (this.pagination == null) { throw new ADBException("pagination cannot be null!!"); } elementList.add(this.pagination); } return new ADBXMLStreamReaderImpl(qName, elementList.toArray(), new Object[0]); } public static class Factory { public static QuerySessionReportType parse(final XMLStreamReader reader) throws Exception { final QuerySessionReportType object = new QuerySessionReportType(); try { while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type") != null) { final String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance", "type"); if (fullTypeName != null) { String nsPrefix = null; if (fullTypeName.indexOf(":") > -1) { nsPrefix = fullTypeName.substring(0, fullTypeName.indexOf(":")); } nsPrefix = nsPrefix == null ? "" : nsPrefix; final String type = fullTypeName.substring(fullTypeName.indexOf(":") + 1); if (!"QuerySessionReportType".equals(type)) { final String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix); return (QuerySessionReportType) ExtensionMapper.getTypeObject(nsUri, type, reader); } } } reader.next(); while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new QName("", "requestor").equals(reader.getName())) { object.setRequestor(RequestorType.Factory.parse(reader)); reader.next(); } else { throw new ADBException("Unexpected subelement " + reader.getLocalName()); } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new QName("", "querySelect").equals(reader.getName())) { object.setQuerySelect(QueryFilterType.Factory.parse(reader)); reader.next(); } else { throw new ADBException("Unexpected subelement " + reader.getLocalName()); } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new QName("", "queryConstraints").equals(reader.getName())) { object.setQueryConstraints(QueryFilterType.Factory.parse(reader)); reader.next(); } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new QName("", "startTime").equals(reader.getName())) { final String content = reader.getElementText(); object.setStartTime(ConverterUtil.convertToDateTime(content)); reader.next(); } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new QName("", "endTime").equals(reader.getName())) { final String content = reader.getElementText(); object.setEndTime(ConverterUtil.convertToDateTime(content)); reader.next(); } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement() && new QName("", "pagination").equals(reader.getName())) { object.setPagination(PaginationType.Factory.parse(reader)); reader.next(); } while (!reader.isStartElement() && !reader.isEndElement()) { reader.next(); } if (reader.isStartElement()) { throw new ADBException("Unexpected subelement " + reader.getLocalName()); } } catch (final XMLStreamException e) { throw new Exception(e); } return object; } } }
jeking3/scheduling-server
Reports/src/au/edu/uts/eng/remotelabs/schedserver/reports/intf/types/QuerySessionReportType.java
Java
bsd-3-clause
20,256
/** * Copyright (c) 2016, The National Archives <pronom@nationalarchives.gsi.gov.uk> * 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 The National Archives 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. */ // // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.1-b02-fcs // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2010.03.22 at 11:40:59 AM GMT // package uk.gov.nationalarchives.droid.report.planets.domain; import java.math.BigDecimal; import java.math.BigInteger; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for YearItemType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="YearItemType"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="year" type="{http://www.w3.org/2001/XMLSchema}gYear"/&gt; * &lt;element name="numFiles" type="{http://www.w3.org/2001/XMLSchema}integer"/&gt; * &lt;element name="totalFileSize" type="{http://www.w3.org/2001/XMLSchema}decimal"/&gt; * &lt;/sequence&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * @deprecated PLANETS XML is now generated using XSLT over normal report xml files. */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "YearItemType", propOrder = { "year", "numFiles", "totalFileSize" }) @Deprecated public class YearItemType { @XmlElement(required = true) @XmlSchemaType(name = "gYear") protected XMLGregorianCalendar year; @XmlElement(required = true) protected BigInteger numFiles; @XmlElement(required = true) protected BigDecimal totalFileSize; /** * Gets the value of the year property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getYear() { return year; } /** * Sets the value of the year property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setYear(XMLGregorianCalendar value) { this.year = value; } /** * Gets the value of the numFiles property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getNumFiles() { return numFiles; } /** * Sets the value of the numFiles property. * * @param value * allowed object is * {@link BigInteger } * */ public void setNumFiles(BigInteger value) { this.numFiles = value; } /** * Gets the value of the totalFileSize property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getTotalFileSize() { return totalFileSize; } /** * Sets the value of the totalFileSize property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setTotalFileSize(BigDecimal value) { this.totalFileSize = value; } }
snail1966/droid
droid-report/src/main/java/uk/gov/nationalarchives/droid/report/planets/domain/YearItemType.java
Java
bsd-3-clause
5,288
/** * Copyright (c) 2016, The National Archives <pronom@nationalarchives.gsi.gov.uk> * 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 The National Archives 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 uk.gov.nationalarchives.droid.command.action; import java.io.PrintWriter; import java.util.Map; import uk.gov.nationalarchives.droid.command.i18n.I18N; import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureFileException; import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureFileInfo; import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureManager; import uk.gov.nationalarchives.droid.core.interfaces.signature.SignatureType; /** * @author rflitcroft * */ public class DisplayDefaultSignatureFileVersionCommand implements DroidCommand { private PrintWriter printWriter; private SignatureManager signatureManager; /** * {@inheritDoc} */ @Override public void execute() throws CommandExecutionException { try { Map<SignatureType, SignatureFileInfo> sigFileInfos = signatureManager.getDefaultSignatures(); for (SignatureFileInfo info : sigFileInfos.values()) { printWriter.println(I18N.getResource(I18N.DEFAULT_SIGNATURE_VERSION, info.getType(), info.getVersion(), info.getFile().getName())); } } catch (SignatureFileException e) { throw new CommandExecutionException(e); } } /** * @param printWriter the printWriter to set */ public void setPrintWriter(PrintWriter printWriter) { this.printWriter = printWriter; } /** * @param signatureManager the signatureManager to set */ public void setSignatureManager(SignatureManager signatureManager) { this.signatureManager = signatureManager; } }
snail1966/droid
droid-command-line/src/main/java/uk/gov/nationalarchives/droid/command/action/DisplayDefaultSignatureFileVersionCommand.java
Java
bsd-3-clause
3,404
/* * Copyright (c) 2010-2011 Mark Allen. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.restfb; import static com.restfb.json.JsonObject.NULL; import static com.restfb.util.ReflectionUtils.findFieldsWithAnnotation; import static com.restfb.util.ReflectionUtils.getFirstParameterizedTypeArgument; import static com.restfb.util.ReflectionUtils.isPrimitive; import static com.restfb.util.StringUtils.isBlank; import static com.restfb.util.StringUtils.trimToEmpty; import static java.util.Collections.unmodifiableList; import static java.util.Collections.unmodifiableSet; import static java.util.logging.Level.FINE; import static java.util.logging.Level.FINER; import static java.util.logging.Level.FINEST; import java.lang.reflect.Field; import java.math.BigDecimal; import java.math.BigInteger; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.logging.Logger; import com.restfb.exception.FacebookJsonMappingException; import com.restfb.json.JsonArray; import com.restfb.json.JsonException; import com.restfb.json.JsonObject; import com.restfb.types.Post.Comments; import com.restfb.util.ReflectionUtils.FieldWithAnnotation; /** * Default implementation of a JSON-to-Java mapper. * * @author <a href="http://restfb.com">Mark Allen</a> */ public class DefaultJsonMapper implements JsonMapper { /** * Logger. */ private static final Logger logger = Logger.getLogger(DefaultJsonMapper.class.getName()); /** * @see com.restfb.JsonMapper#toJavaList(String, Class) */ @Override public <T> List<T> toJavaList(String json, Class<T> type) { json = trimToEmpty(json); if (isBlank(json)) throw new FacebookJsonMappingException("JSON is an empty string - can't map it."); if (type == null) throw new FacebookJsonMappingException("You must specify the Java type to map to."); if (json.startsWith("{")) { // Sometimes Facebook returns the empty object {} when it really should be // returning an empty list [] (example: do an FQL query for a user's // affiliations - it's a list except when there are none, then it turns // into an object). Check for that special case here. if (isEmptyObject(json)) { if (logger.isLoggable(FINER)) logger.finer("Encountered {} when we should've seen []. " + "Mapping the {} as an empty list and moving on..."); return new ArrayList<T>(); } // Special case: if the only element of this object is an array called // "data", then treat it as a list. The Graph API uses this convention for // connections and in a few other places, e.g. comments on the Post // object. // Doing this simplifies mapping, so we don't have to worry about having a // little placeholder object that only has a "data" value. try { JsonObject jsonObject = new JsonObject(json); String[] fieldNames = JsonObject.getNames(jsonObject); if (fieldNames != null) { boolean hasSingleDataProperty = fieldNames.length == 1 && "data".equals(fieldNames[0]); Object jsonDataObject = jsonObject.get("data"); if (!hasSingleDataProperty && !(jsonDataObject instanceof JsonArray)) throw new FacebookJsonMappingException("JSON is an object but is being mapped as a list " + "instead. Offending JSON is '" + json + "'."); json = jsonDataObject.toString(); } } catch (JsonException e) { // Should never get here, but just in case... throw new FacebookJsonMappingException("Unable to convert Facebook response " + "JSON to a list of " + type.getName() + " instances. Offending JSON is " + json, e); } } try { List<T> list = new ArrayList<T>(); JsonArray jsonArray = new JsonArray(json); for (int i = 0; i < jsonArray.length(); i++) list.add(toJavaObject(jsonArray.get(i).toString(), type)); return unmodifiableList(list); } catch (FacebookJsonMappingException e) { throw e; } catch (Exception e) { throw new FacebookJsonMappingException("Unable to convert Facebook response " + "JSON to a list of " + type.getName() + " instances", e); } } /** * @see com.restfb.JsonMapper#toJavaObject(String, Class) */ @Override @SuppressWarnings("unchecked") public <T> T toJavaObject(String json, Class<T> type) { verifyThatJsonIsOfObjectType(json); try { // Are we asked to map to JsonObject? If so, short-circuit right away. if (type.equals(JsonObject.class)) return (T) new JsonObject(json); List<FieldWithAnnotation<Facebook>> fieldsWithAnnotation = findFieldsWithAnnotation(type, Facebook.class); Set<String> facebookFieldNamesWithMultipleMappings = facebookFieldNamesWithMultipleMappings(fieldsWithAnnotation); // If there are no annotated fields, assume we're mapping to a built-in // type. If this is actually the empty object, just return a new instance // of the corresponding Java type. if (fieldsWithAnnotation.size() == 0) if (isEmptyObject(json)) return createInstance(type); else return toPrimitiveJavaType(json, type); // Facebook will sometimes return the string "null". // Check for that and bail early if we find it. if ("null".equals(json)) return null; // Facebook will sometimes return the string "false" to mean null. // Check for that and bail early if we find it. if ("false".equals(json)) { if (logger.isLoggable(FINE)) logger.fine("Encountered 'false' from Facebook when trying to map to " + type.getSimpleName() + " - mapping null instead."); return null; } JsonObject jsonObject = new JsonObject(json); T instance = createInstance(type); if (instance instanceof JsonObject) return (T) jsonObject; // For each Facebook-annotated field on the current Java object, pull data // out of the JSON object and put it in the Java object for (FieldWithAnnotation<Facebook> fieldWithAnnotation : fieldsWithAnnotation) { String facebookFieldName = getFacebookFieldName(fieldWithAnnotation); if (!jsonObject.has(facebookFieldName)) { if (logger.isLoggable(FINER)) logger.finer("No JSON value present for '" + facebookFieldName + "', skipping. JSON is '" + json + "'."); continue; } fieldWithAnnotation.getField().setAccessible(true); // Set the Java field's value. // // If we notice that this Facebook field name is mapped more than once, // go into a special mode where we swallow any exceptions that occur // when mapping to the Java field. This is because Facebook will // sometimes return data in different formats for the same field name. // See issues 56 and 90 for examples of this behavior and discussion. if (facebookFieldNamesWithMultipleMappings.contains(facebookFieldName)) { try { fieldWithAnnotation.getField() .set(instance, toJavaType(fieldWithAnnotation, jsonObject, facebookFieldName)); } catch (FacebookJsonMappingException e) { logMultipleMappingFailedForField(facebookFieldName, fieldWithAnnotation, json); } catch (JsonException e) { logMultipleMappingFailedForField(facebookFieldName, fieldWithAnnotation, json); } } else { fieldWithAnnotation.getField().set(instance, toJavaType(fieldWithAnnotation, jsonObject, facebookFieldName)); } } return instance; } catch (FacebookJsonMappingException e) { throw e; } catch (Exception e) { throw new FacebookJsonMappingException("Unable to map JSON to Java. Offending JSON is '" + json + "'.", e); } } /** * Dumps out a log message when one of a multiple-mapped Facebook field name * JSON-to-Java mapping operation fails. * * @param facebookFieldName * The Facebook field name. * @param fieldWithAnnotation * The Java field to map to and its annotation. * @param json * The JSON that failed to map to the Java field. */ protected void logMultipleMappingFailedForField(String facebookFieldName, FieldWithAnnotation<Facebook> fieldWithAnnotation, String json) { if (!logger.isLoggable(FINER)) return; Field field = fieldWithAnnotation.getField(); if (logger.isLoggable(FINER)) logger.finer("Could not map '" + facebookFieldName + "' to " + field.getDeclaringClass().getSimpleName() + "." + field.getName() + ", but continuing on because '" + facebookFieldName + "' is mapped to multiple fields in " + field.getDeclaringClass().getSimpleName() + ". JSON is " + json); } /** * For a Java field annotated with the {@code Facebook} annotation, figure out * what the corresponding Facebook JSON field name to map to it is. * * @param fieldWithAnnotation * A Java field annotated with the {@code Facebook} annotation. * @return The Facebook JSON field name that should be mapped to this Java * field. */ protected String getFacebookFieldName(FieldWithAnnotation<Facebook> fieldWithAnnotation) { String facebookFieldName = fieldWithAnnotation.getAnnotation().value(); Field field = fieldWithAnnotation.getField(); // If no Facebook field name was specified in the annotation, assume // it's the same name as the Java field if (isBlank(facebookFieldName)) { if (logger.isLoggable(FINEST)) logger.finest("No explicit Facebook field name found for " + field + ", so defaulting to the field name itself (" + field.getName() + ")"); facebookFieldName = field.getName(); } return facebookFieldName; } /** * Finds any Facebook JSON fields that are mapped to more than 1 Java field. * * @param fieldsWithAnnotation * Java fields annotated with the {@code Facebook} annotation. * @return Any Facebook JSON fields that are mapped to more than 1 Java field. */ protected Set<String> facebookFieldNamesWithMultipleMappings(List<FieldWithAnnotation<Facebook>> fieldsWithAnnotation) { Map<String, Integer> facebookFieldsNamesWithOccurrenceCount = new HashMap<String, Integer>(); Set<String> facebookFieldNamesWithMultipleMappings = new HashSet<String>(); // Get a count of Facebook field name occurrences for each // @Facebook-annotated field for (FieldWithAnnotation<Facebook> fieldWithAnnotation : fieldsWithAnnotation) { String fieldName = getFacebookFieldName(fieldWithAnnotation); int occurrenceCount = facebookFieldsNamesWithOccurrenceCount.containsKey(fieldName) ? facebookFieldsNamesWithOccurrenceCount .get(fieldName) : 0; facebookFieldsNamesWithOccurrenceCount.put(fieldName, occurrenceCount + 1); } // Pull out only those field names with multiple mappings for (Entry<String, Integer> entry : facebookFieldsNamesWithOccurrenceCount.entrySet()) if (entry.getValue() > 1) facebookFieldNamesWithMultipleMappings.add(entry.getKey()); return unmodifiableSet(facebookFieldNamesWithMultipleMappings); } /** * @see com.restfb.JsonMapper#toJson(Object) */ @Override public String toJson(Object object) { // Delegate to recursive method return toJsonInternal(object).toString(); } /** * Is the given {@code json} a valid JSON object? * * @param json * The JSON to check. * @throws FacebookJsonMappingException * If {@code json} is not a valid JSON object. */ protected void verifyThatJsonIsOfObjectType(String json) { if (isBlank(json)) throw new FacebookJsonMappingException("JSON is an empty string - can't map it."); if (json.startsWith("[")) throw new FacebookJsonMappingException("JSON is an array but is being mapped as an object " + "- you should map it as a List instead. Offending JSON is '" + json + "'."); } /** * Recursively marshal the given {@code object} to JSON. * <p> * Used by {@link #toJson(Object)}. * * @param object * The object to marshal. * @return JSON representation of the given {@code object}. * @throws FacebookJsonMappingException * If an error occurs while marshaling to JSON. */ protected Object toJsonInternal(Object object) { if (object == null) return NULL; if (object instanceof List<?>) { JsonArray jsonArray = new JsonArray(); for (Object o : (List<?>) object) jsonArray.put(toJsonInternal(o)); return jsonArray; } if (object instanceof Map<?, ?>) { JsonObject jsonObject = new JsonObject(); for (Entry<?, ?> entry : ((Map<?, ?>) object).entrySet()) { if (!(entry.getKey() instanceof String)) throw new FacebookJsonMappingException("Your Map keys must be of type " + String.class + " in order to be converted to JSON. Offending map is " + object); try { jsonObject.put((String) entry.getKey(), toJsonInternal(entry.getValue())); } catch (JsonException e) { throw new FacebookJsonMappingException("Unable to process value '" + entry.getValue() + "' for key '" + entry.getKey() + "' in Map " + object, e); } } return jsonObject; } if (isPrimitive(object)) return object; if (object instanceof BigInteger) return ((BigInteger) object).longValue(); if (object instanceof BigDecimal) return ((BigDecimal) object).doubleValue(); // We've passed the special-case bits, so let's try to marshal this as a // plain old Javabean... List<FieldWithAnnotation<Facebook>> fieldsWithAnnotation = findFieldsWithAnnotation(object.getClass(), Facebook.class); JsonObject jsonObject = new JsonObject(); Set<String> facebookFieldNamesWithMultipleMappings = facebookFieldNamesWithMultipleMappings(fieldsWithAnnotation); if (facebookFieldNamesWithMultipleMappings.size() > 0) throw new FacebookJsonMappingException("Unable to convert to JSON because multiple @" + Facebook.class.getSimpleName() + " annotations for the same name are present: " + facebookFieldNamesWithMultipleMappings); for (FieldWithAnnotation<Facebook> fieldWithAnnotation : fieldsWithAnnotation) { String facebookFieldName = getFacebookFieldName(fieldWithAnnotation); fieldWithAnnotation.getField().setAccessible(true); try { jsonObject.put(facebookFieldName, toJsonInternal(fieldWithAnnotation.getField().get(object))); } catch (Exception e) { throw new FacebookJsonMappingException("Unable to process field '" + facebookFieldName + "' for " + object.getClass(), e); } } return jsonObject; } /** * Given a {@code json} value of something like {@code MyValue} or {@code 123} * , return a representation of that value of type {@code type}. * <p> * This is to support non-legal JSON served up by Facebook for API calls like * {@code Friends.get} (example result: {@code [222333,1240079]}). * * @param <T> * The Java type to map to. * @param json * The non-legal JSON to map to the Java type. * @param type * Type token. * @return Java representation of {@code json}. * @throws FacebookJsonMappingException * If an error occurs while mapping JSON to Java. */ @SuppressWarnings("unchecked") protected <T> T toPrimitiveJavaType(String json, Class<T> type) { if (String.class.equals(type)) { // If the string starts and ends with quotes, remove them, since Facebook // can serve up strings surrounded by quotes. if (json.length() > 1 && json.startsWith("\"") && json.endsWith("\"")) { json = json.replaceFirst("\"", ""); json = json.substring(0, json.length() - 1); } return (T) json; } if (Integer.class.equals(type) || Integer.TYPE.equals(type)) return (T) new Integer(json); if (Boolean.class.equals(type) || Boolean.TYPE.equals(type)) return (T) new Boolean(json); if (Long.class.equals(type) || Long.TYPE.equals(type)) return (T) new Long(json); if (Double.class.equals(type) || Double.TYPE.equals(type)) return (T) new Double(json); if (Float.class.equals(type) || Float.TYPE.equals(type)) return (T) new Float(json); if (BigInteger.class.equals(type)) return (T) new BigInteger(json); if (BigDecimal.class.equals(type)) return (T) new BigDecimal(json); throw new FacebookJsonMappingException("Don't know how to map JSON to " + type + ". Are you sure you're mapping to the right class? " + "Offending JSON is '" + json + "'."); } /** * Extracts JSON data for a field according to its {@code Facebook} annotation * and returns it converted to the proper Java type. * * @param fieldWithAnnotation * The field/annotation pair which specifies what Java type to * convert to. * @param jsonObject * "Raw" JSON object to pull data from. * @param facebookFieldName * Specifies what JSON field to pull "raw" data from. * @return A * @throws JsonException * If an error occurs while mapping JSON to Java. * @throws FacebookJsonMappingException * If an error occurs while mapping JSON to Java. */ protected Object toJavaType(FieldWithAnnotation<Facebook> fieldWithAnnotation, JsonObject jsonObject, String facebookFieldName) throws JsonException, FacebookJsonMappingException { Class<?> type = fieldWithAnnotation.getField().getType(); Object rawValue = jsonObject.get(facebookFieldName); // Short-circuit right off the bat if we've got a null value. if (NULL.equals(rawValue)) return null; if (String.class.equals(type)) { // Special handling here for better error checking. // Since JsonObject.getString() will return literal JSON text even if it's // _not_ a JSON string, we check the marshaled type and bail if needed. // For example, calling JsonObject.getString("results") on the below // JSON... // {"results":[{"name":"Mark Allen"}]} // ... would return the string "[{"name":"Mark Allen"}]" instead of // throwing an error. So we throw the error ourselves. // Per Antonello Naccarato, sometimes FB will return an empty JSON array // instead of an empty string. Look for that here. if (rawValue instanceof JsonArray) if (((JsonArray) rawValue).length() == 0) { if (logger.isLoggable(FINER)) logger.finer("Coercing an empty JSON array " + "to an empty string for " + fieldWithAnnotation); return ""; } // If the user wants a string, _always_ give her a string. // This is useful if, for example, you've got a @Facebook-annotated string // field that you'd like to have a numeric type shoved into. // User beware: this will turn *anything* into a string, which might lead // to results you don't expect. return rawValue.toString(); } if (Integer.class.equals(type) || Integer.TYPE.equals(type)) return new Integer(jsonObject.getInt(facebookFieldName)); if (Boolean.class.equals(type) || Boolean.TYPE.equals(type)) return new Boolean(jsonObject.getBoolean(facebookFieldName)); if (Long.class.equals(type) || Long.TYPE.equals(type)) return new Long(jsonObject.getLong(facebookFieldName)); if (Double.class.equals(type) || Double.TYPE.equals(type)) return new Double(jsonObject.getDouble(facebookFieldName)); if (Float.class.equals(type) || Float.TYPE.equals(type)) return new BigDecimal(jsonObject.getString(facebookFieldName)).floatValue(); if (BigInteger.class.equals(type)) return new BigInteger(jsonObject.getString(facebookFieldName)); if (BigDecimal.class.equals(type)) return new BigDecimal(jsonObject.getString(facebookFieldName)); if (List.class.equals(type)) return toJavaList(rawValue.toString(), getFirstParameterizedTypeArgument(fieldWithAnnotation.getField())); String rawValueAsString = rawValue.toString(); // Hack for issue 76 where FB will sometimes return a Post's Comments as // "[]" instead of an object type (wtf) if (Comments.class.isAssignableFrom(type) && rawValue instanceof JsonArray) { if (logger.isLoggable(FINE)) logger.fine("Encountered comment array '" + rawValueAsString + "' but expected a " + Comments.class.getSimpleName() + " object instead. Working around that " + "by coercing into an empty " + Comments.class.getSimpleName() + " instance..."); JsonObject workaroundJsonObject = new JsonObject(); workaroundJsonObject.put("count", 0); workaroundJsonObject.put("data", new JsonArray()); rawValueAsString = workaroundJsonObject.toString(); } // Some other type - recurse into it return toJavaObject(rawValueAsString, type); } /** * Creates a new instance of the given {@code type}. * * @param <T> * Java type to map to. * @param type * Type token. * @return A new instance of {@code type}. * @throws FacebookJsonMappingException * If an error occurs when creating a new instance ({@code type} is * inaccessible, doesn't have a public no-arg constructor, etc.) */ protected <T> T createInstance(Class<T> type) { String errorMessage = "Unable to create an instance of " + type + ". Please make sure that it's marked 'public' " + "and, if it's a nested class, is marked 'static'. " + "It should have a public, no-argument constructor."; try { return type.newInstance(); } catch (IllegalAccessException e) { throw new FacebookJsonMappingException(errorMessage, e); } catch (InstantiationException e) { throw new FacebookJsonMappingException(errorMessage, e); } } /** * Is the given JSON equivalent to the empty object (<code>{}</code>)? * * @param json * The JSON to check. * @return {@code true} if the JSON is equivalent to the empty object, * {@code false} otherwise. */ protected boolean isEmptyObject(String json) { return "{}".equals(json); } }
gooddata/GoodData-CL
connector/src/main/java/com/restfb/DefaultJsonMapper.java
Java
bsd-3-clause
26,108
/* Copyright (c) 2013, Groupon, 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 GROUPON 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.groupon.mapreduce.mongo.in; import com.groupon.mapreduce.mongo.WritableBSONObject; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.io.Text; import org.apache.hadoop.mapreduce.InputSplit; import org.apache.hadoop.mapreduce.RecordReader; import org.apache.hadoop.mapreduce.TaskAttemptContext; import java.io.IOException; import java.util.Iterator; /** * This reads Mongo Records from an Extent and returns Hadoop Records as WritableBSONObjects. The key * returned to the Mapper is the _id field from the Mongo Record as Text. */ public class MongoRecordReader extends RecordReader<Text, WritableBSONObject> { private Record current = null; private Iterator<Record> iterator = null; private FileSystem fs; @Override public void initialize(InputSplit inputSplit, TaskAttemptContext taskAttemptContext) throws IOException, InterruptedException { MongoInputSplit mongoInputSplit = (MongoInputSplit) inputSplit; fs = ((MongoInputSplit) inputSplit).getExtent().getPath().getFileSystem(taskAttemptContext.getConfiguration()); iterator = mongoInputSplit.getExtent().iterator(fs); } @Override public boolean nextKeyValue() throws IOException, InterruptedException { if (!iterator.hasNext()) return false; current = iterator.next(); return true; } @Override public Text getCurrentKey() throws IOException, InterruptedException { return new Text(current.getId(fs)); } @Override public WritableBSONObject getCurrentValue() throws IOException, InterruptedException { return new WritableBSONObject(current.getContent(fs)); } @Override public float getProgress() throws IOException, InterruptedException { if (!iterator.hasNext()) return 1.0f; return 0.0f; } @Override public void close() throws IOException { } }
groupon/mongo-deep-mapreduce
src/main/java/com/groupon/mapreduce/mongo/in/MongoRecordReader.java
Java
bsd-3-clause
3,408
/* * Copyright (c) 2009-2015, United States Government, as represented by the Secretary of Health and Human Services. * 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 United States Government 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 UNITED STATES GOVERNMENT 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 gov.hhs.fha.nhinc.docquery.nhin.proxy; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.any; import gov.hhs.fha.nhinc.aspect.NwhinInvocationEvent; import gov.hhs.fha.nhinc.common.nhinccommon.AssertionType; import gov.hhs.fha.nhinc.common.nhinccommon.HomeCommunityType; import gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType; import gov.hhs.fha.nhinc.connectmgr.ConnectionManager; import gov.hhs.fha.nhinc.connectmgr.ConnectionManagerCache; import gov.hhs.fha.nhinc.docquery.aspect.AdhocQueryRequestDescriptionBuilder; import gov.hhs.fha.nhinc.docquery.aspect.AdhocQueryResponseDescriptionBuilder; import gov.hhs.fha.nhinc.messaging.client.CONNECTClient; import gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor; import gov.hhs.fha.nhinc.nhinclib.NhincConstants.UDDI_SPEC_VERSION; import ihe.iti.xds_b._2007.RespondingGatewayQueryPortType; import java.lang.reflect.Method; import javax.xml.ws.Service; import oasis.names.tc.ebxml_regrep.xsd.query._3.AdhocQueryRequest; import org.jmock.Mockery; import org.jmock.integration.junit4.JMock; import org.jmock.integration.junit4.JUnit4Mockery; import org.jmock.lib.legacy.ClassImposteriser; import org.junit.Test; import org.junit.runner.RunWith; /** * * @author Neil Webb */ @RunWith(JMock.class) public class NhinDocQueryWebServiceProxyTest { Mockery context = new JUnit4Mockery() { { setImposteriser(ClassImposteriser.INSTANCE); } }; final Service mockService = context.mock(Service.class); final RespondingGatewayQueryPortType mockPort = context.mock(RespondingGatewayQueryPortType.class); @SuppressWarnings("unchecked") private CONNECTClient<RespondingGatewayQueryPortType> client = mock(CONNECTClient.class); private ConnectionManagerCache cache = mock(ConnectionManagerCache.class); private AdhocQueryRequest request; private AssertionType assertion; @Test public void hasBeginOutboundProcessingEvent() throws Exception { Class<NhinDocQueryProxyWebServiceSecuredImpl> clazz = NhinDocQueryProxyWebServiceSecuredImpl.class; Method method = clazz.getMethod("respondingGatewayCrossGatewayQuery", AdhocQueryRequest.class, AssertionType.class, NhinTargetSystemType.class); NwhinInvocationEvent annotation = method.getAnnotation(NwhinInvocationEvent.class); assertNotNull(annotation); assertEquals(AdhocQueryRequestDescriptionBuilder.class, annotation.beforeBuilder()); assertEquals(AdhocQueryResponseDescriptionBuilder.class, annotation.afterReturningBuilder()); assertEquals("Document Query", annotation.serviceType()); assertEquals("", annotation.version()); } @Test public void testNoMtom() throws Exception { NhinDocQueryProxyWebServiceSecuredImpl impl = getImpl(); NhinTargetSystemType target = getTarget("1.1"); impl.respondingGatewayCrossGatewayQuery(request, assertion, target); verify(client, never()).enableMtom(); } @Test public void testUsingGuidance() throws Exception { NhinDocQueryProxyWebServiceSecuredImpl impl = getImpl(); NhinTargetSystemType target = getTarget("1.1"); impl.respondingGatewayCrossGatewayQuery(request, assertion, target); verify(cache).getEndpointURLByServiceNameSpecVersion(any(String.class), any(String.class), any(UDDI_SPEC_VERSION.class)); } /** * @param hcidValue * @return */ private NhinTargetSystemType getTarget(String hcidValue) { NhinTargetSystemType target = new NhinTargetSystemType(); HomeCommunityType hcid = new HomeCommunityType(); hcid.setHomeCommunityId(hcidValue); target.setHomeCommunity(hcid); target.setUseSpecVersion("2.0"); return target; } /** * @return */ private NhinDocQueryProxyWebServiceSecuredImpl getImpl() { return new NhinDocQueryProxyWebServiceSecuredImpl() { /* * (non-Javadoc) * * @see * gov.hhs.fha.nhinc.docquery.nhin.proxy.NhinDocQueryProxyWebServiceSecuredImpl#getCONNECTClientSecured( * gov.hhs.fha.nhinc.messaging.service.port.ServicePortDescriptor, * gov.hhs.fha.nhinc.common.nhinccommon.AssertionType, java.lang.String, * gov.hhs.fha.nhinc.common.nhinccommon.NhinTargetSystemType) */ @Override public CONNECTClient<RespondingGatewayQueryPortType> getCONNECTClientSecured( ServicePortDescriptor<RespondingGatewayQueryPortType> portDescriptor, AssertionType assertion, String url, NhinTargetSystemType target) { return client; } /* (non-Javadoc) * @see gov.hhs.fha.nhinc.docquery.nhin.proxy.NhinDocQueryProxyWebServiceSecuredImpl#getCMInstance() */ @Override protected ConnectionManager getCMInstance() { return cache; } }; } }
beiyuxinke/CONNECT
Product/Production/Services/DocumentQueryCore/src/test/java/gov/hhs/fha/nhinc/docquery/nhin/proxy/NhinDocQueryWebServiceProxyTest.java
Java
bsd-3-clause
6,930
package com.skcraft.plume.event.block; import com.google.common.base.Functions; import com.google.common.base.Predicate; import com.skcraft.plume.event.BulkEvent; import com.skcraft.plume.event.Cause; import com.skcraft.plume.event.DelegateEvent; import com.skcraft.plume.event.Result; import com.skcraft.plume.util.Location3i; import net.minecraft.world.World; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; abstract class BlockEvent extends DelegateEvent implements BulkEvent { private final World world; protected BlockEvent(Cause cause, World world) { super(cause); checkNotNull(world, "world"); this.world = world; } /** * Get the world. * * @return The world */ public World getWorld() { return world; } /** * Get a list of affected locations. * * @return A list of affected locations */ public abstract List<Location3i> getLocations(); /** * Filter the list of affected blocks with the given predicate. If the * predicate returns {@code false}, then the block is removed. * * @param predicate the predicate * @param cancelEventOnFalse true to cancel the event and clear the block * list once the predicate returns {@code false} * @return Whether one or more blocks were filtered out */ public boolean filterLocations(Predicate<Location3i> predicate, boolean cancelEventOnFalse) { return filter(getLocations(), Functions.<Location3i>identity(), predicate, cancelEventOnFalse); } @Override public Result getResult() { if (getLocations().isEmpty()) { return Result.DENY; } return super.getResult(); } @Override public Result getExplicitResult() { return super.getResult(); } }
wizjany/Plume
src/main/java/com/skcraft/plume/event/block/BlockEvent.java
Java
bsd-3-clause
1,892
/* * Copyright (c) 2004-2022, University of Oslo * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * Neither the name of the HISP project nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON * ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.hisp.dhis.expression; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.hisp.dhis.analytics.DataType; import org.hisp.dhis.common.DimensionalItemId; import org.hisp.dhis.common.DimensionalItemObject; import org.hisp.dhis.constant.Constant; import org.hisp.dhis.dataelement.DataElement; import org.hisp.dhis.indicator.Indicator; import org.hisp.dhis.indicator.IndicatorValue; import org.hisp.dhis.organisationunit.OrganisationUnitGroup; import org.hisp.dhis.period.Period; /** * Expressions are mathematical formulas and can contain references to various * elements. * * @author Margrethe Store * @author Lars Helge Overland * @author Jim Grace */ public interface ExpressionService { String ID = ExpressionService.class.getName(); String DAYS_DESCRIPTION = "[Number of days]"; String SYMBOL_DAYS = "[days]"; String SYMBOL_WILDCARD = "*"; String UID_EXPRESSION = "[a-zA-Z]\\w{10}"; String INT_EXPRESSION = "^(0|-?[1-9]\\d*)$"; // ------------------------------------------------------------------------- // Expression CRUD operations // ------------------------------------------------------------------------- /** * Adds a new Expression to the database. * * @param expression The Expression to add. * @return The generated identifier for this Expression. */ long addExpression( Expression expression ); /** * Updates an Expression. * * @param expression The Expression to update. */ void updateExpression( Expression expression ); /** * Deletes an Expression from the database. * * @param expression the expression. */ void deleteExpression( Expression expression ); /** * Get the Expression with the given identifier. * * @param id The identifier. * @return an Expression with the given identifier. */ Expression getExpression( long id ); /** * Gets all Expressions. * * @return A list with all Expressions. */ List<Expression> getAllExpressions(); // ------------------------------------------------------------------------- // Indicator expression logic // ------------------------------------------------------------------------- /** * Returns all dimensional item objects which are present in numerator and * denominator of the given indicators, as a map from id to object. * * @param indicators the collection of indicators. * @return a map from dimensional item id to object. */ Map<DimensionalItemId, DimensionalItemObject> getIndicatorDimensionalItemMap( Collection<Indicator> indicators ); /** * Returns all OrganisationUnitGroups in the numerator and denominator * expressions in the given Indicators. Returns an empty set if the given * indicators are null or empty. * * @param indicators the set of indicators. * @return a Set of OrganisationUnitGroups. */ List<OrganisationUnitGroup> getOrgUnitGroupCountGroups( Collection<Indicator> indicators ); /** * Generates the calculated value for the given parameters based on the * values in the given maps. * * @param indicator the indicator for which to calculate the value. * @param periods a List of periods for which to calculate the value. * @param itemMap map of dimensional item id to object in expression. * @param valueMap the map of data values. * @param orgUnitCountMap the map of organisation unit group member counts. * @return the calculated value as a double. */ IndicatorValue getIndicatorValueObject( Indicator indicator, List<Period> periods, Map<DimensionalItemId, DimensionalItemObject> itemMap, Map<DimensionalItemObject, Object> valueMap, Map<String, Integer> orgUnitCountMap ); /** * Substitutes any constants and org unit group member counts in the * numerator and denominator on all indicators in the given collection. * * @param indicators the set of indicators. */ void substituteIndicatorExpressions( Collection<Indicator> indicators ); // ------------------------------------------------------------------------- // Get information about the expression // ------------------------------------------------------------------------- /** * Tests whether the expression is valid. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return the ExpressionValidationOutcome of the validation. */ ExpressionValidationOutcome expressionIsValid( String expression, ParseType parseType ); /** * Creates an expression description containing the names of the * DimensionalItemObjects from a numeric valued expression. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return An description containing DimensionalItemObjects names. */ String getExpressionDescription( String expression, ParseType parseType ); /** * Creates an expression description containing the names of the * DimensionalItemObjects from an expression string, for an expression that * will return the specified data type. * * @param expression the expression string. * @param parseType the type of expression to parse. * @param dataType the data type for the expression to return. * @return An description containing DimensionalItemObjects names. */ String getExpressionDescription( String expression, ParseType parseType, DataType dataType ); /** * Gets information we need from an expression string. * * @param params the expression parameters. * @return the expression information. */ ExpressionInfo getExpressionInfo( ExpressionParams params ); /** * From expression info, create a "base" expression parameters object with * certain metadata fields supplied that are needed for later evaluation. * <p> * Before evaluation, the caller will need to add to this "base" object * fields such as expression, parseType, dataType, valueMap, etc. * * @param info the expression information. * @return the expression parameters with metadata pre-filled. */ ExpressionParams getBaseExpressionParams( ExpressionInfo info ); /** * Returns UIDs of Data Elements and associated Option Combos (if any) found * in the Data Element Operands an expression. * <p/> * If the Data Element Operand consists of just a Data Element, or if the * Option Combo is a wildcard "*", returns just dataElementUID. * <p/> * If an Option Combo is present, returns dataElementUID.optionComboUID. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of data element identifiers. */ Set<String> getExpressionElementAndOptionComboIds( String expression, ParseType parseType ); /** * Returns all data elements found in the given expression string, including * those found in data element operands. Returns an empty set if the given * expression is null. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of data elements included in the expression string. */ Set<DataElement> getExpressionDataElements( String expression, ParseType parseType ); /** * Returns all CategoryOptionCombo uids in the given expression string that * are used as a data element operand categoryOptionCombo or * attributeOptionCombo. Returns an empty set if the expression is null. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of CategoryOptionCombo uids in the expression string. */ Set<String> getExpressionOptionComboIds( String expression, ParseType parseType ); /** * Returns all dimensional item object ids in the given expression. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return a Set of dimensional item object ids. */ Set<DimensionalItemId> getExpressionDimensionalItemIds( String expression, ParseType parseType ); /** * Returns set of all OrganisationUnitGroup UIDs in the given expression. * * @param expression the expression string. * @param parseType the type of expression to parse. * @return Map of UIDs to OrganisationUnitGroups in the expression string. */ Set<String> getExpressionOrgUnitGroupIds( String expression, ParseType parseType ); // ------------------------------------------------------------------------- // Compute the value of the expression // ------------------------------------------------------------------------- /** * Generates the calculated value for an expression. * * @param params the expression parameters. * @return the calculated value. */ Object getExpressionValue( ExpressionParams params ); // ------------------------------------------------------------------------- // Gets a (possibly cached) constant map // ------------------------------------------------------------------------- /** * Gets the (possibly cached) constant map. * * @return the constant map. */ Map<String, Constant> getConstantMap(); }
hispindia/dhis2-Core
dhis-2/dhis-api/src/main/java/org/hisp/dhis/expression/ExpressionService.java
Java
bsd-3-clause
11,199
package io.flutter.embedding.engine.mutatorsstack; import static junit.framework.TestCase.*; import static org.mockito.Mockito.*; import android.graphics.Matrix; import android.view.MotionEvent; import io.flutter.embedding.android.AndroidTouchProcessor; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.ArgumentCaptor; import org.robolectric.RobolectricTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; @Config(manifest = Config.NONE) @RunWith(RobolectricTestRunner.class) public class FlutterMutatorViewTest { @Test public void canDragViews() { final AndroidTouchProcessor touchProcessor = mock(AndroidTouchProcessor.class); final FlutterMutatorView view = new FlutterMutatorView(RuntimeEnvironment.systemContext, 1.0f, touchProcessor); final FlutterMutatorsStack mutatorStack = mock(FlutterMutatorsStack.class); assertTrue(view.onInterceptTouchEvent(mock(MotionEvent.class))); { view.readyToDisplay(mutatorStack, /*left=*/ 1, /*top=*/ 2, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(1, 2); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } reset(touchProcessor); { view.readyToDisplay(mutatorStack, /*left=*/ 3, /*top=*/ 4, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(1, 2); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } reset(touchProcessor); { view.readyToDisplay(mutatorStack, /*left=*/ 5, /*top=*/ 6, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_MOVE, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(3, 4); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } reset(touchProcessor); { view.readyToDisplay(mutatorStack, /*left=*/ 7, /*top=*/ 8, /*width=*/ 0, /*height=*/ 0); view.onTouchEvent(MotionEvent.obtain(0, 0, MotionEvent.ACTION_DOWN, 0.0f, 0.0f, 0)); final ArgumentCaptor<Matrix> matrixCaptor = ArgumentCaptor.forClass(Matrix.class); verify(touchProcessor).onTouchEvent(any(), matrixCaptor.capture()); final Matrix screenMatrix = new Matrix(); screenMatrix.postTranslate(7, 8); assertTrue(matrixCaptor.getValue().equals(screenMatrix)); } } }
chinmaygarde/flutter_engine
shell/platform/android/test/io/flutter/embedding/engine/mutatorsstack/FlutterMutatorViewTest.java
Java
bsd-3-clause
3,135
package org.hisp.dhis.dxf2.adx; /* * Copyright (c) 2015, UiO * 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. * * 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. */ import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.apache.xerces.util.XMLChar; import org.hisp.dhis.dataelement.DataElementCategory; import org.hisp.dhis.dataelement.DataElementCategoryCombo; import org.hisp.dhis.dataelement.DataElementCategoryOptionCombo; import org.hisp.dhis.dataset.DataSet; import org.hisp.dhis.dataset.DataSetElement; /** * @author bobj */ public class AdxDataSetMetadata { // Lookup category options per cat option combo private final Map<Integer, Map<String, String>> categoryOptionMap; AdxDataSetMetadata( DataSet dataSet ) throws AdxException { categoryOptionMap = new HashMap<>(); Set<DataElementCategoryCombo> catCombos = new HashSet<>(); catCombos.add( dataSet.getCategoryCombo() ); for ( DataSetElement element : dataSet.getDataSetElements() ) { catCombos.add( element.getResolvedCategoryCombo() ); } for ( DataElementCategoryCombo categoryCombo : catCombos ) { for ( DataElementCategoryOptionCombo catOptCombo : categoryCombo.getOptionCombos() ) { addExplodedCategoryAttributes( catOptCombo ); } } } private void addExplodedCategoryAttributes( DataElementCategoryOptionCombo coc ) throws AdxException { Map<String, String> categoryAttributes = new HashMap<>(); if ( !coc.isDefault() ) { for ( DataElementCategory category : coc.getCategoryCombo().getCategories() ) { String categoryCode = category.getCode(); if ( categoryCode == null || !XMLChar.isValidName( categoryCode ) ) { throw new AdxException( "Category code for " + category.getName() + " is missing or invalid: " + categoryCode ); } String catOptCode = category.getCategoryOption( coc ).getCode(); if ( catOptCode == null || catOptCode.isEmpty() ) { throw new AdxException( "CategoryOption code for " + category.getCategoryOption( coc ).getName() + " is missing" ); } categoryAttributes.put( categoryCode, catOptCode ); } } categoryOptionMap.put( coc.getId(), categoryAttributes ); } public Map<String, String> getExplodedCategoryAttributes( int cocId ) { return this.categoryOptionMap.get( cocId ); } }
uonafya/jphes-core
dhis-2/dhis-services/dhis-service-dxf2/src/main/java/org/hisp/dhis/dxf2/adx/AdxDataSetMetadata.java
Java
bsd-3-clause
4,017
/* * This file is part of Pebble. * * Copyright (c) 2014 by Mitchell Bösecke * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ package com.mitchellbosecke.pebble.extension; import com.mitchellbosecke.pebble.attributes.AttributeResolver; import com.mitchellbosecke.pebble.operator.BinaryOperator; import com.mitchellbosecke.pebble.operator.UnaryOperator; import com.mitchellbosecke.pebble.tokenParser.TokenParser; import java.util.List; import java.util.Map; public abstract class AbstractExtension implements Extension { @Override public List<TokenParser> getTokenParsers() { return null; } @Override public List<BinaryOperator> getBinaryOperators() { return null; } @Override public List<UnaryOperator> getUnaryOperators() { return null; } @Override public Map<String, Filter> getFilters() { return null; } @Override public Map<String, Test> getTests() { return null; } @Override public Map<String, Function> getFunctions() { return null; } @Override public Map<String, Object> getGlobalVariables() { return null; } @Override public List<NodeVisitorFactory> getNodeVisitors() { return null; } @Override public List<AttributeResolver> getAttributeResolver() { return null; } }
mbosecke/pebble
pebble/src/main/java/com/mitchellbosecke/pebble/extension/AbstractExtension.java
Java
bsd-3-clause
1,366
/* * 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.cluster.routing.allocation; import org.elasticsearch.Version; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.cluster.metadata.MetaData; import org.elasticsearch.cluster.node.DiscoveryNodes; import org.elasticsearch.cluster.routing.IndexRoutingTable; import org.elasticsearch.cluster.routing.IndexShardRoutingTable; import org.elasticsearch.cluster.routing.RoutingTable; import org.elasticsearch.cluster.routing.ShardRouting; import org.elasticsearch.cluster.routing.ShardRoutingState; import org.elasticsearch.cluster.routing.TestShardRouting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.cluster.ESAllocationTestCase; import java.io.BufferedReader; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import static org.elasticsearch.cluster.routing.ShardRoutingState.INITIALIZING; /** * A base testcase that allows to run tests based on the output of the CAT API * The input is a line based cat/shards output like: * kibana-int 0 p STARTED 2 24.8kb 10.202.245.2 r5-9-35 * * the test builds up a clusterstate from the cat input and optionally runs a full balance on it. * This can be used to debug cluster allocation decisions. */ public abstract class CatAllocationTestCase extends ESAllocationTestCase { protected abstract Path getCatPath() throws IOException; public void testRun() throws IOException { Set<String> nodes = new HashSet<>(); Map<String, Idx> indices = new HashMap<>(); try (BufferedReader reader = Files.newBufferedReader(getCatPath(), StandardCharsets.UTF_8)) { String line = null; // regexp FTW Pattern pattern = Pattern.compile("^(.+)\\s+(\\d)\\s+([rp])\\s+(STARTED|RELOCATING|INITIALIZING|UNASSIGNED)" + "\\s+\\d+\\s+[0-9.a-z]+\\s+(\\d+\\.\\d+\\.\\d+\\.\\d+).*$"); while((line = reader.readLine()) != null) { final Matcher matcher; if ((matcher = pattern.matcher(line)).matches()) { final String index = matcher.group(1); Idx idx = indices.get(index); if (idx == null) { idx = new Idx(index); indices.put(index, idx); } final int shard = Integer.parseInt(matcher.group(2)); final boolean primary = matcher.group(3).equals("p"); ShardRoutingState state = ShardRoutingState.valueOf(matcher.group(4)); String ip = matcher.group(5); nodes.add(ip); ShardRouting routing = TestShardRouting.newShardRouting(index, shard, ip, null, primary, state); idx.add(routing); logger.debug("Add routing {}", routing); } else { fail("can't read line: " + line); } } } logger.info("Building initial routing table"); MetaData.Builder builder = MetaData.builder(); RoutingTable.Builder routingTableBuilder = RoutingTable.builder(); for(Idx idx : indices.values()) { IndexMetaData.Builder idxMetaBuilder = IndexMetaData.builder(idx.name).settings(settings(Version.CURRENT)) .numberOfShards(idx.numShards()).numberOfReplicas(idx.numReplicas()); for (ShardRouting shardRouting : idx.routing) { if (shardRouting.active()) { Set<String> allocationIds = idxMetaBuilder.getInSyncAllocationIds(shardRouting.id()); if (allocationIds == null) { allocationIds = new HashSet<>(); } else { allocationIds = new HashSet<>(allocationIds); } allocationIds.add(shardRouting.allocationId().getId()); idxMetaBuilder.putInSyncAllocationIds(shardRouting.id(), allocationIds); } } IndexMetaData idxMeta = idxMetaBuilder.build(); builder.put(idxMeta, false); IndexRoutingTable.Builder tableBuilder = new IndexRoutingTable.Builder(idxMeta.getIndex()).initializeAsRecovery(idxMeta); Map<Integer, IndexShardRoutingTable> shardIdToRouting = new HashMap<>(); for (ShardRouting r : idx.routing) { IndexShardRoutingTable refData = new IndexShardRoutingTable.Builder(r.shardId()).addShard(r).build(); if (shardIdToRouting.containsKey(r.getId())) { refData = new IndexShardRoutingTable.Builder(shardIdToRouting.get(r.getId())).addShard(r).build(); } shardIdToRouting.put(r.getId(), refData); } for (IndexShardRoutingTable t: shardIdToRouting.values()) { tableBuilder.addIndexShard(t); } IndexRoutingTable table = tableBuilder.build(); routingTableBuilder.add(table); } MetaData metaData = builder.build(); RoutingTable routingTable = routingTableBuilder.build(); DiscoveryNodes.Builder builderDiscoNodes = DiscoveryNodes.builder(); for (String node : nodes) { builderDiscoNodes.add(newNode(node)); } ClusterState clusterState = ClusterState.builder(org.elasticsearch.cluster.ClusterName.CLUSTER_NAME_SETTING .getDefault(Settings.EMPTY)).metaData(metaData).routingTable(routingTable).nodes(builderDiscoNodes.build()).build(); if (balanceFirst()) { clusterState = rebalance(clusterState); } clusterState = allocateNew(clusterState); } protected abstract ClusterState allocateNew(ClusterState clusterState); protected boolean balanceFirst() { return true; } private ClusterState rebalance(ClusterState clusterState) { RoutingTable routingTable;AllocationService strategy = createAllocationService(Settings.builder() .build()); RoutingAllocation.Result routingResult = strategy.reroute(clusterState, "reroute"); clusterState = ClusterState.builder(clusterState).routingResult(routingResult).build(); int numRelocations = 0; while (true) { List<ShardRouting> initializing = clusterState.routingTable().shardsWithState(INITIALIZING); if (initializing.isEmpty()) { break; } logger.debug("Initializing shards: {}", initializing); numRelocations += initializing.size(); routingResult = strategy.applyStartedShards(clusterState, initializing); clusterState = ClusterState.builder(clusterState).routingResult(routingResult).build(); } logger.debug("--> num relocations to get balance: {}", numRelocations); return clusterState; } public class Idx { final String name; final List<ShardRouting> routing = new ArrayList<>(); public Idx(String name) { this.name = name; } public void add(ShardRouting r) { routing.add(r); } public int numReplicas() { int count = 0; for (ShardRouting msr : routing) { if (msr.primary() == false && msr.id()==0) { count++; } } return count; } public int numShards() { int max = 0; for (ShardRouting msr : routing) { if (msr.primary()) { max = Math.max(msr.getId()+1, max); } } return max; } } }
strahanjen/strahanjen.github.io
elasticsearch-master/core/src/test/java/org/elasticsearch/cluster/routing/allocation/CatAllocationTestCase.java
Java
bsd-3-clause
8,869
/** * BSD-style license; for more info see http://pmd.sourceforge.net/license.html */ package net.sourceforge.pmd.rules.design; import net.sourceforge.pmd.AbstractRule; import net.sourceforge.pmd.ast.ASTAssignmentOperator; import net.sourceforge.pmd.ast.ASTConditionalExpression; import net.sourceforge.pmd.ast.ASTEqualityExpression; import net.sourceforge.pmd.ast.ASTExpression; import net.sourceforge.pmd.ast.ASTName; import net.sourceforge.pmd.ast.ASTNullLiteral; import net.sourceforge.pmd.ast.ASTStatementExpression; import net.sourceforge.pmd.symboltable.VariableNameDeclaration; // TODO - should check that this is not the first assignment. e.g., this is OK: // Object x; // x = null; public class NullAssignmentRule extends AbstractRule { public Object visit(ASTNullLiteral node, Object data) { if (node.getNthParent(5) instanceof ASTStatementExpression) { ASTStatementExpression n = (ASTStatementExpression) node.getNthParent(5); if (isAssignmentToFinalField(n)) { return data; } if (n.jjtGetNumChildren() > 2 && n.jjtGetChild(1) instanceof ASTAssignmentOperator) { addViolation(data, node); } } else if (node.getNthParent(4) instanceof ASTConditionalExpression) { // "false" expression of ternary if (isBadTernary((ASTConditionalExpression)node.getNthParent(4))) { addViolation(data, node); } } else if (node.getNthParent(5) instanceof ASTConditionalExpression && node.getNthParent(4) instanceof ASTExpression) { // "true" expression of ternary if (isBadTernary((ASTConditionalExpression)node.getNthParent(5))) { addViolation(data, node); } } return data; } private boolean isAssignmentToFinalField(ASTStatementExpression n) { ASTName name = n.getFirstChildOfType(ASTName.class); return name != null && name.getNameDeclaration() instanceof VariableNameDeclaration && ((VariableNameDeclaration) name.getNameDeclaration()).getAccessNodeParent().isFinal(); } private boolean isBadTernary(ASTConditionalExpression n) { return n.isTernary() && !(n.jjtGetChild(0) instanceof ASTEqualityExpression); } }
pscadiz/pmd-4.2.6-gds
src/net/sourceforge/pmd/rules/design/NullAssignmentRule.java
Java
bsd-3-clause
2,343
package testclasses; import de.unifreiburg.cs.proglang.jgs.support.DynamicLabel; import util.printer.SecurePrinter; public class PrintMediumSuccess { public static void main(String[] args) { String med = "This is medium information"; med = DynamicLabel.makeMedium(med); SecurePrinter.printMedium(med); String low = "This is low information"; low = DynamicLabel.makeLow(low); SecurePrinter.printMedium(low); } }
luminousfennell/jgs
DynamicAnalyzer/src/main/java/testclasses/PrintMediumSuccess.java
Java
bsd-3-clause
430
package edu.pacificu.cs493f15_1.paperorplasticapp; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
eheydemann/PaperOrPlastic
PaperOrPlasticApp/app/src/test/java/edu/pacificu/cs493f15_1/paperorplasticapp/ExampleUnitTest.java
Java
mit
326
package com.hearthsim.test.minion; import com.hearthsim.card.Card; import com.hearthsim.card.CharacterIndex; import com.hearthsim.card.basic.minion.BoulderfistOgre; import com.hearthsim.card.basic.minion.RaidLeader; import com.hearthsim.card.classic.minion.common.ScarletCrusader; import com.hearthsim.card.classic.minion.rare.Abomination; import com.hearthsim.card.minion.Minion; import com.hearthsim.exception.HSException; import com.hearthsim.model.BoardModel; import com.hearthsim.model.PlayerModel; import com.hearthsim.model.PlayerSide; import com.hearthsim.util.tree.HearthTreeNode; import org.junit.Before; import org.junit.Test; import static org.junit.Assert.*; public class TestAbomination { private HearthTreeNode board; private PlayerModel currentPlayer; private PlayerModel waitingPlayer; @Before public void setup() throws HSException { board = new HearthTreeNode(new BoardModel()); currentPlayer = board.data_.getCurrentPlayer(); waitingPlayer = board.data_.getWaitingPlayer(); board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, new RaidLeader()); board.data_.placeMinion(PlayerSide.CURRENT_PLAYER, new BoulderfistOgre()); board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new ScarletCrusader()); board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new RaidLeader()); board.data_.placeMinion(PlayerSide.WAITING_PLAYER, new BoulderfistOgre()); Card fb = new Abomination(); currentPlayer.placeCardHand(fb); currentPlayer.setMana((byte) 8); waitingPlayer.setMana((byte) 8); } @Test public void test0() throws HSException { Card theCard = currentPlayer.getHand().get(0); HearthTreeNode ret = theCard.useOn(PlayerSide.WAITING_PLAYER, CharacterIndex.HERO, board); assertNull(ret); assertEquals(currentPlayer.getHand().size(), 1); assertEquals(currentPlayer.getNumMinions(), 2); assertEquals(waitingPlayer.getNumMinions(), 3); assertEquals(currentPlayer.getMana(), 8); assertEquals(waitingPlayer.getMana(), 8); assertEquals(currentPlayer.getHero().getHealth(), 30); assertEquals(waitingPlayer.getHero().getHealth(), 30); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 1); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 7); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 4); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertTrue(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield()); } @Test public void test1() throws HSException { Card theCard = currentPlayer.getHand().get(0); HearthTreeNode ret = theCard.useOn(PlayerSide.CURRENT_PLAYER, CharacterIndex.HERO, board); assertFalse(ret == null); assertEquals(currentPlayer.getHand().size(), 0); assertEquals(currentPlayer.getNumMinions(), 3); assertEquals(waitingPlayer.getNumMinions(), 3); assertEquals(currentPlayer.getMana(), 3); assertEquals(waitingPlayer.getMana(), 8); assertEquals(currentPlayer.getHero().getHealth(), 30); assertEquals(waitingPlayer.getHero().getHealth(), 30); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 4); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 1); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 7); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 5); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 4); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertTrue(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield()); } @Test public void test2() throws HSException { Card theCard = currentPlayer.getHand().get(0); HearthTreeNode ret = theCard.useOn(PlayerSide.CURRENT_PLAYER, CharacterIndex.HERO, board); assertFalse(ret == null); assertEquals(currentPlayer.getHand().size(), 0); assertEquals(currentPlayer.getNumMinions(), 3); assertEquals(waitingPlayer.getNumMinions(), 3); assertEquals(currentPlayer.getMana(), 3); assertEquals(waitingPlayer.getMana(), 8); assertEquals(currentPlayer.getHero().getHealth(), 30); assertEquals(waitingPlayer.getHero().getHealth(), 30); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalHealth(), 4); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalHealth(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getTotalHealth(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalHealth(), 1); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalHealth(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalHealth(), 7); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 5); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 4); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertTrue(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield()); //attack the Ogre... should kill everything except the Scarlet Crusader Minion attacker = currentPlayer.getCharacter(CharacterIndex.MINION_1); attacker.hasAttacked(false); ret = attacker.attack(PlayerSide.WAITING_PLAYER, CharacterIndex.MINION_3, ret); assertFalse(ret == null); assertEquals(currentPlayer.getHand().size(), 0); assertEquals(currentPlayer.getNumMinions(), 1); assertEquals(waitingPlayer.getNumMinions(), 1); assertEquals(currentPlayer.getMana(), 3); assertEquals(waitingPlayer.getMana(), 8); assertEquals(currentPlayer.getHero().getHealth(), 28); assertEquals(waitingPlayer.getHero().getHealth(), 28); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 5); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 1); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 6); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 3); assertFalse(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield()); } @Test public void test3() throws HSException { Card theCard = currentPlayer.getHand().get(0); HearthTreeNode ret = theCard.useOn(PlayerSide.CURRENT_PLAYER, CharacterIndex.HERO, board); assertFalse(ret == null); assertEquals(currentPlayer.getHand().size(), 0); assertEquals(currentPlayer.getNumMinions(), 3); assertEquals(waitingPlayer.getNumMinions(), 3); assertEquals(currentPlayer.getMana(), 3); assertEquals(waitingPlayer.getMana(), 8); assertEquals(currentPlayer.getHero().getHealth(), 30); assertEquals(waitingPlayer.getHero().getHealth(), 30); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 4); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 1); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 7); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 5); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 4); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertTrue(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield()); //Silence the Abomination first, then attack with it Minion attacker = currentPlayer.getCharacter(CharacterIndex.MINION_1); attacker.silenced(PlayerSide.CURRENT_PLAYER, board); attacker.hasAttacked(false); attacker.attack(PlayerSide.WAITING_PLAYER, CharacterIndex.MINION_3, ret); assertEquals(currentPlayer.getHand().size(), 0); assertEquals(currentPlayer.getNumMinions(), 2); assertEquals(waitingPlayer.getNumMinions(), 3); assertEquals(currentPlayer.getMana(), 3); assertEquals(waitingPlayer.getMana(), 8); assertEquals(currentPlayer.getHero().getHealth(), 30); assertEquals(waitingPlayer.getHero().getHealth(), 30); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getHealth(), 1); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getHealth(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getHealth(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 2); assertEquals(currentPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 7); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getTotalAttack(), 4); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_2).getTotalAttack(), 2); assertEquals(waitingPlayer.getCharacter(CharacterIndex.MINION_3).getTotalAttack(), 7); assertTrue(waitingPlayer.getCharacter(CharacterIndex.MINION_1).getDivineShield()); } }
slaymaker1907/HearthSim
src/test/java/com/hearthsim/test/minion/TestAbomination.java
Java
mit
11,770
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.node_monitors; import hudson.Extension; import hudson.FilePath; import hudson.Functions; import hudson.model.Computer; import hudson.remoting.Callable; import jenkins.model.Jenkins; import hudson.node_monitors.DiskSpaceMonitorDescriptor.DiskSpace; import org.kohsuke.stapler.DataBoundConstructor; import java.io.IOException; import java.text.ParseException; /** * Checks available disk space of the remote FS root. * Requires Mustang. * * @author Kohsuke Kawaguchi * @since 1.123 */ public class DiskSpaceMonitor extends AbstractDiskSpaceMonitor { @DataBoundConstructor public DiskSpaceMonitor(String freeSpaceThreshold) throws ParseException { super(freeSpaceThreshold); } public DiskSpaceMonitor() {} public DiskSpace getFreeSpace(Computer c) { return DESCRIPTOR.get(c); } @Override public String getColumnCaption() { // Hide this column from non-admins return Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER) ? super.getColumnCaption() : null; } public static final DiskSpaceMonitorDescriptor DESCRIPTOR = new DiskSpaceMonitorDescriptor() { public String getDisplayName() { return Messages.DiskSpaceMonitor_DisplayName(); } @Override protected Callable<DiskSpace, IOException> createCallable(Computer c) { FilePath p = c.getNode().getRootPath(); if(p==null) return null; return p.asCallableWith(new GetUsableSpace()); } }; @Extension public static DiskSpaceMonitorDescriptor install() { if(Functions.isMustangOrAbove()) return DESCRIPTOR; return null; } }
chenDoInG/jenkins
core/src/main/java/hudson/node_monitors/DiskSpaceMonitor.java
Java
mit
2,868
package bf.io.openshop.entities; public class Page { private long id; private String title; private String text; public Page() { } public long getId() { return id; } public void setId(long id) { this.id = id; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getText() { return text; } public void setText(String text) { this.text = text; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Page page = (Page) o; if (id != page.id) return false; if (title != null ? !title.equals(page.title) : page.title != null) return false; return !(text != null ? !text.equals(page.text) : page.text != null); } @Override public int hashCode() { int result = (int) (id ^ (id >>> 32)); result = 31 * result + (title != null ? title.hashCode() : 0); result = 31 * result + (text != null ? text.hashCode() : 0); return result; } @Override public String toString() { return "Page{" + "id=" + id + ", title='" + title + '\'' + ", text='" + text + '\'' + '}'; } }
openshopio/openshop.io-android
app/src/main/java/bf/io/openshop/entities/Page.java
Java
mit
1,413
/* * The MIT License * * Copyright (c) 2004-2009, Sun Microsystems, Inc., Kohsuke Kawaguchi * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package hudson.model; import hudson.model.MultiStageTimeSeries.TimeScale; import hudson.model.queue.SubTask; import java.io.OutputStream; import java.nio.file.Files; import java.nio.file.StandardOpenOption; import org.jfree.chart.JFreeChart; import org.junit.Test; import javax.imageio.ImageIO; import java.awt.image.BufferedImage; import java.io.File; import java.io.IOException; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; /** * @author Kohsuke Kawaguchi */ public class LoadStatisticsTest { @Test public void graph() throws IOException { LoadStatistics ls = new LoadStatistics(0, 0) { public int computeIdleExecutors() { throw new UnsupportedOperationException(); } public int computeTotalExecutors() { throw new UnsupportedOperationException(); } public int computeQueueLength() { throw new UnsupportedOperationException(); } @Override protected Iterable<Node> getNodes() { throw new UnsupportedOperationException(); } @Override protected boolean matches(Queue.Item item, SubTask subTask) { throw new UnsupportedOperationException(); } }; for (int i = 0; i < 50; i++) { ls.onlineExecutors.update(4); ls.busyExecutors.update(3); ls.availableExecutors.update(1); ls.queueLength.update(3); } for (int i = 0; i < 50; i++) { ls.onlineExecutors.update(0); ls.busyExecutors.update(0); ls.availableExecutors.update(0); ls.queueLength.update(1); } JFreeChart chart = ls.createTrendChart(TimeScale.SEC10).createChart(); BufferedImage image = chart.createBufferedImage(400, 200); File tempFile = File.createTempFile("chart-", "png"); try (OutputStream os = Files.newOutputStream(tempFile.toPath(), StandardOpenOption.DELETE_ON_CLOSE)) { ImageIO.write(image, "PNG", os); } finally { tempFile.delete(); } } @Test public void isModernWorks() throws Exception { assertThat(LoadStatistics.isModern(Modern.class), is(true)); assertThat(LoadStatistics.isModern(LoadStatistics.class), is(false)); } private static class Modern extends LoadStatistics { protected Modern(int initialOnlineExecutors, int initialBusyExecutors) { super(initialOnlineExecutors, initialBusyExecutors); } @Override public int computeIdleExecutors() { return 0; } @Override public int computeTotalExecutors() { return 0; } @Override public int computeQueueLength() { return 0; } @Override protected Iterable<Node> getNodes() { return null; } @Override protected boolean matches(Queue.Item item, SubTask subTask) { return false; } } }
oleg-nenashev/jenkins
core/src/test/java/hudson/model/LoadStatisticsTest.java
Java
mit
4,339
package com.xruby.runtime.lang; public abstract class RubyConstant extends RubyBasic { public static RubyConstant QFALSE = new RubyConstant(RubyRuntime.FalseClassClass) { public boolean isTrue() { return false; } }; public static RubyConstant QTRUE = new RubyConstant(RubyRuntime.TrueClassClass) { public boolean isTrue() { return true; } }; public static RubyConstant QNIL = new RubyConstant(RubyRuntime.NilClassClass) { public boolean isTrue() { return false; } public String toStr() { throw new RubyException(RubyRuntime.TypeErrorClass, "Cannot convert nil into String"); } }; private RubyConstant(RubyClass c) { super(c); } }
Yashi100/rhodes3.3.2
platform/bb/RubyVM/src/com/xruby/runtime/lang/RubyConstant.java
Java
mit
802
package br.pucrio.opus.smells.tests.visitor; import java.io.File; import java.io.IOException; import java.util.List; import org.eclipse.jdt.core.dom.CompilationUnit; import org.eclipse.jdt.core.dom.FieldDeclaration; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import br.pucrio.opus.smells.ast.visitors.FieldDeclarationCollector; import br.pucrio.opus.smells.tests.util.CompilationUnitLoader; public class FieldDeclarationCollectorTest { private CompilationUnit compilationUnit; @Before public void setUp() throws IOException{ File file = new File("test/br/pucrio/opus/smells/tests/dummy/FieldDeclaration.java"); this.compilationUnit = CompilationUnitLoader.getCompilationUnit(file); } @Test public void allFieldsCollectionCountTest() { FieldDeclarationCollector visitor = new FieldDeclarationCollector(); this.compilationUnit.accept(visitor); List<FieldDeclaration> collectedFields = visitor.getNodesCollected(); Assert.assertEquals(6, collectedFields.size()); } }
diegocedrim/organic
test/br/pucrio/opus/smells/tests/visitor/FieldDeclarationCollectorTest.java
Java
mit
1,022
package org.jsondoc.core.issues.issue151; import org.jsondoc.core.annotation.Api; import org.jsondoc.core.annotation.ApiMethod; import org.jsondoc.core.annotation.ApiResponseObject; @Api(name = "Foo Services", description = "bla, bla, bla ...", group = "foogroup") public class FooController { @ApiMethod(path = { "/api/foo" }, description = "Main foo service") @ApiResponseObject public FooWrapper<BarPojo> getBar() { return null; } @ApiMethod(path = { "/api/foo-wildcard" }, description = "Main foo service with wildcard") @ApiResponseObject public FooWrapper<?> wildcard() { return null; } }
sarhanm/jsondoc
jsondoc-core/src/test/java/org/jsondoc/core/issues/issue151/FooController.java
Java
mit
612
package com.tale.model; import com.blade.jdbc.annotation.Table; import java.io.Serializable; // @Table(name = "t_comments", pk = "coid") public class Comments implements Serializable { private static final long serialVersionUID = 1L; // comment表主键 private Integer coid; // post表主键,关联字段 private Integer cid; // 评论生成时的GMT unix时间戳 private Integer created; // 评论作者 private String author; // 评论所属用户id private Integer author_id; // 评论所属内容作者id private Integer owner_id; // 评论者邮件 private String mail; // 评论者网址 private String url; // 评论者ip地址 private String ip; // 评论者客户端 private String agent; // 评论内容 private String content; // 评论类型 private String type; // 评论状态 private String status; // 父级评论 private Integer parent; public Comments() { } public Integer getCoid() { return coid; } public void setCoid(Integer coid) { this.coid = coid; } public Integer getCid() { return cid; } public void setCid(Integer cid) { this.cid = cid; } public Integer getCreated() { return created; } public void setCreated(Integer created) { this.created = created; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getMail() { return mail; } public void setMail(String mail) { this.mail = mail; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public String getAgent() { return agent; } public void setAgent(String agent) { this.agent = agent; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Integer getParent() { return parent; } public void setParent(Integer parent) { this.parent = parent; } public Integer getAuthor_id() { return author_id; } public void setAuthor_id(Integer author_id) { this.author_id = author_id; } public Integer getOwner_id() { return owner_id; } public void setOwner_id(Integer owner_id) { this.owner_id = owner_id; } }
sanmubird/yuanjihua_blog
src/main/java/com/tale/model/Comments.java
Java
mit
2,962
package engine.actions; import engine.gameObject.GameObject; import authoring.model.collections.GameObjectsCollection; public class FixedCollisionTypeAction extends PhysicsTypeAction { public FixedCollisionTypeAction (String type, String secondType, Double value) { super(type, secondType, value); // TODO Auto-generated constructor stub } @Override public void applyPhysics (GameObjectsCollection myObjects) { GameObject firstCollisionObject = null; GameObject secondCollisionObject = null; for (GameObject g : myObjects){ if (g.getIdentifier().getType().equals(myType) && g.isCollisionEnabled()){ firstCollisionObject = g; } if (g.getIdentifier().getType().equals(mySecondType) && g.isCollisionEnabled()){ secondCollisionObject = g; } } myCollision.fixedCollision(firstCollisionObject, secondCollisionObject); } }
goose2460/game_author_cs308
src/engine/actions/FixedCollisionTypeAction.java
Java
mit
989
package com.jvm_bloggers.core.data_fetching.blog_posts; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.routing.RoundRobinPool; import com.jvm_bloggers.core.data_fetching.blogs.PreventConcurrentExecutionSafeguard; import com.jvm_bloggers.core.rss.SyndFeedProducer; import com.jvm_bloggers.entities.blog.Blog; import com.jvm_bloggers.entities.blog.BlogRepository; import com.jvm_bloggers.entities.metadata.Metadata; import com.jvm_bloggers.entities.metadata.MetadataKeys; import com.jvm_bloggers.entities.metadata.MetadataRepository; import com.jvm_bloggers.utils.NowProvider; import lombok.NoArgsConstructor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Component; @Component @NoArgsConstructor public class BlogPostsFetcher { private BlogRepository blogRepository; private ActorRef rssCheckingActor; private MetadataRepository metadataRepository; private NowProvider nowProvider; private PreventConcurrentExecutionSafeguard concurrentExecutionSafeguard = new PreventConcurrentExecutionSafeguard(); @Autowired public BlogPostsFetcher(ActorSystem actorSystem, BlogRepository blogRepository, BlogPostService blogPostService, SyndFeedProducer syndFeedFactory, MetadataRepository metadataRepository, NowProvider nowProvider) { this.blogRepository = blogRepository; final ActorRef blogPostStoringActor = actorSystem .actorOf(NewBlogPostStoringActor.props(blogPostService)); rssCheckingActor = actorSystem.actorOf(new RoundRobinPool(10) .props(RssCheckingActor.props(blogPostStoringActor, syndFeedFactory)), "rss-checkers"); this.metadataRepository = metadataRepository; this.nowProvider = nowProvider; } void refreshPosts() { concurrentExecutionSafeguard.preventConcurrentExecution(this::startFetchingProcess); } @Async("singleThreadExecutor") public void refreshPostsAsynchronously() { refreshPosts(); } private Void startFetchingProcess() { blogRepository.findAllActiveBlogs() .filter(Blog::isActive) .forEach(person -> rssCheckingActor.tell(new RssLink(person), ActorRef.noSender())); final Metadata dateOfLastFetch = metadataRepository .findByName(MetadataKeys.DATE_OF_LAST_FETCHING_BLOG_POSTS); dateOfLastFetch.setValue(nowProvider.now().toString()); metadataRepository.save(dateOfLastFetch); return null; } public boolean isFetchingProcessInProgress() { return concurrentExecutionSafeguard.isExecuting(); } }
jvm-bloggers/jvm-bloggers
src/main/java/com/jvm_bloggers/core/data_fetching/blog_posts/BlogPostsFetcher.java
Java
mit
2,766
package com.lichkin.framework.springboot.controllers.impl; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import com.lichkin.framework.bases.LKDatas; import com.lichkin.framework.bases.annotations.WithOutLogin; import com.lichkin.framework.springboot.controllers.LKController; /** * 页面跳转逻辑 * @author SuZhou LichKin Information Technology Co., Ltd. */ @Controller @RequestMapping(value = "/demo") public class LKDemoController extends LKController { /** * 页面跳转 * @param requestDatas 请求参数,由框架自动解析请求的参数并注入。 * @param subUrl 子路径 * @return 页面路径,附带了请求参数及请求路径的相关信息。 */ @WithOutLogin @RequestMapping(value = "/{subUrl}.html", method = RequestMethod.GET) public ModelAndView toGo(final LKDatas requestDatas, @PathVariable(value = "subUrl") final String subUrl) { return getModelAndView(requestDatas); } }
china-zhuangxuxin/LKFramework
lichkin-springboot-demos/lichkin-springboot-demo-web/src/main/java/com/lichkin/framework/springboot/controllers/impl/LKDemoController.java
Java
mit
1,209
package au.com.codeka.planetrender; import java.util.Random; import au.com.codeka.common.PerlinNoise; import au.com.codeka.common.Vector2; import au.com.codeka.common.Vector3; /** * This class takes a ray that's going in a certain direction and warps it based on a noise pattern. This is used * to generate misshapen asteroid images, for example. */ public class RayWarper { private NoiseGenerator mNoiseGenerator; private double mWarpFactor; public RayWarper(Template.WarpTemplate tmpl, Random rand) { if (tmpl.getNoiseGenerator() == Template.WarpTemplate.NoiseGenerator.Perlin) { mNoiseGenerator = new PerlinGenerator(tmpl, rand); } else if (tmpl.getNoiseGenerator() == Template.WarpTemplate.NoiseGenerator.Spiral) { mNoiseGenerator = new SpiralGenerator(tmpl, rand); } mWarpFactor = tmpl.getWarpFactor(); } public void warp(Vector3 vec, double u, double v) { mNoiseGenerator.warp(vec, u, v, mWarpFactor); } static abstract class NoiseGenerator { protected double getNoise(double u, double v) { return 0.0; } protected Vector3 getValue(double u, double v) { double x = getNoise(u * 0.25, v * 0.25); double y = getNoise(0.25 + u * 0.25, v * 0.25); double z = getNoise(u * 0.25, 0.25 + v * 0.25); return Vector3.pool.borrow().reset(x, y, z); } protected void warp(Vector3 vec, double u, double v, double factor) { Vector3 warpVector = getValue(u, v); warpVector.reset(warpVector.x * factor + (1.0 - factor), warpVector.y * factor + (1.0 - factor), warpVector.z * factor + (1.0 - factor)); vec.reset(vec.x * warpVector.x, vec.y * warpVector.y, vec.z * warpVector.z); Vector3.pool.release(warpVector); } } static class PerlinGenerator extends NoiseGenerator { private PerlinNoise mNoise; public PerlinGenerator(Template.WarpTemplate tmpl, Random rand) { mNoise = new TemplatedPerlinNoise(tmpl.getParameter(Template.PerlinNoiseTemplate.class), rand); } @Override public double getNoise(double u, double v) { return mNoise.getNoise(u, v); } } static class SpiralGenerator extends NoiseGenerator { public SpiralGenerator(Template.WarpTemplate tmpl, Random rand) { } @Override protected void warp(Vector3 vec, double u, double v, double factor) { Vector2 uv = Vector2.pool.borrow().reset(u, v); uv.rotate(factor * uv.length() * 2.0 * Math.PI * 2.0 / 360.0); vec.reset(uv.x, -uv.y, 1.0); Vector2.pool.release(uv); } } }
jife94/wwmmo
planet-render/src/au/com/codeka/planetrender/RayWarper.java
Java
mit
2,860
package cn.mutils.app.alipay; import org.junit.Test; import static org.junit.Assert.*; /** * To work on unit tests, switch the Test Artifact in the Build Variants view. */ public class ExampleUnitTest { @Test public void addition_isCorrect() throws Exception { assertEquals(4, 2 + 2); } }
lounien/OApp
Alipay/src/test/java/cn/mutils/app/alipay/ExampleUnitTest.java
Java
mit
313
package org.telegram.android.views.dialog; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.drawable.Drawable; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.SystemClock; import android.text.TextPaint; import android.util.AttributeSet; import android.util.TypedValue; import android.view.View; import android.widget.AbsListView; import android.widget.HeaderViewListAdapter; import android.widget.ListAdapter; import android.widget.ListView; import org.telegram.android.R; import org.telegram.android.TelegramApplication; import org.telegram.android.log.Logger; import org.telegram.android.ui.FontController; import org.telegram.android.ui.TextUtil; /** * Created by ex3ndr on 15.11.13. */ public class ConversationListView extends ListView { private static final String TAG = "ConversationListView"; private static final int DELTA = 26; private static final long ANIMATION_DURATION = 200; private static final int ACTIVATE_DELTA = 50; private static final long UI_TIMEOUT = 900; private TelegramApplication application; private String visibleDate = null; private int formattedVisibleDate = -1; private int timeDivMeasure; private String visibleDateNext = null; private int formattedVisibleDateNext = -1; private int timeDivMeasureNext; private TextPaint timeDivPaint; private Drawable serviceDrawable; private Rect servicePadding; private int offset; private int oldHeight; private long animationTime = 0; private boolean isTimeVisible = false; private Handler handler = new Handler(Looper.getMainLooper()) { @Override public void handleMessage(Message msg) { Logger.d(TAG, "notify"); if (msg.what == 0) { if (isTimeVisible) { isTimeVisible = false; scrollDistance = 0; animationTime = SystemClock.uptimeMillis(); } invalidate(); } else if (msg.what == 1) { isTimeVisible = true; invalidate(); } } }; private int scrollDistance; public ConversationListView(Context context) { super(context); init(); } public ConversationListView(Context context, AttributeSet attrs) { super(context, attrs); init(); } public ConversationListView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); init(); } public VisibleViewItem[] dump() { int childCount = getChildCount(); int idCount = 0; int headerCount = 0; for (int i = 0; i < childCount; i++) { int index = getFirstVisiblePosition() + i; long id = getItemIdAtPosition(index); if (id > 0) { idCount++; } else { headerCount++; } } VisibleViewItem[] res = new VisibleViewItem[idCount]; int resIndex = 0; for (int i = 0; i < childCount; i++) { View v = getChildAt(i); int index = getFirstVisiblePosition() + i; long id = getItemIdAtPosition(index); if (id > 0) { int top = ((v == null) ? 0 : v.getTop()) - getPaddingTop(); res[resIndex++] = new VisibleViewItem(index + headerCount, top, id); } } return res; } @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { VisibleViewItem[] items = null; if (changed) { items = dump(); } super.onLayout(changed, l, t, r, b); if (changed) { final int changeDelta = (b - t) - oldHeight; if (changeDelta < 0 && items.length > 0) { final VisibleViewItem item = items[items.length - 1]; setSelectionFromTop(item.getIndex(), item.getTop() + changeDelta); post(new Runnable() { @Override public void run() { setSelectionFromTop(item.getIndex(), item.getTop() + changeDelta); } }); } } oldHeight = b - t; } private void init() { application = (TelegramApplication) getContext().getApplicationContext(); setOnScrollListener(new ScrollListener()); serviceDrawable = getResources().getDrawable(R.drawable.st_bubble_service); servicePadding = new Rect(); serviceDrawable.getPadding(servicePadding); timeDivPaint = new TextPaint(Paint.ANTI_ALIAS_FLAG | Paint.SUBPIXEL_TEXT_FLAG); timeDivPaint.setTextSize(getSp(15)); timeDivPaint.setColor(0xffFFFFFF); timeDivPaint.setTypeface(FontController.loadTypeface(getContext(), "regular")); } private void drawTime(Canvas canvas, int drawOffset, float alpha, boolean first) { int w = first ? timeDivMeasure : timeDivMeasureNext; serviceDrawable.setAlpha((int) (alpha * 255)); timeDivPaint.setAlpha((int) (alpha * 255)); serviceDrawable.setBounds( getWidth() / 2 - w / 2 - servicePadding.left, getPx(44 - 8) - serviceDrawable.getIntrinsicHeight() + drawOffset, getWidth() / 2 + w / 2 + servicePadding.right, getPx(44 - 8) + drawOffset); serviceDrawable.draw(canvas); canvas.drawText(first ? visibleDate : visibleDateNext, getWidth() / 2 - w / 2, getPx(44 - 17) + drawOffset, timeDivPaint); } @Override public void draw(Canvas canvas) { super.draw(canvas); boolean isAnimated = false; boolean isShown; if (isTimeVisible) { isShown = isTimeVisible; } else { isShown = SystemClock.uptimeMillis() - animationTime < ANIMATION_DURATION; } if (isShown) { float animationRatio = 1.0f; if (SystemClock.uptimeMillis() - animationTime < ANIMATION_DURATION) { isAnimated = true; animationRatio = (SystemClock.uptimeMillis() - animationTime) / ((float) ANIMATION_DURATION); if (animationRatio > 1.0f) { animationRatio = 1.0f; } if (!isTimeVisible) { animationRatio = 1.0f - animationRatio; } } int drawOffset = offset; if (offset == 0) { if (visibleDate != null) { drawTime(canvas, drawOffset, 1.0f * animationRatio, true); } } else { float ratio = Math.min(1.0f, Math.abs(offset / (float) getPx(DELTA))); if (visibleDateNext != null) { drawTime(canvas, drawOffset + getPx(DELTA), ratio * animationRatio, false); } if (visibleDate != null) { drawTime(canvas, drawOffset, (1.0f - ratio) * animationRatio, true); } } } if (isAnimated) { invalidate(); } } protected int getPx(float dp) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics()); } protected int getSp(float sp) { return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, sp, getResources().getDisplayMetrics()); } private class ScrollListener implements OnScrollListener { private int state = SCROLL_STATE_IDLE; private int lastVisibleItem = -1; private int lastTop = 0; private int lastScrollY = -1; @Override public void onScrollStateChanged(AbsListView absListView, int i) { if (i == SCROLL_STATE_FLING || i == SCROLL_STATE_TOUCH_SCROLL) { handler.removeMessages(0); } if (i == SCROLL_STATE_IDLE) { handler.removeMessages(0); handler.sendEmptyMessageDelayed(0, UI_TIMEOUT); } state = i; } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { // if (lastScrollY == -1) { // lastScrollY = getScrollY(); // } else if (lastScrollY != getScrollY()) { // lastScrollY = getScrollY(); // application.getImageController().doPause(); // } if (lastVisibleItem == -1 || lastVisibleItem != firstVisibleItem || state == SCROLL_STATE_IDLE) { lastVisibleItem = firstVisibleItem; lastTop = 0; View view = getChildAt(0 + getHeaderViewsCount()); if (view != null) { lastTop = view.getTop(); } } else { View view = getChildAt(0 + getHeaderViewsCount()); if (view != null) { int topDelta = Math.abs(view.getTop() - lastTop); lastTop = view.getTop(); scrollDistance += topDelta; if (scrollDistance > getPx(ACTIVATE_DELTA) && !isTimeVisible) { isTimeVisible = true; animationTime = SystemClock.uptimeMillis(); handler.removeMessages(0); } } } // handler.removeMessages(0); ListAdapter adapter = getAdapter(); if (adapter instanceof HeaderViewListAdapter) { adapter = ((HeaderViewListAdapter) adapter).getWrappedAdapter(); } if (adapter instanceof ConversationAdapter) { if (firstVisibleItem == 0) { visibleDate = null; visibleDateNext = null; formattedVisibleDate = -1; formattedVisibleDateNext = -1; View view = getChildAt(1); if (view != null) { offset = Math.min(view.getTop() - getPx(DELTA), 0); if (adapter.getCount() > 0) { int date = ((ConversationAdapter) adapter).getItemDate(0); visibleDateNext = TextUtil.formatDateLong(date); timeDivMeasureNext = (int) timeDivPaint.measureText(visibleDateNext); } } return; } int realFirstVisibleItem = firstVisibleItem - getHeaderViewsCount(); if (realFirstVisibleItem >= 0 && realFirstVisibleItem < adapter.getCount()) { int date = ((ConversationAdapter) adapter).getItemDate(realFirstVisibleItem); int prevDate = date; boolean isSameDays = true; if (realFirstVisibleItem > 0 && realFirstVisibleItem + 2 < adapter.getCount()) { prevDate = ((ConversationAdapter) adapter).getItemDate(realFirstVisibleItem + 1); isSameDays = TextUtil.areSameDays(prevDate, date); } if (isSameDays) { offset = 0; } else { View view = getChildAt(firstVisibleItem - realFirstVisibleItem); if (view != null) { offset = Math.min(view.getTop() - getPx(DELTA), 0); } if (!TextUtil.areSameDays(prevDate, System.currentTimeMillis() / 1000)) { if (!TextUtil.areSameDays(prevDate, formattedVisibleDateNext)) { formattedVisibleDateNext = prevDate; visibleDateNext = TextUtil.formatDateLong(prevDate); timeDivMeasureNext = (int) timeDivPaint.measureText(visibleDateNext); } } else { visibleDateNext = null; formattedVisibleDateNext = -1; } } if (!TextUtil.areSameDays(date, System.currentTimeMillis() / 1000)) { if (!TextUtil.areSameDays(date, formattedVisibleDate)) { formattedVisibleDate = date; visibleDate = TextUtil.formatDateLong(date); timeDivMeasure = (int) timeDivPaint.measureText(visibleDate); } } else { visibleDate = null; formattedVisibleDate = -1; } } } } } }
ex3ndr/telegram
app/src/main/java/org/telegram/android/views/dialog/ConversationListView.java
Java
mit
13,050
/******************************************************************************* * Copyright (c) 2011, 2020 Eurotech and/or its affiliates and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Eurotech ******************************************************************************/ package org.eclipse.kura.net; import java.util.Map; import org.osgi.annotation.versioning.ProviderType; import org.osgi.service.event.Event; /** * An event raised when a network interface has been removed from the system. * * @noextend This class is not intended to be subclassed by clients. */ @ProviderType public class NetInterfaceRemovedEvent extends Event { /** Topic of the NetworkInterfaceRemovedEvent */ public static final String NETWORK_EVENT_INTERFACE_REMOVED_TOPIC = "org/eclipse/kura/net/NetworkEvent/interface/REMOVED"; /** Name of the property to access the network interface name */ public static final String NETWORK_EVENT_INTERFACE_PROPERTY = "network.interface"; public NetInterfaceRemovedEvent(Map<String, ?> properties) { super(NETWORK_EVENT_INTERFACE_REMOVED_TOPIC, properties); } /** * Returns the name of the removed interface. * * @return */ public String getInterfaceName() { return (String) getProperty(NETWORK_EVENT_INTERFACE_PROPERTY); } }
ctron/kura
kura/org.eclipse.kura.api/src/main/java/org/eclipse/kura/net/NetInterfaceRemovedEvent.java
Java
epl-1.0
1,545
package invalid; public class TestInvalidFieldInitializer3 { private Object field= /*]*/foo()/*[*/; public Object foo() { return field; } }
maxeler/eclipse
eclipse.jdt.ui/org.eclipse.jdt.ui.tests.refactoring/resources/InlineMethodWorkspace/TestCases/invalid/TestInvalidFieldInitializer3.java
Java
epl-1.0
151
/* ********************************************************************** ** ** Copyright notice ** ** ** ** (c) 2005-2009 RSSOwl Development Team ** ** http://www.rssowl.org/ ** ** ** ** All rights reserved ** ** ** ** This program and the accompanying materials are made available under ** ** the terms of the Eclipse Public License v1.0 which accompanies this ** ** distribution, and is available at: ** ** http://www.rssowl.org/legal/epl-v10.html ** ** ** ** A copy is found in the file epl-v10.html and important notices to the ** ** license from the team is found in the textfile LICENSE.txt distributed ** ** in this package. ** ** ** ** This copyright notice MUST APPEAR in all copies of the file! ** ** ** ** Contributors: ** ** RSSOwl Development Team - initial API and implementation ** ** ** ** ********************************************************************** */ package org.rssowl.core.internal.persist.service; import org.rssowl.core.persist.IEntity; import org.rssowl.core.persist.event.ModelEvent; import org.rssowl.core.persist.event.runnable.EventRunnable; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.List; import java.util.Map; /** * A {@link Map} of {@link ModelEvent} pointing to {@link EventRunnable}. */ public class EventsMap { private static final EventsMap INSTANCE = new EventsMap(); private static class InternalMap extends HashMap<Class<? extends ModelEvent>, EventRunnable<? extends ModelEvent>> { InternalMap() { super(); } } private final ThreadLocal<InternalMap> fEvents = new ThreadLocal<InternalMap>(); private final ThreadLocal<Map<IEntity, ModelEvent>> fEventTemplatesMap = new ThreadLocal<Map<IEntity, ModelEvent>>(); private EventsMap() { // Enforce singleton pattern } public final static EventsMap getInstance() { return INSTANCE; } public final void putPersistEvent(ModelEvent event) { EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(event); eventRunnable.addCheckedPersistEvent(event); } public final void putUpdateEvent(ModelEvent event) { EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(event); eventRunnable.addCheckedUpdateEvent(event); } public final void putRemoveEvent(ModelEvent event) { EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(event); eventRunnable.addCheckedRemoveEvent(event); } public final boolean containsPersistEvent(Class<? extends ModelEvent> eventClass, IEntity entity) { EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass); return eventRunnable.getPersistEvents().contains(entity); } public final boolean containsUpdateEvent(Class<? extends ModelEvent> eventClass, IEntity entity) { EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass); return eventRunnable.getUpdateEvents().contains(entity); } public final boolean containsRemoveEvent(Class<? extends ModelEvent> eventClass, IEntity entity) { EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass); return eventRunnable.getRemoveEvents().contains(entity); } private EventRunnable<? extends ModelEvent> getEventRunnable(Class<? extends ModelEvent> eventClass) { InternalMap map = fEvents.get(); if (map == null) { map = new InternalMap(); fEvents.set(map); } EventRunnable<? extends ModelEvent> eventRunnable = map.get(eventClass); return eventRunnable; } private EventRunnable<? extends ModelEvent> getEventRunnable(ModelEvent event) { Class<? extends ModelEvent> eventClass = event.getClass(); EventRunnable<? extends ModelEvent> eventRunnable = getEventRunnable(eventClass); if (eventRunnable == null) { eventRunnable = event.createEventRunnable(); fEvents.get().put(eventClass, eventRunnable); } return eventRunnable; } public EventRunnable<? extends ModelEvent> removeEventRunnable(Class<? extends ModelEvent> klass) { InternalMap map = fEvents.get(); if (map == null) return null; EventRunnable<? extends ModelEvent> runnable = map.remove(klass); return runnable; } public List<EventRunnable<?>> getEventRunnables() { InternalMap map = fEvents.get(); if (map == null) return new ArrayList<EventRunnable<?>>(0); List<EventRunnable<?>> eventRunnables = new ArrayList<EventRunnable<?>>(map.size()); for (Map.Entry<Class<? extends ModelEvent>, EventRunnable<? extends ModelEvent>> entry : map.entrySet()) { eventRunnables.add(entry.getValue()); } return eventRunnables; } public List<EventRunnable<?>> removeEventRunnables() { InternalMap map = fEvents.get(); if (map == null) return new ArrayList<EventRunnable<?>>(0); List<EventRunnable<?>> eventRunnables = getEventRunnables(); map.clear(); return eventRunnables; } public void putEventTemplate(ModelEvent event) { Map<IEntity, ModelEvent> map = fEventTemplatesMap.get(); if (map == null) { map = new IdentityHashMap<IEntity, ModelEvent>(); fEventTemplatesMap.set(map); } map.put(event.getEntity(), event); } public final Map<IEntity, ModelEvent> getEventTemplatesMap() { Map<IEntity, ModelEvent> map = fEventTemplatesMap.get(); if (map == null) return Collections.emptyMap(); return Collections.unmodifiableMap(fEventTemplatesMap.get()); } public Map<IEntity, ModelEvent> removeEventTemplatesMap() { Map<IEntity, ModelEvent> map = fEventTemplatesMap.get(); fEventTemplatesMap.remove(); return map; } }
rssowl/RSSOwl
org.rssowl.core/src/org/rssowl/core/internal/persist/service/EventsMap.java
Java
epl-1.0
6,658
/******************************************************************************* * Copyright (c) 2011, 2020 Eurotech and/or its affiliates and others * * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Eurotech *******************************************************************************/ package org.eclipse.kura.web.shared.model; import java.io.Serializable; import java.util.Date; import org.eclipse.kura.web.shared.DateUtils; public class GwtDeviceConfig extends GwtBaseModel implements Serializable { private static final long serialVersionUID = 1708831984640005284L; public GwtDeviceConfig() { } @Override @SuppressWarnings({ "unchecked" }) public <X> X get(String property) { if ("lastEventOnFormatted".equals(property)) { return (X) DateUtils.formatDateTime((Date) get("lastEventOn")); } else if ("uptimeFormatted".equals(property)) { if (getUptime() == -1) { return (X) "Unknown"; } else { return (X) String.valueOf(getUptime()); } } else { return super.get(property); } } public String getAccountName() { return get("accountName"); } public void setAccountName(String accountName) { set("accountName", accountName); } public String getClientId() { return (String) get("clientId"); } public void setClientId(String clientId) { set("clientId", clientId); } public Long getUptime() { return (Long) get("uptime"); } public String getUptimeFormatted() { return (String) get("uptimeFormatted"); } public void setUptime(Long uptime) { set("uptime", uptime); } public String getGwtDeviceStatus() { return (String) get("gwtDeviceStatus"); } public void setGwtDeviceStatus(String gwtDeviceStatus) { set("gwtDeviceStatus", gwtDeviceStatus); } public String getDisplayName() { return (String) get("displayName"); } public void setDisplayName(String displayName) { set("displayName", displayName); } public String getModelName() { return (String) get("modelName"); } public void setModelName(String modelName) { set("modelName", modelName); } public String getModelId() { return (String) get("modelId"); } public void setModelId(String modelId) { set("modelId", modelId); } public String getPartNumber() { return (String) get("partNumber"); } public void setPartNumber(String partNumber) { set("partNumber", partNumber); } public String getSerialNumber() { return (String) get("serialNumber"); } public void setSerialNumber(String serialNumber) { set("serialNumber", serialNumber); } public String getAvailableProcessors() { return (String) get("availableProcessors"); } public void setAvailableProcessors(String availableProcessors) { set("availableProcessors", availableProcessors); } public String getTotalMemory() { return (String) get("totalMemory"); } public void setTotalMemory(String totalMemory) { set("totalMemory", totalMemory); } public String getFirmwareVersion() { return (String) get("firmwareVersion"); } public void setFirmwareVersion(String firmwareVersion) { set("firmwareVersion", firmwareVersion); } public String getBiosVersion() { return (String) get("biosVersion"); } public void setBiosVersion(String biosVersion) { set("biosVersion", biosVersion); } public String getOs() { return (String) get("os"); } public void setOs(String os) { set("os", os); } public String getOsVersion() { return (String) get("osVersion"); } public void setOsVersion(String osVersion) { set("osVersion", osVersion); } public String getOsArch() { return (String) get("osArch"); } public void setOsArch(String osArch) { set("osArch", osArch); } public String getJvmName() { return (String) get("jvmName"); } public void setJvmName(String jvmName) { set("jvmName", jvmName); } public String getJvmVersion() { return (String) get("jvmVersion"); } public void setJvmVersion(String jvmVersion) { set("jvmVersion", jvmVersion); } public String getJvmProfile() { return (String) get("jvmProfile"); } public void setJvmProfile(String jvmProfile) { set("jvmProfile", jvmProfile); } public String getOsgiFramework() { return (String) get("osgiFramework"); } public void setOsgiFramework(String osgiFramework) { set("osgiFramework", osgiFramework); } public String getOsgiFrameworkVersion() { return (String) get("osgiFrameworkVersion"); } public void setOsgiFrameworkVersion(String osgiFrameworkVersion) { set("osgiFrameworkVersion", osgiFrameworkVersion); } public String getConnectionInterface() { return (String) get("connectionInterface"); } public void setConnectionInterface(String connectionInterface) { set("connectionInterface", connectionInterface); } public String getConnectionIp() { return (String) get("connectionIp"); } public void setConnectionIp(String connectionIp) { set("connectionIp", connectionIp); } public String getAcceptEncoding() { return (String) get("acceptEncoding"); } public void setAcceptEncoding(String acceptEncoding) { set("acceptEncoding", acceptEncoding); } public String getApplicationIdentifiers() { return (String) get("applicationIdentifiers"); } public void setApplicationIdentifiers(String applicationIdentifiers) { set("applicationIdentifiers", applicationIdentifiers); } public Double getGpsLatitude() { return (Double) get("gpsLatitude"); } public void setGpsLatitude(Double gpsLatitude) { set("gpsLatitude", gpsLatitude); } public Double getGpsLongitude() { return (Double) get("gpsLongitude"); } public void setGpsLongitude(Double gpsLongitude) { set("gpsLongitude", gpsLongitude); } public Double getGpsAltitude() { return (Double) get("gpsAltitude"); } public void setGpsAltitude(Double gpsAltitude) { set("gpsAltitude", gpsAltitude); } public String getGpsAddress() { return (String) get("gpsAddress"); } public void setGpsAddress(String gpsAddress) { set("gpsAddress", gpsAddress); } public Date getLastEventOn() { return (Date) get("lastEventOn"); } public String getLastEventOnFormatted() { return (String) get("lastEventOnFormatted"); } public void setLastEventOn(Date lastEventDate) { set("lastEventOn", lastEventDate); } public String getLastEventType() { return (String) get("lastEventType"); } public void setLastEventType(String lastEventType) { set("lastEventType", lastEventType); } public boolean isOnline() { return getGwtDeviceStatus().compareTo("CONNECTED") == 0; } }
ctron/kura
kura/org.eclipse.kura.web2/src/main/java/org/eclipse/kura/web/shared/model/GwtDeviceConfig.java
Java
epl-1.0
7,591
/* * Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.controller.sal.connector.remoterpc; import com.google.common.base.Optional; import junit.framework.Assert; import org.junit.*; import org.opendaylight.controller.sal.connector.api.RpcRouter; import org.opendaylight.controller.sal.connector.remoterpc.api.RoutingTable; import org.opendaylight.controller.sal.connector.remoterpc.utils.MessagingUtil; import org.opendaylight.controller.sal.core.api.Broker; import org.opendaylight.controller.sal.core.api.RpcRegistrationListener; import org.opendaylight.yangtools.yang.data.api.CompositeNode; import org.zeromq.ZMQ; import zmq.Ctx; import zmq.SocketBase; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.ThreadPoolExecutor; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class ServerImplTest { private static ZMQ.Context context; private ServerImpl server; private Broker.ProviderSession brokerSession; private RoutingTableProvider routingTableProvider; private RpcRegistrationListener listener; ExecutorService pool; //Server configuration private final int HANDLER_COUNT = 2; private final int HWM = 200; private final int port = 5554; //server address private final String SERVER_ADDRESS = "tcp://localhost:5554"; //@BeforeClass public static void init() { context = ZMQ.context(1); } //@AfterClass public static void destroy() { MessagingUtil.closeZmqContext(context); } @Before public void setup() throws InterruptedException { context = ZMQ.context(1); brokerSession = mock(Broker.ProviderSession.class); routingTableProvider = mock(RoutingTableProvider.class); listener = mock(RpcRegistrationListener.class); server = new ServerImpl(port); server.setBrokerSession(brokerSession); RoutingTable<RpcRouter.RouteIdentifier, String> mockRoutingTable = new MockRoutingTable<String, String>(); Optional<RoutingTable<RpcRouter.RouteIdentifier, String>> optionalRoutingTable = Optional.fromNullable(mockRoutingTable); when(routingTableProvider.getRoutingTable()).thenReturn(optionalRoutingTable); when(brokerSession.addRpcRegistrationListener(listener)).thenReturn(null); when(brokerSession.getSupportedRpcs()).thenReturn(Collections.EMPTY_SET); when(brokerSession.rpc(null, mock(CompositeNode.class))).thenReturn(null); server.start(); Thread.sleep(5000);//wait for server to start } @After public void tearDown() throws InterruptedException { if (pool != null) pool.shutdown(); if (server != null) server.stop(); MessagingUtil.closeZmqContext(context); Thread.sleep(5000);//wait for server to stop Assert.assertEquals(ServerImpl.State.STOPPED, server.getStatus()); } @Test public void getBrokerSession_Call_ShouldReturnBrokerSession() throws Exception { Optional<Broker.ProviderSession> mayBeBroker = server.getBrokerSession(); if (mayBeBroker.isPresent()) Assert.assertEquals(brokerSession, mayBeBroker.get()); else Assert.fail("Broker does not exist in Remote RPC Server"); } @Test public void start_Call_ShouldSetServerStatusToStarted() throws Exception { Assert.assertEquals(ServerImpl.State.STARTED, server.getStatus()); } @Test public void start_Call_ShouldCreateNZmqSockets() throws Exception { final int EXPECTED_COUNT = 2 + HANDLER_COUNT; //1 ROUTER + 1 DEALER + HANDLER_COUNT Optional<ZMQ.Context> mayBeContext = server.getZmqContext(); if (mayBeContext.isPresent()) Assert.assertEquals(EXPECTED_COUNT, findSocketCount(mayBeContext.get())); else Assert.fail("ZMQ Context does not exist in Remote RPC Server"); } @Test public void start_Call_ShouldCreate1ServerThread() { final String SERVER_THREAD_NAME = "remote-rpc-server"; final int EXPECTED_COUNT = 1; List<Thread> serverThreads = findThreadsWithName(SERVER_THREAD_NAME); Assert.assertEquals(EXPECTED_COUNT, serverThreads.size()); } @Test public void start_Call_ShouldCreateNHandlerThreads() { //final String WORKER_THREAD_NAME = "remote-rpc-worker"; final int EXPECTED_COUNT = HANDLER_COUNT; Optional<ServerRequestHandler> serverRequestHandlerOptional = server.getHandler(); if (serverRequestHandlerOptional.isPresent()){ ServerRequestHandler handler = serverRequestHandlerOptional.get(); ThreadPoolExecutor workerPool = handler.getWorkerPool(); Assert.assertEquals(EXPECTED_COUNT, workerPool.getPoolSize()); } else { Assert.fail("Server is in illegal state. ServerHandler does not exist"); } } @Test public void testStop() throws Exception { } @Test public void testOnRouteUpdated() throws Exception { } @Test public void testOnRouteDeleted() throws Exception { } private int findSocketCount(ZMQ.Context context) throws NoSuchFieldException, IllegalAccessException { Field ctxField = context.getClass().getDeclaredField("ctx"); ctxField.setAccessible(true); Ctx ctx = Ctx.class.cast(ctxField.get(context)); Field socketListField = ctx.getClass().getDeclaredField("sockets"); socketListField.setAccessible(true); List<SocketBase> sockets = List.class.cast(socketListField.get(ctx)); return sockets.size(); } private List<Thread> findThreadsWithName(String name) { Thread[] threads = new Thread[Thread.activeCount()]; Thread.enumerate(threads); List<Thread> foundThreads = new ArrayList(); for (Thread t : threads) { if (t.getName().startsWith(name)) foundThreads.add(t); } return foundThreads; } }
yuyf10/opendaylight-controller
opendaylight/md-sal/sal-remoterpc-connector/implementation/src/test/java/org/opendaylight/controller/sal/connector/remoterpc/ServerImplTest.java
Java
epl-1.0
6,052
/******************************************************************************* * Copyright (c) 2010 - 2013 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation * Lars Vogel <lars.Vogel@gmail.com> - Bug 419770 *******************************************************************************/ package com.vogella.e4.appmodel.app.handlers; import org.eclipse.e4.core.di.annotations.Execute; import org.eclipse.e4.ui.workbench.IWorkbench; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.swt.widgets.Shell; public class QuitHandler { @Execute public void execute(IWorkbench workbench, Shell shell){ if (MessageDialog.openConfirm(shell, "Confirmation", "Do you want to exit?")) { workbench.close(); } } }
scela/EclipseCon2014
com.vogella.e4.appmodel.app/src/com/vogella/e4/appmodel/app/handlers/QuitHandler.java
Java
epl-1.0
1,040
/* * Copyright (c) 2012-2018 Red Hat, Inc. * This program and the accompanying materials are made * available under the terms of the Eclipse Public License 2.0 * which is available at https://www.eclipse.org/legal/epl-2.0/ * * SPDX-License-Identifier: EPL-2.0 * * Contributors: * Red Hat, Inc. - initial API and implementation */ package org.eclipse.che.ide.ext.git.client.compare; import org.eclipse.che.ide.api.resources.Project; import org.eclipse.che.ide.ext.git.client.compare.FileStatus.Status; /** * Describes changed in any way project files. Supports adding and removing items dynamically. * * @author Mykola Morhun */ public class MutableAlteredFiles extends AlteredFiles { /** * Parses raw git diff string and creates advanced representation. * * @param project the project under diff operation * @param diff plain result of git diff operation */ public MutableAlteredFiles(Project project, String diff) { super(project, diff); } /** * Creates mutable altered files list based on changes from another project. * * @param project the project under diff operation * @param alteredFiles changes from another project */ public MutableAlteredFiles(Project project, AlteredFiles alteredFiles) { super(project, ""); this.alteredFilesStatuses.putAll(alteredFiles.alteredFilesStatuses); this.alteredFilesList.addAll(alteredFiles.alteredFilesList); } /** * Creates an empty list of altered files. * * @param project the project under diff operation */ public MutableAlteredFiles(Project project) { super(project, ""); } /** * Adds or updates a file in altered file list. If given file is already exists does nothing. * * @param file full path to file and its name relatively to project root * @param status git status of the file * @return true if file was added or updated and false if the file is already exists in this list */ public boolean addFile(String file, Status status) { if (status.equals(alteredFilesStatuses.get(file))) { return false; } if (alteredFilesStatuses.put(file, status) == null) { // it's not a status change, new file was added alteredFilesList.add(file); } return true; } /** * Removes given file from the altered files list. If given file isn't present does nothing. * * @param file full path to file and its name relatively to project root * @return true if the file was deleted and false otherwise */ public boolean removeFile(String file) { alteredFilesStatuses.remove(file); return alteredFilesList.remove(file); } }
akervern/che
plugins/plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/client/compare/MutableAlteredFiles.java
Java
epl-1.0
2,645
/** * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.activemq.transport.multicast; import java.net.SocketAddress; import java.nio.ByteBuffer; import org.apache.activemq.command.Command; import org.apache.activemq.command.Endpoint; import org.apache.activemq.transport.udp.DatagramEndpoint; import org.apache.activemq.transport.udp.DatagramHeaderMarshaller; /** * * */ public class MulticastDatagramHeaderMarshaller extends DatagramHeaderMarshaller { private final byte[] localUriAsBytes; public MulticastDatagramHeaderMarshaller(String localUri) { this.localUriAsBytes = localUri.getBytes(); } public Endpoint createEndpoint(ByteBuffer readBuffer, SocketAddress address) { int size = readBuffer.getInt(); byte[] data = new byte[size]; readBuffer.get(data); return new DatagramEndpoint(new String(data), address); } public void writeHeader(Command command, ByteBuffer writeBuffer) { writeBuffer.putInt(localUriAsBytes.length); writeBuffer.put(localUriAsBytes); super.writeHeader(command, writeBuffer); } }
Mark-Booth/daq-eclipse
uk.ac.diamond.org.apache.activemq/org/apache/activemq/transport/multicast/MulticastDatagramHeaderMarshaller.java
Java
epl-1.0
1,880
/******************************************************************************* * Copyright (c) 2010 Oak Ridge National Laboratory. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html ******************************************************************************/ package org.csstudio.trends.databrowser2.propsheet; import org.csstudio.swt.rtplot.undo.UndoableActionManager; import org.csstudio.trends.databrowser2.Activator; import org.csstudio.trends.databrowser2.Messages; import org.csstudio.trends.databrowser2.model.PVItem; import org.csstudio.trends.databrowser2.preferences.Preferences; import org.eclipse.jface.action.Action; /** Action that configures PVs to use default archive data sources. * @author Kay Kasemir */ public class UseDefaultArchivesAction extends Action { final private UndoableActionManager operations_manager; final private PVItem pvs[]; /** Initialize * @param shell Parent shell for dialog * @param pvs PVs that should use default archives */ public UseDefaultArchivesAction(final UndoableActionManager operations_manager, final PVItem pvs[]) { super(Messages.UseDefaultArchives, Activator.getDefault().getImageDescriptor("icons/archive.gif")); //$NON-NLS-1$ this.operations_manager = operations_manager; this.pvs = pvs; } @Override public void run() { new AddArchiveCommand(operations_manager, pvs, Preferences.getArchives(), true); } }
ControlSystemStudio/cs-studio
applications/databrowser/databrowser-plugins/org.csstudio.trends.databrowser2/src/org/csstudio/trends/databrowser2/propsheet/UseDefaultArchivesAction.java
Java
epl-1.0
1,688
/* * Debrief - the Open Source Maritime Analysis Application * http://debrief.info * * (C) 2000-2014, PlanetMayo Ltd * * This library is free software; you can redistribute it and/or * modify it under the terms of the Eclipse Public License v1.0 * (http://www.eclipse.org/legal/epl-v10.html) * * 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. */ package MWC.GUI.Properties.Swing; // Copyright MWC 1999, Debrief 3 Project // $RCSfile: SwingDatePropertyEditor.java,v $ // @author $Author: Ian.Mayo $ // @version $Revision: 1.3 $ // $Log: SwingDatePropertyEditor.java,v $ // Revision 1.3 2004/11/26 11:32:48 Ian.Mayo // Moving closer, supporting checking for time resolution // // Revision 1.2 2004/05/25 15:29:37 Ian.Mayo // Commit updates from home // // Revision 1.1.1.1 2004/03/04 20:31:20 ian // no message // // Revision 1.1.1.1 2003/07/17 10:07:26 Ian.Mayo // Initial import // // Revision 1.2 2002-05-28 09:25:47+01 ian_mayo // after switch to new system // // Revision 1.1 2002-05-28 09:14:33+01 ian_mayo // Initial revision // // Revision 1.1 2002-04-11 14:01:26+01 ian_mayo // Initial revision // // Revision 1.1 2001-08-31 10:36:55+01 administrator // Tidied up layout, so all data is displayed when editor panel is first opened // // Revision 1.0 2001-07-17 08:43:31+01 administrator // Initial revision // // Revision 1.4 2001-07-12 12:06:59+01 novatech // use tooltips to show the date format // // Revision 1.3 2001-01-21 21:38:23+00 novatech // handle focusGained = select all text // // Revision 1.2 2001-01-17 09:41:37+00 novatech // factor generic processing to parent class, and provide support for NULL values // // Revision 1.1 2001-01-03 13:42:39+00 novatech // Initial revision // // Revision 1.1.1.1 2000/12/12 21:45:37 ianmayo // initial version // // Revision 1.5 2000-10-09 13:35:47+01 ian_mayo // Switched stack traces to go to log file // // Revision 1.4 2000-04-03 10:48:57+01 ian_mayo // squeeze up the controls // // Revision 1.3 2000-02-02 14:25:07+00 ian_mayo // correct package naming // // Revision 1.2 1999-11-23 11:05:03+00 ian_mayo // further introduction of SWING components // // Revision 1.1 1999-11-16 16:07:19+00 ian_mayo // Initial revision // // Revision 1.1 1999-11-16 16:02:29+00 ian_mayo // Initial revision // // Revision 1.2 1999-11-11 18:16:09+00 ian_mayo // new class, now working // // Revision 1.1 1999-10-12 15:36:48+01 ian_mayo // Initial revision // // Revision 1.1 1999-08-26 10:05:48+01 administrator // Initial revision // import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import MWC.GUI.Dialogs.DialogFactory; import MWC.GenericData.HiResDate; import MWC.Utilities.TextFormatting.DebriefFormatDateTime; public class SwingDatePropertyEditor extends MWC.GUI.Properties.DatePropertyEditor implements java.awt.event.FocusListener { ///////////////////////////////////////////////////////////// // member variables //////////////////////////////////////////////////////////// /** * field to edit the date */ JTextField _theDate; /** * field to edit the time */ JTextField _theTime; /** * label to show the microsecodns */ JLabel _theMicrosTxt; /** * panel to hold everything */ JPanel _theHolder; ///////////////////////////////////////////////////////////// // constructor //////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////// // member functions //////////////////////////////////////////////////////////// /** * build the editor */ public java.awt.Component getCustomEditor() { _theHolder = new JPanel(); final java.awt.BorderLayout bl1 = new java.awt.BorderLayout(); bl1.setVgap(0); bl1.setHgap(0); final java.awt.BorderLayout bl2 = new java.awt.BorderLayout(); bl2.setVgap(0); bl2.setHgap(0); final JPanel lPanel = new JPanel(); lPanel.setLayout(bl1); final JPanel rPanel = new JPanel(); rPanel.setLayout(bl2); _theHolder.setLayout(new java.awt.GridLayout(0, 2)); _theDate = new JTextField(); _theDate.setToolTipText("Format: " + NULL_DATE); _theTime = new JTextField(); _theTime.setToolTipText("Format: " + NULL_TIME); lPanel.add("Center", new JLabel("Date:", JLabel.RIGHT)); lPanel.add("East", _theDate); rPanel.add("Center", new JLabel("Time:", JLabel.RIGHT)); rPanel.add("East", _theTime); _theHolder.add(lPanel); _theHolder.add(rPanel); // get the fields to select the full text when they're selected _theDate.addFocusListener(this); _theTime.addFocusListener(this); // right, just see if we are in hi-res DTG editing mode if (HiResDate.inHiResProcessingMode()) { // ok, add a button to allow the user to enter DTG data final JButton editMicros = new JButton("Micros"); editMicros.addActionListener(new ActionListener() { public void actionPerformed(final ActionEvent e) { editMicrosPressed(); } }); // ok, we' _theMicrosTxt = new JLabel(".."); _theHolder.add(_theMicrosTxt); _theHolder.add(editMicros); } resetData(); return _theHolder; } /** * user wants to edit the microseconds. give him a popup */ void editMicrosPressed() { //To change body of created methods use File | Settings | File Templates. final Integer res = DialogFactory.getInteger("Edit microseconds", "Enter microseconds",(int) _theMicros); // did user enter anything? if(res != null) { // store the data _theMicros = res.intValue(); // and update the screen resetData(); } } /** * get the date text as a string */ protected String getDateText() { return _theDate.getText(); } /** * get the date text as a string */ protected String getTimeText() { return _theTime.getText(); } /** * set the date text in string form */ protected void setDateText(final String val) { if (_theHolder != null) { _theDate.setText(val); } } /** * set the time text in string form */ protected void setTimeText(final String val) { if (_theHolder != null) { _theTime.setText(val); } } /** * show the user how many microseconds there are * * @param val */ protected void setMicroText(final long val) { // output the number of microseconds _theMicrosTxt.setText(DebriefFormatDateTime.formatMicros(new HiResDate(0, val)) + " micros"); } ///////////////////////////// // focus listener support classes ///////////////////////////// /** * Invoked when a component gains the keyboard focus. */ public void focusGained(final FocusEvent e) { final java.awt.Component c = e.getComponent(); if (c instanceof JTextField) { final JTextField jt = (JTextField) c; jt.setSelectionStart(0); jt.setSelectionEnd(jt.getText().length()); } } /** * Invoked when a component loses the keyboard focus. */ public void focusLost(final FocusEvent e) { } }
alastrina123/debrief
org.mwc.cmap.legacy/src/MWC/GUI/Properties/Swing/SwingDatePropertyEditor.java
Java
epl-1.0
7,774
package io.mycat.backend.postgresql; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.channels.NetworkChannel; import java.nio.channels.SocketChannel; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import io.mycat.backend.jdbc.ShowVariables; import io.mycat.backend.mysql.CharsetUtil; import io.mycat.backend.mysql.nio.MySQLConnectionHandler; import io.mycat.backend.mysql.nio.handler.ResponseHandler; import io.mycat.backend.postgresql.packet.Query; import io.mycat.backend.postgresql.packet.Terminate; import io.mycat.backend.postgresql.utils.PIOUtils; import io.mycat.backend.postgresql.utils.PacketUtils; import io.mycat.backend.postgresql.utils.PgSqlApaterUtils; import io.mycat.config.Isolations; import io.mycat.net.BackendAIOConnection; import io.mycat.route.RouteResultsetNode; import io.mycat.server.ServerConnection; import io.mycat.server.parser.ServerParse; import io.mycat.util.exception.UnknownTxIsolationException; /************************************************************* * PostgreSQL Native Connection impl * * @author Coollf * */ public class PostgreSQLBackendConnection extends BackendAIOConnection { public static enum BackendConnectionState { closed, connected, connecting } private static class StatusSync { private final Boolean autocommit; private final Integer charsetIndex; private final String schema; private final AtomicInteger synCmdCount; private final Integer txtIsolation; private final boolean xaStarted; public StatusSync(boolean xaStarted, String schema, Integer charsetIndex, Integer txtIsolation, Boolean autocommit, int synCount) { super(); this.xaStarted = xaStarted; this.schema = schema; this.charsetIndex = charsetIndex; this.txtIsolation = txtIsolation; this.autocommit = autocommit; this.synCmdCount = new AtomicInteger(synCount); } public boolean synAndExecuted(PostgreSQLBackendConnection conn) { int remains = synCmdCount.decrementAndGet(); if (remains == 0) {// syn command finished this.updateConnectionInfo(conn); conn.metaDataSyned = true; return false; } else if (remains < 0) { return true; } return false; } private void updateConnectionInfo(PostgreSQLBackendConnection conn) { conn.xaStatus = (xaStarted) ? 1 : 0; if (schema != null) { conn.schema = schema; conn.oldSchema = conn.schema; } if (charsetIndex != null) { conn.setCharset(CharsetUtil.getCharset(charsetIndex)); } if (txtIsolation != null) { conn.txIsolation = txtIsolation; } if (autocommit != null) { conn.autocommit = autocommit; } } } private static final Query _COMMIT = new Query("commit"); private static final Query _ROLLBACK = new Query("rollback"); private static void getCharsetCommand(StringBuilder sb, int clientCharIndex) { sb.append("SET names '").append(CharsetUtil.getCharset(clientCharIndex).toUpperCase()).append("';"); } /** * 获取 更改事物级别sql * * @param * @param txIsolation */ private static void getTxIsolationCommand(StringBuilder sb, int txIsolation) { switch (txIsolation) { case Isolations.READ_UNCOMMITTED: sb.append("SET SESSION TRANSACTION ISOLATION LEVEL READ UNCOMMITTED;"); return; case Isolations.READ_COMMITTED: sb.append("SET SESSION TRANSACTION ISOLATION LEVEL READ COMMITTED;"); return; case Isolations.REPEATED_READ: sb.append("SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ;"); return; case Isolations.SERIALIZABLE: sb.append("SET SESSION TRANSACTION ISOLATION LEVEL SERIALIZABLE;"); return; default: throw new UnknownTxIsolationException("txIsolation:" + txIsolation); } } private Object attachment; private volatile boolean autocommit=true; private volatile boolean borrowed; protected volatile String charset = "utf8"; /*** * 当前事物ID */ private volatile String currentXaTxId; /** * 来自子接口 */ private volatile boolean fromSlaveDB; /**** * PG是否在事物中 */ private volatile boolean inTransaction = false; private AtomicBoolean isQuit = new AtomicBoolean(false); private volatile long lastTime; /** * 元数据同步 */ private volatile boolean metaDataSyned = true; private volatile boolean modifiedSQLExecuted = false; private volatile String oldSchema; /** * 密码 */ private volatile String password; /** * 数据源配置 */ private PostgreSQLDataSource pool; /*** * 响应handler */ private volatile ResponseHandler responseHandler; /*** * 对应数据库空间 */ private volatile String schema; // PostgreSQL服务端密码 private volatile int serverSecretKey; private volatile BackendConnectionState state = BackendConnectionState.connecting; private volatile StatusSync statusSync; private volatile int txIsolation; /*** * 用户名 */ private volatile String user; private volatile int xaStatus; public PostgreSQLBackendConnection(NetworkChannel channel, boolean fromSlaveDB) { super(channel); this.fromSlaveDB = fromSlaveDB; } @Override public void commit() { ByteBuffer buf = this.allocate(); _COMMIT.write(buf); this.write(buf); } @Override public void execute(RouteResultsetNode rrn, ServerConnection sc, boolean autocommit) throws IOException { int sqlType = rrn.getSqlType(); String orgin = rrn.getStatement(); if (LOGGER.isDebugEnabled()) { LOGGER.debug("{}查询任务。。。。{}", id, rrn.getStatement()); LOGGER.debug(orgin); } //FIX BUG https://github.com/MyCATApache/Mycat-Server/issues/1185 if (sqlType == ServerParse.SELECT || sqlType == ServerParse.SHOW) { if (sqlType == ServerParse.SHOW) { //此处进行部分SHOW 语法适配 String _newSql = PgSqlApaterUtils.apater(orgin); if(_newSql.trim().substring(0,4).equalsIgnoreCase("show")){//未能适配成功 ShowVariables.execute(sc, orgin, this); return; } } else if ("SELECT CONNECTION_ID()".equalsIgnoreCase(orgin)) { ShowVariables.justReturnValue(sc, String.valueOf(sc.getId()), this); return; } } if (!modifiedSQLExecuted && rrn.isModifySQL()) { modifiedSQLExecuted = true; } String xaTXID = sc.getSession2().getXaTXID(); synAndDoExecute(xaTXID, rrn, sc.getCharsetIndex(), sc.getTxIsolation(), autocommit); } @Override public Object getAttachment() { return attachment; } private void getAutocommitCommand(StringBuilder sb, boolean autoCommit) { if (autoCommit) { sb.append(/*"SET autocommit=1;"*/"");//Fix bug 由于 PG9.0 开始不支持此选项,默认是为自动提交逻辑。 } else { sb.append("begin transaction;"); } } @Override public long getLastTime() { return lastTime; } public String getPassword() { return password; } public PostgreSQLDataSource getPool() { return pool; } public ResponseHandler getResponseHandler() { return responseHandler; } @Override public String getSchema() { return this.schema; } public int getServerSecretKey() { return serverSecretKey; } public BackendConnectionState getState() { return state; } @Override public int getTxIsolation() { return txIsolation; } public String getUser() { return user; } @Override public boolean isAutocommit() { return autocommit; } @Override public boolean isBorrowed() { return borrowed; } @Override public boolean isClosedOrQuit() { return isClosed() || isQuit.get(); } @Override public boolean isFromSlaveDB() { return fromSlaveDB; } public boolean isInTransaction() { return inTransaction; } @Override public boolean isModifiedSQLExecuted() { return modifiedSQLExecuted; } @Override public void onConnectFailed(Throwable t) { if (handler instanceof MySQLConnectionHandler) { } } @Override public void onConnectfinish() { LOGGER.debug("连接后台真正完成"); try { SocketChannel chan = (SocketChannel) this.channel; ByteBuffer buf = PacketUtils.makeStartUpPacket(user, schema); buf.flip(); chan.write(buf); } catch (Exception e) { LOGGER.error("Connected PostgreSQL Send StartUpPacket ERROR", e); throw new RuntimeException(e); } } protected final int getPacketLength(ByteBuffer buffer, int offset) { // Pg 协议获取包长度的方法和mysql 不一样 return PIOUtils.redInteger4(buffer, offset + 1) + 1; } /********** * 此查询用于心跳检查和获取连接后的健康检查 */ @Override public void query(String query) throws UnsupportedEncodingException { RouteResultsetNode rrn = new RouteResultsetNode("default", ServerParse.SELECT, query); synAndDoExecute(null, rrn, this.charsetIndex, this.txIsolation, true); } @Override public void quit() { if (isQuit.compareAndSet(false, true) && !isClosed()) { if (state == BackendConnectionState.connected) {// 断开 与PostgreSQL连接 Terminate terminate = new Terminate(); ByteBuffer buf = this.allocate(); terminate.write(buf); write(buf); } else { close("normal"); } } } /******* * 记录sql执行信息 */ @Override public void recordSql(String host, String schema, String statement) { LOGGER.debug(String.format("executed sql: host=%s,schema=%s,statement=%s", host, schema, statement)); } @Override public void release() { if (!metaDataSyned) {/* * indicate connection not normalfinished ,and * we can't know it's syn status ,so close it */ LOGGER.warn("can't sure connection syn result,so close it " + this); this.responseHandler = null; this.close("syn status unkown "); return; } metaDataSyned = true; attachment = null; statusSync = null; modifiedSQLExecuted = false; setResponseHandler(null); pool.releaseChannel(this); } @Override public void rollback() { ByteBuffer buf = this.allocate(); _ROLLBACK.write(buf); this.write(buf); } @Override public void setAttachment(Object attachment) { this.attachment = attachment; } @Override public void setBorrowed(boolean borrowed) { this.borrowed = borrowed; } public void setInTransaction(boolean inTransaction) { this.inTransaction = inTransaction; } @Override public void setLastTime(long currentTimeMillis) { this.lastTime = currentTimeMillis; } public void setPassword(String password) { this.password = password; } public void setPool(PostgreSQLDataSource pool) { this.pool = pool; } @Override public boolean setResponseHandler(ResponseHandler commandHandler) { this.responseHandler = commandHandler; return true; } @Override public void setSchema(String newSchema) { String curSchema = schema; if (curSchema == null) { this.schema = newSchema; this.oldSchema = newSchema; } else { this.oldSchema = curSchema; this.schema = newSchema; } } public void setServerSecretKey(int serverSecretKey) { this.serverSecretKey = serverSecretKey; } public void setState(BackendConnectionState state) { this.state = state; } public void setUser(String user) { this.user = user; } private void synAndDoExecute(String xaTxID, RouteResultsetNode rrn, int clientCharSetIndex, int clientTxIsoLation, boolean clientAutoCommit) { String xaCmd = null; boolean conAutoComit = this.autocommit; String conSchema = this.schema; // never executed modify sql,so auto commit boolean expectAutocommit = !modifiedSQLExecuted || isFromSlaveDB() || clientAutoCommit; if (!expectAutocommit && xaTxID != null && xaStatus == 0) { clientTxIsoLation = Isolations.SERIALIZABLE; xaCmd = "XA START " + xaTxID + ';'; currentXaTxId = xaTxID; } int schemaSyn = conSchema.equals(oldSchema) ? 0 : 1; int charsetSyn = (this.charsetIndex == clientCharSetIndex) ? 0 : 1; int txIsoLationSyn = (txIsolation == clientTxIsoLation) ? 0 : 1; int autoCommitSyn = (conAutoComit == expectAutocommit) ? 0 : 1; int synCount = schemaSyn + charsetSyn + txIsoLationSyn + autoCommitSyn; if (synCount == 0) { String sql = rrn.getStatement(); Query query = new Query(PgSqlApaterUtils.apater(sql)); ByteBuffer buf = this.allocate();// XXX 此处处理问题 query.write(buf); this.write(buf); return; } // TODO COOLLF 此处大锅待实现. 相关 事物, 切换 库,自动提交等功能实现 StringBuilder sb = new StringBuilder(); if (charsetSyn == 1) { getCharsetCommand(sb, clientCharSetIndex); } if (txIsoLationSyn == 1) { getTxIsolationCommand(sb, clientTxIsoLation); } if (autoCommitSyn == 1) { getAutocommitCommand(sb, expectAutocommit); } if (xaCmd != null) { sb.append(xaCmd); } if (LOGGER.isDebugEnabled()) { LOGGER.debug("con need syn ,total syn cmd " + synCount + " commands " + sb.toString() + "schema change:" + ("" != null) + " con:" + this); } metaDataSyned = false; statusSync = new StatusSync(xaCmd != null, conSchema, clientCharSetIndex, clientTxIsoLation, expectAutocommit, synCount); String sql = sb.append(PgSqlApaterUtils.apater(rrn.getStatement())).toString(); if(LOGGER.isDebugEnabled()){ LOGGER.debug("con={}, SQL={}", this, sql); } Query query = new Query(sql); ByteBuffer buf = allocate();// 申请ByetBuffer query.write(buf); this.write(buf); metaDataSyned = true; } public void close(String reason) { if (!isClosed.get()) { isQuit.set(true); super.close(reason); pool.connectionClosed(this); if (this.responseHandler != null) { this.responseHandler.connectionClose(this, reason); responseHandler = null; } } } @Override public boolean syncAndExcute() { StatusSync sync = this.statusSync; if (sync != null) { boolean executed = sync.synAndExecuted(this); if (executed) { statusSync = null; } return executed; } return true; } @Override public String toString() { return "PostgreSQLBackendConnection [id=" + id + ", host=" + host + ", port=" + port + ", localPort=" + localPort + "]"; } }
inspur-iop/Mycat-Server
src/main/java/io/mycat/backend/postgresql/PostgreSQLBackendConnection.java
Java
gpl-2.0
14,050
/* * #%L * Fork of MDB Tools (Java port). * %% * Copyright (C) 2008 - 2013 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * This program 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 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 Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ /* * Created on Jan 14, 2005 * * TODO To change the template for this generated file go to * Window - Preferences - Java - Code Style - Code Templates */ package mdbtools.libmdb06util; /** * @author calvin * * TODO To change the template for this generated type comment go to * Window - Preferences - Java - Code Style - Code Templates */ public class mdbver { public static void main(String[] args) { } }
ctrueden/bioformats
components/forks/mdbtools/src/mdbtools/libmdb06util/mdbver.java
Java
gpl-2.0
1,360
/* StreamHandler.java -- A class for publishing log messages to instances of java.io.OutputStream Copyright (C) 2002 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package java.util.logging; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; /** * A <code>StreamHandler</code> publishes <code>LogRecords</code> to * a instances of <code>java.io.OutputStream</code>. * * @author Sascha Brawer (brawer@acm.org) */ public class StreamHandler extends Handler { private OutputStream out; private Writer writer; /** * Indicates the current state of this StreamHandler. The value * should be one of STATE_FRESH, STATE_PUBLISHED, or STATE_CLOSED. */ private int streamState = STATE_FRESH; /** * streamState having this value indicates that the StreamHandler * has been created, but the publish(LogRecord) method has not been * called yet. If the StreamHandler has been constructed without an * OutputStream, writer will be null, otherwise it is set to a * freshly created OutputStreamWriter. */ private static final int STATE_FRESH = 0; /** * streamState having this value indicates that the publish(LocRecord) * method has been called at least once. */ private static final int STATE_PUBLISHED = 1; /** * streamState having this value indicates that the close() method * has been called. */ private static final int STATE_CLOSED = 2; /** * Creates a <code>StreamHandler</code> without an output stream. * Subclasses can later use {@link * #setOutputStream(java.io.OutputStream)} to associate an output * stream with this StreamHandler. */ public StreamHandler() { this(null, null); } /** * Creates a <code>StreamHandler</code> that formats log messages * with the specified Formatter and publishes them to the specified * output stream. * * @param out the output stream to which the formatted log messages * are published. * * @param formatter the <code>Formatter</code> that will be used * to format log messages. */ public StreamHandler(OutputStream out, Formatter formatter) { this(out, "java.util.logging.StreamHandler", Level.INFO, formatter, SimpleFormatter.class); } StreamHandler( OutputStream out, String propertyPrefix, Level defaultLevel, Formatter formatter, Class defaultFormatterClass) { this.level = LogManager.getLevelProperty(propertyPrefix + ".level", defaultLevel); this.filter = (Filter) LogManager.getInstanceProperty( propertyPrefix + ".filter", /* must be instance of */ Filter.class, /* default: new instance of */ null); if (formatter != null) this.formatter = formatter; else this.formatter = (Formatter) LogManager.getInstanceProperty( propertyPrefix + ".formatter", /* must be instance of */ Formatter.class, /* default: new instance of */ defaultFormatterClass); try { String enc = LogManager.getLogManager().getProperty(propertyPrefix + ".encoding"); /* make sure enc actually is a valid encoding */ if ((enc != null) && (enc.length() > 0)) new String(new byte[0], enc); this.encoding = enc; } catch (Exception _) { } if (out != null) { try { changeWriter(out, getEncoding()); } catch (UnsupportedEncodingException uex) { /* This should never happen, since the validity of the encoding * name has been checked above. */ throw new RuntimeException(uex.getMessage()); } } } private void checkOpen() { if (streamState == STATE_CLOSED) throw new IllegalStateException(this.toString() + " has been closed"); } private void checkFresh() { checkOpen(); if (streamState != STATE_FRESH) throw new IllegalStateException("some log records have been published to " + this); } private void changeWriter(OutputStream out, String encoding) throws UnsupportedEncodingException { OutputStreamWriter writer; /* The logging API says that a null encoding means the default * platform encoding. However, java.io.OutputStreamWriter needs * another constructor for the default platform encoding, * passing null would throw an exception. */ if (encoding == null) writer = new OutputStreamWriter(out); else writer = new OutputStreamWriter(out, encoding); /* Closing the stream has side effects -- do this only after * creating a new writer has been successful. */ if ((streamState != STATE_FRESH) || (this.writer != null)) close(); this.writer = writer; this.out = out; this.encoding = encoding; streamState = STATE_FRESH; } /** * Sets the character encoding which this handler uses for publishing * log records. The encoding of a <code>StreamHandler</code> must be * set before any log records have been published. * * @param encoding the name of a character encoding, or <code>null</code> * for the default encoding. * * @throws SecurityException if a security manager exists and * the caller is not granted the permission to control the * the logging infrastructure. * * @exception IllegalStateException if any log records have been * published to this <code>StreamHandler</code> before. Please * be aware that this is a pecularity of the GNU implementation. * While the API specification indicates that it is an error * if the encoding is set after records have been published, * it does not mandate any specific behavior for that case. */ public void setEncoding(String encoding) throws SecurityException, UnsupportedEncodingException { /* The inherited implementation first checks whether the invoking * code indeed has the permission to control the logging infra- * structure, and throws a SecurityException if this was not the * case. * * Next, it verifies that the encoding is supported and throws * an UnsupportedEncodingExcpetion otherwise. Finally, it remembers * the name of the encoding. */ super.setEncoding(encoding); checkFresh(); /* If out is null, setEncoding is being called before an output * stream has been set. In that case, we need to check that the * encoding is valid, and remember it if this is the case. Since * this is exactly what the inherited implementation of * Handler.setEncoding does, we can delegate. */ if (out != null) { /* The logging API says that a null encoding means the default * platform encoding. However, java.io.OutputStreamWriter needs * another constructor for the default platform encoding, passing * null would throw an exception. */ if (encoding == null) writer = new OutputStreamWriter(out); else writer = new OutputStreamWriter(out, encoding); } } /** * Changes the output stream to which this handler publishes * logging records. * * @throws SecurityException if a security manager exists and * the caller is not granted the permission to control * the logging infrastructure. * * @throws NullPointerException if <code>out</code> * is <code>null</code>. */ protected void setOutputStream(OutputStream out) throws SecurityException { LogManager.getLogManager().checkAccess(); /* Throw a NullPointerException if out is null. */ out.getClass(); try { changeWriter(out, getEncoding()); } catch (UnsupportedEncodingException ex) { /* This seems quite unlikely to happen, unless the underlying * implementation of java.io.OutputStreamWriter changes its * mind (at runtime) about the set of supported character * encodings. */ throw new RuntimeException(ex.getMessage()); } } /** * Publishes a <code>LogRecord</code> to the associated output * stream, provided the record passes all tests for being loggable. * The <code>StreamHandler</code> will localize the message of the * log record and substitute any message parameters. * * <p>Most applications do not need to call this method directly. * Instead, they will use use a {@link Logger}, which will create * LogRecords and distribute them to registered handlers. * * <p>In case of an I/O failure, the <code>ErrorManager</code> * of this <code>Handler</code> will be informed, but the caller * of this method will not receive an exception. * * <p>If a log record is being published to a * <code>StreamHandler</code> that has been closed earlier, the Sun * J2SE 1.4 reference can be observed to silently ignore the * call. The GNU implementation, however, intentionally behaves * differently by informing the <code>ErrorManager</code> associated * with this <code>StreamHandler</code>. Since the condition * indicates a programming error, the programmer should be * informed. It also seems extremely unlikely that any application * would depend on the exact behavior in this rather obscure, * erroneous case -- especially since the API specification does not * prescribe what is supposed to happen. * * @param record the log event to be published. */ public void publish(LogRecord record) { String formattedMessage; if (!isLoggable(record)) return; if (streamState == STATE_FRESH) { try { writer.write(formatter.getHead(this)); } catch (java.io.IOException ex) { reportError(null, ex, ErrorManager.WRITE_FAILURE); return; } catch (Exception ex) { reportError(null, ex, ErrorManager.GENERIC_FAILURE); return; } streamState = STATE_PUBLISHED; } try { formattedMessage = formatter.format(record); } catch (Exception ex) { reportError(null, ex, ErrorManager.FORMAT_FAILURE); return; } try { writer.write(formattedMessage); } catch (Exception ex) { reportError(null, ex, ErrorManager.WRITE_FAILURE); } } /** * Checks whether or not a <code>LogRecord</code> would be logged * if it was passed to this <code>StreamHandler</code> for publication. * * <p>The <code>StreamHandler</code> implementation first checks * whether a writer is present and the handler's level is greater * than or equal to the severity level threshold. In a second step, * if a {@link Filter} has been installed, its {@link * Filter#isLoggable(LogRecord) isLoggable} method is * invoked. Subclasses of <code>StreamHandler</code> can override * this method to impose their own constraints. * * @param record the <code>LogRecord</code> to be checked. * * @return <code>true</code> if <code>record</code> would * be published by {@link #publish(LogRecord) publish}, * <code>false</code> if it would be discarded. * * @see #setLevel(Level) * @see #setFilter(Filter) * @see Filter#isLoggable(LogRecord) * * @throws NullPointerException if <code>record</code> is * <code>null</code>. */ public boolean isLoggable(LogRecord record) { return (writer != null) && super.isLoggable(record); } /** * Forces any data that may have been buffered to the underlying * output device. * * <p>In case of an I/O failure, the <code>ErrorManager</code> * of this <code>Handler</code> will be informed, but the caller * of this method will not receive an exception. * * <p>If a <code>StreamHandler</code> that has been closed earlier * is closed a second time, the Sun J2SE 1.4 reference can be * observed to silently ignore the call. The GNU implementation, * however, intentionally behaves differently by informing the * <code>ErrorManager</code> associated with this * <code>StreamHandler</code>. Since the condition indicates a * programming error, the programmer should be informed. It also * seems extremely unlikely that any application would depend on the * exact behavior in this rather obscure, erroneous case -- * especially since the API specification does not prescribe what is * supposed to happen. */ public void flush() { try { checkOpen(); if (writer != null) writer.flush(); } catch (Exception ex) { reportError(null, ex, ErrorManager.FLUSH_FAILURE); } } /** * Closes this <code>StreamHandler</code> after having forced any * data that may have been buffered to the underlying output * device. * * <p>As soon as <code>close</code> has been called, * a <code>Handler</code> should not be used anymore. Attempts * to publish log records, to flush buffers, or to modify the * <code>Handler</code> in any other way may throw runtime * exceptions after calling <code>close</code>.</p> * * <p>In case of an I/O failure, the <code>ErrorManager</code> * of this <code>Handler</code> will be informed, but the caller * of this method will not receive an exception.</p> * * <p>If a <code>StreamHandler</code> that has been closed earlier * is closed a second time, the Sun J2SE 1.4 reference can be * observed to silently ignore the call. The GNU implementation, * however, intentionally behaves differently by informing the * <code>ErrorManager</code> associated with this * <code>StreamHandler</code>. Since the condition indicates a * programming error, the programmer should be informed. It also * seems extremely unlikely that any application would depend on the * exact behavior in this rather obscure, erroneous case -- * especially since the API specification does not prescribe what is * supposed to happen. * * @throws SecurityException if a security manager exists and * the caller is not granted the permission to control * the logging infrastructure. */ public void close() throws SecurityException { LogManager.getLogManager().checkAccess(); try { /* Although flush also calls checkOpen, it catches * any exceptions and reports them to the ErrorManager * as flush failures. However, we want to report * a closed stream as a close failure, not as a * flush failure here. Therefore, we call checkOpen() * before flush(). */ checkOpen(); flush(); if (writer != null) { if (formatter != null) { /* Even if the StreamHandler has never published a record, * it emits head and tail upon closing. An earlier version * of the GNU Classpath implementation did not emitted * anything. However, this had caused XML log files to be * entirely empty instead of containing no log records. */ if (streamState == STATE_FRESH) writer.write(formatter.getHead(this)); if (streamState != STATE_CLOSED) writer.write(formatter.getTail(this)); } streamState = STATE_CLOSED; writer.close(); } } catch (Exception ex) { reportError(null, ex, ErrorManager.CLOSE_FAILURE); } } }
aosm/gcc_40
libjava/java/util/logging/StreamHandler.java
Java
gpl-2.0
16,999
/* * Copyright (c) 2014, 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 test.css.controls.api; import org.junit.Test; import client.test.Keywords; import client.test.Smoke; import org.junit.BeforeClass; import org.junit.Before; import test.javaclient.shared.TestBase; import static test.css.controls.ControlPage.ScrollPanes; import test.javaclient.shared.screenshots.ScreenshotUtils; /** * Generated test */ public class ScrollPanesAPICssTest extends TestBase { { ScreenshotUtils.setComparatorDistance(0.003f); } @BeforeClass public static void runUI() { test.css.controls.api.APIStylesApp.main(null); } @Before public void createPage () { ((test.css.controls.api.APIStylesApp)getApplication()).open(ScrollPanes); } /** * test ScrollPane with css: -fx-border-color */ @Test public void ScrollPanes_BORDER_COLOR() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-COLOR", true); } /** * test ScrollPane with css: -fx-border-width */ @Test public void ScrollPanes_BORDER_WIDTH() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-WIDTH", true); } /** * test ScrollPane with css: -fx-border-width-dotted */ @Test public void ScrollPanes_BORDER_WIDTH_dotted() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-WIDTH-dotted", true); } /** * test ScrollPane with css: -fx-border-width-dashed */ @Test public void ScrollPanes_BORDER_WIDTH_dashed() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-WIDTH-dashed", true); } /** * test ScrollPane with css: -fx-border-inset */ @Test public void ScrollPanes_BORDER_INSET() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-INSET", true); } /** * test ScrollPane with css: -fx-border-style-dashed */ @Test public void ScrollPanes_BORDER_STYLE_DASHED() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-STYLE-DASHED", true); } /** * test ScrollPane with css: -fx-border-style-dotted */ @Test public void ScrollPanes_BORDER_STYLE_DOTTED() throws Exception { testAdditionalAction(ScrollPanes.name(), "BORDER-STYLE-DOTTED", true); } /** * test ScrollPane with css: -fx-image-border */ @Test public void ScrollPanes_IMAGE_BORDER() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER", true); } /** * test ScrollPane with css: -fx-image-border-insets */ @Test public void ScrollPanes_IMAGE_BORDER_INSETS() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-INSETS", true); } /** * test ScrollPane with css: -fx-image-border-no-repeat */ @Test public void ScrollPanes_IMAGE_BORDER_NO_REPEAT() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-NO-REPEAT", true); } /** * test ScrollPane with css: -fx-image-border-repeat-x */ @Test public void ScrollPanes_IMAGE_BORDER_REPEAT_X() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-REPEAT-X", true); } /** * test ScrollPane with css: -fx-image-border-repeat-y */ @Test public void ScrollPanes_IMAGE_BORDER_REPEAT_Y() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-REPEAT-Y", true); } /** * test ScrollPane with css: -fx-image-border-round */ @Test public void ScrollPanes_IMAGE_BORDER_ROUND() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-ROUND", true); } /** * test ScrollPane with css: -fx-image-border-space */ @Test public void ScrollPanes_IMAGE_BORDER_SPACE() throws Exception { testAdditionalAction(ScrollPanes.name(), "IMAGE-BORDER-SPACE", true); } public String getName() { return "ControlCss"; } }
teamfx/openjfx-8u-dev-tests
functional/FXCssTests/test/test/css/controls/api/ScrollPanesAPICssTest.java
Java
gpl-2.0
5,253
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2007-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 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 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 General Public License for more details. * * You should have received a copy of the GNU 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.netmgt.threshd; import java.util.Date; import java.util.HashMap; import java.util.Map; import org.opennms.netmgt.EventConstants; import org.opennms.netmgt.xml.event.Event; import org.springframework.util.Assert; /** * Implements a relative change threshold check. A 'value' setting of * less than 1.0 means that a threshold will fire if the current value * is less than or equal to the previous value multiplied by the 'value' * setting. A 'value' setting greater than 1.0 causes the threshold to * fire if the current value is greater than or equal to the previous * value multiplied by the 'value' setting. A 'value' setting of 1.0 * (unity) is not allowed, as it represents no change. Zero valued * samples (0.0) are ignored, as 0.0 multiplied by anything is 0.0 (if * they were not ignored, an interface that gets no traffic would always * trigger a threshold, for example). * * @author ranger * @version $Id: $ */ public class ThresholdEvaluatorRelativeChange implements ThresholdEvaluator { private static final String TYPE = "relativeChange"; /** {@inheritDoc} */ @Override public ThresholdEvaluatorState getThresholdEvaluatorState(BaseThresholdDefConfigWrapper threshold) { return new ThresholdEvaluatorStateRelativeChange(threshold); } /** {@inheritDoc} */ @Override public boolean supportsType(String type) { return TYPE.equals(type); } public static class ThresholdEvaluatorStateRelativeChange extends AbstractThresholdEvaluatorState { private BaseThresholdDefConfigWrapper m_thresholdConfig; private double m_multiplier; private double m_lastSample = 0.0; private double m_previousTriggeringSample; public ThresholdEvaluatorStateRelativeChange(BaseThresholdDefConfigWrapper threshold) { Assert.notNull(threshold, "threshold argument cannot be null"); setThresholdConfig(threshold); } public void setThresholdConfig(BaseThresholdDefConfigWrapper thresholdConfig) { Assert.notNull(thresholdConfig.getType(), "threshold must have a 'type' value set"); Assert.notNull(thresholdConfig.getDatasourceExpression(), "threshold must have a 'ds-name' value set"); Assert.notNull(thresholdConfig.getDsType(), "threshold must have a 'ds-type' value set"); Assert.isTrue(thresholdConfig.hasValue(), "threshold must have a 'value' value set"); Assert.isTrue(thresholdConfig.hasRearm(), "threshold must have a 'rearm' value set"); Assert.isTrue(thresholdConfig.hasTrigger(), "threshold must have a 'trigger' value set"); Assert.isTrue(TYPE.equals(thresholdConfig.getType()), "threshold for ds-name '" + thresholdConfig.getDatasourceExpression() + "' has type of '" + thresholdConfig.getType() + "', but this evaluator only supports thresholds with a 'type' value of '" + TYPE + "'"); Assert.isTrue(!Double.isNaN(thresholdConfig.getValue()), "threshold must have a 'value' value that is a number"); Assert.isTrue(thresholdConfig.getValue() != Double.POSITIVE_INFINITY && thresholdConfig.getValue() != Double.NEGATIVE_INFINITY, "threshold must have a 'value' value that is not positive or negative infinity"); Assert.isTrue(thresholdConfig.getValue() != 1.0, "threshold must not be unity (1.0)"); m_thresholdConfig = thresholdConfig; setMultiplier(thresholdConfig.getValue()); } @Override public BaseThresholdDefConfigWrapper getThresholdConfig() { return m_thresholdConfig; } @Override public Status evaluate(double dsValue) { //Fix for Bug 2275 so we handle negative numbers //It will not handle values which cross the 0 boundary (from - to +, or v.v.) properly, but // after some discussion, we can't come up with a sensible scenario when that would actually happen. // If such a scenario eventuates, reconsider dsValue=Math.abs(dsValue); if (getLastSample() != 0.0) { double threshold = getMultiplier() * getLastSample(); if (getMultiplier() < 1.0) { if (dsValue <= threshold) { setPreviousTriggeringSample(getLastSample()); setLastSample(dsValue); return Status.TRIGGERED; } } else { if (dsValue >= threshold) { setPreviousTriggeringSample(getLastSample()); setLastSample(dsValue); return Status.TRIGGERED; } } setLastSample(dsValue); } setLastSample(dsValue); return Status.NO_CHANGE; } public Double getLastSample() { return m_lastSample; } public void setLastSample(double lastSample) { m_lastSample = lastSample; } @Override public Event getEventForState(Status status, Date date, double dsValue, CollectionResourceWrapper resource) { if (status == Status.TRIGGERED) { String uei=getThresholdConfig().getTriggeredUEI(); if(uei==null || "".equals(uei)) { uei=EventConstants.RELATIVE_CHANGE_THRESHOLD_EVENT_UEI; } return createBasicEvent(uei, date, dsValue, resource); } else { return null; } } private Event createBasicEvent(String uei, Date date, double dsValue, CollectionResourceWrapper resource) { Map<String,String> params = new HashMap<String,String>(); params.put("previousValue", formatValue(getPreviousTriggeringSample())); params.put("multiplier", Double.toString(getThresholdConfig().getValue())); // params.put("trigger", Integer.toString(getThresholdConfig().getTrigger())); // params.put("rearm", Double.toString(getThresholdConfig().getRearm())); return createBasicEvent(uei, date, dsValue, resource, params); } public double getPreviousTriggeringSample() { return m_previousTriggeringSample; } public void setPreviousTriggeringSample(double previousTriggeringSample) { m_previousTriggeringSample = previousTriggeringSample; } public double getMultiplier() { return m_multiplier; } public void setMultiplier(double multiplier) { m_multiplier = multiplier; } @Override public ThresholdEvaluatorState getCleanClone() { return new ThresholdEvaluatorStateRelativeChange(m_thresholdConfig); } // FIXME This must be implemented correctly @Override public boolean isTriggered() { return false; } // FIXME This must be implemented correctly @Override public void clearState() { } } }
rfdrake/opennms
opennms-services/src/main/java/org/opennms/netmgt/threshd/ThresholdEvaluatorRelativeChange.java
Java
gpl-2.0
8,358
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.vm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class add_o32_rAX_Id extends Executable { final int immd; public add_o32_rAX_Id(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); immd = Modrm.Id(input); } public Branch execute(Processor cpu) { cpu.flagOp1 = cpu.r_eax.get32(); cpu.flagOp2 = immd; cpu.flagResult = (cpu.flagOp1 + cpu.flagOp2); cpu.r_eax.set32(cpu.flagResult); cpu.flagIns = UCodes.ADD32; cpu.flagStatus = OSZAPC; return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
ianopolous/JPC
src/org/jpc/emulator/execution/opcodes/vm/add_o32_rAX_Id.java
Java
gpl-2.0
1,923
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.vm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class fdiv_ST1_ST1 extends Executable { public fdiv_ST1_ST1(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); int modrm = input.readU8(); } public Branch execute(Processor cpu) { double freg0 = cpu.fpu.ST(1); double freg1 = cpu.fpu.ST(1); if (((freg0 == 0.0) && (freg1 == 0.0)) || (Double.isInfinite(freg0) && Double.isInfinite(freg1))) cpu.fpu.setInvalidOperation(); if ((freg0 == 0.0) && !Double.isNaN(freg1) && !Double.isInfinite(freg1)) cpu.fpu.setZeroDivide(); cpu.fpu.setST(1, freg0/freg1); return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
ysangkok/JPC
src/org/jpc/emulator/execution/opcodes/vm/fdiv_ST1_ST1.java
Java
gpl-2.0
2,046
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2011-2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 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 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 General Public License for more details. * * You should have received a copy of the GNU 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.netmgt.icmp; import java.net.InetAddress; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>SinglePingResponseCallback class.</p> * * @author <a href="mailto:ranger@opennms.org">Ben Reed</a> * @author <a href="mailto:brozow@opennms.org">Mathew Brozowski</a> */ public class SinglePingResponseCallback implements PingResponseCallback { private static final Logger LOG = LoggerFactory .getLogger(SinglePingResponseCallback.class); /** * Value of round-trip-time for the ping in microseconds. */ private Long m_responseTime = null; private InetAddress m_host; private Throwable m_error = null; private CountDownLatch m_latch = new CountDownLatch(1); /** * <p>Constructor for SinglePingResponseCallback.</p> * * @param host a {@link java.net.InetAddress} object. */ public SinglePingResponseCallback(InetAddress host) { m_host = host; } /** {@inheritDoc} */ @Override public void handleResponse(InetAddress address, EchoPacket response) { try { info("got response for address " + address + ", thread " + response.getIdentifier() + ", seq " + response.getSequenceNumber() + " with a responseTime "+response.elapsedTime(TimeUnit.MILLISECONDS)+"ms"); m_responseTime = (long)Math.round(response.elapsedTime(TimeUnit.MICROSECONDS)); } finally { m_latch.countDown(); } } /** {@inheritDoc} */ @Override public void handleTimeout(InetAddress address, EchoPacket request) { try { assert(request != null); info("timed out pinging address " + address + ", thread " + request.getIdentifier() + ", seq " + request.getSequenceNumber()); } finally { m_latch.countDown(); } } /** {@inheritDoc} */ @Override public void handleError(InetAddress address, EchoPacket request, Throwable t) { try { m_error = t; info("an error occurred pinging " + address, t); } finally { m_latch.countDown(); } } /** * <p>waitFor</p> * * @param timeout a long. * @throws java.lang.InterruptedException if any. */ public void waitFor(long timeout) throws InterruptedException { m_latch.await(timeout, TimeUnit.MILLISECONDS); } /** * <p>waitFor</p> * * @throws java.lang.InterruptedException if any. */ public void waitFor() throws InterruptedException { info("waiting for ping to "+m_host+" to finish"); m_latch.await(); info("finished waiting for ping to "+m_host+" to finish"); } public void rethrowError() throws Exception { if (m_error instanceof Error) { throw (Error)m_error; } else if (m_error instanceof Exception) { throw (Exception)m_error; } } /** * <p>Getter for the field <code>responseTime</code>.</p> * * @return a {@link java.lang.Long} object. */ public Long getResponseTime() { return m_responseTime; } public Throwable getError() { return m_error; } /** * <p>info</p> * * @param msg a {@link java.lang.String} object. */ public void info(String msg) { LOG.info(msg); } /** * <p>info</p> * * @param msg a {@link java.lang.String} object. * @param t a {@link java.lang.Throwable} object. */ public void info(String msg, Throwable t) { LOG.info(msg, t); } }
rfdrake/opennms
opennms-icmp/opennms-icmp-api/src/main/java/org/opennms/netmgt/icmp/SinglePingResponseCallback.java
Java
gpl-2.0
4,879
/* * Copyright (c) 2008, 2010, 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.codename1.ui; import com.codename1.ui.animations.CommonTransitions; import com.codename1.ui.animations.Transition; import com.codename1.ui.events.ActionEvent; import com.codename1.ui.events.ActionListener; import com.codename1.ui.geom.Rectangle; import com.codename1.impl.VirtualKeyboardInterface; import com.codename1.ui.layouts.BorderLayout; import com.codename1.ui.layouts.BoxLayout; import com.codename1.ui.plaf.Style; import com.codename1.ui.plaf.UIManager; import java.util.Enumeration; import java.util.Hashtable; import java.util.Vector; /** * This class represent the Codename One Light Weight Virtual Keyboard * * @author Chen Fishbein */ public class VirtualKeyboard extends Dialog implements VirtualKeyboardInterface{ private static final String MARKER_COMMIT_ON_DISPOSE = "$VKB_COM$"; private static final String MARKER_TINT_COLOR = "$VKB_TINT$"; private static final String MARKER_VKB = "$VKB$"; private static Transition transitionIn = CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, true, 500); private static Transition transitionOut = CommonTransitions.createSlide(CommonTransitions.SLIDE_VERTICAL, false, 500); private int inputType; /** * This keymap represents qwerty keyboard */ public static final String[][] DEFAULT_QWERTY = new String[][]{ {"q", "w", "e", "r", "t", "y", "u", "i", "o", "p"}, {"a", "s", "d", "f", "g", "h", "j", "k", "l"}, {"$Shift$", "z", "x", "c", "v", "b", "n", "m", "$Delete$"}, {"$Mode$", "$T9$", "$Space$", "$OK$"} }; /** * This keymap represents numbers keyboard */ public static final String[][] DEFAULT_NUMBERS = new String[][]{ {"1", "2", "3",}, {"4", "5", "6",}, {"7", "8", "9",}, {"*", "0", "#",}, {"$Mode$", "$Space$", "$Delete$", "$OK$"} }; /** * This keymap represents numbers and symbols keyboard */ public static final String[][] DEFAULT_NUMBERS_SYMBOLS = new String[][]{ {"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}, {"-", "/", ":", ";", "(", ")", "$", "&", "@"}, {".", ",", "?", "!", "'", "\"", "$Delete$"}, {"$Mode$", "$Space$", "$OK$"} }; /** * This keymap represents symbols keyboard */ public static final String[][] DEFAULT_SYMBOLS = new String[][]{ {"[", "]", "{", "}", "#", "%", "^", "*", "+", "="}, {"_", "\\", "|", "~", "<", ">", "\u00A3", "\u00A5"}, {":-0", ";-)", ":-)", ":-(", ":P", ":D", "$Delete$"}, {"$Mode$", "$Space$", "$OK$"} }; /** * The String that represent the qwerty mode. */ public static final String QWERTY_MODE = "ABC"; /** * The String that represent the numbers mode. */ public static final String NUMBERS_MODE = "123"; /** * The String that represent the numbers sybols mode. */ public static final String NUMBERS_SYMBOLS_MODE = ".,123"; /** * The String that represent the symbols mode. */ public static final String SYMBOLS_MODE = ".,?"; private static Hashtable modesMap = new Hashtable(); private static String[] defaultInputModeOrder = {QWERTY_MODE, NUMBERS_SYMBOLS_MODE, NUMBERS_MODE, SYMBOLS_MODE}; private String currentMode = defaultInputModeOrder[0]; private String[] inputModeOrder = defaultInputModeOrder; private TextField inputField; private Container buttons = new Container(new BoxLayout(BoxLayout.Y_AXIS)); private TextPainter txtPainter = new TextPainter(); private boolean upperCase = false; private Button currentButton; public static final int INSERT_CHAR = 1; public static final int DELETE_CHAR = 2; public static final int CHANGE_MODE = 3; public static final int SHIFT = 4; public static final int OK = 5; public static final int SPACE = 6; public static final int T9 = 7; private Hashtable specialButtons = new Hashtable(); private TextArea field; private boolean finishedT9Edit = true; private String originalText; private boolean useSoftKeys = false; private static boolean showTooltips = true; private boolean okPressed; private static Class vkbClass; private VirtualKeyboard vkb; public final static String NAME = "CodenameOne_VirtualKeyboard"; private boolean isShowing = false; private static Hashtable defaultInputModes = null; /** * Creates a new instance of VirtualKeyboard */ public VirtualKeyboard() { setLayout(new BorderLayout()); setDialogUIID("Container"); getContentPane().setUIID("VKB"); setAutoDispose(false); setDisposeWhenPointerOutOfBounds(true); setTransitionInAnimator(transitionIn); setTransitionOutAnimator(transitionOut); getTitleComponent().getParent().removeComponent(getTitleComponent()); if(showTooltips) { setGlassPane(txtPainter); } } public void setInputType(int inputType) { if((inputType & TextArea.NUMERIC) == TextArea.NUMERIC || (inputType & TextArea.PHONENUMBER) == TextArea.PHONENUMBER) { setInputModeOrder(new String []{NUMBERS_MODE}); return; } if((inputType & TextArea.DECIMAL) == TextArea.DECIMAL) { setInputModeOrder(new String []{NUMBERS_SYMBOLS_MODE}); return; } setInputModeOrder(defaultInputModeOrder); } static class InputField extends TextField { private TextArea field; InputField(TextArea field) { this.field = field; setInputMode(field.getInputMode()); setConstraint(field.getConstraint()); } public boolean hasFocus() { return true; } public String getUIID() { return "VKBTextInput"; } public void deleteChar() { super.deleteChar(); field.setText(getText()); if (field instanceof TextField) { ((TextField) field).setCursorPosition(getCursorPosition()); } } public void setCursorPosition(int i) { super.setCursorPosition(i); // this can happen since this method is invoked from a constructor of the base class... if(field != null && field.getText().length() > i && field instanceof TextField) { ((TextField) field).setCursorPosition(i); } } public void setText(String t) { super.setText(t); // this can happen since this method is invoked from a constructor of the base class... if(field != null) { // mirror events into the parent field.setText(t); } } public boolean validChar(String c) { if (field instanceof TextField) { return ((TextField) field).validChar(c); } return true; } } /** * Invoked internally by the implementation to indicate the text field that will be * edited by the virtual keyboard * * @param field the text field instance */ public void setTextField(final TextArea field) { this.field = field; removeAll(); okPressed = false; if(field instanceof TextField){ useSoftKeys = ((TextField)field).isUseSoftkeys(); ((TextField)field).setUseSoftkeys(false); } originalText = field.getText(); inputField = new InputField(field); inputField.setText(originalText); inputField.setCursorPosition(field.getCursorPosition()); inputField.setConstraint(field.getConstraint()); inputField.setInputModeOrder(new String[]{"ABC"}); inputField.setMaxSize(field.getMaxSize()); initModes(); setInputType(field.getConstraint()); initSpecialButtons(); addComponent(BorderLayout.NORTH, inputField); buttons.getStyle().setPadding(0, 0, 0, 0); addComponent(BorderLayout.CENTER, buttons); initInputButtons(upperCase); inputField.setUseSoftkeys(false); applyRTL(false); } /** * @inheritDoc */ public void show() { super.showPacked(BorderLayout.SOUTH, true); } /** * @inheritDoc */ protected void autoAdjust(int w, int h) { //if the t9 input is currently editing do not dispose dialog if (finishedT9Edit) { setTransitionOutAnimator(CommonTransitions.createEmpty()); dispose(); } } /** * init all virtual keyboard modes, such as QWERTY_MODE, NUMBERS_SYMBOLS_MODE... * to add an addtitional mode a developer needs to override this method and * add a mode by calling addInputMode method */ protected void initModes() { addInputMode(QWERTY_MODE, DEFAULT_QWERTY); addInputMode(NUMBERS_SYMBOLS_MODE, DEFAULT_NUMBERS_SYMBOLS); addInputMode(SYMBOLS_MODE, DEFAULT_SYMBOLS); addInputMode(NUMBERS_MODE, DEFAULT_NUMBERS); if(defaultInputModes != null) { Enumeration e = defaultInputModes.keys(); while(e.hasMoreElements()) { String key = (String)e.nextElement(); addInputMode(key, (String[][])defaultInputModes.get(key)); } } } /** * Sets the current virtual keyboard mode. * * @param mode the String that represents the mode(QWERTY_MODE, * SYMBOLS_MODE, ...) */ protected void setCurrentMode(String mode) { this.currentMode = mode; } /** * Gets the current mode. * * @return the String that represents the current mode(QWERTY_MODE, * SYMBOLS_MODE, ...) */ protected String getCurrentMode() { return currentMode; } private void initInputButtons(boolean upperCase) { buttons.removeAll(); int largestLine = 0; String[][] currentKeyboardChars = (String[][]) modesMap.get(currentMode); for (int i = 1; i < currentKeyboardChars.length; i++) { if (currentKeyboardChars[i].length > currentKeyboardChars[largestLine].length) { largestLine = i; } } int length = currentKeyboardChars[largestLine].length; if(length == 0) { return; } Button dummy = createButton(new Command("dummy"), 0); int buttonMargins = dummy.getUnselectedStyle().getMargin(dummy.isRTL(), LEFT) + dummy.getUnselectedStyle().getMargin(dummy.isRTL(), RIGHT); Container row = null; int rowW = (Display.getInstance().getDisplayWidth() - getDialogStyle().getPadding(false, LEFT) - getDialogStyle().getPadding(false, RIGHT) - getDialogStyle().getMargin(false, LEFT) - getDialogStyle().getMargin(false, RIGHT)); int availableSpace = rowW - length * buttonMargins; int buttonSpace = (availableSpace) / length; for (int i = 0; i < currentKeyboardChars.length; i++) { int rowWidth = rowW; row = new Container(new BoxLayout(BoxLayout.X_AXIS)); row.getUnselectedStyle().setMargin(0, 0, 0, 0); Vector specialsButtons = new Vector(); for (int j = 0; j < currentKeyboardChars[i].length; j++) { String txt = currentKeyboardChars[i][j]; Button b = null; if (txt.startsWith("$") && txt.endsWith("$") && txt.length() > 1) { //add a special button Button cmd = (Button) specialButtons.get(txt.substring(1, txt.length() - 1)); Command c = null; int prefW = 0; if(cmd != null){ c = cmd.getCommand(); int space = ((Integer) cmd.getClientProperty("space")).intValue(); if (space != -1) { prefW = availableSpace * space / 100; } } b = createButton(c, prefW, "VKBSpecialButton"); if (prefW != 0) { rowWidth -= (b.getPreferredW() + buttonMargins); } else { //if we can't determind the size at this stage, wait until //the loops ends and give the remains size to the special //button specialsButtons.addElement(b); } } else { if (upperCase) { txt = txt.toUpperCase(); } b = createInputButton(txt, buttonSpace); rowWidth -= (b.getPreferredW() + buttonMargins); } if (currentButton != null) { if (currentButton.getCommand() != null && b.getCommand() != null && currentButton.getCommand().getId() == b.getCommand().getId()) { currentButton = b; } if (currentButton.getText().equals(b.getText())) { currentButton = b; } } row.addComponent(b); } int emptySpace = Math.max(rowWidth, 0); //if we have special buttons on the keyboard give them the size or //else give the remain size to the row margins if (specialsButtons.size() > 0) { int prefW = emptySpace / specialsButtons.size(); for (int j = 0; j < specialsButtons.size(); j++) { Button special = (Button) specialsButtons.elementAt(j); special.setPreferredW(prefW); } } else { row.getUnselectedStyle().setPadding(Component.LEFT, 0); row.getUnselectedStyle().setPadding(Component.RIGHT, 0); row.getUnselectedStyle().setMarginUnit(new byte[]{Style.UNIT_TYPE_PIXELS, Style.UNIT_TYPE_PIXELS, Style.UNIT_TYPE_PIXELS, Style.UNIT_TYPE_PIXELS}); row.getUnselectedStyle().setMargin(Component.LEFT, emptySpace / 2); row.getUnselectedStyle().setMargin(Component.RIGHT, emptySpace / 2); } buttons.addComponent(row); } applyRTL(false); } private Button createInputButton(String text, int prefSize) { Button b = createButton(new Command(text, INSERT_CHAR), prefSize); b.putClientProperty("glasspane", "true"); return b; } private Button createButton(Command cmd, int prefSize) { return createButton(cmd, prefSize, "VKBButton"); } private Button createButton(Command cmd, int prefSize, String uiid) { Button btn; if(cmd != null){ btn = new Button(cmd); }else{ btn = new Button(); btn.setVisible(false); } final Button b = btn; b.setUIID(uiid); b.setEndsWith3Points(false); b.setAlignment(Component.CENTER); prefSize = Math.max(prefSize, b.getPreferredW()); b.setPreferredW(prefSize); b.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { currentButton = b; } }); return b; } /** * Add an input mode to the virtual keyboard * * @param mode a string that represents the identifier of the mode * @param inputChars 2 dimensional String array that contains buttons String * and special buttons (a special button is identified with $...$ marks * e.g: "$Space$") */ public static void addDefaultInputMode(String mode, String[][] inputChars) { if(defaultInputModes == null) { defaultInputModes = new Hashtable(); } defaultInputModes.put(mode, inputChars); } /** * Add an input mode to the virtual keyboard * * @param mode a string that represents the identifier of the mode * @param inputChars 2 dimentional String array that contains buttons String * and special buttons (a special button is identified with $...$ marks * e.g: "$Space$") */ public void addInputMode(String mode, String[][] inputChars) { modesMap.put(mode, inputChars); } /** * This method adds a special button to the virtual keyboard * * @param key the string identifier from within the relevant input mode * @param cmd the Command to invoke when this button is invoked. */ public void addSpecialButton(String key, Command cmd) { addSpecialButton(key, cmd, -1); } /** * This method adds a special button to the virtual keyboard * * @param key the string identifier from within the relevant input mode * @param cmd the Command to invoke when this button is invoked. * @param space how much space in percentage from the overall row * the special button should occupy */ public void addSpecialButton(String key, Command cmd, int space) { Button b = new Button(cmd); b.putClientProperty("space", new Integer(space)); specialButtons.put(key, b); } private String getNextMode(String current) { for (int i = 0; i < inputModeOrder.length - 1; i++) { String mode = inputModeOrder[i]; if(mode.equals(current)){ return inputModeOrder[i + 1]; } } return inputModeOrder[0]; } /** * @inheritDoc */ public void pointerPressed(int x, int y) { super.pointerPressed(x, y); Component cmp = getComponentAt(x, y); if (showTooltips && cmp != null && cmp instanceof Button && cmp.getClientProperty("glasspane") != null) { txtPainter.showButtonOnGlasspane((Button) cmp); } } /** * @inheritDoc */ public void pointerDragged(int x, int y) { super.pointerDragged(x, y); Component cmp = getComponentAt(x, y); if (showTooltips && cmp != null && cmp instanceof Button && cmp.getClientProperty("glasspane") != null) { txtPainter.showButtonOnGlasspane((Button) cmp); } } /** * @inheritDoc */ public void pointerReleased(int x, int y) { if(showTooltips) { txtPainter.clear(); } super.pointerReleased(x, y); } /** * This method initialize all the virtual keyboard special buttons. */ protected void initSpecialButtons() { //specialButtons.clear(); addSpecialButton("Shift", new Command("SH", SHIFT), 15); addSpecialButton("Delete", new Command("Del", DELETE_CHAR), 15); addSpecialButton("T9", new Command("T9", T9), 15); addSpecialButton("Mode", new Command(getNextMode(currentMode), CHANGE_MODE)); addSpecialButton("Space", new Command("Space", SPACE), 50); addSpecialButton("OK", new Command("Ok", OK)); } /** * Returns the order in which input modes are toggled * * @return the order of the input modes */ public String[] getInputModeOrder() { return inputModeOrder; } /** * Sets the order in which input modes are toggled and allows disabling/hiding * an input mode * * @param order the order for the input modes in this field */ public void setInputModeOrder(String[] order) { inputModeOrder = order; setCurrentMode(order[0]); } /** * Returns the order in which input modes are toggled by default * * @return the default order of the input mode */ public static String[] getDefaultInputModeOrder() { return defaultInputModeOrder; } /** * Sets the order in which input modes are toggled by default and allows * disabling/hiding an input mode * * @param order the order for the input modes in all future created fields */ public static void setDefaultInputModeOrder(String[] order) { defaultInputModeOrder = order; } class TextPainter implements Painter { private Label label = new Label(); private boolean paint = true; public TextPainter() { label = new Label(); label.setUIID("VKBtooltip"); } public void showButtonOnGlasspane(Button button) { if(label.getText().equals(button.getText())){ return; } paint = true; repaint(label.getAbsoluteX()-2, label.getAbsoluteY()-2, label.getWidth()+4, label.getHeight()+4); label.setText(button.getText()); label.setSize(label.getPreferredSize()); label.setX(button.getAbsoluteX() + (button.getWidth() - label.getWidth()) / 2); label.setY(button.getAbsoluteY() - label.getPreferredH() * 4 / 3); repaint(label.getAbsoluteX()-2, label.getAbsoluteY()-2, label.getPreferredW()+4, label.getPreferredH()+4); } public void paint(Graphics g, Rectangle rect) { if (paint) { label.paintComponent(g); } } private void clear() { paint = false; repaint(); } } private void updateText(String txt) { field.setText(txt); if(field instanceof TextField){ ((TextField)field).setCursorPosition(txt.length()); } if(okPressed){ field.fireActionEvent(); if(field instanceof TextField){ ((TextField)field).fireDoneEvent(); } } } /** * @inheritDoc */ protected void actionCommand(Command cmd) { super.actionCommand(cmd); switch (cmd.getId()) { case OK: okPressed = true; updateText(inputField.getText()); dispose(); break; case INSERT_CHAR: Button btn = currentButton; String text = btn.getText(); if (inputField.getText().length() == 0) { inputField.setText(text); inputField.setCursorPosition(text.length()); } else { inputField.insertChars(text); } break; case SPACE: if (inputField.getText().length() == 0) { inputField.setText(" "); } else { inputField.insertChars(" "); } break; case DELETE_CHAR: inputField.deleteChar(); break; case CHANGE_MODE: currentMode = getNextMode(currentMode); Display.getInstance().callSerially(new Runnable() { public void run() { initInputButtons(upperCase); String next = getNextMode(currentMode); currentButton.setText(next); currentButton.getCommand().setCommandName(next); setTransitionOutAnimator(CommonTransitions.createEmpty()); setTransitionInAnimator(CommonTransitions.createEmpty()); revalidate(); show(); } }); return; case SHIFT: if (currentMode.equals(QWERTY_MODE)) { upperCase = !upperCase; Display.getInstance().callSerially(new Runnable() { public void run() { initInputButtons(upperCase); revalidate(); } }); } return; case T9: finishedT9Edit = false; if(field != null){ Display.getInstance().editString(field, field.getMaxSize(), field.getConstraint(), field.getText()); }else{ Display.getInstance().editString(inputField, inputField.getMaxSize(), inputField.getConstraint(), inputField.getText()); } dispose(); finishedT9Edit = true; } } /** * @inheritDoc */ public void dispose() { if (field != null) { if (!okPressed && !isCommitOnDispose(field) && finishedT9Edit) { field.setText(originalText); } if(field instanceof TextField){ ((TextField)field).setUseSoftkeys(useSoftKeys); } setTransitionInAnimator(transitionIn); field = null; } currentMode = inputModeOrder[0]; super.dispose(); } /** * @inheritDoc */ protected void onShow() { super.onShow(); setTransitionOutAnimator(transitionOut); } /** * This method returns the Virtual Keyboard TextField. * * @return the the Virtual Keyboard TextField. */ protected TextField getInputField() { return inputField; } /** * Indicates whether the VKB should commit changes to the text field when the VKB * is closed not via the OK button. This might be useful for some situations such * as searches * * @param tf the text field to mark as commit on dispose * @param b the value of commit on dispose, true to always commit changes */ public static void setCommitOnDispose(TextField tf, boolean b) { tf.putClientProperty(MARKER_COMMIT_ON_DISPOSE, new Boolean(b)); } /** * This method is used to bind a specific instance of a virtual keyboard to a specific TextField. * For example if a specific TextField requires only numeric input consider using this method as follows: * * TextField tf = new TextField(); * tf.setConstraint(TextField.NUMERIC); * tf.setInputModeOrder(new String[]{"123"}); * VirtualKeyboard vkb = new VirtualKeyboard(); * vkb.setInputModeOrder(new String[]{VirtualKeyboard.NUMBERS_MODE}); * VirtualKeyboard.bindVirtualKeyboard(tf, vkb); * * @param t the TextField to bind a VirualKeyboard to. * @param vkb the binded VirualKeyboard. */ public static void bindVirtualKeyboard(TextArea t, VirtualKeyboard vkb) { t.putClientProperty(MARKER_VKB, vkb); } /** * This method returns the Textfield associated VirtualKeyboard, * see bindVirtualKeyboard(TextField tf, VirtualKeyboard vkb) method. * * @param t a TextField.that might have an associated VirtualKeyboard instance * @return a VirtualKeyboard instance or null if not exists. */ public static VirtualKeyboard getVirtualKeyboard(TextArea t) { return (VirtualKeyboard) t.getClientProperty(MARKER_VKB); } /** * Indicates whether the given text field should commit on dispose * * @param tf the text field * @return true if the text field should save the data despite the fact that it * was disposed in an irregular way */ public static boolean isCommitOnDispose(TextArea tf) { Boolean b = (Boolean)tf.getClientProperty(MARKER_COMMIT_ON_DISPOSE); return (b != null) && b.booleanValue(); } /** * Sets the tint color for the virtual keyboard when shown on top of this text field * see the form tint methods for more information * * @param tf the relevant text field * @param tint the tint color with an alpha channel */ public static void setVKBTint(TextField tf, int tint) { tf.putClientProperty(MARKER_TINT_COLOR, new Integer(tint)); } /** * The tint color for the virtual keyboard when shown on top of this text field * see the form tint methods for more information * * @param tf the relevant text field * @return the tint color with an alpha channel */ public static int getVKBTint(TextArea tf) { Integer v = (Integer)tf.getClientProperty(MARKER_TINT_COLOR); if(v != null) { return v.intValue(); } Form current = Display.getInstance().getCurrent(); return current.getUIManager().getLookAndFeel().getDefaultFormTintColor(); } /** * Indicates whether tooltips should be shown when the keys in the VKB are pressed * * @return the showTooltips */ public static boolean isShowTooltips() { return showTooltips; } /** * Indicates whether tooltips should be shown when the keys in the VKB are pressed * * @param aShowTooltips true to show tooltips */ public static void setShowTooltips(boolean aShowTooltips) { showTooltips = aShowTooltips; } /** * The transition in for the VKB * * @return the transitionIn */ public static Transition getTransitionIn() { return transitionIn; } /** * The transition in for the VKB * * @param aTransitionIn the transitionIn to set */ public static void setTransitionIn(Transition aTransitionIn) { transitionIn = aTransitionIn; } /** * The transition out for the VKB * * @return the transitionOut */ public static Transition getTransitionOut() { return transitionOut; } /** * The transition out for the VKB * * @param aTransitionOut the transitionOut to set */ public static void setTransitionOut(Transition aTransitionOut) { transitionOut = aTransitionOut; } /** * Shows the virtual keyboard that is assoiciated with the displayed TextField * or displays the default virtual keyboard. * * @param show it show is true open the relevant keyboard, if close dispose * the displayed keyboard */ public void showKeyboard(boolean show) { isShowing = show; Form current = Display.getInstance().getCurrent(); if (show) { Component foc = current.getFocused(); if(foc instanceof Container) { foc = ((Container)foc).getLeadComponent(); } TextArea txtCmp = (TextArea) foc; if (txtCmp != null) { if(vkb != null && vkb.contains(txtCmp)){ return; } vkb = VirtualKeyboard.getVirtualKeyboard(txtCmp); if(vkb == null){ vkb = createVirtualKeyboard(); } vkb.setTextField(txtCmp); int oldTint = current.getTintColor(); current.setTintColor(VirtualKeyboard.getVKBTint(txtCmp)); boolean third = com.codename1.ui.Display.getInstance().isThirdSoftButton(); com.codename1.ui.Display.getInstance().setThirdSoftButton(false); boolean qwerty = txtCmp.isQwertyInput(); if(txtCmp instanceof TextField){ ((TextField) txtCmp).setQwertyInput(true); } vkb.showDialog(); if (txtCmp instanceof TextField) { ((TextField) txtCmp).setQwertyInput(qwerty); } com.codename1.ui.Display.getInstance().setThirdSoftButton(third); current.setTintColor(oldTint); } } } /** * Sets the default virtual keyboard class for the com.codename1.ui.VirtualKeyboard * type * This class is used as the default virtual keyboard class if the current * platform VirtualKeyboard is com.codename1.ui.VirtualKeyboard. * Platform VirtualKeyboard is defined here: * Display.getIntance().setDefaultVirtualKeyboard(VirtualKeyboardInterface vkb) * * @param vkbClazz this class must extend VirtualKeyboard. */ public static void setDefaultVirtualKeyboardClass(Class vkbClazz){ vkbClass = vkbClazz; } private VirtualKeyboard createVirtualKeyboard() { try { if(vkbClass != null){ return (VirtualKeyboard) vkbClass.newInstance(); }else{ return new VirtualKeyboard(); } } catch (Exception ex) { ex.printStackTrace(); return new VirtualKeyboard(); } } /** * @see VirtualKeyboardInterface */ public String getVirtualKeyboardName() { return NAME; } /** * @see VirtualKeyboardInterface */ public boolean isVirtualKeyboardShowing() { return isShowing; } }
skyHALud/codenameone
CodenameOne/src/com/codename1/ui/VirtualKeyboard.java
Java
gpl-2.0
34,489
/* * Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package org.graalvm.compiler.lir.asm; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import org.graalvm.compiler.core.common.type.DataPointerConstant; /** * Class for chunks of data that go into the data section. */ public class ArrayDataPointerConstant extends DataPointerConstant { private final byte[] data; public ArrayDataPointerConstant(byte[] array, int alignment) { super(alignment); data = array.clone(); } public ArrayDataPointerConstant(short[] array, int alignment) { super(alignment); ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 2); byteBuffer.order(ByteOrder.nativeOrder()); byteBuffer.asShortBuffer().put(array); data = byteBuffer.array(); } public ArrayDataPointerConstant(int[] array, int alignment) { super(alignment); ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 4); byteBuffer.order(ByteOrder.nativeOrder()); byteBuffer.asIntBuffer().put(array); data = byteBuffer.array(); } public ArrayDataPointerConstant(float[] array, int alignment) { super(alignment); ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 4); byteBuffer.order(ByteOrder.nativeOrder()); byteBuffer.asFloatBuffer().put(array); data = byteBuffer.array(); } public ArrayDataPointerConstant(double[] array, int alignment) { super(alignment); ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 8); byteBuffer.order(ByteOrder.nativeOrder()); byteBuffer.asDoubleBuffer().put(array); data = byteBuffer.array(); } public ArrayDataPointerConstant(long[] array, int alignment) { super(alignment); ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 8); byteBuffer.order(ByteOrder.nativeOrder()); byteBuffer.asLongBuffer().put(array); data = byteBuffer.array(); } @Override public boolean isDefaultForKind() { return false; } @Override public void serialize(ByteBuffer buffer) { buffer.put(data); } @Override public int getSerializedSize() { return data.length; } @Override public String toValueString() { return "ArrayDataPointerConstant" + Arrays.toString(data); } }
md-5/jdk10
src/jdk.internal.vm.compiler/share/classes/org.graalvm.compiler.lir/src/org/graalvm/compiler/lir/asm/ArrayDataPointerConstant.java
Java
gpl-2.0
3,453
/* JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine Copyright (C) 2012-2013 Ian Preston This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. 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. Details (including contact information) can be found at: jpc.sourceforge.net or the developer website sourceforge.net/projects/jpc/ End of licence header */ package org.jpc.emulator.execution.opcodes.rm; import org.jpc.emulator.execution.*; import org.jpc.emulator.execution.decoder.*; import org.jpc.emulator.processor.*; import org.jpc.emulator.processor.fpu64.*; import static org.jpc.emulator.processor.Processor.*; public class rep_movsb_a32 extends Executable { final int segIndex; public rep_movsb_a32(int blockStart, int eip, int prefices, PeekableInputStream input) { super(blockStart, eip); segIndex = Prefices.getSegment(prefices, Processor.DS_INDEX); } public Branch execute(Processor cpu) { Segment seg = cpu.segs[segIndex]; StaticOpcodes.rep_movsb_a32(cpu, seg); return Branch.None; } public boolean isBranch() { return false; } public String toString() { return this.getClass().getName(); } }
ysangkok/JPC
src/org/jpc/emulator/execution/opcodes/rm/rep_movsb_a32.java
Java
gpl-2.0
1,819
/** * This file is part of Aion-Lightning <aion-lightning.org>. * * Aion-Lightning 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. * * Aion-Lightning 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 Aion-Lightning. * If not, see <http://www.gnu.org/licenses/>. * * * Credits goes to all Open Source Core Developer Groups listed below * Please do not change here something, ragarding the developer credits, except the "developed by XXXX". * Even if you edit a lot of files in this source, you still have no rights to call it as "your Core". * Everybody knows that this Emulator Core was developed by Aion Lightning * @-Aion-Unique- * @-Aion-Lightning * @Aion-Engine * @Aion-Extreme * @Aion-NextGen * @Aion-Core Dev. */ package quest.beluslan; import com.aionemu.gameserver.model.gameobjects.Item; import com.aionemu.gameserver.model.gameobjects.Npc; import com.aionemu.gameserver.model.gameobjects.player.Player; import com.aionemu.gameserver.questEngine.handlers.HandlerResult; import com.aionemu.gameserver.questEngine.handlers.QuestHandler; import com.aionemu.gameserver.model.DialogAction; import com.aionemu.gameserver.questEngine.model.QuestEnv; import com.aionemu.gameserver.questEngine.model.QuestState; import com.aionemu.gameserver.questEngine.model.QuestStatus; import com.aionemu.gameserver.services.QuestService; import com.aionemu.gameserver.world.zone.ZoneName; /** * @author Ritsu * */ public class _2533BeritrasCurse extends QuestHandler { private final static int questId = 2533; public _2533BeritrasCurse() { super(questId); } @Override public void register() { qe.registerQuestNpc(204801).addOnQuestStart(questId); //Gigrite qe.registerQuestNpc(204801).addOnTalkEvent(questId); qe.registerQuestItem(182204425, questId);//Empty Durable Potion Bottle qe.registerOnQuestTimerEnd(questId); } @Override public HandlerResult onItemUseEvent(final QuestEnv env, Item item) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs != null && qs.getStatus() == QuestStatus.START) { if (player.isInsideZone(ZoneName.get("BERITRAS_WEAPON_220040000"))) { QuestService.questTimerStart(env, 300); return HandlerResult.fromBoolean(useQuestItem(env, item, 0, 1, false, 182204426, 1, 0)); } } return HandlerResult.SUCCESS; // ?? } @Override public boolean onDialogEvent(QuestEnv env) { final Player player = env.getPlayer(); int targetId = 0; if (env.getVisibleObject() instanceof Npc) { targetId = ((Npc) env.getVisibleObject()).getNpcId(); } final QuestState qs = player.getQuestStateList().getQuestState(questId); DialogAction dialog = env.getDialog(); if (qs == null || qs.getStatus() == QuestStatus.NONE) { if (targetId == 204801) { if (dialog == DialogAction.QUEST_SELECT) { return sendQuestDialog(env, 4762); } else if (dialog == DialogAction.QUEST_ACCEPT_1) { if (!giveQuestItem(env, 182204425, 1)) { return true; } return sendQuestStartDialog(env); } else { return sendQuestStartDialog(env); } } } else if (qs.getStatus() == QuestStatus.START) { int var = qs.getQuestVarById(0); if (targetId == 204801) { switch (dialog) { case QUEST_SELECT: if (var == 1) { qs.setStatus(QuestStatus.REWARD); updateQuestStatus(env); return sendQuestDialog(env, 1352); } case SELECT_QUEST_REWARD: { QuestService.questTimerEnd(env); return sendQuestDialog(env, 5); } } } } else if (qs.getStatus() == QuestStatus.REWARD) { if (targetId == 204801) { return sendQuestEndDialog(env); } } return false; } @Override public boolean onQuestTimerEndEvent(QuestEnv env) { Player player = env.getPlayer(); QuestState qs = player.getQuestStateList().getQuestState(questId); if (qs != null && qs.getStatus() == QuestStatus.START) { removeQuestItem(env, 182204426, 1); QuestService.abandonQuest(player, questId); player.getController().updateNearbyQuests(); return true; } return false; } }
GiGatR00n/Aion-Core-v4.7.5
AC-Game/data/scripts/system/handlers/quest/beluslan/_2533BeritrasCurse.java
Java
gpl-2.0
5,403
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 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 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 General Public License for more details. * * You should have received a copy of the GNU 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.netmgt.dao.api; import org.opennms.netmgt.model.OnmsMemo; /** * @author <a href="mailto:Markus@OpenNMS.com">Markus Neumann</a> */ public interface MemoDao extends OnmsDao<OnmsMemo, Integer> { }
rfdrake/opennms
opennms-dao-api/src/main/java/org/opennms/netmgt/dao/api/MemoDao.java
Java
gpl-2.0
1,404
package lejos.robotics.mapping; import java.io.*; import java.util.ArrayList; import lejos.geom.Line; import lejos.geom.Rectangle; /* * WARNING: THIS CLASS IS SHARED BETWEEN THE classes AND pccomms PROJECTS. * DO NOT EDIT THE VERSION IN pccomms AS IT WILL BE OVERWRITTEN WHEN THE PROJECT IS BUILT. */ /** * <p>This class loads map data from a Shapefile and produces a LineMap object, which can * be used by the leJOS navigation package.</p> * * <p>There are many map editors which can use the Shapefile format (OpenEV, Global Mapper). Once you * have created a map, export it as Shapefile. This will produce three files ending in .shp .shx and * .dbf. The only file used by this class is .shp.</p> * * <p>NOTE: Shapefiles can only contain one type of shape data (polygon or polyline, not both). A single file can't * mix polylines with polygons.</p> * * <p>This class' code can parse points and multipoints. However, a LineMap object can't deal with * points (only lines) so points and multipoints are discarded.</p> * * @author BB * */ public class ShapefileLoader { /* OTHER POTENTIAL MAP FILE FORMATS TO ADD: * (none have really been researched yet for viability) * KML * GML * WMS? (more of a service than a file) * MIF/MID (MapInfo) * SVG (Scalable Vector Graphics) * EPS (Encapsulated Post Script) * DXF (Autodesk) * AI (Adobe Illustrator) * */ // 2D shape types types: private static final byte NULL_SHAPE = 0; private static final byte POINT = 1; private static final byte POLYLINE = 3; private static final byte POLYGON = 5; private static final byte MULTIPOINT = 8; private final int SHAPEFILE_ID = 0x0000270a; DataInputStream data_is = null; /** * Creates a ShapefileLoader object using an input stream. Likely you will use a FileInputStream * which points to the *.shp file containing the map data. * @param in */ public ShapefileLoader(InputStream in) { this.data_is = new DataInputStream(in); } /** * Retrieves a LineMap object from the Shapefile input stream. * @return the line map * @throws IOException */ public LineMap readLineMap() throws IOException { ArrayList <Line> lines = new ArrayList <Line> (); int fileCode = data_is.readInt(); // Big Endian if(fileCode != SHAPEFILE_ID) throw new IOException("File is not a Shapefile"); data_is.skipBytes(20); // Five int32 unused by Shapefile /*int fileLength =*/ data_is.readInt(); //System.out.println("Length: " + fileLength); // TODO: Docs say length is in 16-bit words. Unsure if this is strictly correct. Seems higher than what hex editor shows. /*int version =*/ readLEInt(); //System.out.println("Version: " + version); /*int shapeType =*/ readLEInt(); //System.out.println("Shape type: " + shapeType); // These x and y min/max values define bounding rectangle: double xMin = readLEDouble(); double yMin = readLEDouble(); double xMax = readLEDouble(); double yMax = readLEDouble(); // Create bounding rectangle: Rectangle rect = new Rectangle((float)xMin, (float)yMin, (float)(xMax - xMin), (float)(yMax - yMin)); /*double zMin =*/ readLEDouble(); /*double zMax =*/ readLEDouble(); /*double mMin =*/ readLEDouble(); /*double mMax =*/ readLEDouble(); // TODO These values seem to be rounded down to nearest 0.5. Must round them up? //System.out.println("Xmin " + xMin + " Ymin " + yMin); //System.out.println("Xmax " + xMax + " Ymax " + yMax); try { // TODO: This is a cheesy way to detect EOF condition. Not very good coding. while(2 > 1) { // TODO: Temp code to keep it looping. Should really detect EOF condition. // NOW ONTO READING INDIVIDUAL SHAPES: // Record Header (2 values): /*int recordNum =*/ data_is.readInt(); int recordLen = data_is.readInt(); // TODO: in 16-bit words. Might cause bug if number of shapes gets bigger than 16-bit short? // Record (variable length depending on shape type): int recShapeType = readLEInt(); // Now to read the actual shape data switch (recShapeType) { case NULL_SHAPE: break; case POINT: // DO WE REALLY NEED TO DEAL WITH POINT? Feature might use them possibly. /*double pointX =*/ readLEDouble(); // TODO: skip bytes instead /*double pointY =*/ readLEDouble(); break; case POLYLINE: // NOTE: Data structure for polygon/polyline is identical. Code should work for both. case POLYGON: // Polygons can contain multiple polygons, such as a donut with outer ring and inner ring for hole. // Max bounding rect: 4 doubles in a row. TODO: Discard bounding rect. values and skip instead. /*double polyxMin =*/ readLEDouble(); /*double polyyMin =*/ readLEDouble(); /*double polyxMax =*/ readLEDouble(); /*double polyyMax =*/ readLEDouble(); int numParts = readLEInt(); int numPoints = readLEInt(); // Retrieve array of indexes for each part in the polygon int [] partIndex = new int[numParts]; for(int i=0;i<numParts;i++) { partIndex[i] = readLEInt(); } // Now go through numParts times pulling out points double firstX=0; double firstY=0; for(int i=0;i<numPoints-1;i++) { // Could check here if onto new polygon (i = next index). If so, do something with line formation. for(int j=0;j<numParts;j++) { if(i == partIndex[j]) { firstX = readLEDouble(); firstY = readLEDouble(); continue; } } double secondX = readLEDouble(); double secondY = readLEDouble(); Line myLine = new Line((float)firstX, (float)firstY, (float)secondX, (float)secondY); lines.add(myLine); firstX = secondX; firstY = secondY; } break; case MULTIPOINT: // TODO: DO WE REALLY NEED TO DEAL WITH MULTIPOINT? Comment out and skip bytes? /*double multixMin = */readLEDouble(); /*double multiyMin = */readLEDouble(); /*double multixMax = */readLEDouble(); /*double multiyMax = */readLEDouble(); int multiPoints = readLEInt(); double [] xVals = new double[multiPoints]; double [] yVals = new double[multiPoints]; for(int i=0;i<multiPoints;i++) { xVals[i] = readLEDouble(); yVals[i] = readLEDouble(); } break; default: // IGNORE REST OF SHAPE TYPES and skip over data using recordLen value //System.out.println("Some other unknown shape"); data_is.skipBytes(recordLen); // TODO: Check if this works on polyline or point } } // END OF WHILE } catch(EOFException e) { // End of File, just needs to continue } Line [] arrList = new Line [lines.size()]; return new LineMap(lines.toArray(arrList), rect); } /** * Translates a little endian int into a big endian int * * @return int A big endian int */ private int readLEInt() throws IOException { int byte1, byte2, byte3, byte4; synchronized (this) { byte1 = data_is.read(); byte2 = data_is.read(); byte3 = data_is.read(); byte4 = data_is.read(); } if (byte4 == -1) { throw new EOFException(); } return (byte4 << 24) + (byte3 << 16) + (byte2 << 8) + byte1; } /** * Reads a little endian double into a big endian double * * @return double A big endian double */ private final double readLEDouble() throws IOException { return Double.longBitsToDouble(this.readLELong()); } /** * Translates a little endian long into a big endian long * * @return long A big endian long */ private long readLELong() throws IOException { long byte1 = data_is.read(); long byte2 = data_is.read(); long byte3 = data_is.read(); long byte4 = data_is.read(); long byte5 = data_is.read(); long byte6 = data_is.read(); long byte7 = data_is.read(); long byte8 = data_is.read(); if (byte8 == -1) { throw new EOFException(); } return (byte8 << 56) + (byte7 << 48) + (byte6 << 40) + (byte5 << 32) + (byte4 << 24) + (byte3 << 16) + (byte2 << 8) + byte1; } }
atsoc0ocsav/IEEE-Firefighter
ieeefirefighter-beta/pc/pccomm-src/lejos/robotics/mapping/ShapefileLoader.java
Java
gpl-2.0
9,323
/* * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ module test { // jdk.test.resources.classes.MyResourcesProvider is in named.bundles. requires named.bundles; uses jdk.test.resources.classes.MyResourcesProvider; uses jdk.test.resources.props.MyResourcesProvider; }
FauxFaux/jdk9-jdk
test/java/util/ResourceBundle/modules/visibility/src/test/module-info.java
Java
gpl-2.0
1,283
/* Copyright 2005,2006 Sven Reimers, Florian Vogler * * This file is part of the Software Quality Environment Project. * * The Software Quality Environment Project is free software: * you can redistribute it and/or modify it under the terms of the * GNU General Public License as published by the Free Software Foundation, * either version 2 of the License, or (at your option) any later version. * * The Software Quality Environment Project 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 Foobar. If not, see <http://www.gnu.org/licenses/>. */ package org.nbheaven.sqe.codedefects.history.action; import java.awt.EventQueue; import java.awt.event.ActionEvent; import java.util.Collection; import javax.swing.AbstractAction; import javax.swing.Action; import org.nbheaven.sqe.codedefects.core.util.SQECodedefectSupport; import org.nbheaven.sqe.codedefects.history.util.CodeDefectHistoryPersistence; import org.netbeans.api.project.Project; import org.openide.util.ContextAwareAction; import org.openide.util.ImageUtilities; import org.openide.util.Lookup; import org.openide.util.LookupEvent; import org.openide.util.LookupListener; import org.openide.util.NbBundle; import org.openide.util.Utilities; /** * * @author Sven Reimers */ public class SnapshotAction extends AbstractAction implements LookupListener, ContextAwareAction { private Lookup context; private Lookup.Result<Project> lkpInfo; public SnapshotAction() { this(Utilities.actionsGlobalContext()); } public SnapshotAction(Lookup context) { putValue("noIconInMenu", Boolean.TRUE); // NOI18N putValue(Action.SHORT_DESCRIPTION, NbBundle.getMessage(SnapshotAction.class, "HINT_Action")); putValue(SMALL_ICON, ImageUtilities.image2Icon(ImageUtilities.loadImage("org/nbheaven/sqe/codedefects/history/resources/camera.png"))); this.context = context; //The thing we want to listen for the presence or absence of //on the global selection Lookup.Template<Project> tpl = new Lookup.Template<Project>(Project.class); lkpInfo = context.lookup(tpl); lkpInfo.addLookupListener(this); resultChanged(null); } @Override public Action createContextAwareInstance(Lookup context) { return new SnapshotAction(context); } @Override public void resultChanged(LookupEvent ev) { updateEnableState(); } public String getName() { return NbBundle.getMessage(SnapshotAction.class, "LBL_Action"); } @Override public void actionPerformed(ActionEvent actionEvent) { if (null != getActiveProject()) { Project project = getActiveProject(); CodeDefectHistoryPersistence.addSnapshot(project); } } private void updateEnableState() { if (!EventQueue.isDispatchThread()) { EventQueue.invokeLater(() -> updateEnableState()); return; } setEnabled(SQECodedefectSupport.isQualityAwareProject(getActiveProject())); } private Project getActiveProject() { Collection<? extends Project> projects = lkpInfo.allInstances(); if (projects.size() == 1) { Project project = projects.iterator().next(); return project; } return null; } }
sqe-team/sqe
codedefects.history/src/org/nbheaven/sqe/codedefects/history/action/SnapshotAction.java
Java
gpl-2.0
3,600
/*- * #%L * Fiji distribution of ImageJ for the life sciences. * %% * Copyright (C) 2007 - 2017 Fiji developers. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ package spim.fiji.plugin; import ij.gui.GenericDialog; import ij.plugin.PlugIn; import java.io.File; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Random; import mpicbg.spim.data.sequence.Channel; import mpicbg.spim.data.sequence.ViewDescription; import mpicbg.spim.data.sequence.ViewId; import mpicbg.spim.data.sequence.VoxelDimensions; import mpicbg.spim.io.IOFunctions; import net.imglib2.KDTree; import net.imglib2.RealPoint; import net.imglib2.neighborsearch.KNearestNeighborSearchOnKDTree; import spim.fiji.plugin.queryXML.LoadParseQueryXML; import spim.fiji.plugin.thinout.ChannelProcessThinOut; import spim.fiji.plugin.thinout.Histogram; import spim.fiji.spimdata.SpimData2; import spim.fiji.spimdata.interestpoints.InterestPoint; import spim.fiji.spimdata.interestpoints.InterestPointList; import spim.fiji.spimdata.interestpoints.ViewInterestPointLists; import spim.fiji.spimdata.interestpoints.ViewInterestPoints; public class ThinOut_Detections implements PlugIn { public static boolean[] defaultShowHistogram; public static int[] defaultSubSampling; public static String[] defaultNewLabels; public static int[] defaultRemoveKeep; public static double[] defaultCutoffThresholdMin, defaultCutoffThresholdMax; public static String[] removeKeepChoice = new String[]{ "Remove Range", "Keep Range" }; public static double defaultThresholdMinValue = 0; public static double defaultThresholdMaxValue = 5; public static int defaultSubSamplingValue = 1; public static String defaultNewLabelText = "thinned-out"; public static int defaultRemoveKeepValue = 0; // 0 == remove, 1 == keep @Override public void run( final String arg ) { final LoadParseQueryXML xml = new LoadParseQueryXML(); if ( !xml.queryXML( "", true, false, true, true ) ) return; final SpimData2 data = xml.getData(); final List< ViewId > viewIds = SpimData2.getAllViewIdsSorted( data, xml.getViewSetupsToProcess(), xml.getTimePointsToProcess() ); // ask which channels have the objects we are searching for final List< ChannelProcessThinOut > channels = getChannelsAndLabels( data, viewIds ); if ( channels == null ) return; // get the actual min/max thresholds for cutting out if ( !getThinOutThresholds( data, viewIds, channels ) ) return; // thin out detections and save the new interestpoint files if ( !thinOut( data, viewIds, channels, true ) ) return; // write new xml SpimData2.saveXML( data, xml.getXMLFileName(), xml.getClusterExtension() ); } public static boolean thinOut( final SpimData2 spimData, final List< ViewId > viewIds, final List< ChannelProcessThinOut > channels, final boolean save ) { final ViewInterestPoints vip = spimData.getViewInterestPoints(); for ( final ChannelProcessThinOut channel : channels ) { final double minDistance = channel.getMin(); final double maxDistance = channel.getMax(); final boolean keepRange = channel.keepRange(); for ( final ViewId viewId : viewIds ) { final ViewDescription vd = spimData.getSequenceDescription().getViewDescription( viewId ); if ( !vd.isPresent() || vd.getViewSetup().getChannel().getId() != channel.getChannel().getId() ) continue; final ViewInterestPointLists vipl = vip.getViewInterestPointLists( viewId ); final InterestPointList oldIpl = vipl.getInterestPointList( channel.getLabel() ); if ( oldIpl.getInterestPoints() == null ) oldIpl.loadInterestPoints(); final VoxelDimensions voxelSize = vd.getViewSetup().getVoxelSize(); // assemble the list of points (we need two lists as the KDTree sorts the list) // we assume that the order of list2 and points is preserved! final List< RealPoint > list1 = new ArrayList< RealPoint >(); final List< RealPoint > list2 = new ArrayList< RealPoint >(); final List< double[] > points = new ArrayList< double[] >(); for ( final InterestPoint ip : oldIpl.getInterestPoints() ) { list1.add ( new RealPoint( ip.getL()[ 0 ] * voxelSize.dimension( 0 ), ip.getL()[ 1 ] * voxelSize.dimension( 1 ), ip.getL()[ 2 ] * voxelSize.dimension( 2 ) ) ); list2.add ( new RealPoint( ip.getL()[ 0 ] * voxelSize.dimension( 0 ), ip.getL()[ 1 ] * voxelSize.dimension( 1 ), ip.getL()[ 2 ] * voxelSize.dimension( 2 ) ) ); points.add( ip.getL() ); } // make the KDTree final KDTree< RealPoint > tree = new KDTree< RealPoint >( list1, list1 ); // Nearest neighbor for each point, populate the new list final KNearestNeighborSearchOnKDTree< RealPoint > nn = new KNearestNeighborSearchOnKDTree< RealPoint >( tree, 2 ); final InterestPointList newIpl = new InterestPointList( oldIpl.getBaseDir(), new File( oldIpl.getFile().getParentFile(), "tpId_" + viewId.getTimePointId() + "_viewSetupId_" + viewId.getViewSetupId() + "." + channel.getNewLabel() ) ); newIpl.setInterestPoints( new ArrayList< InterestPoint >() ); int id = 0; for ( int j = 0; j < list2.size(); ++j ) { final RealPoint p = list2.get( j ); nn.search( p ); // first nearest neighbor is the point itself, we need the second nearest final double d = nn.getDistance( 1 ); if ( ( keepRange && d >= minDistance && d <= maxDistance ) || ( !keepRange && ( d < minDistance || d > maxDistance ) ) ) { newIpl.getInterestPoints().add( new InterestPoint( id++, points.get( j ).clone() ) ); } } if ( keepRange ) newIpl.setParameters( "thinned-out '" + channel.getLabel() + "', kept range from " + minDistance + " to " + maxDistance ); else newIpl.setParameters( "thinned-out '" + channel.getLabel() + "', removed range from " + minDistance + " to " + maxDistance ); vipl.addInterestPointList( channel.getNewLabel(), newIpl ); IOFunctions.println( new Date( System.currentTimeMillis() ) + ": TP=" + vd.getTimePointId() + " ViewSetup=" + vd.getViewSetupId() + ", Detections: " + oldIpl.getInterestPoints().size() + " >>> " + newIpl.getInterestPoints().size() ); if ( save && !newIpl.saveInterestPoints() ) { IOFunctions.println( "Error saving interest point list: " + new File( newIpl.getBaseDir(), newIpl.getFile().toString() + newIpl.getInterestPointsExt() ) ); return false; } } } return true; } public static boolean getThinOutThresholds( final SpimData2 spimData, final List< ViewId > viewIds, final List< ChannelProcessThinOut > channels ) { for ( final ChannelProcessThinOut channel : channels ) if ( channel.showHistogram() ) plotHistogram( spimData, viewIds, channel ); if ( defaultCutoffThresholdMin == null || defaultCutoffThresholdMin.length != channels.size() || defaultCutoffThresholdMax == null || defaultCutoffThresholdMax.length != channels.size() ) { defaultCutoffThresholdMin = new double[ channels.size() ]; defaultCutoffThresholdMax = new double[ channels.size() ]; for ( int i = 0; i < channels.size(); ++i ) { defaultCutoffThresholdMin[ i ] = defaultThresholdMinValue; defaultCutoffThresholdMax[ i ] = defaultThresholdMaxValue; } } if ( defaultRemoveKeep == null || defaultRemoveKeep.length != channels.size() ) { defaultRemoveKeep = new int[ channels.size() ]; for ( int i = 0; i < channels.size(); ++i ) defaultRemoveKeep[ i ] = defaultRemoveKeepValue; } final GenericDialog gd = new GenericDialog( "Define cut-off threshold" ); for ( int c = 0; c < channels.size(); ++c ) { final ChannelProcessThinOut channel = channels.get( c ); gd.addChoice( "Channel_" + channel.getChannel().getName() + "_", removeKeepChoice, removeKeepChoice[ defaultRemoveKeep[ c ] ] ); gd.addNumericField( "Channel_" + channel.getChannel().getName() + "_range_lower_threshold", defaultCutoffThresholdMin[ c ], 2 ); gd.addNumericField( "Channel_" + channel.getChannel().getName() + "_range_upper_threshold", defaultCutoffThresholdMax[ c ], 2 ); gd.addMessage( "" ); } gd.showDialog(); if ( gd.wasCanceled() ) return false; for ( int c = 0; c < channels.size(); ++c ) { final ChannelProcessThinOut channel = channels.get( c ); final int removeKeep = defaultRemoveKeep[ c ] = gd.getNextChoiceIndex(); if ( removeKeep == 1 ) channel.setKeepRange( true ); else channel.setKeepRange( false ); channel.setMin( defaultCutoffThresholdMin[ c ] = gd.getNextNumber() ); channel.setMax( defaultCutoffThresholdMax[ c ] = gd.getNextNumber() ); if ( channel.getMin() >= channel.getMax() ) { IOFunctions.println( "You selected the minimal threshold larger than the maximal threshold for channel " + channel.getChannel().getName() ); IOFunctions.println( "Stopping." ); return false; } else { if ( channel.keepRange() ) IOFunctions.println( "Channel " + channel.getChannel().getName() + ": keep only distances from " + channel.getMin() + " >>> " + channel.getMax() ); else IOFunctions.println( "Channel " + channel.getChannel().getName() + ": remove distances from " + channel.getMin() + " >>> " + channel.getMax() ); } } return true; } public static Histogram plotHistogram( final SpimData2 spimData, final List< ViewId > viewIds, final ChannelProcessThinOut channel ) { final ViewInterestPoints vip = spimData.getViewInterestPoints(); // list of all distances final ArrayList< Double > distances = new ArrayList< Double >(); final Random rnd = new Random( System.currentTimeMillis() ); String unit = null; for ( final ViewId viewId : viewIds ) { final ViewDescription vd = spimData.getSequenceDescription().getViewDescription( viewId ); if ( !vd.isPresent() || vd.getViewSetup().getChannel().getId() != channel.getChannel().getId() ) continue; final ViewInterestPointLists vipl = vip.getViewInterestPointLists( viewId ); final InterestPointList ipl = vipl.getInterestPointList( channel.getLabel() ); final VoxelDimensions voxelSize = vd.getViewSetup().getVoxelSize(); if ( ipl.getInterestPoints() == null ) ipl.loadInterestPoints(); if ( unit == null ) unit = vd.getViewSetup().getVoxelSize().unit(); // assemble the list of points final List< RealPoint > list = new ArrayList< RealPoint >(); for ( final InterestPoint ip : ipl.getInterestPoints() ) { list.add ( new RealPoint( ip.getL()[ 0 ] * voxelSize.dimension( 0 ), ip.getL()[ 1 ] * voxelSize.dimension( 1 ), ip.getL()[ 2 ] * voxelSize.dimension( 2 ) ) ); } // make the KDTree final KDTree< RealPoint > tree = new KDTree< RealPoint >( list, list ); // Nearest neighbor for each point final KNearestNeighborSearchOnKDTree< RealPoint > nn = new KNearestNeighborSearchOnKDTree< RealPoint >( tree, 2 ); for ( final RealPoint p : list ) { // every n'th point only if ( rnd.nextDouble() < 1.0 / (double)channel.getSubsampling() ) { nn.search( p ); // first nearest neighbor is the point itself, we need the second nearest distances.add( nn.getDistance( 1 ) ); } } } final Histogram h = new Histogram( distances, 100, "Distance Histogram [Channel=" + channel.getChannel().getName() + "]", unit ); h.showHistogram(); IOFunctions.println( "Channel " + channel.getChannel().getName() + ": min distance=" + h.getMin() + ", max distance=" + h.getMax() ); return h; } public static ArrayList< ChannelProcessThinOut > getChannelsAndLabels( final SpimData2 spimData, final List< ViewId > viewIds ) { // build up the dialog final GenericDialog gd = new GenericDialog( "Choose segmentations to thin out" ); final List< Channel > channels = SpimData2.getAllChannelsSorted( spimData, viewIds ); final int nAllChannels = spimData.getSequenceDescription().getAllChannelsOrdered().size(); if ( Interest_Point_Registration.defaultChannelLabels == null || Interest_Point_Registration.defaultChannelLabels.length != nAllChannels ) Interest_Point_Registration.defaultChannelLabels = new int[ nAllChannels ]; if ( defaultShowHistogram == null || defaultShowHistogram.length != channels.size() ) { defaultShowHistogram = new boolean[ channels.size() ]; for ( int i = 0; i < channels.size(); ++i ) defaultShowHistogram[ i ] = true; } if ( defaultSubSampling == null || defaultSubSampling.length != channels.size() ) { defaultSubSampling = new int[ channels.size() ]; for ( int i = 0; i < channels.size(); ++i ) defaultSubSampling[ i ] = defaultSubSamplingValue; } if ( defaultNewLabels == null || defaultNewLabels.length != channels.size() ) { defaultNewLabels = new String[ channels.size() ]; for ( int i = 0; i < channels.size(); ++i ) defaultNewLabels[ i ] = defaultNewLabelText; } // check which channels and labels are available and build the choices final ArrayList< String[] > channelLabels = new ArrayList< String[] >(); int j = 0; for ( final Channel channel : channels ) { final String[] labels = Interest_Point_Registration.getAllInterestPointLabelsForChannel( spimData, viewIds, channel, "thin out" ); if ( Interest_Point_Registration.defaultChannelLabels[ j ] >= labels.length ) Interest_Point_Registration.defaultChannelLabels[ j ] = 0; String ch = channel.getName().replace( ' ', '_' ); gd.addCheckbox( "Channel_" + ch + "_Display_distance_histogram", defaultShowHistogram[ j ] ); gd.addChoice( "Channel_" + ch + "_Interest_points", labels, labels[ Interest_Point_Registration.defaultChannelLabels[ j ] ] ); gd.addStringField( "Channel_" + ch + "_New_label", defaultNewLabels[ j ], 20 ); gd.addNumericField( "Channel_" + ch + "_Subsample histogram", defaultSubSampling[ j ], 0, 5, "times" ); channelLabels.add( labels ); ++j; } gd.showDialog(); if ( gd.wasCanceled() ) return null; // assemble which channels have been selected with with label final ArrayList< ChannelProcessThinOut > channelsToProcess = new ArrayList< ChannelProcessThinOut >(); j = 0; for ( final Channel channel : channels ) { final boolean showHistogram = defaultShowHistogram[ j ] = gd.getNextBoolean(); final int channelChoice = Interest_Point_Registration.defaultChannelLabels[ j ] = gd.getNextChoiceIndex(); final String newLabel = defaultNewLabels[ j ] = gd.getNextString(); final int subSampling = defaultSubSampling[ j ] = (int)Math.round( gd.getNextNumber() ); if ( channelChoice < channelLabels.get( j ).length - 1 ) { String label = channelLabels.get( j )[ channelChoice ]; if ( label.contains( Interest_Point_Registration.warningLabel ) ) label = label.substring( 0, label.indexOf( Interest_Point_Registration.warningLabel ) ); channelsToProcess.add( new ChannelProcessThinOut( channel, label, newLabel, showHistogram, subSampling ) ); } ++j; } return channelsToProcess; } public static void main( final String[] args ) { new ThinOut_Detections().run( null ); } }
bigdataviewer/SPIM_Registration
src/main/java/spim/fiji/plugin/ThinOut_Detections.java
Java
gpl-2.0
15,827
/* * XMIResultFormatter.java * * Copyright (c) 2011, Database Research Group, Institute of Computer Science, University of Heidelberg. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU General Public License. * * authors: Andreas Fay, Jannik Strötgen * email: fay@stud.uni-heidelberg.de, stroetgen@uni-hd.de * * HeidelTime is a multilingual, cross-domain temporal tagger. * For details, see http://dbs.ifi.uni-heidelberg.de/heideltime */ package de.unihd.dbs.heideltime.standalone.components.impl; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.List; import java.util.regex.MatchResult; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.apache.uima.cas.impl.XmiCasSerializer; import org.apache.uima.jcas.JCas; import org.apache.uima.util.XMLSerializer; import de.unihd.dbs.heideltime.standalone.components.ResultFormatter; /** * Result formatter based on XMI. * * @see {@link org.apache.uima.examples.xmi.XmiWriterCasConsumer} * * @author Andreas Fay, University of Heidelberg * @version 1.0 */ public class XMIResultFormatter implements ResultFormatter { @Override public String format(JCas jcas) throws Exception { ByteArrayOutputStream outStream = null; try { // Write XMI outStream = new ByteArrayOutputStream(); XmiCasSerializer ser = new XmiCasSerializer(jcas.getTypeSystem()); XMLSerializer xmlSer = new XMLSerializer(outStream, false); ser.serialize(jcas.getCas(), xmlSer.getContentHandler()); // Convert output stream to string // String newOut = outStream.toString("UTF-8"); String newOut = outStream.toString(); // System.err.println("NEWOUT:"+newOut); // // if (newOut.matches("^<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>.*$")){ // newOut = newOut.replaceFirst("<\\?xml version=\"1.0\" encoding=\"UTF-8\"\\?>", // "<\\?xml version=\"1.0\" encoding=\""+Charset.defaultCharset().name()+"\"\\?>"); // } // if (newOut.matches("^.*?sofaString=\"(.*?)\".*$")){ // for (MatchResult r : findMatches(Pattern.compile("^(.*?sofaString=\")(.*?)(\".*)$"), newOut)){ // String stringBegin = r.group(1); // String sofaString = r.group(2); // System.err.println("SOFASTRING:"+sofaString); // String stringEnd = r.group(3); // // The sofaString is encoded as UTF-8. // // However, at this point it has to be translated back into the defaultCharset. // byte[] defaultDocText = new String(sofaString.getBytes(), "UTF-8").getBytes(Charset.defaultCharset().name()); // String docText = new String(defaultDocText); // System.err.println("DOCTEXT:"+docText); // newOut = stringBegin + docText + stringEnd; //// newOut = newOut.replaceFirst("sofaString=\".*?\"", "sofaString=\"" + docText + "\""); // } // } // System.err.println("NEWOUT:"+newOut); return newOut; } finally { if (outStream != null) { outStream.close(); } } } /** * Find all the matches of a pattern in a charSequence and return the * results as list. * * @param pattern * @param s * @return */ public static Iterable<MatchResult> findMatches(Pattern pattern, CharSequence s) { List<MatchResult> results = new ArrayList<MatchResult>(); for (Matcher m = pattern.matcher(s); m.find();) results.add(m.toMatchResult()); return results; } }
reboutli-crim/heideltime
src/main/java/de/unihd/dbs/heideltime/standalone/components/impl/XMIResultFormatter.java
Java
gpl-3.0
3,537
// Copyright (C) 2012 Tuma Solutions, LLC // Team Functionality Add-ons for the Process Dashboard // // 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. // // Additional permissions also apply; see the README-license.txt // file in the project root directory for more information. // // 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, see <http://www.gnu.org/licenses/>. // // The author(s) may be contacted at: // processdash@tuma-solutions.com // processdash-devel@lists.sourceforge.net package teamdash.wbs.columns; import teamdash.wbs.WBSModel; import teamdash.wbs.WBSNode; import teamdash.wbs.WBSNodeTest; public class ErrorNotesColumn extends AbstractNotesColumn { /** The ID we use for this column in the data model */ public static final String COLUMN_ID = "Error Notes"; /** The attribute this column uses to store task notes for a WBS node */ public static final String VALUE_ATTR = "Error Notes"; public ErrorNotesColumn(String authorName) { super(VALUE_ATTR, authorName); this.columnID = COLUMN_ID; this.columnName = resources.getString("Error_Notes.Name"); } @Override protected String getEditDialogTitle() { return columnName; } @Override protected Object getEditDialogHeader(WBSNode node) { return new Object[] { resources.getStrings("Error_Notes.Edit_Dialog_Header"), " " }; } public static String getTextAt(WBSNode node) { return getTextAt(node, VALUE_ATTR); } public static String getTooltipAt(WBSNode node, boolean includeByline) { return getTooltipAt(node, includeByline, VALUE_ATTR); } /** * Find nodes that have errors attached, and expand their ancestors as * needed to ensure that they are visible. * * @param wbs * the WBSModel * @param belowNode * an optional starting point for the search, to limit expansion * to a particular branch of the tree; can be null to search from * the root * @param condition * an optional condition to test; only nodes matching the * condition will be made visible. Can be null to show all nodes * with errors */ public static void showNodesWithErrors(WBSModel wbs, WBSNode belowNode, WBSNodeTest condition) { if (belowNode == null) belowNode = wbs.getRoot(); for (WBSNode node : wbs.getDescendants(belowNode)) { String errText = getTextAt(node, VALUE_ATTR); if (errText != null && errText.trim().length() > 0) { if (condition == null || condition.test(node)) wbs.makeVisible(node); } } } }
superzadeh/processdash
teamdash/src/teamdash/wbs/columns/ErrorNotesColumn.java
Java
gpl-3.0
3,288
/* Copyright 2013 Red Hat, Inc. and/or its affiliates. This file is part of lightblue. 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, see <http://www.gnu.org/licenses/>. */ package com.redhat.lightblue.config; import org.junit.Assert; import org.junit.Test; import com.fasterxml.jackson.databind.JsonNode; import com.redhat.lightblue.Request; import com.redhat.lightblue.crud.DeleteRequest; import com.redhat.lightblue.util.test.FileUtil; import static com.redhat.lightblue.util.JsonUtils.json; public class CrudValidationTest { @Test public void testValidInputWithNonValidating() throws Exception { LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration()); // Emulate configuration lbf.getJsonTranslator().setValidation(Request.class, false); String jsonString = FileUtil.readFile("valid-deletion-req.json"); JsonNode node = json(jsonString); DeleteRequest req = lbf.getJsonTranslator().parse(DeleteRequest.class, node); Assert.assertNotNull(req); } @Test public void testInvalidInputWithNonValidating() throws Exception { LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration()); // Emulate configuration lbf.getJsonTranslator().setValidation(Request.class, false); String jsonString = FileUtil.readFile("invalid-deletion-req.json"); JsonNode node = json(jsonString); DeleteRequest req = lbf.getJsonTranslator().parse(DeleteRequest.class, node); Assert.assertNotNull(req); } @Test public void testValidInputWithValidating() throws Exception { LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration()); // Emulate configuration lbf.getJsonTranslator().setValidation(Request.class, true); String jsonString = FileUtil.readFile("valid-deletion-req.json"); JsonNode node = json(jsonString); DeleteRequest req = lbf.getJsonTranslator().parse(DeleteRequest.class, node); Assert.assertNotNull(req); } @Test public void testInvalidInputWithValidating() throws Exception { LightblueFactory lbf = new LightblueFactory(new DataSourcesConfiguration()); // Emulate configuration lbf.getJsonTranslator().setValidation(Request.class, true); String jsonString = FileUtil.readFile("invalid-deletion-req.json"); JsonNode node = json(jsonString); try { lbf.getJsonTranslator().parse(DeleteRequest.class, node); Assert.fail(); } catch (Exception e) { System.out.println(e); } } }
bserdar/lightblue-core
config/src/test/java/com/redhat/lightblue/config/CrudValidationTest.java
Java
gpl-3.0
3,200
/* * Copyright (c) 2018 OBiBa. All rights reserved. * * This program and the accompanying materials * are made available under the terms of the GNU Public License v3.0. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.obiba.mica.micaConfig.service; import org.obiba.mica.micaConfig.domain.PopulationConfig; import org.obiba.mica.micaConfig.repository.PopulationConfigRepository; import org.springframework.stereotype.Component; import javax.inject.Inject; @Component public class PopulationConfigService extends EntityConfigService<PopulationConfig> { @Inject PopulationConfigRepository populationConfigRepository; @Override protected PopulationConfigRepository getRepository() { return populationConfigRepository; } @Override protected String getDefaultId() { return "default"; } @Override protected PopulationConfig createEmptyForm() { return new PopulationConfig(); } @Override protected String getDefaultDefinitionResourcePath() { return "classpath:config/population-form/definition.json"; } @Override protected String getMandatoryDefinitionResourcePath() { return "classpath:config/population-form/definition-mandatory.json"; } @Override protected String getDefaultSchemaResourcePath() { return "classpath:config/population-form/schema.json"; } @Override protected String getMandatorySchemaResourcePath() { return "classpath:config/population-form/schema-mandatory.json"; } }
obiba/mica2
mica-core/src/main/java/org/obiba/mica/micaConfig/service/PopulationConfigService.java
Java
gpl-3.0
1,583
package com.github.bordertech.wcomponents.examples; import com.github.bordertech.wcomponents.RadioButtonGroup; import com.github.bordertech.wcomponents.Size; import com.github.bordertech.wcomponents.WLabel; import com.github.bordertech.wcomponents.WPanel; import com.github.bordertech.wcomponents.WRadioButton; import com.github.bordertech.wcomponents.layout.FlowLayout; import com.github.bordertech.wcomponents.layout.FlowLayout.Alignment; /** * {@link WRadioButton} example. * * @author Yiannis Paschalidis * @since 1.0.0 */ public class RadioButtonExample extends WPanel { /** * Creates a RadioButtonExample. */ public RadioButtonExample() { this.setLayout(new FlowLayout(Alignment.VERTICAL)); WPanel panel = new WPanel(); RadioButtonGroup group1 = new RadioButtonGroup(); panel.add(group1); WRadioButton rb1 = group1.addRadioButton(1); panel.add(new WLabel("Default", rb1)); panel.add(rb1); this.add(panel); panel = new WPanel(); RadioButtonGroup group2 = new RadioButtonGroup(); panel.add(group2); WRadioButton rb2 = group2.addRadioButton(1); rb2.setSelected(true); panel.add(new WLabel("Initially selected", rb2)); panel.add(rb2); this.add(panel); panel = new WPanel(); RadioButtonGroup group3 = new RadioButtonGroup(); panel.add(group3); WRadioButton rb3 = group3.addRadioButton(1); rb3.setDisabled(true); rb3.setToolTip("This is disabled."); panel.add(new WLabel("Disabled", rb3)); panel.add(rb3); this.add(panel); RadioButtonGroup group = new RadioButtonGroup(); WRadioButton rb4 = group.addRadioButton("A"); WRadioButton rb5 = group.addRadioButton("B"); WRadioButton rb6 = group.addRadioButton("C"); panel = new WPanel(); panel.setLayout(new FlowLayout(Alignment.LEFT, Size.MEDIUM)); add(new WLabel("Group")); panel.add(new WLabel("A", rb4)); panel.add(rb4); panel.add(new WLabel("B", rb5)); panel.add(rb5); panel.add(new WLabel("C", rb6)); panel.add(rb6); panel.add(group); this.add(panel); } }
bordertechorg/wcomponents
wcomponents-examples/src/main/java/com/github/bordertech/wcomponents/examples/RadioButtonExample.java
Java
gpl-3.0
2,008
/* * Crafter Studio Web-content authoring solution * Copyright (C) 2007-2016 Crafter Software Corporation. * * 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, see <http://www.gnu.org/licenses/>. */ package org.craftercms.studio.impl.v1.service.activity; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.*; import net.sf.json.JSONObject; import org.apache.commons.collections.CollectionUtils; import org.apache.commons.lang3.StringUtils; import org.craftercms.commons.validation.annotations.param.ValidateIntegerParam; import org.craftercms.commons.validation.annotations.param.ValidateParams; import org.craftercms.commons.validation.annotations.param.ValidateSecurePathParam; import org.craftercms.commons.validation.annotations.param.ValidateStringParam; import org.craftercms.studio.api.v1.constant.StudioConstants; import org.craftercms.studio.api.v1.constant.DmConstants; import org.craftercms.studio.api.v1.dal.AuditFeed; import org.craftercms.studio.api.v1.dal.AuditFeedMapper; import org.craftercms.studio.api.v1.exception.ServiceException; import org.craftercms.studio.api.v1.exception.SiteNotFoundException; import org.craftercms.studio.api.v1.log.Logger; import org.craftercms.studio.api.v1.log.LoggerFactory; import org.craftercms.studio.api.v1.service.AbstractRegistrableService; import org.craftercms.studio.api.v1.service.activity.ActivityService; import org.craftercms.studio.api.v1.service.content.ContentService; import org.craftercms.studio.api.v1.service.deployment.DeploymentService; import org.craftercms.studio.api.v1.service.objectstate.State; import org.craftercms.studio.api.v1.service.site.SiteService; import org.craftercms.studio.api.v1.to.ContentItemTO; import org.craftercms.studio.api.v1.util.DebugUtils; import org.craftercms.studio.api.v1.util.StudioConfiguration; import org.springframework.beans.factory.annotation.Autowired; import org.craftercms.studio.api.v1.service.security.SecurityService; import static org.craftercms.studio.api.v1.constant.StudioConstants.CONTENT_TYPE_PAGE; import static org.craftercms.studio.api.v1.util.StudioConfiguration.ACTIVITY_USERNAME_CASE_SENSITIVE; public class ActivityServiceImpl extends AbstractRegistrableService implements ActivityService { private static final Logger logger = LoggerFactory.getLogger(ActivityServiceImpl.class); protected static final int MAX_LEN_USER_ID = 255; // needs to match schema: // feed_user_id, // post_user_id protected static final int MAX_LEN_SITE_ID = 255; // needs to match schema: // site_network protected static final int MAX_LEN_ACTIVITY_TYPE = 255; // needs to match // schema: // activity_type protected static final int MAX_LEN_ACTIVITY_DATA = 4000; // needs to match // schema: // activity_data protected static final int MAX_LEN_APP_TOOL_ID = 36; // needs to match // schema: app_tool /** activity post properties **/ protected static final String ACTIVITY_PROP_ACTIVITY_SUMMARY = "activitySummary"; protected static final String ACTIVITY_PROP_ID = "id"; protected static final String ACTIVITY_PROP_POST_DATE = "postDate"; protected static final String ACTIVITY_PROP_USER = "user"; protected static final String ACTIVITY_PROP_FEEDUSER = "feedUserId"; protected static final String ACTIVITY_PROP_CONTENTID = "contentId"; /** activity feed format **/ protected static final String ACTIVITY_FEED_FORMAT = "json"; @Autowired protected AuditFeedMapper auditFeedMapper; protected SiteService siteService; protected ContentService contentService; protected SecurityService securityService; protected StudioConfiguration studioConfiguration; protected DeploymentService deploymentService; @Override public void register() { getServicesManager().registerService(ActivityService.class, this); } @Override @ValidateParams public void postActivity(@ValidateStringParam(name = "site") String site, @ValidateStringParam(name = "user") String user, @ValidateSecurePathParam(name = "contentId") String contentId, ActivityType activity, ActivitySource source, Map<String,String> extraInfo) { JSONObject activityPost = new JSONObject(); activityPost.put(ACTIVITY_PROP_USER, user); activityPost.put(ACTIVITY_PROP_ID, contentId); if (extraInfo != null) { activityPost.putAll(extraInfo); } String contentType = null; if (extraInfo != null) { contentType = extraInfo.get(DmConstants.KEY_CONTENT_TYPE); } postActivity(activity.toString(), source.toString(), site, null, activityPost.toString(),contentId,contentType, user); } private void postActivity(String activityType, String activitySource, String siteNetwork, String appTool, String activityData, String contentId, String contentType, String approver) { String currentUser = (StringUtils.isEmpty(approver)) ? securityService.getCurrentUser() : approver; try { // optional - default to empty string if (siteNetwork == null) { siteNetwork = ""; } else if (siteNetwork.length() > MAX_LEN_SITE_ID) { throw new ServiceException("Invalid site network - exceeds " + MAX_LEN_SITE_ID + " chars: " + siteNetwork); } // optional - default to empty string if (appTool == null) { appTool = ""; } else if (appTool.length() > MAX_LEN_APP_TOOL_ID) { throw new ServiceException("Invalid app tool - exceeds " + MAX_LEN_APP_TOOL_ID + " chars: " + appTool); } // required if (StringUtils.isEmpty(activityType)) { throw new ServiceException("Invalid activity type - activity type is empty"); } else if (activityType.length() > MAX_LEN_ACTIVITY_TYPE) { throw new ServiceException("Invalid activity type - exceeds " + MAX_LEN_ACTIVITY_TYPE + " chars: " + activityType); } // optional - default to empty string if (activityData == null) { activityData = ""; } else if (activityType.length() > MAX_LEN_ACTIVITY_DATA) { throw new ServiceException("Invalid activity data - exceeds " + MAX_LEN_ACTIVITY_DATA + " chars: " + activityData); } // required if (StringUtils.isEmpty(currentUser)) { throw new ServiceException("Invalid user - user is empty"); } else if (currentUser.length() > MAX_LEN_USER_ID) { throw new ServiceException("Invalid user - exceeds " + MAX_LEN_USER_ID + " chars: " + currentUser); } else { // user names are not case-sensitive currentUser = currentUser.toLowerCase(); } if (contentType == null) { contentType = CONTENT_TYPE_PAGE; } } catch (ServiceException e) { // log error and throw exception logger.error("Error in getting feeds", e); } try { ZonedDateTime postDate = ZonedDateTime.now(ZoneOffset.UTC); AuditFeed activityPost = new AuditFeed(); activityPost.setUserId(currentUser); activityPost.setSiteNetwork(siteNetwork); activityPost.setSummary(activityData); activityPost.setType(activityType); activityPost.setCreationDate(postDate); activityPost.setModifiedDate(postDate); activityPost.setSummaryFormat("json"); activityPost.setContentId(contentId); activityPost.setContentType(contentType); activityPost.setSource(activitySource); try { activityPost.setCreationDate(ZonedDateTime.now(ZoneOffset.UTC)); long postId = insertFeedEntry(activityPost); activityPost.setId(postId); logger.debug("Posted: " + activityPost); } catch (Exception e) { throw new ServiceException("Failed to post activity: " + e, e); } } catch (ServiceException e) { // log error, subsume exception (for post activity) logger.error("Error in posting feed", e); } } private long insertFeedEntry(AuditFeed activityFeed) { DebugUtils.addDebugStack(logger); logger.debug("Insert activity " + activityFeed.getContentId()); Long id = auditFeedMapper.insertActivityFeed(activityFeed); return (id != null ? id : -1); } @Override @ValidateParams public void renameContentId(@ValidateStringParam(name = "site") String site, @ValidateSecurePathParam(name = "oldUrl") String oldUrl, @ValidateSecurePathParam(name = "newUrl") String newUrl) { DebugUtils.addDebugStack(logger); logger.debug("Rename " + oldUrl + " to " + newUrl); Map<String, String> params = new HashMap<String, String>(); params.put("newPath", newUrl); params.put("site", site); params.put("oldPath", oldUrl); auditFeedMapper.renameContent(params); } @Override @ValidateParams public List<ContentItemTO> getActivities(@ValidateStringParam(name = "site") String site, @ValidateStringParam(name = "user") String user, @ValidateIntegerParam(name = "num") int num, @ValidateStringParam(name = "sort") String sort, boolean ascending, boolean excludeLive, @ValidateStringParam(name = "filterType") String filterType) throws ServiceException { int startPos = 0; List<ContentItemTO> contentItems = new ArrayList<ContentItemTO>(); boolean hasMoreItems = true; while(contentItems.size() < num && hasMoreItems){ int remainingItems = num - contentItems.size(); hasMoreItems = getActivityFeeds(user, site, startPos, num , filterType, excludeLive,contentItems,remainingItems); startPos = startPos+num; } if(contentItems.size() > num){ return contentItems.subList(0, num); } return contentItems; } /** * * Returns all non-live items if hideLiveItems is true, else should return all feeds back * */ protected boolean getActivityFeeds(String user, String site,int startPos, int size, String filterType,boolean hideLiveItems,List<ContentItemTO> contentItems,int remainingItem){ List<String> activityFeedEntries = new ArrayList<String>(); if (!getUserNamesAreCaseSensitive()) { user = user.toLowerCase(); } List<AuditFeed> activityFeeds = null; activityFeeds = selectUserFeedEntries(user, ACTIVITY_FEED_FORMAT, site, startPos, size, filterType, hideLiveItems); for (AuditFeed activityFeed : activityFeeds) { activityFeedEntries.add(activityFeed.getJSONString()); } boolean hasMoreItems=true; //if number of items returned is less than size it means that table has no more records if(activityFeedEntries.size()<size){ hasMoreItems=false; } if (activityFeedEntries != null && activityFeedEntries.size() > 0) { for (int index = 0; index < activityFeedEntries.size() && remainingItem!=0; index++) { JSONObject feedObject = JSONObject.fromObject(activityFeedEntries.get(index)); String id = (feedObject.containsKey(ACTIVITY_PROP_CONTENTID)) ? feedObject.getString(ACTIVITY_PROP_CONTENTID) : ""; ContentItemTO item = createActivityItem(site, feedObject, id); item.published = true; item.setPublished(true); ZonedDateTime pubDate = deploymentService.getLastDeploymentDate(site, id); item.publishedDate = pubDate; item.setPublishedDate(pubDate); contentItems.add(item); remainingItem--; } } logger.debug("Total Item post live filter : " + contentItems.size() + " hasMoreItems : "+hasMoreItems); return hasMoreItems; } /** * create an activity from the given feed * * @param site * @param feedObject * @return activity */ protected ContentItemTO createActivityItem(String site, JSONObject feedObject, String id) { try { ContentItemTO item = contentService.getContentItem(site, id, 0); if(item == null || item.isDeleted()) { item = contentService.createDummyDmContentItemForDeletedNode(site, id); String modifier = (feedObject.containsKey(ACTIVITY_PROP_FEEDUSER)) ? feedObject.getString(ACTIVITY_PROP_FEEDUSER) : ""; if(modifier != null && !modifier.isEmpty()) { item.user = modifier; } String activitySummary = (feedObject.containsKey(ACTIVITY_PROP_ACTIVITY_SUMMARY)) ? feedObject.getString(ACTIVITY_PROP_ACTIVITY_SUMMARY) : ""; JSONObject summaryObject = JSONObject.fromObject(activitySummary); if (summaryObject.containsKey(DmConstants.KEY_CONTENT_TYPE)) { String contentType = (String)summaryObject.get(DmConstants.KEY_CONTENT_TYPE); item.contentType = contentType; } if(summaryObject.containsKey(StudioConstants.INTERNAL_NAME)) { String internalName = (String)summaryObject.get(StudioConstants.INTERNAL_NAME); item.internalName = internalName; } if(summaryObject.containsKey(StudioConstants.BROWSER_URI)) { String browserUri = (String)summaryObject.get(StudioConstants.BROWSER_URI); item.browserUri = browserUri; } item.setLockOwner(""); } String postDate = (feedObject.containsKey(ACTIVITY_PROP_POST_DATE)) ? feedObject.getString(ACTIVITY_PROP_POST_DATE) : ""; ZonedDateTime editedDate = ZonedDateTime.parse(postDate); if (editedDate != null) { item.eventDate = editedDate.withZoneSameInstant(ZoneOffset.UTC); } else { item.eventDate = editedDate; } return item; } catch (Exception e) { logger.error("Error fetching content item for [" + id + "]", e.getMessage()); return null; } } private List<AuditFeed> selectUserFeedEntries(String feedUserId, String format, String siteId, int startPos, int feedSize, String contentType, boolean hideLiveItems) { HashMap<String,Object> params = new HashMap<String,Object>(); params.put("userId",feedUserId); params.put("summaryFormat",format); params.put("siteNetwork",siteId); params.put("startPos", startPos); params.put("feedSize", feedSize); params.put("activities", Arrays.asList(ActivityType.CREATED, ActivityType.DELETED, ActivityType.UPDATED, ActivityType.MOVED)); if(StringUtils.isNotEmpty(contentType) && !contentType.toLowerCase().equals("all")){ params.put("contentType",contentType.toLowerCase()); } if (hideLiveItems) { List<String> statesValues = new ArrayList<String>(); for (State state : State.LIVE_STATES) { statesValues.add(state.name()); } params.put("states", statesValues); return auditFeedMapper.selectUserFeedEntriesHideLive(params); } else { return auditFeedMapper.selectUserFeedEntries(params); } } @Override @ValidateParams public AuditFeed getDeletedActivity(@ValidateStringParam(name = "site") String site, @ValidateSecurePathParam(name = "path") String path) { HashMap<String,String> params = new HashMap<String,String>(); params.put("contentId", path); params.put("siteNetwork", site); String activityType = ActivityType.DELETED.toString(); params.put("activityType", activityType); return auditFeedMapper.getDeletedActivity(params); } @Override @ValidateParams public void deleteActivitiesForSite(@ValidateStringParam(name = "site") String site) { Map<String, String> params = new HashMap<String, String>(); params.put("site", site); auditFeedMapper.deleteActivitiesForSite(params); } @Override @ValidateParams public List<AuditFeed> getAuditLogForSite(@ValidateStringParam(name = "site") String site, @ValidateIntegerParam(name = "start") int start, @ValidateIntegerParam(name = "number") int number, @ValidateStringParam(name = "user") String user, List<String> actions) throws SiteNotFoundException { if (!siteService.exists(site)) { throw new SiteNotFoundException(); } else { Map<String, Object> params = new HashMap<String, Object>(); params.put("site", site); params.put("start", start); params.put("number", number); if (StringUtils.isNotEmpty(user)) { params.put("user", user); } if (CollectionUtils.isNotEmpty(actions)) { params.put("actions", actions); } return auditFeedMapper.getAuditLogForSite(params); } } @Override @ValidateParams public long getAuditLogForSiteTotal(@ValidateStringParam(name = "site") String site, @ValidateStringParam(name = "user") String user, List<String> actions) throws SiteNotFoundException { if (!siteService.exists(site)) { throw new SiteNotFoundException(); } else { Map<String, Object> params = new HashMap<String, Object>(); params.put("site", site); if (StringUtils.isNotEmpty(user)) { params.put("user", user); } if (CollectionUtils.isNotEmpty(actions)) { params.put("actions", actions); } return auditFeedMapper.getAuditLogForSiteTotal(params); } } public boolean getUserNamesAreCaseSensitive() { boolean toReturn = Boolean.parseBoolean(studioConfiguration.getProperty(ACTIVITY_USERNAME_CASE_SENSITIVE)); return toReturn; } public SiteService getSiteService() { return siteService; } public void setSiteService(final SiteService siteService) { this.siteService = siteService; } public void setContentService(ContentService contentService) { this.contentService = contentService; } public SecurityService getSecurityService() {return securityService; } public void setSecurityService(SecurityService securityService) { this.securityService = securityService; } public StudioConfiguration getStudioConfiguration() { return studioConfiguration; } public void setStudioConfiguration(StudioConfiguration studioConfiguration) { this.studioConfiguration = studioConfiguration; } public DeploymentService getDeploymentService() { return deploymentService; } public void setDeploymentService(DeploymentService deploymentService) { this.deploymentService = deploymentService; } }
dejan-brkic/studio2
src/main/java/org/craftercms/studio/impl/v1/service/activity/ActivityServiceImpl.java
Java
gpl-3.0
20,008
package org.thoughtcrime.securesms.testutil; import org.signal.core.util.logging.Log; public final class SystemOutLogger extends Log.Logger { @Override public void v(String tag, String message, Throwable t, boolean keepLonger) { printlnFormatted('v', tag, message, t); } @Override public void d(String tag, String message, Throwable t, boolean keepLonger) { printlnFormatted('d', tag, message, t); } @Override public void i(String tag, String message, Throwable t, boolean keepLonger) { printlnFormatted('i', tag, message, t); } @Override public void w(String tag, String message, Throwable t, boolean keepLonger) { printlnFormatted('w', tag, message, t); } @Override public void e(String tag, String message, Throwable t, boolean keepLonger) { printlnFormatted('e', tag, message, t); } @Override public void flush() { } private void printlnFormatted(char level, String tag, String message, Throwable t) { System.out.println(format(level, tag, message, t)); } private String format(char level, String tag, String message, Throwable t) { if (t != null) { return String.format("%c[%s] %s %s:%s", level, tag, message, t.getClass().getSimpleName(), t.getMessage()); } else { return String.format("%c[%s] %s", level, tag, message); } } }
WhisperSystems/Signal-Android
app/src/test/java/org/thoughtcrime/securesms/testutil/SystemOutLogger.java
Java
gpl-3.0
1,332
// Openbravo POS is a point of sales application designed for touch screens. // Copyright (C) 2007-2009 Openbravo, S.L. // http://www.openbravo.com/product/pos // // This file is part of Openbravo POS. // // Openbravo POS 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. // // Openbravo POS 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 Openbravo POS. If not, see <http://www.gnu.org/licenses/>. package com.openbravo.pos.printer.escpos; public class CodesIthaca extends Codes { private static final byte[] INITSEQUENCE = {}; private static final byte[] CHAR_SIZE_0 = {0x1D, 0x21, 0x00}; private static final byte[] CHAR_SIZE_1 = {0x1D, 0x21, 0x01}; private static final byte[] CHAR_SIZE_2 = {0x1D, 0x21, 0x30}; private static final byte[] CHAR_SIZE_3 = {0x1D, 0x21, 0x31}; public static final byte[] BOLD_SET = {0x1B, 0x45, 0x01}; public static final byte[] BOLD_RESET = {0x1B, 0x45, 0x00}; public static final byte[] UNDERLINE_SET = {0x1B, 0x2D, 0x01}; public static final byte[] UNDERLINE_RESET = {0x1B, 0x2D, 0x00}; private static final byte[] OPEN_DRAWER = {0x1B, 0x78, 0x01}; private static final byte[] PARTIAL_CUT = {0x1B, 0x50, 0x00}; private static final byte[] IMAGE_HEADER = {0x1D, 0x76, 0x30, 0x03}; private static final byte[] NEW_LINE = {0x0D, 0x0A}; // Print and carriage return /** Creates a new instance of CodesIthaca */ public CodesIthaca() { } public byte[] getInitSequence() { return INITSEQUENCE; } public byte[] getSize0() { return CHAR_SIZE_0; } public byte[] getSize1() { return CHAR_SIZE_1; } public byte[] getSize2() { return CHAR_SIZE_2; } public byte[] getSize3() { return CHAR_SIZE_3; } public byte[] getBoldSet() { return BOLD_SET; } public byte[] getBoldReset() { return BOLD_RESET; } public byte[] getUnderlineSet() { return UNDERLINE_SET; } public byte[] getUnderlineReset() { return UNDERLINE_RESET; } public byte[] getOpenDrawer() { return OPEN_DRAWER; } public byte[] getCutReceipt() { return PARTIAL_CUT; } public byte[] getNewLine() { return NEW_LINE; } public byte[] getImageHeader() { return IMAGE_HEADER; } public int getImageWidth() { return 256; } }
ZarGate/OpenbravoPOS
src-pos/com/openbravo/pos/printer/escpos/CodesIthaca.java
Java
gpl-3.0
2,760
package com.redhat.jcliff; import java.io.StringBufferInputStream; import java.util.List; import java.util.ArrayList; import java.util.Map; import java.util.Set; import org.junit.Assert; import org.junit.Before; import org.junit.Test; import org.jboss.dmr.ModelNode; public class DeploymentTest { @Test public void replace() throws Exception { ModelNode newDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>\"deleted\", \"app2\"=>{\"NAME\"=>\"app2\",\"path\"=>\"blah\"} }")); ModelNode existingDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>{\"NAME\"=>\"app1\"},\"app2\"=>{\"NAME\"=>\"app2\"}}")); Deployment d=new Deployment(new Ctx(),true); Map<String,Set<String>> map=d.findDeploymentsToReplace(newDeployments,existingDeployments); Assert.assertEquals("app2",map.get("app2").iterator().next()); Assert.assertNull(map.get("app1")); Assert.assertEquals(1,map.size()); } @Test public void newdeployments() throws Exception { ModelNode newDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>\"deleted\", \"app2\"=>{\"NAME\"=>\"app2\",\"path\"=>\"blah\"},\"app3\"=>{\"NAME\"=>\"app3\"} }")); ModelNode existingDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>{\"NAME\"=>\"app1\"},\"app2\"=>{\"NAME\"=>\"app2\"}}")); Deployment d=new Deployment(new Ctx(),true); String[] news=d.getNewDeployments(newDeployments,existingDeployments.keys()); Assert.assertEquals(1,news.length); Assert.assertEquals("app3",news[0]); } @Test public void undeployments() throws Exception { ModelNode newDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>\"deleted\", \"app2\"=>{\"NAME\"=>\"app2\",\"path\"=>\"blah\"},\"app3\"=>{\"NAME\"=>\"app3\"}, \"app4\"=>\"deleted\" }")); ModelNode existingDeployments=ModelNode.fromStream(new StringBufferInputStream("{\"app1\"=>{\"NAME\"=>\"app1\"},\"app2\"=>{\"NAME\"=>\"app2\"}}")); Deployment d=new Deployment(new Ctx(),true); String[] und=d.getUndeployments(newDeployments,existingDeployments); Assert.assertEquals(1,und.length); Assert.assertEquals("app1",und[0]); } }
mkrakowitzer/jcliff
src/test/java/com/redhat/jcliff/DeploymentTest.java
Java
gpl-3.0
2,307
package net.tropicraft.world.genlayer; import net.minecraft.world.gen.layer.IntCache; public class GenLayerTropiVoronoiZoom extends GenLayerTropicraft { public enum Mode { CARTESIAN, MANHATTAN; } public Mode zoomMode; public GenLayerTropiVoronoiZoom(long seed, GenLayerTropicraft parent, Mode zoomMode) { super(seed); super.parent = parent; this.zoomMode = zoomMode; this.setZoom(1); } /** * Returns a list of integer values generated by this layer. These may be interpreted as temperatures, rainfall * amounts, or biomeList[] indices based on the particular GenLayer subclass. */ public int[] getInts(int x, int y, int width, int length) { final int randomResolution = 1024; final double half = 0.5D; final double almostTileSize = 3.6D; final double tileSize = 4D; x -= 2; y -= 2; int scaledX = x >> 2; int scaledY = y >> 2; int scaledWidth = (width >> 2) + 2; int scaledLength = (length >> 2) + 2; int[] parentValues = this.parent.getInts(scaledX, scaledY, scaledWidth, scaledLength); int bitshiftedWidth = scaledWidth - 1 << 2; int bitshiftedLength = scaledLength - 1 << 2; int[] aint1 = IntCache.getIntCache(bitshiftedWidth * bitshiftedLength); int i; for(int j = 0; j < scaledLength - 1; ++j) { i = 0; int baseValue = parentValues[i + 0 + (j + 0) * scaledWidth]; for(int advancedValueJ = parentValues[i + 0 + (j + 1) * scaledWidth]; i < scaledWidth - 1; ++i) { this.initChunkSeed((long)(i + scaledX << 2), (long)(j + scaledY << 2)); double offsetY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize; double offsetX = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize; this.initChunkSeed((long)(i + scaledX + 1 << 2), (long)(j + scaledY << 2)); double offsetYY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize; double offsetXY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize; this.initChunkSeed((long)(i + scaledX << 2), (long)(j + scaledY + 1 << 2)); double offsetYX = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize; double offsetXX = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize; this.initChunkSeed((long)(i + scaledX + 1 << 2), (long)(j + scaledY + 1 << 2)); double offsetYXY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize; double offsetXXY = ((double)this.nextInt(randomResolution) / randomResolution - half) * almostTileSize + tileSize; int advancedValueI = parentValues[i + 1 + (j + 0) * scaledWidth] & 255; int advancedValueIJ = parentValues[i + 1 + (j + 1) * scaledWidth] & 255; for(int innerX = 0; innerX < 4; ++innerX) { int index = ((j << 2) + innerX) * bitshiftedWidth + (i << 2); for(int innerY = 0; innerY < 4; ++innerY) { double baseDistance; double distanceY; double distanceX; double distanceXY; switch(zoomMode) { case CARTESIAN: baseDistance = ((double)innerX - offsetX) * ((double)innerX - offsetX) + ((double)innerY - offsetY) * ((double)innerY - offsetY); distanceY = ((double)innerX - offsetXY) * ((double)innerX - offsetXY) + ((double)innerY - offsetYY) * ((double)innerY - offsetYY); distanceX = ((double)innerX - offsetXX) * ((double)innerX - offsetXX) + ((double)innerY - offsetYX) * ((double)innerY - offsetYX); distanceXY = ((double)innerX - offsetXXY) * ((double)innerX - offsetXXY) + ((double)innerY - offsetYXY) * ((double)innerY - offsetYXY); break; case MANHATTAN: baseDistance = Math.abs(innerX - offsetX) + Math.abs(innerY - offsetY); distanceY = Math.abs(innerX - offsetXY) + Math.abs(innerY - offsetYY); distanceX = Math.abs(innerX - offsetXX) + Math.abs(innerY - offsetYX); distanceXY = Math.abs(innerX - offsetXXY) + Math.abs(innerY - offsetYXY); break; default: baseDistance = ((double)innerX - offsetX) * ((double)innerX - offsetX) + ((double)innerY - offsetY) * ((double)innerY - offsetY); distanceY = ((double)innerX - offsetXY) * ((double)innerX - offsetXY) + ((double)innerY - offsetYY) * ((double)innerY - offsetYY); distanceX = ((double)innerX - offsetXX) * ((double)innerX - offsetXX) + ((double)innerY - offsetYX) * ((double)innerY - offsetYX); distanceXY = ((double)innerX - offsetXXY) * ((double)innerX - offsetXXY) + ((double)innerY - offsetYXY) * ((double)innerY - offsetYXY); } if(baseDistance < distanceY && baseDistance < distanceX && baseDistance < distanceXY) { aint1[index++] = baseValue; } else if(distanceY < baseDistance && distanceY < distanceX && distanceY < distanceXY) { aint1[index++] = advancedValueI; } else if(distanceX < baseDistance && distanceX < distanceY && distanceX < distanceXY) { aint1[index++] = advancedValueJ; } else { aint1[index++] = advancedValueIJ; } } } baseValue = advancedValueI; advancedValueJ = advancedValueIJ; } } int[] aint2 = IntCache.getIntCache(width * length); for(i = 0; i < length; ++i) { System.arraycopy(aint1, (i + (y & 3)) * bitshiftedWidth + (x & 3), aint2, i * width, width); } return aint2; } @Override public void setZoom(int zoom) { this.zoom = zoom; parent.setZoom(zoom * 4); } }
Vexatos/Tropicraft
src/main/java/net/tropicraft/world/genlayer/GenLayerTropiVoronoiZoom.java
Java
mpl-2.0
6,674
/* * This file is part of LibrePlan * * Copyright (C) 2009-2010 Fundación para o Fomento da Calidade Industrial e * Desenvolvemento Tecnolóxico de Galicia * Copyright (C) 2010-2011 Igalia, S.L. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.libreplan.business.resources.entities; import java.util.Collections; import java.util.HashSet; import java.util.Set; import org.apache.commons.lang3.StringUtils; import org.hibernate.validator.constraints.NotEmpty; import javax.validation.Valid; /** * Represents entity. It is another type of work resource. * * @author Javier Moran Rua <jmoran@igalia.com> * @author Fernando Bellas Permuy <fbellas@udc.es> */ public class Machine extends Resource { private final static ResourceEnum type = ResourceEnum.MACHINE; private String name; private String description; private Set<MachineWorkersConfigurationUnit> configurationUnits = new HashSet<>(); @Valid public Set<MachineWorkersConfigurationUnit> getConfigurationUnits() { return Collections.unmodifiableSet(configurationUnits); } public void addMachineWorkersConfigurationUnit(MachineWorkersConfigurationUnit unit) { configurationUnits.add(unit); } public void removeMachineWorkersConfigurationUnit(MachineWorkersConfigurationUnit unit) { configurationUnits.remove(unit); } public static Machine createUnvalidated(String code, String name, String description) { Machine machine = create(new Machine(), code); machine.name = name; machine.description = description; return machine; } public void updateUnvalidated(String name, String description) { if (!StringUtils.isBlank(name)) { this.name = name; } if (!StringUtils.isBlank(description)) { this.description = description; } } /** * Used by Hibernate. Do not use! */ protected Machine() {} public static Machine create() { return create(new Machine()); } public static Machine create(String code) { return create(new Machine(), code); } @NotEmpty(message = "machine name not specified") public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public String getShortDescription() { return name + " (" + getCode() + ")"; } public void setDescription(String description) { this.description = description; } @Override protected boolean isCriterionSatisfactionOfCorrectType(CriterionSatisfaction c) { return c.getResourceType().equals(ResourceEnum.MACHINE); } @Override public ResourceEnum getType() { return type; } @Override public String toString() { return String.format("MACHINE: %s", name); } @Override public String getHumanId() { return name; } }
PaulLuchyn/libreplan
libreplan-business/src/main/java/org/libreplan/business/resources/entities/Machine.java
Java
agpl-3.0
3,681
/** * Copyright © MyCollab * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.mycollab.vaadin.web.ui; import com.vaadin.ui.CheckBox; import com.vaadin.ui.themes.ValoTheme; /** * @author MyCollab Ltd. * @since 3.0 */ public class CheckBoxDecor extends CheckBox { private static final long serialVersionUID = 1L; public CheckBoxDecor(String title, boolean value) { super(title, value); this.addStyleName(ValoTheme.CHECKBOX_SMALL); } }
aglne/mycollab
mycollab-web/src/main/java/com/mycollab/vaadin/web/ui/CheckBoxDecor.java
Java
agpl-3.0
1,104
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2016-2016 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2016 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.netmgt.poller.remote.metadata; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; import org.junit.Before; import org.junit.Test; import org.opennms.netmgt.poller.remote.metadata.MetadataField.Validator; public class EmailValidatorTest { private Validator m_validator; @Before public void setUp() { m_validator = new EmailValidator(); } @Test public void testValid() { assertTrue(m_validator.isValid("ranger@opennms.org")); assertTrue(m_validator.isValid("ranger@monkey.esophagus")); assertTrue(m_validator.isValid("ranger@giant.list.of.sub.domains.com")); } @Test public void testInvalid() { assertFalse(m_validator.isValid("ranger@opennms")); assertFalse(m_validator.isValid("ranger.monkey.esophagus")); assertFalse(m_validator.isValid("ranger@")); assertFalse(m_validator.isValid("@foo.com")); assertFalse(m_validator.isValid("@foo.com.")); assertFalse(m_validator.isValid("@foo.com")); assertFalse(m_validator.isValid(".@foo.com")); assertFalse(m_validator.isValid(".e@foo.com")); } }
aihua/opennms
features/poller/remote/src/test/java/org/opennms/netmgt/poller/remote/metadata/EmailValidatorTest.java
Java
agpl-3.0
2,394
/* * ProActive Parallel Suite(TM): * The Open Source library for parallel and distributed * Workflows & Scheduling, Orchestration, Cloud Automation * and Big Data Analysis on Enterprise Grids & Clouds. * * Copyright (c) 2007 - 2017 ActiveEon * Contact: contact@activeeon.com * * This library 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: version 3 of * the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. */ package org.objectweb.proactive.core.jmx.mbean; import java.io.Serializable; /** * This interface is used to add a class loader to the MBean Server repository. * See JMX Specification, version 1.4 ; Chap 8.4.1 : 'A class loader is added to the repository if it is registered as an MBean'. * @author The ProActive Team */ public interface JMXClassLoaderMBean extends Serializable { }
paraita/programming
programming-core/src/main/java/org/objectweb/proactive/core/jmx/mbean/JMXClassLoaderMBean.java
Java
agpl-3.0
1,413
/* * Kuali Coeus, a comprehensive research administration system for higher education. * * Copyright 2005-2016 Kuali, Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.coeus.propdev.impl.action; import org.apache.commons.lang3.StringUtils; import org.kuali.coeus.sys.framework.rule.KcTransactionalDocumentRuleBase; import org.kuali.rice.core.api.util.RiceKeyConstants; public class ProposalDevelopmentRejectionRule extends KcTransactionalDocumentRuleBase { private static final String ACTION_REASON = "proposalDevelopmentRejectionBean.actionReason"; public boolean proccessProposalDevelopmentRejection(ProposalDevelopmentActionBean bean) { boolean valid = true; if (StringUtils.isEmpty(bean.getActionReason())) { valid = false; String errorParams = ""; reportError(ACTION_REASON, RiceKeyConstants.ERROR_REQUIRED, errorParams); } return valid; } }
kuali/kc
coeus-impl/src/main/java/org/kuali/coeus/propdev/impl/action/ProposalDevelopmentRejectionRule.java
Java
agpl-3.0
1,586
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.opencms.gwt.shared.sort; import java.util.Comparator; /** * Comparator for objects with a type property.<p> * * @see I_CmsHasType * * @since 8.0.0 */ public class CmsComparatorType implements Comparator<I_CmsHasType> { /** Sort order flag. */ private boolean m_ascending; /** * Constructor.<p> * * @param ascending if <code>true</code> order is ascending */ public CmsComparatorType(boolean ascending) { m_ascending = ascending; } /** * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object) */ public int compare(I_CmsHasType o1, I_CmsHasType o2) { int result = o1.getType().compareTo(o2.getType()); return m_ascending ? result : -result; } }
ggiudetti/opencms-core
src/org/opencms/gwt/shared/sort/CmsComparatorType.java
Java
lgpl-2.1
1,889
package railo.runtime.search.lucene2.query; import railo.commons.lang.StringUtil; public final class Concator implements Op { private Op left; private Op right; public Concator(Op left,Op right) { this.left=left; this.right=right; } @Override public String toString() { if(left instanceof Literal && right instanceof Literal) { String str=((Literal)left).literal+" "+((Literal)right).literal; return "\""+StringUtil.replace(str, "\"", "\"\"", false)+"\""; } return left+" "+right; } }
modius/railo
railo-java/railo-core/src/railo/runtime/search/lucene2/query/Concator.java
Java
lgpl-2.1
516
package org.hivedb.hibernate; import org.hibernate.HibernateException; import org.hibernate.Session; import org.hibernate.shards.session.OpenSessionEvent; import java.sql.SQLException; public class RecordNodeOpenSessionEvent implements OpenSessionEvent { public static ThreadLocal<String> node = new ThreadLocal<String>(); public static String getNode() { return node.get(); } public static void setNode(Session session) { node.set(getNode(session)); } public void onOpenSession(Session session) { setNode(session); } @SuppressWarnings("deprecation") private static String getNode(Session session) { String node = ""; if (session != null) { try { node = session.connection().getMetaData().getURL(); } catch (SQLException ex) { } catch (HibernateException ex) { } } return node; } }
britt/hivedb
src/main/java/org/hivedb/hibernate/RecordNodeOpenSessionEvent.java
Java
lgpl-2.1
834
package railo.runtime.functions.dateTime; import java.util.TimeZone; import railo.runtime.PageContext; import railo.runtime.exp.ExpressionException; import railo.runtime.ext.function.Function; import railo.runtime.tag.util.DeprecatedUtil; import railo.runtime.type.dt.DateTime; import railo.runtime.type.dt.DateTimeImpl; /** * Implements the CFML Function now * @deprecated removed with no replacement */ public final class NowServer implements Function { /** * @param pc * @return server time * @throws ExpressionException */ public static DateTime call(PageContext pc ) throws ExpressionException { DeprecatedUtil.function(pc,"nowServer"); long now = System.currentTimeMillis(); int railo = pc.getTimeZone().getOffset(now); int server = TimeZone.getDefault().getOffset(now); return new DateTimeImpl(pc,now-(railo-server),false); } }
JordanReiter/railo
railo-java/railo-core/src/railo/runtime/functions/dateTime/NowServer.java
Java
lgpl-2.1
870
package org.hivedb.hibernate.simplified; import org.apache.log4j.Logger; import org.hibernate.HibernateException; import org.hibernate.action.Executable; import org.hibernate.event.PostDeleteEvent; import org.hibernate.event.PostDeleteEventListener; import org.hivedb.Hive; import org.hivedb.HiveLockableException; import org.hivedb.configuration.EntityConfig; import org.hivedb.configuration.EntityHiveConfig; import org.hivedb.hibernate.HiveIndexer; import org.hivedb.util.classgen.ReflectionTools; import org.hivedb.util.functional.Transform; import org.hivedb.util.functional.Unary; import java.io.Serializable; /** * This is an alternative way of deleting the hive indexes after successful * transaction completion (instead of using a custom Interceptor) and up * for discussion. Hooked up via org.hibernate.cfg.Configuration. * getEventListeners().setPostDeleteEventListeners * * @author mellwanger */ public class PostDeleteEventListenerImpl implements PostDeleteEventListener { private static final Logger log = Logger.getLogger(PostInsertEventListenerImpl.class); private final EntityHiveConfig hiveConfig; private final HiveIndexer indexer; public PostDeleteEventListenerImpl(EntityHiveConfig hiveConfig, Hive hive) { this.hiveConfig = hiveConfig; indexer = new HiveIndexer(hive); } public void onPostDelete(final PostDeleteEvent event) { event.getSession().getActionQueue().execute(new Executable() { public void afterTransactionCompletion(boolean success) { if (success) { deleteIndexes(event.getEntity()); } } public void beforeExecutions() throws HibernateException { // TODO Auto-generated method stub } public void execute() throws HibernateException { // TODO Auto-generated method stub } public Serializable[] getPropertySpaces() { // TODO Auto-generated method stub return null; } public boolean hasAfterTransactionCompletion() { return true; } }); } @SuppressWarnings("unchecked") private Class resolveEntityClass(Class clazz) { return ReflectionTools.whichIsImplemented( clazz, Transform.map(new Unary<EntityConfig, Class>() { public Class f(EntityConfig entityConfig) { return entityConfig.getRepresentedInterface(); } }, hiveConfig.getEntityConfigs())); } private void deleteIndexes(Object entity) { try { final Class<?> resolvedEntityClass = resolveEntityClass(entity.getClass()); if (resolvedEntityClass != null) indexer.delete(hiveConfig.getEntityConfig(entity.getClass()), entity); } catch (HiveLockableException e) { log.warn(e); } } }
aruanruan/hivedb
src/main/java/org/hivedb/hibernate/simplified/PostDeleteEventListenerImpl.java
Java
lgpl-2.1
2,748
import java.util.*; public class LineNumbersTest extends LinkedList<Object>{ public LineNumbersTest(int x) { super((x & 0) == 1 ? new LinkedList<Object>((x & 1) == x++ ? new ArrayList<Object>() : new HashSet<Object>()) :new HashSet<Object>()); super.add(x = getLineNo()); this.add(x = getLineNo()); } static int getLineNo() { return new Throwable().fillInStackTrace().getStackTrace()[1].getLineNumber(); } public static void main(String[] args) { System.out.println(getLineNo()); System.out.println(new Throwable().fillInStackTrace().getStackTrace()[0].getFileName()); System.out.println(getLineNo()); System.out.println(new LineNumbersTest(2)); List<Object> foo = new ArrayList<>(); System.out.println(foo.addAll(foo)); } }
xtiankisutsa/MARA_Framework
tools/decompilers/Krakatau/tests/disassembler/source/LineNumbersTest.java
Java
lgpl-3.0
857
package org.opennaas.client.rest; import java.io.FileNotFoundException; import java.util.List; import javax.ws.rs.core.MediaType; import javax.xml.bind.JAXBException; import org.apache.log4j.Logger; import org.opennaas.extensions.router.model.EnabledLogicalElement.EnabledState; import org.opennaas.extensions.router.model.GRETunnelConfiguration; import org.opennaas.extensions.router.model.GRETunnelService; import com.sun.jersey.api.client.Client; import com.sun.jersey.api.client.ClientResponse; import com.sun.jersey.api.client.GenericType; import com.sun.jersey.api.client.WebResource; public class GRETunnelTest { private static final Logger LOGGER = Logger.getLogger(GRETunnelTest.class); public static void main(String[] args) throws FileNotFoundException, JAXBException { createGRETunnel(); deleteGRETunnel(); showGRETunnelConfiguration(); } /** * */ private static void createGRETunnel() { ClientResponse response = null; String url = "http://localhost:8888/opennaas/router/lolaM20/gretunnel/createGRETunnel"; try { Client client = Client.create(); WebResource webResource = client.resource(url); response = webResource.type(MediaType.APPLICATION_XML).post(ClientResponse.class, getGRETunnelService()); LOGGER.info("Response code: " + response.getStatus()); } catch (Exception e) { LOGGER.error(e.getMessage()); } } /** * */ private static void deleteGRETunnel() { ClientResponse response = null; String url = "http://localhost:8888/opennaas/router/lolaM20/gretunnel/deleteGRETunnel"; try { Client client = Client.create(); WebResource webResource = client.resource(url); response = webResource.type(MediaType.APPLICATION_XML).post(ClientResponse.class, getGRETunnelService()); LOGGER.info("Response code: " + response.getStatus()); } catch (Exception e) { LOGGER.error(e.getMessage()); } } /** * */ private static void showGRETunnelConfiguration() { List<GRETunnelService> response = null; String url = "http://localhost:8888/opennaas/router/lolaM20/gretunnel/showGRETunnelConfiguration"; GenericType<List<GRETunnelService>> genericType = new GenericType<List<GRETunnelService>>() { }; try { Client client = Client.create(); WebResource webResource = client.resource(url); response = webResource.accept(MediaType.APPLICATION_XML).post(genericType); LOGGER.info("Number of GRETunnels: " + response.size()); } catch (Exception e) { LOGGER.error(e.getMessage()); } } /** * @return */ private static GRETunnelService getGRETunnelService() { GRETunnelService greTunnelService = new GRETunnelService(); greTunnelService.setName("MyTunnelService"); greTunnelService.setEnabledState(EnabledState.OTHER); GRETunnelConfiguration greTunnelConfiguration = new GRETunnelConfiguration(); greTunnelConfiguration.setCaption("MyCaption"); greTunnelConfiguration.setInstanceID("MyInstanceId"); greTunnelService.setGRETunnelConfiguration(greTunnelConfiguration); return greTunnelService; } }
dana-i2cat/opennaas
utils/rest-client/src/test/java/org/opennaas/client/rest/GRETunnelTest.java
Java
lgpl-3.0
3,036
package examples.Bricklet.Moisture; import com.tinkerforge.BrickletMoisture; import com.tinkerforge.IPConnection; public class ExampleSimple { private static final String host = "localhost"; private static final int port = 4223; private static final String UID = "XYZ"; // Change to your UID // Note: To make the examples code cleaner we do not handle exceptions. Exceptions you // might normally want to catch are described in the documentation public static void main(String args[]) throws Exception { IPConnection ipcon = new IPConnection(); // Create IP connection BrickletMoisture al = new BrickletMoisture(UID, ipcon); // Create device object ipcon.connect(host, port); // Connect to brickd // Don't use device before ipcon is connected // Get current moisture value int moisture = al.getMoistureValue(); // Can throw com.tinkerforge.TimeoutException System.out.println("Moisture Value: " + moisture); System.console().readLine("Press key to exit\n"); ipcon.disconnect(); } }
jaggr2/ch.bfh.fbi.mobiComp.17herz
com.tinkerforge/src/examples/Bricklet/Moisture/ExampleSimple.java
Java
apache-2.0
1,020
/** * Copyright 2015 LinkedIn Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ package wherehows.ingestion.converters; import com.linkedin.events.metadata.DatasetIdentifier; import com.linkedin.events.metadata.DeploymentDetail; import com.linkedin.events.metadata.MetadataChangeEvent; import java.util.Collections; import org.testng.annotations.Test; import static org.testng.Assert.*; public class KafkaLogCompactionConverterTest { @Test public void testConvert() { MetadataChangeEvent event = new MetadataChangeEvent(); event.datasetIdentifier = new DatasetIdentifier(); event.datasetIdentifier.dataPlatformUrn = "urn:li:dataPlatform:kafka"; DeploymentDetail deployment = new DeploymentDetail(); deployment.additionalDeploymentInfo = Collections.singletonMap("EI", "compact"); event.deploymentInfo = Collections.singletonList(deployment); MetadataChangeEvent newEvent = new KafkaLogCompactionConverter().convert(event); assertEquals(newEvent.datasetIdentifier.dataPlatformUrn, "urn:li:dataPlatform:kafka-lc"); } @Test public void testNotConvert() { KafkaLogCompactionConverter converter = new KafkaLogCompactionConverter(); MetadataChangeEvent event = new MetadataChangeEvent(); event.datasetIdentifier = new DatasetIdentifier(); event.datasetIdentifier.dataPlatformUrn = "foo"; DeploymentDetail deployment = new DeploymentDetail(); deployment.additionalDeploymentInfo = Collections.singletonMap("EI", "compact"); event.deploymentInfo = Collections.singletonList(deployment); MetadataChangeEvent newEvent = converter.convert(event); assertEquals(newEvent.datasetIdentifier.dataPlatformUrn, "foo"); event.datasetIdentifier.dataPlatformUrn = "urn:li:dataPlatform:kafka"; event.deploymentInfo = null; newEvent = converter.convert(event); assertEquals(newEvent.datasetIdentifier.dataPlatformUrn, "urn:li:dataPlatform:kafka"); event.datasetIdentifier.dataPlatformUrn = "urn:li:dataPlatform:kafka"; deployment.additionalDeploymentInfo = Collections.singletonMap("EI", "delete"); event.deploymentInfo = Collections.singletonList(deployment); newEvent = converter.convert(event); assertEquals(newEvent.datasetIdentifier.dataPlatformUrn, "urn:li:dataPlatform:kafka"); } }
alyiwang/WhereHows
wherehows-ingestion/src/test/java/wherehows/ingestion/converters/KafkaLogCompactionConverterTest.java
Java
apache-2.0
2,728
/** * 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.util; import org.apache.camel.ContextTestSupport; import org.apache.camel.builder.RouteBuilder; import org.apache.camel.model.ModelHelper; /** * */ public class DumpModelAsXmlChoiceFilterRouteTest extends ContextTestSupport { public void testDumpModelAsXml() throws Exception { String xml = ModelHelper.dumpModelAsXml(context.getRouteDefinition("myRoute")); assertNotNull(xml); log.info(xml); assertTrue(xml.contains("<header>gold</header>")); assertTrue(xml.contains("<header>extra-gold</header>")); assertTrue(xml.contains("<simple>${body} contains Camel</simple>")); } @Override protected RouteBuilder createRouteBuilder() throws Exception { return new RouteBuilder() { @Override public void configure() throws Exception { from("direct:start").routeId("myRoute") .to("log:input") .choice() .when().header("gold") .to("mock:gold") .filter().header("extra-gold") .to("mock:extra-gold") .endChoice() .when().simple("${body} contains Camel") .to("mock:camel") .otherwise() .to("mock:other") .end() .to("mock:result"); } }; } }
engagepoint/camel
camel-core/src/test/java/org/apache/camel/util/DumpModelAsXmlChoiceFilterRouteTest.java
Java
apache-2.0
2,322
/** * 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.fineract.template.api; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.DefaultValue; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.PUT; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.Context; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.MultivaluedMap; import javax.ws.rs.core.UriInfo; import org.apache.fineract.commands.domain.CommandWrapper; import org.apache.fineract.commands.service.CommandWrapperBuilder; import org.apache.fineract.commands.service.PortfolioCommandSourceWritePlatformService; import org.apache.fineract.infrastructure.core.api.ApiRequestParameterHelper; import org.apache.fineract.infrastructure.core.data.CommandProcessingResult; import org.apache.fineract.infrastructure.core.serialization.ApiRequestJsonSerializationSettings; import org.apache.fineract.infrastructure.core.serialization.DefaultToApiJsonSerializer; import org.apache.fineract.infrastructure.security.service.PlatformSecurityContext; import org.apache.fineract.template.data.TemplateData; import org.apache.fineract.template.domain.Template; import org.apache.fineract.template.domain.TemplateEntity; import org.apache.fineract.template.domain.TemplateType; import org.apache.fineract.template.service.TemplateDomainService; import org.apache.fineract.template.service.TemplateMergeService; import org.codehaus.jackson.map.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Component; @Path("/templates") @Consumes({ MediaType.APPLICATION_JSON }) @Produces({ MediaType.APPLICATION_JSON }) @Component @Scope("singleton") public class TemplatesApiResource { private final Set<String> RESPONSE_TEMPLATES_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id")); private final Set<String> RESPONSE_TEMPLATE_DATA_PARAMETERS = new HashSet<>(Arrays.asList("id", "entities", "types", "template")); private final String RESOURCE_NAME_FOR_PERMISSION = "template"; private final PlatformSecurityContext context; private final DefaultToApiJsonSerializer<Template> toApiJsonSerializer; private final DefaultToApiJsonSerializer<TemplateData> templateDataApiJsonSerializer; private final ApiRequestParameterHelper apiRequestParameterHelper; private final TemplateDomainService templateService; private final TemplateMergeService templateMergeService; private final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService; @Autowired public TemplatesApiResource(final PlatformSecurityContext context, final DefaultToApiJsonSerializer<Template> toApiJsonSerializer, final DefaultToApiJsonSerializer<TemplateData> templateDataApiJsonSerializer, final ApiRequestParameterHelper apiRequestParameterHelper, final TemplateDomainService templateService, final TemplateMergeService templateMergeService, final PortfolioCommandSourceWritePlatformService commandsSourceWritePlatformService) { this.context = context; this.toApiJsonSerializer = toApiJsonSerializer; this.templateDataApiJsonSerializer = templateDataApiJsonSerializer; this.apiRequestParameterHelper = apiRequestParameterHelper; this.templateService = templateService; this.templateMergeService = templateMergeService; this.commandsSourceWritePlatformService = commandsSourceWritePlatformService; } @GET public String retrieveAll(@DefaultValue("-1") @QueryParam("typeId") final int typeId, @DefaultValue("-1") @QueryParam("entityId") final int entityId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.RESOURCE_NAME_FOR_PERMISSION); // FIXME - we dont use the ORM when doing fetches - we write SQL and // fetch through JDBC returning data to be serialized to JSON List<Template> templates = new ArrayList<>(); if (typeId != -1 && entityId != -1) { templates = this.templateService.getAllByEntityAndType(TemplateEntity.values()[entityId], TemplateType.values()[typeId]); } else { templates = this.templateService.getAll(); } final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, templates, this.RESPONSE_TEMPLATES_DATA_PARAMETERS); } @GET @Path("template") public String template(@Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.RESOURCE_NAME_FOR_PERMISSION); final TemplateData templateData = TemplateData.template(); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.templateDataApiJsonSerializer.serialize(settings, templateData, this.RESPONSE_TEMPLATES_DATA_PARAMETERS); } @POST public String createTemplate(final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().createTemplate().withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } @GET @Path("{templateId}") public String retrieveOne(@PathParam("templateId") final Long templateId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.RESOURCE_NAME_FOR_PERMISSION); final Template template = this.templateService.findOneById(templateId); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.toApiJsonSerializer.serialize(settings, template, this.RESPONSE_TEMPLATES_DATA_PARAMETERS); } @GET @Path("{templateId}/template") public String getTemplateByTemplate(@PathParam("templateId") final Long templateId, @Context final UriInfo uriInfo) { this.context.authenticatedUser().validateHasReadPermission(this.RESOURCE_NAME_FOR_PERMISSION); final TemplateData template = TemplateData.template(this.templateService.findOneById(templateId)); final ApiRequestJsonSerializationSettings settings = this.apiRequestParameterHelper.process(uriInfo.getQueryParameters()); return this.templateDataApiJsonSerializer.serialize(settings, template, this.RESPONSE_TEMPLATE_DATA_PARAMETERS); } @PUT @Path("{templateId}") public String saveTemplate(@PathParam("templateId") final Long templateId, final String apiRequestBodyAsJson) { final CommandWrapper commandRequest = new CommandWrapperBuilder().updateTemplate(templateId).withJson(apiRequestBodyAsJson).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } @DELETE @Path("{templateId}") public String deleteTemplate(@PathParam("templateId") final Long templateId) { final CommandWrapper commandRequest = new CommandWrapperBuilder().deleteTemplate(templateId).build(); final CommandProcessingResult result = this.commandsSourceWritePlatformService.logCommandSource(commandRequest); return this.toApiJsonSerializer.serialize(result); } @POST @Path("{templateId}") @Produces({ MediaType.TEXT_HTML }) public String mergeTemplate(@PathParam("templateId") final Long templateId, @Context final UriInfo uriInfo, final String apiRequestBodyAsJson) throws MalformedURLException, IOException { final Template template = this.templateService.findOneById(templateId); @SuppressWarnings("unchecked") final HashMap<String, Object> result = new ObjectMapper().readValue(apiRequestBodyAsJson, HashMap.class); final MultivaluedMap<String, String> parameters = uriInfo.getQueryParameters(); final Map<String, Object> parametersMap = new HashMap<>(); for (final Map.Entry<String, List<String>> entry : parameters.entrySet()) { if (entry.getValue().size() == 1) { parametersMap.put(entry.getKey(), entry.getValue().get(0)); } else { parametersMap.put(entry.getKey(), entry.getValue()); } } parametersMap.put("BASE_URI", uriInfo.getBaseUri()); parametersMap.putAll(result); return this.templateMergeService.compile(template, parametersMap); } }
RanjithKumar5550/RanMifos
fineract-provider/src/main/java/org/apache/fineract/template/api/TemplatesApiResource.java
Java
apache-2.0
9,902
/* * 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.jsmpp.bean; /** * This is simple DataCoding. Only contains Alphabet (DEFAULT and 8-bit) and * Message Class. * * @author uudashr * */ public class SimpleDataCoding implements DataCoding { private final Alphabet alphabet; private final MessageClass messageClass; /** * Construct Data Coding using default Alphabet and * {@link MessageClass#CLASS1} Message Class. */ public SimpleDataCoding() { this(Alphabet.ALPHA_DEFAULT, MessageClass.CLASS1); } /** * Construct Data Coding using specified Alphabet and Message Class. * * @param alphabet is the alphabet. Only support * {@link Alphabet#ALPHA_DEFAULT} and {@link Alphabet#ALPHA_8_BIT}. * @param messageClass * @throws IllegalArgumentException if alphabet is <tt>null</tt> or using * non {@link Alphabet#ALPHA_DEFAULT} and * {@link Alphabet#ALPHA_8_BIT} alphabet or * <code>messageClass</code> is null. */ public SimpleDataCoding(Alphabet alphabet, MessageClass messageClass) throws IllegalArgumentException { if (alphabet == null) { throw new IllegalArgumentException( "Alphabet is mandatory, can't be null"); } if (alphabet.equals(Alphabet.ALPHA_UCS2) || alphabet.isReserved()) { throw new IllegalArgumentException( "Supported alphabet for SimpleDataCoding does not include " + Alphabet.ALPHA_UCS2 + " or " + "reserved alphabet codes. Current alphabet is " + alphabet); } if (messageClass == null) { throw new IllegalArgumentException( "MessageClass is mandatory, can't be null"); } this.alphabet = alphabet; this.messageClass = messageClass; } public Alphabet getAlphabet() { return alphabet; } public MessageClass getMessageClass() { return messageClass; } public byte toByte() { // base byte is 11110xxx or 0xf0, others injected byte value = (byte)0xf0; value |= alphabet.value(); value |= messageClass.value(); return value; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((alphabet == null) ? 0 : alphabet.hashCode()); result = prime * result + ((messageClass == null) ? 0 : messageClass.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; SimpleDataCoding other = (SimpleDataCoding)obj; if (alphabet == null) { if (other.alphabet != null) return false; } else if (!alphabet.equals(other.alphabet)) return false; if (messageClass == null) { if (other.messageClass != null) return false; } else if (!messageClass.equals(other.messageClass)) return false; return true; } @Override public String toString() { return "DataCoding:" + (0xff & toByte()); } }
amdtelecom/jsmpp
jsmpp/src/main/java/org/jsmpp/bean/SimpleDataCoding.java
Java
apache-2.0
3,967
/* * Copyright 2013-2014 Richard M. Hightower * 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. * * __________ _____ __ .__ * \______ \ ____ ____ ____ /\ / \ _____ | | _|__| ____ ____ * | | _// _ \ / _ \ / \ \/ / \ / \\__ \ | |/ / |/ \ / ___\ * | | ( <_> | <_> ) | \ /\ / Y \/ __ \| <| | | \/ /_/ > * |______ /\____/ \____/|___| / \/ \____|__ (____ /__|_ \__|___| /\___ / * \/ \/ \/ \/ \/ \//_____/ * ____. ___________ _____ ______________.___. * | |____ ___ _______ \_ _____/ / _ \ / _____/\__ | | * | \__ \\ \/ /\__ \ | __)_ / /_\ \ \_____ \ / | | * /\__| |/ __ \\ / / __ \_ | \/ | \/ \ \____ | * \________(____ /\_/ (____ / /_______ /\____|__ /_______ / / ______| * \/ \/ \/ \/ \/ \/ */ package org.boon.validation.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, ElementType.TYPE, ElementType.FIELD } ) public @interface Email { String detailMessage() default ""; String summaryMessage() default ""; }
wprice/boon
boon/src/main/java/org/boon/validation/annotations/Email.java
Java
apache-2.0
2,011
/* * Copyright 2000-2015 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.usages.impl.rules; import com.intellij.openapi.project.Project; import com.intellij.openapi.roots.GeneratedSourcesFilter; import com.intellij.openapi.vfs.VirtualFile; import com.intellij.usageView.UsageInfo; import com.intellij.usageView.UsageViewBundle; import com.intellij.usages.*; import com.intellij.usages.rules.PsiElementUsage; import com.intellij.usages.rules.SingleParentUsageGroupingRule; import com.intellij.usages.rules.UsageInFile; import org.jetbrains.annotations.NonNls; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; /** * @author max */ public class NonCodeUsageGroupingRule extends SingleParentUsageGroupingRule { private final Project myProject; public NonCodeUsageGroupingRule(Project project) { myProject = project; } private static class CodeUsageGroup extends UsageGroupBase { private static final UsageGroup INSTANCE = new CodeUsageGroup(); private CodeUsageGroup() { super(0); } @Override @NotNull public String getText(UsageView view) { return view == null ? UsageViewBundle.message("node.group.code.usages") : view.getPresentation().getCodeUsagesString(); } public String toString() { //noinspection HardCodedStringLiteral return "CodeUsages"; } } private static class UsageInGeneratedCodeGroup extends UsageGroupBase { public static final UsageGroup INSTANCE = new UsageInGeneratedCodeGroup(); private UsageInGeneratedCodeGroup() { super(3); } @Override @NotNull public String getText(UsageView view) { return view == null ? UsageViewBundle.message("node.usages.in.generated.code") : view.getPresentation().getUsagesInGeneratedCodeString(); } public String toString() { return "UsagesInGeneratedCode"; } } private static class NonCodeUsageGroup extends UsageGroupBase { public static final UsageGroup INSTANCE = new NonCodeUsageGroup(); private NonCodeUsageGroup() { super(2); } @Override @NotNull public String getText(UsageView view) { return view == null ? UsageViewBundle.message("node.non.code.usages") : view.getPresentation().getNonCodeUsagesString(); } @Override public void update() { } public String toString() { //noinspection HardCodedStringLiteral return "NonCodeUsages"; } } private static class DynamicUsageGroup extends UsageGroupBase { public static final UsageGroup INSTANCE = new DynamicUsageGroup(); @NonNls private static final String DYNAMIC_CAPTION = "Dynamic usages"; public DynamicUsageGroup() { super(1); } @Override @NotNull public String getText(UsageView view) { if (view == null) { return DYNAMIC_CAPTION; } else { final String dynamicCodeUsagesString = view.getPresentation().getDynamicCodeUsagesString(); return dynamicCodeUsagesString == null ? DYNAMIC_CAPTION : dynamicCodeUsagesString; } } public String toString() { //noinspection HardCodedStringLiteral return "DynamicUsages"; } } @Nullable @Override protected UsageGroup getParentGroupFor(@NotNull Usage usage, @NotNull UsageTarget[] targets) { if (usage instanceof UsageInFile) { VirtualFile file = ((UsageInFile)usage).getFile(); if (file != null && GeneratedSourcesFilter.isGeneratedSourceByAnyFilter(file, myProject)) { return UsageInGeneratedCodeGroup.INSTANCE; } } if (usage instanceof PsiElementUsage) { if (usage instanceof UsageInfo2UsageAdapter) { final UsageInfo usageInfo = ((UsageInfo2UsageAdapter)usage).getUsageInfo(); if (usageInfo.isDynamicUsage()) { return DynamicUsageGroup.INSTANCE; } } if (((PsiElementUsage)usage).isNonCodeUsage()) { return NonCodeUsageGroup.INSTANCE; } else { return CodeUsageGroup.INSTANCE; } } return null; } }
signed/intellij-community
platform/usageView/src/com/intellij/usages/impl/rules/NonCodeUsageGroupingRule.java
Java
apache-2.0
4,612
/* * 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.gamelift.model.transform; import java.util.Map; import java.util.Map.Entry; import java.math.*; import java.nio.ByteBuffer; import com.amazonaws.services.gamelift.model.*; import com.amazonaws.transform.SimpleTypeJsonUnmarshallers.*; import com.amazonaws.transform.*; import com.fasterxml.jackson.core.JsonToken; import static com.fasterxml.jackson.core.JsonToken.*; /** * CreateAliasResult JSON Unmarshaller */ public class CreateAliasResultJsonUnmarshaller implements Unmarshaller<CreateAliasResult, JsonUnmarshallerContext> { public CreateAliasResult unmarshall(JsonUnmarshallerContext context) throws Exception { CreateAliasResult createAliasResult = new CreateAliasResult(); int originalDepth = context.getCurrentDepth(); String currentParentElement = context.getCurrentParentElement(); int targetDepth = originalDepth + 1; JsonToken token = context.getCurrentToken(); if (token == null) token = context.nextToken(); if (token == VALUE_NULL) return null; while (true) { if (token == null) break; if (token == FIELD_NAME || token == START_OBJECT) { if (context.testExpression("Alias", targetDepth)) { context.nextToken(); createAliasResult.setAlias(AliasJsonUnmarshaller .getInstance().unmarshall(context)); } } else if (token == END_ARRAY || token == END_OBJECT) { if (context.getLastParsedParentElement() == null || context.getLastParsedParentElement().equals( currentParentElement)) { if (context.getCurrentDepth() <= originalDepth) break; } } token = context.nextToken(); } return createAliasResult; } private static CreateAliasResultJsonUnmarshaller instance; public static CreateAliasResultJsonUnmarshaller getInstance() { if (instance == null) instance = new CreateAliasResultJsonUnmarshaller(); return instance; } }
flofreud/aws-sdk-java
aws-java-sdk-gamelift/src/main/java/com/amazonaws/services/gamelift/model/transform/CreateAliasResultJsonUnmarshaller.java
Java
apache-2.0
2,842
// Copyright 2017 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.android.desugar.io; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.io.ByteStreams; import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** Output provider is a zip file. */ class ZipOutputFileProvider implements OutputFileProvider { private final ZipOutputStream out; public ZipOutputFileProvider(Path root) throws IOException { out = new ZipOutputStream(new BufferedOutputStream(Files.newOutputStream(root))); } @Override public void copyFrom(String filename, InputFileProvider inputFileProvider) throws IOException { // TODO(bazel-team): Avoid de- and re-compressing resource files out.putNextEntry(inputFileProvider.getZipEntry(filename)); try (InputStream is = inputFileProvider.getInputStream(filename)) { ByteStreams.copy(is, out); } out.closeEntry(); } @Override public void write(String filename, byte[] content) throws IOException { checkArgument(filename.equals(DESUGAR_DEPS_FILENAME) || filename.endsWith(".class"), "Expect file to be copied: %s", filename); writeStoredEntry(out, filename, content); } @Override public void close() throws IOException { out.close(); } private static void writeStoredEntry(ZipOutputStream out, String filename, byte[] content) throws IOException { // Need to pre-compute checksum for STORED (uncompressed) entries) CRC32 checksum = new CRC32(); checksum.update(content); ZipEntry result = new ZipEntry(filename); result.setTime(0L); // Use stable timestamp Jan 1 1980 result.setCrc(checksum.getValue()); result.setSize(content.length); result.setCompressedSize(content.length); // Write uncompressed, since this is just an intermediary artifact that // we will convert to .dex result.setMethod(ZipEntry.STORED); out.putNextEntry(result); out.write(content); out.closeEntry(); } }
dropbox/bazel
src/tools/android/java/com/google/devtools/build/android/desugar/io/ZipOutputFileProvider.java
Java
apache-2.0
2,761
/** * JBoss, Home of Professional Open Source. * Copyright 2014-2022 Red Hat, Inc., and individual 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.jboss.pnc.coordinator.test; import org.jboss.pnc.common.json.ConfigurationParseException; import org.jboss.pnc.mock.repository.BuildConfigurationRepositoryMock; import org.jboss.pnc.model.BuildConfiguration; import org.jboss.pnc.model.BuildConfigurationSet; import org.jboss.pnc.enums.RebuildMode; import org.jboss.pnc.spi.datastore.DatastoreException; import org.jboss.pnc.spi.exception.CoreException; import org.junit.Before; import org.junit.Test; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.concurrent.TimeoutException; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; /** * Group consists of configA,config B and configC. <br/> * configC is independent, configB depends on configA. <br/> * * * config1 is an "outside" dependency of configA * * <p> * Author: Michal Szynkiewicz, michal.l.szynkiewicz@gmail.com Date: 9/14/16 Time: 12:09 PM * </p> */ public class OutsideGroupDependentConfigsTest extends AbstractDependentBuildTest { private BuildConfiguration config1; private BuildConfiguration configA; private BuildConfiguration configB; private BuildConfigurationSet configSet; @Before public void initialize() throws DatastoreException, ConfigurationParseException { config1 = buildConfig("1"); configA = buildConfig("A", config1); configB = buildConfig("B", configA); BuildConfiguration configC = buildConfig("C"); configSet = configSet(configA, configB, configC); buildConfigurationRepository = spy(new BuildConfigurationRepositoryMock()); when(buildConfigurationRepository.queryWithPredicates(any())) .thenReturn(new ArrayList<>(configSet.getBuildConfigurations())); super.initialize(); saveConfig(config1); configSet.getBuildConfigurations().forEach(this::saveConfig); insertNewBuildRecords(config1, configA, configB, configC); makeResult(configA).dependOn(config1); } @Test public void shouldNotRebuildIfDependencyIsNotRebuilt() throws CoreException, TimeoutException, InterruptedException { build(configSet, RebuildMode.IMPLICIT_DEPENDENCY_CHECK); waitForEmptyBuildQueue(); List<BuildConfiguration> configsWithTasks = getBuiltConfigs(); assertThat(configsWithTasks).isEmpty(); } @Test public void shouldRebuildOnlyDependent() throws CoreException, TimeoutException, InterruptedException { insertNewBuildRecords(config1); build(configSet, RebuildMode.IMPLICIT_DEPENDENCY_CHECK); waitForEmptyBuildQueue(); List<BuildConfiguration> configsWithTasks = getBuiltConfigs(); assertThat(configsWithTasks).hasSameElementsAs(Arrays.asList(configA, configB)); } }
project-ncl/pnc
build-coordinator/src/test/java/org/jboss/pnc/coordinator/test/OutsideGroupDependentConfigsTest.java
Java
apache-2.0
3,646
/* This file is part of SableCC ( http://sablecc.org ). * * See the NOTICE file distributed with this work for copyright information. * * 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.sablecc.sablecc.semantics; public class Context { private Grammar grammar; }
Herve-M/sablecc
src/org/sablecc/sablecc/semantics/Context.java
Java
apache-2.0
794
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.facebook.presto.operator; import com.facebook.presto.sql.planner.plan.PlanNodeId; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; import com.google.common.collect.ImmutableList; import io.airlift.units.DataSize; import io.airlift.units.Duration; import javax.annotation.Nullable; import javax.annotation.concurrent.Immutable; import java.util.Optional; import static com.google.common.base.Preconditions.checkArgument; import static io.airlift.units.DataSize.succinctBytes; import static java.util.Objects.requireNonNull; import static java.util.concurrent.TimeUnit.NANOSECONDS; @Immutable public class OperatorStats { private final int operatorId; private final PlanNodeId planNodeId; private final String operatorType; private final long totalDrivers; private final long addInputCalls; private final Duration addInputWall; private final Duration addInputCpu; private final Duration addInputUser; private final DataSize inputDataSize; private final long inputPositions; private final double sumSquaredInputPositions; private final long getOutputCalls; private final Duration getOutputWall; private final Duration getOutputCpu; private final Duration getOutputUser; private final DataSize outputDataSize; private final long outputPositions; private final Duration blockedWall; private final long finishCalls; private final Duration finishWall; private final Duration finishCpu; private final Duration finishUser; private final DataSize memoryReservation; private final DataSize systemMemoryReservation; private final Optional<BlockedReason> blockedReason; private final OperatorInfo info; @JsonCreator public OperatorStats( @JsonProperty("operatorId") int operatorId, @JsonProperty("planNodeId") PlanNodeId planNodeId, @JsonProperty("operatorType") String operatorType, @JsonProperty("totalDrivers") long totalDrivers, @JsonProperty("addInputCalls") long addInputCalls, @JsonProperty("addInputWall") Duration addInputWall, @JsonProperty("addInputCpu") Duration addInputCpu, @JsonProperty("addInputUser") Duration addInputUser, @JsonProperty("inputDataSize") DataSize inputDataSize, @JsonProperty("inputPositions") long inputPositions, @JsonProperty("sumSquaredInputPositions") double sumSquaredInputPositions, @JsonProperty("getOutputCalls") long getOutputCalls, @JsonProperty("getOutputWall") Duration getOutputWall, @JsonProperty("getOutputCpu") Duration getOutputCpu, @JsonProperty("getOutputUser") Duration getOutputUser, @JsonProperty("outputDataSize") DataSize outputDataSize, @JsonProperty("outputPositions") long outputPositions, @JsonProperty("blockedWall") Duration blockedWall, @JsonProperty("finishCalls") long finishCalls, @JsonProperty("finishWall") Duration finishWall, @JsonProperty("finishCpu") Duration finishCpu, @JsonProperty("finishUser") Duration finishUser, @JsonProperty("memoryReservation") DataSize memoryReservation, @JsonProperty("systemMemoryReservation") DataSize systemMemoryReservation, @JsonProperty("blockedReason") Optional<BlockedReason> blockedReason, @JsonProperty("info") OperatorInfo info) { checkArgument(operatorId >= 0, "operatorId is negative"); this.operatorId = operatorId; this.planNodeId = requireNonNull(planNodeId, "planNodeId is null"); this.operatorType = requireNonNull(operatorType, "operatorType is null"); this.totalDrivers = totalDrivers; this.addInputCalls = addInputCalls; this.addInputWall = requireNonNull(addInputWall, "addInputWall is null"); this.addInputCpu = requireNonNull(addInputCpu, "addInputCpu is null"); this.addInputUser = requireNonNull(addInputUser, "addInputUser is null"); this.inputDataSize = requireNonNull(inputDataSize, "inputDataSize is null"); checkArgument(inputPositions >= 0, "inputPositions is negative"); this.inputPositions = inputPositions; this.sumSquaredInputPositions = sumSquaredInputPositions; this.getOutputCalls = getOutputCalls; this.getOutputWall = requireNonNull(getOutputWall, "getOutputWall is null"); this.getOutputCpu = requireNonNull(getOutputCpu, "getOutputCpu is null"); this.getOutputUser = requireNonNull(getOutputUser, "getOutputUser is null"); this.outputDataSize = requireNonNull(outputDataSize, "outputDataSize is null"); checkArgument(outputPositions >= 0, "outputPositions is negative"); this.outputPositions = outputPositions; this.blockedWall = requireNonNull(blockedWall, "blockedWall is null"); this.finishCalls = finishCalls; this.finishWall = requireNonNull(finishWall, "finishWall is null"); this.finishCpu = requireNonNull(finishCpu, "finishCpu is null"); this.finishUser = requireNonNull(finishUser, "finishUser is null"); this.memoryReservation = requireNonNull(memoryReservation, "memoryReservation is null"); this.systemMemoryReservation = requireNonNull(systemMemoryReservation, "systemMemoryReservation is null"); this.blockedReason = blockedReason; this.info = info; } @JsonProperty public int getOperatorId() { return operatorId; } @JsonProperty public PlanNodeId getPlanNodeId() { return planNodeId; } @JsonProperty public String getOperatorType() { return operatorType; } @JsonProperty public long getTotalDrivers() { return totalDrivers; } @JsonProperty public long getAddInputCalls() { return addInputCalls; } @JsonProperty public Duration getAddInputWall() { return addInputWall; } @JsonProperty public Duration getAddInputCpu() { return addInputCpu; } @JsonProperty public Duration getAddInputUser() { return addInputUser; } @JsonProperty public DataSize getInputDataSize() { return inputDataSize; } @JsonProperty public long getInputPositions() { return inputPositions; } @JsonProperty public double getSumSquaredInputPositions() { return sumSquaredInputPositions; } @JsonProperty public long getGetOutputCalls() { return getOutputCalls; } @JsonProperty public Duration getGetOutputWall() { return getOutputWall; } @JsonProperty public Duration getGetOutputCpu() { return getOutputCpu; } @JsonProperty public Duration getGetOutputUser() { return getOutputUser; } @JsonProperty public DataSize getOutputDataSize() { return outputDataSize; } @JsonProperty public long getOutputPositions() { return outputPositions; } @JsonProperty public Duration getBlockedWall() { return blockedWall; } @JsonProperty public long getFinishCalls() { return finishCalls; } @JsonProperty public Duration getFinishWall() { return finishWall; } @JsonProperty public Duration getFinishCpu() { return finishCpu; } @JsonProperty public Duration getFinishUser() { return finishUser; } @JsonProperty public DataSize getMemoryReservation() { return memoryReservation; } @JsonProperty public DataSize getSystemMemoryReservation() { return systemMemoryReservation; } @JsonProperty public Optional<BlockedReason> getBlockedReason() { return blockedReason; } @Nullable @JsonProperty public OperatorInfo getInfo() { return info; } public OperatorStats add(OperatorStats... operators) { return add(ImmutableList.copyOf(operators)); } public OperatorStats add(Iterable<OperatorStats> operators) { long totalDrivers = this.totalDrivers; long addInputCalls = this.addInputCalls; long addInputWall = this.addInputWall.roundTo(NANOSECONDS); long addInputCpu = this.addInputCpu.roundTo(NANOSECONDS); long addInputUser = this.addInputUser.roundTo(NANOSECONDS); long inputDataSize = this.inputDataSize.toBytes(); long inputPositions = this.inputPositions; double sumSquaredInputPositions = this.sumSquaredInputPositions; long getOutputCalls = this.getOutputCalls; long getOutputWall = this.getOutputWall.roundTo(NANOSECONDS); long getOutputCpu = this.getOutputCpu.roundTo(NANOSECONDS); long getOutputUser = this.getOutputUser.roundTo(NANOSECONDS); long outputDataSize = this.outputDataSize.toBytes(); long outputPositions = this.outputPositions; long blockedWall = this.blockedWall.roundTo(NANOSECONDS); long finishCalls = this.finishCalls; long finishWall = this.finishWall.roundTo(NANOSECONDS); long finishCpu = this.finishCpu.roundTo(NANOSECONDS); long finishUser = this.finishUser.roundTo(NANOSECONDS); long memoryReservation = this.memoryReservation.toBytes(); long systemMemoryReservation = this.systemMemoryReservation.toBytes(); Optional<BlockedReason> blockedReason = this.blockedReason; Mergeable<OperatorInfo> base = getMergeableInfoOrNull(info); for (OperatorStats operator : operators) { checkArgument(operator.getOperatorId() == operatorId, "Expected operatorId to be %s but was %s", operatorId, operator.getOperatorId()); totalDrivers += operator.totalDrivers; addInputCalls += operator.getAddInputCalls(); addInputWall += operator.getAddInputWall().roundTo(NANOSECONDS); addInputCpu += operator.getAddInputCpu().roundTo(NANOSECONDS); addInputUser += operator.getAddInputUser().roundTo(NANOSECONDS); inputDataSize += operator.getInputDataSize().toBytes(); inputPositions += operator.getInputPositions(); sumSquaredInputPositions += operator.getSumSquaredInputPositions(); getOutputCalls += operator.getGetOutputCalls(); getOutputWall += operator.getGetOutputWall().roundTo(NANOSECONDS); getOutputCpu += operator.getGetOutputCpu().roundTo(NANOSECONDS); getOutputUser += operator.getGetOutputUser().roundTo(NANOSECONDS); outputDataSize += operator.getOutputDataSize().toBytes(); outputPositions += operator.getOutputPositions(); finishCalls += operator.getFinishCalls(); finishWall += operator.getFinishWall().roundTo(NANOSECONDS); finishCpu += operator.getFinishCpu().roundTo(NANOSECONDS); finishUser += operator.getFinishUser().roundTo(NANOSECONDS); blockedWall += operator.getBlockedWall().roundTo(NANOSECONDS); memoryReservation += operator.getMemoryReservation().toBytes(); systemMemoryReservation += operator.getSystemMemoryReservation().toBytes(); if (operator.getBlockedReason().isPresent()) { blockedReason = operator.getBlockedReason(); } OperatorInfo info = operator.getInfo(); if (base != null && info != null && base.getClass() == info.getClass()) { base = mergeInfo(base, info); } } return new OperatorStats( operatorId, planNodeId, operatorType, totalDrivers, addInputCalls, new Duration(addInputWall, NANOSECONDS).convertToMostSuccinctTimeUnit(), new Duration(addInputCpu, NANOSECONDS).convertToMostSuccinctTimeUnit(), new Duration(addInputUser, NANOSECONDS).convertToMostSuccinctTimeUnit(), succinctBytes(inputDataSize), inputPositions, sumSquaredInputPositions, getOutputCalls, new Duration(getOutputWall, NANOSECONDS).convertToMostSuccinctTimeUnit(), new Duration(getOutputCpu, NANOSECONDS).convertToMostSuccinctTimeUnit(), new Duration(getOutputUser, NANOSECONDS).convertToMostSuccinctTimeUnit(), succinctBytes(outputDataSize), outputPositions, new Duration(blockedWall, NANOSECONDS).convertToMostSuccinctTimeUnit(), finishCalls, new Duration(finishWall, NANOSECONDS).convertToMostSuccinctTimeUnit(), new Duration(finishCpu, NANOSECONDS).convertToMostSuccinctTimeUnit(), new Duration(finishUser, NANOSECONDS).convertToMostSuccinctTimeUnit(), succinctBytes(memoryReservation), succinctBytes(systemMemoryReservation), blockedReason, (OperatorInfo) base); } @SuppressWarnings("unchecked") private static Mergeable<OperatorInfo> getMergeableInfoOrNull(OperatorInfo info) { Mergeable<OperatorInfo> base = null; if (info instanceof Mergeable) { base = (Mergeable<OperatorInfo>) info; } return base; } @SuppressWarnings("unchecked") private static <T> Mergeable<T> mergeInfo(Mergeable<T> base, T other) { return (Mergeable<T>) base.mergeWith(other); } public OperatorStats summarize() { return new OperatorStats( operatorId, planNodeId, operatorType, totalDrivers, addInputCalls, addInputWall, addInputCpu, addInputUser, inputDataSize, inputPositions, sumSquaredInputPositions, getOutputCalls, getOutputWall, getOutputCpu, getOutputUser, outputDataSize, outputPositions, blockedWall, finishCalls, finishWall, finishCpu, finishUser, memoryReservation, systemMemoryReservation, blockedReason, (info != null && info.isFinal()) ? info : null); } }
marsorp/blog
presto166/presto-main/src/main/java/com/facebook/presto/operator/OperatorStats.java
Java
apache-2.0
15,302
/* * 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.client; import org.elasticsearch.ExceptionsHelper; import org.elasticsearch.action.ActionListener; import org.elasticsearch.action.GenericAction; import org.elasticsearch.action.admin.cluster.reroute.ClusterRerouteAction; import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotAction; import org.elasticsearch.action.admin.cluster.stats.ClusterStatsAction; import org.elasticsearch.action.admin.cluster.storedscripts.DeleteStoredScriptAction; import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheAction; import org.elasticsearch.action.admin.indices.create.CreateIndexAction; import org.elasticsearch.action.admin.indices.flush.FlushAction; import org.elasticsearch.action.admin.indices.stats.IndicesStatsAction; import org.elasticsearch.action.delete.DeleteAction; import org.elasticsearch.action.get.GetAction; import org.elasticsearch.action.index.IndexAction; import org.elasticsearch.action.search.SearchAction; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.common.xcontent.XContentType; import org.elasticsearch.env.Environment; import org.elasticsearch.test.ESTestCase; import org.elasticsearch.threadpool.ThreadPool; import java.util.HashMap; import java.util.Map; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.notNullValue; public abstract class AbstractClientHeadersTestCase extends ESTestCase { protected static final Settings HEADER_SETTINGS = Settings.builder() .put(ThreadContext.PREFIX + ".key1", "val1") .put(ThreadContext.PREFIX + ".key2", "val 2") .build(); private static final GenericAction[] ACTIONS = new GenericAction[] { // client actions GetAction.INSTANCE, SearchAction.INSTANCE, DeleteAction.INSTANCE, DeleteStoredScriptAction.INSTANCE, IndexAction.INSTANCE, // cluster admin actions ClusterStatsAction.INSTANCE, CreateSnapshotAction.INSTANCE, ClusterRerouteAction.INSTANCE, // indices admin actions CreateIndexAction.INSTANCE, IndicesStatsAction.INSTANCE, ClearIndicesCacheAction.INSTANCE, FlushAction.INSTANCE }; protected ThreadPool threadPool; private Client client; @Override public void setUp() throws Exception { super.setUp(); Settings settings = Settings.builder() .put(HEADER_SETTINGS) .put("path.home", createTempDir().toString()) .put("node.name", "test-" + getTestName()) .put(Environment.PATH_HOME_SETTING.getKey(), createTempDir().toString()) .build(); threadPool = new ThreadPool(settings); client = buildClient(settings, ACTIONS); } @Override public void tearDown() throws Exception { super.tearDown(); client.close(); terminate(threadPool); } protected abstract Client buildClient(Settings headersSettings, GenericAction[] testedActions); public void testActions() { // TODO this is a really shitty way to test it, we need to figure out a way to test all the client methods // without specifying each one (reflection doesn't as each action needs its own special settings, without // them, request validation will fail before the test is executed. (one option is to enable disabling the // validation in the settings??? - ugly and conceptually wrong) // choosing arbitrary top level actions to test client.prepareGet("idx", "type", "id").execute(new AssertingActionListener<>(GetAction.NAME, client.threadPool())); client.prepareSearch().execute(new AssertingActionListener<>(SearchAction.NAME, client.threadPool())); client.prepareDelete("idx", "type", "id").execute(new AssertingActionListener<>(DeleteAction.NAME, client.threadPool())); client.admin().cluster().prepareDeleteStoredScript("lang", "id").execute(new AssertingActionListener<>(DeleteStoredScriptAction.NAME, client.threadPool())); client.prepareIndex("idx", "type", "id").setSource("source", XContentType.JSON).execute(new AssertingActionListener<>(IndexAction.NAME, client.threadPool())); // choosing arbitrary cluster admin actions to test client.admin().cluster().prepareClusterStats().execute(new AssertingActionListener<>(ClusterStatsAction.NAME, client.threadPool())); client.admin().cluster().prepareCreateSnapshot("repo", "bck").execute(new AssertingActionListener<>(CreateSnapshotAction.NAME, client.threadPool())); client.admin().cluster().prepareReroute().execute(new AssertingActionListener<>(ClusterRerouteAction.NAME, client.threadPool())); // choosing arbitrary indices admin actions to test client.admin().indices().prepareCreate("idx").execute(new AssertingActionListener<>(CreateIndexAction.NAME, client.threadPool())); client.admin().indices().prepareStats().execute(new AssertingActionListener<>(IndicesStatsAction.NAME, client.threadPool())); client.admin().indices().prepareClearCache("idx1", "idx2").execute(new AssertingActionListener<>(ClearIndicesCacheAction.NAME, client.threadPool())); client.admin().indices().prepareFlush().execute(new AssertingActionListener<>(FlushAction.NAME, client.threadPool())); } public void testOverrideHeader() throws Exception { String key1Val = randomAlphaOfLength(5); Map<String, String> expected = new HashMap<>(); expected.put("key1", key1Val); expected.put("key2", "val 2"); client.threadPool().getThreadContext().putHeader("key1", key1Val); client.prepareGet("idx", "type", "id") .execute(new AssertingActionListener<>(GetAction.NAME, expected, client.threadPool())); client.admin().cluster().prepareClusterStats() .execute(new AssertingActionListener<>(ClusterStatsAction.NAME, expected, client.threadPool())); client.admin().indices().prepareCreate("idx") .execute(new AssertingActionListener<>(CreateIndexAction.NAME, expected, client.threadPool())); } protected static void assertHeaders(Map<String, String> headers, Map<String, String> expected) { assertNotNull(headers); assertEquals(expected.size(), headers.size()); for (Map.Entry<String, String> expectedEntry : expected.entrySet()) { assertEquals(headers.get(expectedEntry.getKey()), expectedEntry.getValue()); } } protected static void assertHeaders(ThreadPool pool) { assertHeaders(pool.getThreadContext().getHeaders(), (Map)HEADER_SETTINGS.getAsSettings(ThreadContext.PREFIX).getAsStructuredMap()); } public static class InternalException extends Exception { private final String action; public InternalException(String action) { this.action = action; } } protected static class AssertingActionListener<T> implements ActionListener<T> { private final String action; private final Map<String, String> expectedHeaders; private final ThreadPool pool; public AssertingActionListener(String action, ThreadPool pool) { this(action, (Map)HEADER_SETTINGS.getAsSettings(ThreadContext.PREFIX).getAsStructuredMap(), pool); } public AssertingActionListener(String action, Map<String, String> expectedHeaders, ThreadPool pool) { this.action = action; this.expectedHeaders = expectedHeaders; this.pool = pool; } @Override public void onResponse(T t) { fail("an internal exception was expected for action [" + action + "]"); } @Override public void onFailure(Exception t) { Throwable e = unwrap(t, InternalException.class); assertThat("expected action [" + action + "] to throw an internal exception", e, notNullValue()); assertThat(action, equalTo(((InternalException) e).action)); Map<String, String> headers = pool.getThreadContext().getHeaders(); assertHeaders(headers, expectedHeaders); } public Throwable unwrap(Throwable t, Class<? extends Throwable> exceptionType) { int counter = 0; Throwable result = t; while (!exceptionType.isInstance(result)) { if (result.getCause() == null) { return null; } if (result.getCause() == result) { return null; } if (counter++ > 10) { // dear god, if we got more than 10 levels down, WTF? just bail fail("Exception cause unwrapping ran for 10 levels: " + ExceptionsHelper.stackTrace(t)); return null; } result = result.getCause(); } return result; } } }
nezirus/elasticsearch
core/src/test/java/org/elasticsearch/client/AbstractClientHeadersTestCase.java
Java
apache-2.0
9,899
package org.jetbrains.plugins.scala.lang.formatter; import com.intellij.openapi.application.ApplicationManager; import com.intellij.openapi.command.CommandProcessor; import com.intellij.openapi.editor.Document; import com.intellij.openapi.editor.EditorFactory; import com.intellij.openapi.editor.impl.DocumentImpl; import com.intellij.openapi.util.TextRange; import com.intellij.openapi.util.io.FileUtil; import com.intellij.openapi.util.text.StringUtil; import com.intellij.psi.PsiDocumentManager; import com.intellij.psi.PsiFile; import com.intellij.psi.codeStyle.CodeStyleManager; import com.intellij.psi.codeStyle.CodeStyleSettings; import com.intellij.psi.codeStyle.CodeStyleSettingsManager; import com.intellij.psi.codeStyle.CommonCodeStyleSettings; import com.intellij.testFramework.LightIdeaTestCase; import com.intellij.util.IncorrectOperationException; import org.jetbrains.plugins.scala.ScalaLanguage; import org.jetbrains.plugins.scala.lang.formatting.settings.ScalaCodeStyleSettings; import org.jetbrains.plugins.scala.util.TestUtils; import java.io.File; import java.util.EnumMap; import java.util.Map; /** * Base class for java formatter tests that holds utility methods. * * @author Denis Zhdanov * @since Apr 27, 2010 6:26:29 PM */ //todo: almost duplicate from Java public abstract class AbstractScalaFormatterTestBase extends LightIdeaTestCase { protected enum Action {REFORMAT, INDENT} private interface TestFormatAction { void run(PsiFile psiFile, int startOffset, int endOffset); } private static final Map<Action, TestFormatAction> ACTIONS = new EnumMap<Action, TestFormatAction>(Action.class); static { ACTIONS.put(Action.REFORMAT, new TestFormatAction() { public void run(PsiFile psiFile, int startOffset, int endOffset) { CodeStyleManager.getInstance(getProject()).reformatText(psiFile, startOffset, endOffset); } }); ACTIONS.put(Action.INDENT, new TestFormatAction() { public void run(PsiFile psiFile, int startOffset, int endOffset) { CodeStyleManager.getInstance(getProject()).adjustLineIndent(psiFile, startOffset); } }); } private static final String BASE_PATH = TestUtils.getTestDataPath() + "/psi/formatter"; public TextRange myTextRange; public TextRange myLineRange; public CommonCodeStyleSettings getCommonSettings() { return getSettings().getCommonSettings(ScalaLanguage.INSTANCE); } public ScalaCodeStyleSettings getScalaSettings() { return getSettings().getCustomSettings(ScalaCodeStyleSettings.class); } public CodeStyleSettings getSettings() { return CodeStyleSettingsManager.getSettings(getProject()); } public CommonCodeStyleSettings.IndentOptions getIndentOptions() { return getCommonSettings().getIndentOptions(); } public void doTest() throws Exception { doTest(getTestName(false) + ".scala", getTestName(false) + "_after.scala"); } public void doTest(String fileNameBefore, String fileNameAfter) throws Exception { doTextTest(Action.REFORMAT, loadFile(fileNameBefore), loadFile(fileNameAfter)); } public void doTextTest(final String text, String textAfter) throws IncorrectOperationException { doTextTest(Action.REFORMAT, StringUtil.convertLineSeparators(text), StringUtil.convertLineSeparators(textAfter)); } public void doTextTest(final Action action, final String text, String textAfter) throws IncorrectOperationException { final PsiFile file = createFile("A.scala", text); if (myLineRange != null) { final DocumentImpl document = new DocumentImpl(text); myTextRange = new TextRange(document.getLineStartOffset(myLineRange.getStartOffset()), document.getLineEndOffset(myLineRange.getEndOffset())); } /* CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { performFormatting(file); } }); } }, null, null); assertEquals(prepareText(textAfter), prepareText(file.getText())); */ final PsiDocumentManager manager = PsiDocumentManager.getInstance(getProject()); final Document document = manager.getDocument(file); CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { document.replaceString(0, document.getTextLength(), text); manager.commitDocument(document); try { TextRange rangeToUse = myTextRange; if (rangeToUse == null) { rangeToUse = file.getTextRange(); } ACTIONS.get(action).run(file, rangeToUse.getStartOffset(), rangeToUse.getEndOffset()); } catch (IncorrectOperationException e) { assertTrue(e.getLocalizedMessage(), false); } } }); } }, "", ""); if (document == null) { fail("Don't expect the document to be null"); return; } assertEquals(prepareText(textAfter), prepareText(document.getText())); manager.commitDocument(document); assertEquals(prepareText(textAfter), prepareText(file.getText())); } //todo: was unused, should be deleted (??) /* public void doMethodTest(final String before, final String after) throws Exception { doTextTest( Action.REFORMAT, "class Foo{\n" + " void foo() {\n" + before + '\n' + " }\n" + "}", "class Foo {\n" + " void foo() {\n" + shiftIndentInside(after, 8, false) + '\n' + " }\n" + "}" ); } public void doClassTest(final String before, final String after) throws Exception { doTextTest( Action.REFORMAT, "class Foo{\n" + before + '\n' + "}", "class Foo {\n" + shiftIndentInside(after, 4, false) + '\n' + "}" ); }*/ private static String prepareText(String actual) { if (actual.startsWith("\n")) { actual = actual.substring(1); } if (actual.startsWith("\n")) { actual = actual.substring(1); } // Strip trailing spaces final Document doc = EditorFactory.getInstance().createDocument(actual); CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() { public void run() { ApplicationManager.getApplication().runWriteAction(new Runnable() { public void run() { ((DocumentImpl)doc).stripTrailingSpaces(getProject()); } }); } }, "formatting", null); return doc.getText().trim(); } private static String loadFile(String name) throws Exception { String fullName = BASE_PATH + File.separatorChar + name; String text = new String(FileUtil.loadFileText(new File(fullName))); text = StringUtil.convertLineSeparators(text); return text; } @Override protected void setUp() throws Exception { super.setUp(); TestUtils.disableTimerThread(); } }
ilinum/intellij-scala
test/org/jetbrains/plugins/scala/lang/formatter/AbstractScalaFormatterTestBase.java
Java
apache-2.0
7,072