repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
jmccrae/naisc
core/src/main/java/org/insightcentre/unlp/naisc/util/Vectors.java
1100
package org.insightcentre.unlp.naisc.util; import it.unimi.dsi.fastutil.ints.Int2DoubleMap; /** * Tools for working with vectors * * @author John McCrae <john@mccr.ae> */ public class Vectors { private Vectors() {} /** * Calculate the cosine of two vectors * @param _v1 Vector 1 * @param _v2 Vector 2 * @return Sum(x*y)/(norm(x)*norm(y)) */ public static double cosine(Vector _v1, Vector _v2) { final Vector v1 = _v1.size() < _v2.size() ? _v1 : _v2; final Vector v2 = _v1.size() < _v2.size() ? _v2 : _v1; if(v1.len() != v2.len()) throw new LinearAlgebraException(String.format("Vector lengths do not match %d <-> %d", v1.len(), v2.len())); double aa = 0, ab = 0; for(Int2DoubleMap.Entry s : v1.sparseEntrySet()) { aa += s.getDoubleValue()*s.getDoubleValue(); ab += s.getDoubleValue()*v2.getDouble(s.getIntKey()); } final double bnorm = v2.norm(); if(aa == 0 && bnorm == 0) { return 0.0; } else { return ab / Math.sqrt(aa) / bnorm; } } }
gpl-2.0
PauloLuan/android-dynamic-form
dynamic-form/src/terracore/formgenerator/autocompletetext/AsyncAutoCompleteQuery.java
4618
/** * * Based on DatabaseAutoCompleteLibrary by Joseph Rios * * https://github.com/alotau/DatabaseAutoCompleteLibrary * * * */ package terracore.formgenerator.autocompletetext; import java.util.List; import terracore.formgenerator.database.DatabaseDao; import android.content.Context; import android.database.Cursor; import android.os.AsyncTask; import android.util.Log; public class AsyncAutoCompleteQuery extends AsyncTask<String, Integer, Cursor> { private final String LOG_TAG = getClass().getSimpleName(); private AutoCompleteListener caller; private Context context; /* Query Properties */ private String databaseName; boolean distinct; private String tableName; private String[] selectColumns; private List<String> whereColumns; private String selection; private String matchingText; private String[] selectionArgs; private String groupBy; private String having; private String orderBy; private int limit = 30; private String limitStr = "30"; public AsyncAutoCompleteQuery( AutoCompleteListener caller, Context context, String databaseName, boolean distinct, String tableName, String[] columns, List<String> whereColumns, String matchingText, String[] selectionArgs, String groupBy, String having, String orderBy, int limit) { this.caller = caller; this.context = context; this.databaseName = databaseName; this.distinct = distinct; this.tableName = tableName; this.selectColumns = columns; this.whereColumns = whereColumns; this.matchingText = matchingText; this.selectionArgs = selectionArgs; this.groupBy = groupBy; this.having = having; this.orderBy = orderBy; this.limit = limit; this.limitStr = String.valueOf(limit); this.execute(); } @Override protected Cursor doInBackground(String... params) { //String[] selectColumns = columnNames.toArray(new String[columnNames.size()]); selection = generateLikeClause(); Cursor cursor = DatabaseDao.generateCursor(context, databaseName, distinct, tableName, params, selection, params, groupBy, having, orderBy, limitStr); return cursor; } /** * Where / Like clause. */ public String generateLikeClause() { String selection = ""; for (int i = 0; i < whereColumns.size(); i++) { selection += whereColumns.get(i) + " LIKE '%" + matchingText + "%'"; if (i != whereColumns.size() - 1) { selection += " OR "; } } return selection; } @Override protected void onCancelled() { super.onCancelled(); } @Override protected void onPostExecute(Cursor cursor) { Log.i(LOG_TAG, "Quantidade de registros: " + cursor.getCount()); if (cursor != null) { caller.onCompletion(cursor); //myDbHelper.close(); } else { Log.d("AsyncQuery", "db was null."); caller.onCompletion(null); } } }
gpl-2.0
cybertk/blackberry-linphone
submodules/jliblinphone/submodules/externals/sip-for-me/src/sip4me/gov/nist/javax/sdp/fields/PhoneField.java
2497
/******************************************************************************* * Product of NIST/ITL Advanced Networking Technologies Division (ANTD). * *******************************************************************************/ package sip4me.gov.nist.javax.sdp.fields; import sip4me.gov.nist.core.Separators; import sip4me.gov.nist.javax.sdp.SdpException; import sip4me.gov.nist.javax.sdp.SdpParseException; /** * Phone Field SDP header * *@version JSR141-PUBLIC-REVIEW (subject to change). * *@author Olivier Deruelle <deruelle@antd.nist.gov> *@author M. Ranganathan <mranga@nist.gov> <br/> * *<a href="{@docRoot}/uncopyright.html">This code is in the public domain.</a> * */ public class PhoneField extends SDPField { protected String name; protected String phoneNumber; public Object clone() { PhoneField retval = new PhoneField(); retval.name = this.name; retval.phoneNumber = this.phoneNumber; return retval; } public PhoneField() { super(PHONE_FIELD); } public String getName() { return name ; } public String getPhoneNumber() { return phoneNumber ; } /** * Set the name member * *@param name - the name to set. */ public void setName(String name) { this.name = name ; } /** * Set the phoneNumber member *@param phoneNumber - phone number to set. */ public void setPhoneNumber(String phoneNumber) { this.phoneNumber = phoneNumber ; } /** Returns the value. * @throws SdpParseException * @return the value. */ public String getValue() throws SdpParseException { return getName(); } /** Sets the value. * @param value the - new information. * @throws SdpException if the value is null */ public void setValue(String value) throws SdpException{ if (value==null) throw new SdpException("The value parameter is null"); else setName(value); } /** * Get the string encoded version of this object * @since v1.0 * Here, we implement only the "name <phoneNumber>" form * and not the "phoneNumber (name)" form */ public String encode() { String encoded_string; encoded_string = PHONE_FIELD; if (name != null) { encoded_string += name + Separators.LESS_THAN; } encoded_string += phoneNumber; if (name != null) { encoded_string += Separators.GREATER_THAN; } encoded_string += Separators.NEWLINE; return encoded_string; } }
gpl-2.0
retanoj/J2EEScan
src/main/java/burp/j2ee/CustomScanIssue.java
2020
package burp.j2ee; import burp.IHttpRequestResponse; import burp.IHttpService; import burp.IScanIssue; import java.net.URL; public class CustomScanIssue implements IScanIssue { private IHttpService httpService; private URL url; private IHttpRequestResponse httpMessages; private String name; private String detail; private Risk severity; private String remedy; private Confidence confidence = Confidence.Certain; public CustomScanIssue( IHttpService httpService, URL url, IHttpRequestResponse httpMessages, String name, String detail, String remedy, Risk severity, Confidence confidence) { this.httpService = httpService; this.url = url; this.httpMessages = httpMessages; this.name = name; this.detail = detail; this.remedy = remedy; this.severity = severity; this.confidence = confidence; } @Override public URL getUrl() { return url; } @Override public String getIssueName() { return name; } @Override public int getIssueType() { return 0; } @Override public String getSeverity() { return severity.toString(); } @Override // "Certain", "Firm" or "Tentative" public String getConfidence() { return confidence.toString(); } @Override public String getIssueBackground() { return null; } @Override public String getRemediationBackground() { return null; } @Override public String getIssueDetail() { return detail; } @Override public String getRemediationDetail() { return remedy; } @Override public IHttpRequestResponse[] getHttpMessages() { return new IHttpRequestResponse[]{httpMessages}; } @Override public IHttpService getHttpService() { return httpService; } }
gpl-2.0
BIORIMP/biorimp
BIO-RIMP/test_data/code/cio/src/main/java/org/apache/commons/io/filefilter/CanReadFileFilter.java
2980
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.filefilter; import java.io.File; import java.io.Serializable; /** * This filter accepts <code>File</code>s that can be read. * <p> * Example, showing how to print out a list of the * current directory's <i>readable</i> files: * * <pre> * File dir = new File("."); * String[] files = dir.list( CanReadFileFilter.CAN_READ ); * for ( int i = 0; i &lt; files.length; i++ ) { * System.out.println(files[i]); * } * </pre> * * <p> * Example, showing how to print out a list of the * current directory's <i>un-readable</i> files: * * <pre> * File dir = new File("."); * String[] files = dir.list( CanReadFileFilter.CANNOT_READ ); * for ( int i = 0; i &lt; files.length; i++ ) { * System.out.println(files[i]); * } * </pre> * * <p> * Example, showing how to print out a list of the * current directory's <i>read-only</i> files: * * <pre> * File dir = new File("."); * String[] files = dir.list( CanReadFileFilter.READ_ONLY ); * for ( int i = 0; i &lt; files.length; i++ ) { * System.out.println(files[i]); * } * </pre> * * @since 1.3 * @version $Id: CanReadFileFilter.java 1304052 2012-03-22 20:55:29Z ggregory $ */ public class CanReadFileFilter extends AbstractFileFilter implements Serializable { /** Singleton instance of <i>readable</i> filter */ public static final IOFileFilter CAN_READ = new CanReadFileFilter(); /** Singleton instance of not <i>readable</i> filter */ public static final IOFileFilter CANNOT_READ = new NotFileFilter(CAN_READ); /** Singleton instance of <i>read-only</i> filter */ public static final IOFileFilter READ_ONLY = new AndFileFilter(CAN_READ, CanWriteFileFilter.CANNOT_WRITE); /** * Restrictive consructor. */ protected CanReadFileFilter() { } /** * Checks to see if the file can be read. * * @param file the File to check. * @return <code>true</code> if the file can be * read, otherwise <code>false</code>. */ @Override public boolean accept(File file) { return file.canRead(); } }
gpl-2.0
ElvisLouis/code
work/java/ROBOT/src/ANN/AttitudeAnalysis.java
1167
package ANN; import java.io.UnsupportedEncodingException; import knowcreater.Rule; import knowcreater.Tool; public class AttitudeAnalysis { private BP bpPositive, bpNegative; private static double sum = 0; public AttitudeAnalysis() { bpPositive = Tool.getPositiveBP(); bpNegative = Tool.getNegativeBP(); } private BP getPositive() { return bpPositive; } private BP getNegative() { return bpNegative; } public double query() throws UnsupportedEncodingException { String input = ""; for (int i = 0, length = Rule.getWord().length; i < length; i++) { input = Rule.getWord()[i].getWord(); Tool.getPrintWriter().println(Tool.getResult(getPositive().test(Tool.getDoubleMatrix(Tool.changeCode(input))), true) + "\t is the positive ."); Tool.getPrintWriter().println(Tool.getResult(getNegative().test(Tool.getDoubleMatrix(Tool.changeCode(input))), false) + "\t is the negative ."); sum += (Tool.getResult(getPositive().test(Tool.getDoubleMatrix(Tool.changeCode(input))), true) - Tool.getResult(getNegative().test(Tool.getDoubleMatrix(Tool.changeCode(input))), false)); } return sum; } }
gpl-2.0
megagorilla/Containing
ContainingController/test/nhl/containing/server/pathfinding/GraphTest.java
3298
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package nhl.containing.server.pathfinding; import com.jme3.math.Vector3f; import java.util.ArrayList; import java.util.List; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import static org.junit.Assert.*; /** * * @author Sander */ public class GraphTest { public GraphTest() { } @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { } @After public void tearDown() { } /** * Test of dijkstra method, of class Graph. * not testable */ // @Test // public void testDijkstra() { // System.out.println("dijkstra"); // String startName = "a1"; // Graph instance = new Graph(ShortestPath.GRAPH); // instance.dijkstra(startName); // // String startName2 = ""; // Graph instance2 = new Graph(ShortestPath.GRAPH); // instance2.dijkstra(startName2); // } /** * Test of printPath method, of class Graph. */ @Test public void testPrintPath() { System.out.println("printPath"); String startName = "a1"; String endNameRight = "a2"; String endNameWrong = "wrongAtPringPath"; Graph instance = new Graph(ShortestPath.GRAPH); instance.dijkstra(startName); List<Vector3f> list = instance.getLocations(endNameRight); if(list == null) { fail("The list is empty while endName is righ"); } instance = new Graph(ShortestPath.GRAPH); instance.dijkstra(startName); List<Vector3f> list2 = instance.getLocations(endNameWrong); if(list2 != null){ fail("The list is not empty while endName is wrong"); } } /** * Test of getLocations method, of class Graph. */ @Test public void testGetLocations() { System.out.println("getLocations"); String endNameRight = "d4"; String endNameWrong = "wrongAtGetLocations"; Graph instance = new Graph(ShortestPath.GRAPH); instance.dijkstra("a1"); List expResultRight = new ArrayList(); expResultRight.add(new Vector3f(303.5f, 0.0f, -778.5f)); expResultRight.add(new Vector3f(316.5f, 0.0f, -791.5f)); expResultRight.add(new Vector3f(-316.5f, 0.0f, -791.5f)); expResultRight.add(new Vector3f(-303.5f, 0.0f, -778.5f)); List result = instance.getLocations(endNameRight); assertEquals(expResultRight, result); Graph instance2 = new Graph(ShortestPath.GRAPH); instance.dijkstra("a1"); List result2 = instance2.getLocations(endNameWrong); assertNull(result2); } /** * Test of printAllPaths method, of class Graph. * Not Used and not testable */ // @Test // public void testPrintAllPaths() { // System.out.println("printAllPaths"); // Graph instance = new Graph(ShortestPath.GRAPH); // instance.printAllPaths(); // // } }
gpl-2.0
jeffgdotorg/opennms
features/collection/shell-commands/src/main/java/org/opennms/netmgt/collection/commands/ListCollectors.java
2002
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2017-2017 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2017 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.collection.commands; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service; import org.opennms.netmgt.collection.api.ServiceCollectorRegistry; @Command(scope = "opennms", name = "list-collectors", description = "Lists all of the available collectors.") @Service public class ListCollectors implements Action { @Reference private ServiceCollectorRegistry registry; @Override public Object execute() throws Exception { registry.getCollectorClassNames().stream().sorted().forEachOrdered(e -> { System.out.printf("%s\n", e); }); return null; } }
gpl-2.0
lucasmends/einfachJSON
src/com/lucasmends/einfachjson/parser/core/concrete/MapAtributeParser.java
787
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.lucasmends.einfachjson.parser.core.concrete; import com.lucasmends.einfachjson.criteria.CriteriaBuilder; import com.lucasmends.einfachjson.parser.core.TemplateAtributeParser; /** * * @author lucas */ public class MapAtributeParser extends TemplateAtributeParser{ public MapAtributeParser(){ super(); this.accepetdType = CriteriaBuilder.mapType(); } @Override protected String value(Object value) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
gpl-2.0
hwan2z/springTest01
SpringMVCOrder/src/main/java/com/hwan/order/domain/OrderItem.java
474
package com.hwan.order.domain; public class OrderItem { private long id; private int amount; private Product product; public long getId() { return id; } public void setId(long id) { this.id = id; } public int getAmount() { return amount; } public void setAmount(int amount) { this.amount = amount; } public Product getProduct() { return product; } public void setProduct(Product product) { this.product = product; } }
gpl-2.0
joetopshot/freeplane
freeplane/src/main/java/org/freeplane/features/nodestyle/NodeStyleController.java
16879
/* * Freeplane - mind map editor * Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev * * This file is created by Dimitry Polivaev in 2008. * * 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/>. */ package org.freeplane.features.nodestyle; import java.awt.Color; import java.awt.Font; import java.util.Collection; import org.freeplane.core.extension.IExtension; import org.freeplane.core.io.ReadManager; import org.freeplane.core.io.WriteManager; import org.freeplane.core.resources.ResourceController; import org.freeplane.core.ui.LengthUnits; import org.freeplane.core.util.Quantity; import org.freeplane.features.map.MapController; import org.freeplane.features.map.MapModel; import org.freeplane.features.map.NodeModel; import org.freeplane.features.mode.CombinedPropertyChain; import org.freeplane.features.mode.Controller; import org.freeplane.features.mode.ExclusivePropertyChain; import org.freeplane.features.mode.IPropertyHandler; import org.freeplane.features.mode.ModeController; import org.freeplane.features.nodestyle.NodeStyleModel.Shape; import org.freeplane.features.nodestyle.NodeStyleModel.TextAlign; import org.freeplane.features.styles.IStyle; import org.freeplane.features.styles.LogicalStyleController; import org.freeplane.features.styles.MapStyleModel; /** * @author Dimitry Polivaev */ public class NodeStyleController implements IExtension { public static Color standardNodeTextColor = Color.BLACK; public static NodeStyleController getController() { final ModeController modeController = Controller.getCurrentModeController(); return getController(modeController); } public static NodeStyleController getController(ModeController modeController) { return (NodeStyleController) modeController.getExtension(NodeStyleController.class); } public static void install( final NodeStyleController styleController) { final ModeController modeController = Controller.getCurrentModeController(); modeController.addExtension(NodeStyleController.class, styleController); } final private ExclusivePropertyChain<Color, NodeModel> backgroundColorHandlers; // // // final private Controller controller; final private CombinedPropertyChain<Font, NodeModel> fontHandlers; final private ModeController modeController; final private ExclusivePropertyChain<ShapeConfigurationModel, NodeModel> shapeHandlers; final private ExclusivePropertyChain<Color, NodeModel> textColorHandlers; final private ExclusivePropertyChain<TextAlign, NodeModel> textAlignHandlers; public static final String NODE_NUMBERING = "NodeNumbering"; private static final Quantity<LengthUnits> DEFAULT_MINIMUM_WIDTH = new Quantity<LengthUnits>(0, LengthUnits.cm); private static final Quantity<LengthUnits> DEFAULT_MAXIMUM_WIDTH = new Quantity<LengthUnits>(10, LengthUnits.cm); public NodeStyleController(final ModeController modeController) { this.modeController = modeController; // controller = modeController.getController(); fontHandlers = new CombinedPropertyChain<Font, NodeModel>(true); textColorHandlers = new ExclusivePropertyChain<Color, NodeModel>(); backgroundColorHandlers = new ExclusivePropertyChain<Color, NodeModel>(); shapeHandlers = new ExclusivePropertyChain<ShapeConfigurationModel, NodeModel>(); textAlignHandlers = new ExclusivePropertyChain<TextAlign, NodeModel>(); addFontGetter(IPropertyHandler.DEFAULT, new IPropertyHandler<Font, NodeModel>() { public Font getProperty(final NodeModel node, final Font currentValue) { final Font defaultFont = NodeStyleController.getDefaultFont(); return defaultFont; } }); addFontGetter(IPropertyHandler.STYLE, new IPropertyHandler<Font, NodeModel>() { public Font getProperty(final NodeModel node, final Font currentValue) { final Font defaultFont = getStyleFont(currentValue, node.getMap(), LogicalStyleController.getController(modeController).getStyles(node)); return defaultFont; } }); addColorGetter(IPropertyHandler.DEFAULT, new IPropertyHandler<Color, NodeModel>() { public Color getProperty(final NodeModel node, final Color currentValue) { return standardNodeTextColor; } }); addColorGetter(IPropertyHandler.STYLE, new IPropertyHandler<Color, NodeModel>() { public Color getProperty(final NodeModel node, final Color currentValue) { return getStyleTextColor(node.getMap(), LogicalStyleController.getController(modeController).getStyles(node)); } }); addBackgroundColorGetter(IPropertyHandler.STYLE, new IPropertyHandler<Color, NodeModel>() { public Color getProperty(final NodeModel node, final Color currentValue) { return getStyleBackgroundColor(node.getMap(), LogicalStyleController.getController(modeController).getStyles(node)); } }); addShapeGetter(IPropertyHandler.STYLE, new IPropertyHandler<ShapeConfigurationModel, NodeModel>() { public ShapeConfigurationModel getProperty(final NodeModel node, final ShapeConfigurationModel currentValue) { final MapModel map = node.getMap(); final LogicalStyleController styleController = LogicalStyleController.getController(modeController); final Collection<IStyle> style = styleController.getStyles(node); final ShapeConfigurationModel returnedShape = getStyleShape(map, style); return returnedShape; } }); addShapeGetter(IPropertyHandler.DEFAULT, new IPropertyHandler<ShapeConfigurationModel, NodeModel>() { public ShapeConfigurationModel getProperty(final NodeModel node, final ShapeConfigurationModel currentValue) { return ShapeConfigurationModel.AS_PARENT; } }); addTextAlignGetter(IPropertyHandler.DEFAULT, new IPropertyHandler<TextAlign, NodeModel>() { public TextAlign getProperty(final NodeModel node, final TextAlign currentValue) { return TextAlign.DEFAULT; } }); addTextAlignGetter(IPropertyHandler.STYLE, new IPropertyHandler<TextAlign, NodeModel>() { public TextAlign getProperty(final NodeModel node, final TextAlign currentValue) { return getTextAlign(node.getMap(), LogicalStyleController.getController(modeController).getStyles(node)); } }); final MapController mapController = modeController.getMapController(); final ReadManager readManager = mapController.getReadManager(); final WriteManager writeManager = mapController.getWriteManager(); final NodeStyleBuilder styleBuilder = new NodeStyleBuilder(this); styleBuilder.registerBy(readManager, writeManager); } public IPropertyHandler<Color, NodeModel> addBackgroundColorGetter(final Integer key, final IPropertyHandler<Color, NodeModel> getter) { return backgroundColorHandlers.addGetter(key, getter); } public IPropertyHandler<Color, NodeModel> addColorGetter(final Integer key, final IPropertyHandler<Color, NodeModel> getter) { return textColorHandlers.addGetter(key, getter); } public IPropertyHandler<TextAlign, NodeModel> addTextAlignGetter(final Integer key, final IPropertyHandler<TextAlign, NodeModel> getter) { return textAlignHandlers.addGetter(key, getter); } public IPropertyHandler<Font, NodeModel> addFontGetter(final Integer key, final IPropertyHandler<Font, NodeModel> getter) { return fontHandlers.addGetter(key, getter); } public IPropertyHandler<ShapeConfigurationModel, NodeModel> addShapeGetter(final Integer key, final IPropertyHandler<ShapeConfigurationModel, NodeModel> getter) { return shapeHandlers.addGetter(key, getter); } public Color getBackgroundColor(final NodeModel node) { return backgroundColorHandlers.getProperty(node); } public Color getColor(final NodeModel node) { return textColorHandlers.getProperty(node); } private Color getStyleBackgroundColor(final MapModel map, final Collection<IStyle> styleKeys) { final MapStyleModel model = MapStyleModel.getExtension(map); for(IStyle styleKey : styleKeys){ final NodeModel styleNode = model.getStyleNode(styleKey); if (styleNode == null) { continue; } final NodeStyleModel styleModel = NodeStyleModel.getModel(styleNode); if (styleModel == null) { continue; } final Color styleColor =styleModel.getBackgroundColor(); if (styleColor == null) { continue; } return styleColor; } return null; } private Quantity<LengthUnits> getStyleMaxNodeWidth(final MapModel map, final Collection<IStyle> styleKeys) { final MapStyleModel model = MapStyleModel.getExtension(map); for(IStyle styleKey : styleKeys){ final NodeModel styleNode = model.getStyleNode(styleKey); if (styleNode == null) { continue; } final NodeSizeModel sizeModel = NodeSizeModel.getModel(styleNode); if (sizeModel == null) { continue; } final Quantity<LengthUnits> maxTextWidth = sizeModel.getMaxNodeWidth(); if (maxTextWidth == null) { continue; } return maxTextWidth; } return DEFAULT_MAXIMUM_WIDTH; } private Quantity<LengthUnits> getStyleMinWidth(final MapModel map, final Collection<IStyle> styleKeys) { final MapStyleModel model = MapStyleModel.getExtension(map); for(IStyle styleKey : styleKeys){ final NodeModel styleNode = model.getStyleNode(styleKey); if (styleNode == null) { continue; } final NodeSizeModel sizeModel = NodeSizeModel.getModel(styleNode); if (sizeModel == null) { continue; } final Quantity<LengthUnits> minWidth = sizeModel.getMinNodeWidth(); if (minWidth == null) { continue; } return minWidth; } return DEFAULT_MINIMUM_WIDTH; } public static Font getDefaultFont() { final int fontSize = NodeStyleController.getDefaultFontSize(); final int fontStyle = NodeStyleController.getDefaultFontStyle(); final String fontFamily = NodeStyleController.getDefaultFontFamilyName(); return new Font(fontFamily, fontStyle, fontSize); } /** */ private static String getDefaultFontFamilyName() { return ResourceController.getResourceController().getProperty("defaultfont"); } private static int getDefaultFontStyle() { return ResourceController.getResourceController().getIntProperty("defaultfontstyle", 0); } private static int getDefaultFontSize() { return ResourceController.getResourceController().getIntProperty("defaultfontsize", 10); } public Font getDefaultFont(final MapModel map, final IStyle style) { final MapStyleModel model = MapStyleModel.getExtension(map); final NodeModel styleNode = model.getStyleNodeSafe(style); return getFont(styleNode); } private Font getStyleFont(final Font baseFont, final MapModel map, final Collection<IStyle> collection) { final MapStyleModel model = MapStyleModel.getExtension(map); Boolean bold = null; Boolean italic = null; String fontFamilyName = null; Integer fontSize = null; for(IStyle styleKey : collection){ final NodeModel styleNode = model.getStyleNode(styleKey); if (styleNode == null) { continue; } final NodeStyleModel styleModel = NodeStyleModel.getModel(styleNode); if (styleModel == null) { continue; } if (bold == null) bold = styleModel.isBold(); if (italic == null) italic = styleModel.isItalic(); if (fontFamilyName == null) fontFamilyName = styleModel.getFontFamilyName(); if (fontSize == null) fontSize = styleModel.getFontSize(); if(bold != null && italic != null && fontFamilyName != null && fontSize != null) break; } return createFont(baseFont, fontFamilyName, fontSize, bold, italic); } public TextAlign getTextAlign(final NodeModel node) { return textAlignHandlers.getProperty(node); } private Font createFont(final Font baseFont, String family, Integer size, Boolean bold, Boolean italic) { if (family == null && size == null && bold == null && italic == null) { return baseFont; } if (family == null) { family = baseFont.getFamily(); } if (size == null) { size = baseFont.getSize(); } if (bold == null) { bold = baseFont.isBold(); } if (italic == null) { italic = baseFont.isItalic(); } int style = 0; if (bold) { style += Font.BOLD; } if (italic) { style += Font.ITALIC; } return new Font(family, style, size); } private ShapeConfigurationModel getStyleShape(final MapModel map, final Collection<IStyle> style) { final MapStyleModel model = MapStyleModel.getExtension(map); for(IStyle styleKey : style){ final NodeModel styleNode = model.getStyleNode(styleKey); if (styleNode == null) { continue; } final NodeStyleModel styleModel = NodeStyleModel.getModel(styleNode); if (styleModel == null) { continue; } final ShapeConfigurationModel shapeConfiguration = styleModel.getShapeConfiguration(); if (shapeConfiguration.getShape() == null) { continue; } return shapeConfiguration; } return null; } private Color getStyleTextColor(final MapModel map, final Collection<IStyle> collection) { final MapStyleModel model = MapStyleModel.getExtension(map); for(IStyle styleKey : collection){ final NodeModel styleNode = model.getStyleNode(styleKey); if (styleNode == null) { continue; } final NodeStyleModel styleModel = NodeStyleModel.getModel(styleNode); if (styleModel == null) { continue; } final Color styleColor = styleModel == null ? null : styleModel.getColor(); if (styleColor == null) { continue; } return styleColor; } return null; } private TextAlign getTextAlign(final MapModel map, final Collection<IStyle> style) { final MapStyleModel model = MapStyleModel.getExtension(map); for(IStyle styleKey : style){ final NodeModel styleNode = model.getStyleNode(styleKey); if (styleNode == null) { continue; } final NodeStyleModel styleModel = NodeStyleModel.getModel(styleNode); if (styleModel == null) { continue; } final TextAlign textAlign = styleModel.getTextAlign(); if (textAlign == null) { continue; } return textAlign; } return null; } public Font getFont(final NodeModel node) { final Font font = fontHandlers.getProperty(node, null); return font; } public String getFontFamilyName(final NodeModel node) { final Font font = getFont(node); return font.getFamily(); } public int getFontSize(final NodeModel node) { final Font font = getFont(node); return font.getSize(); } public Shape getShape(final NodeModel node) { final ShapeConfigurationModel shapeConfiguration = shapeHandlers.getProperty(node); return shapeConfiguration.getShape(); } public ShapeConfigurationModel getShapeConfiguration(NodeModel node) { final ShapeConfigurationModel shapeConfiguration = shapeHandlers.getProperty(node); return shapeConfiguration; } public boolean isBold(final NodeModel node) { return getFont(node).isBold(); } public boolean isItalic(final NodeModel node) { return getFont(node).isItalic(); } public Boolean getNodeNumbering(NodeModel node) { final NodeStyleModel style = (NodeStyleModel) node.getExtension(NodeStyleModel.class); if (style == null) return false; final Boolean nodeNumbering = style.getNodeNumbering(); return nodeNumbering == null ? false : nodeNumbering.booleanValue(); } public String getNodeFormat(NodeModel node) { final NodeStyleModel style = (NodeStyleModel) node.getExtension(NodeStyleModel.class); return style == null ? null : style.getNodeFormat(); } public Quantity<LengthUnits> getMaxWidth(NodeModel node) { final MapModel map = node.getMap(); final LogicalStyleController styleController = LogicalStyleController.getController(modeController); final Collection<IStyle> style = styleController.getStyles(node); final Quantity<LengthUnits> maxTextWidth = getStyleMaxNodeWidth(map, style); return maxTextWidth; } public Quantity<LengthUnits> getMinWidth(NodeModel node) { final MapModel map = node.getMap(); final LogicalStyleController styleController = LogicalStyleController.getController(modeController); final Collection<IStyle> style = styleController.getStyles(node); final Quantity<LengthUnits> minWidth = getStyleMinWidth(map, style); return minWidth; } public ModeController getModeController() { return modeController; } }
gpl-2.0
Hafiz-Waleed-Hussain/hull-isb
android-hull/Civichackathon/Hull/app/src/main/java/com/highndry/hull/fragments/FragmentOne.java
4116
package com.highndry.hull.fragments; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.os.AsyncTask; import android.os.Bundle; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.ListView; import com.facebook.HttpMethod; import com.facebook.Request; import com.facebook.Response; import com.facebook.model.GraphObject; import com.facebook.model.GraphUser; import com.highndry.hull.MissionDetailActivity_; import com.highndry.hull.R; import com.highndry.hull.adapters.CustomMissionAdapter; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseFacebookUtils; import com.parse.ParseObject; import com.parse.ParseQuery; import com.parse.ParseUser; import com.parse.SignUpCallback; import com.pkmmte.view.CircularImageView; import com.squareup.picasso.Picasso; import org.androidannotations.annotations.EFragment; import org.androidannotations.annotations.UiThread; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedInputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import java.util.ArrayList; import java.util.List; /** * Created by ahmadalinasir on 2/21/15. * */ @EFragment public class FragmentOne extends Fragment { CustomMissionAdapter customMissionAdapter; ListView missionList; private FrameLayout mFrameOverlay; List<ParseObject> missionsCopy; //ParseObject parseObject; @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_one, container, false); //customMissionAdapter = new CustomMissionAdapter() missionList = (ListView) rootView.findViewById(R.id.missionList); mFrameOverlay = (FrameLayout) rootView.findViewById(R.id.overlay); ParseQuery<ParseObject> query = ParseQuery.getQuery("Mission"); setProgressDialog(true); query.findInBackground(new FindCallback<ParseObject>() { public void done(List<ParseObject> missions, ParseException e) { if (e == null) { setProgressDialog(false); missionsCopy = new ArrayList<ParseObject>(); missionsCopy = missions; customMissionAdapter = new CustomMissionAdapter(getActivity(),R.layout.mission_item,missions); missionList.setAdapter(customMissionAdapter); Log.d("missions", "Retrieved " + missions.size() + " missions"); } else { //Log.d("score", "Error: " + e.getMessage()); } } }); /*Bundle bundle = new Bundle(); bundle.putString("fields", "picture.type(large),quotes,email,first_name,last_name,username");*/ //profilePicture = (CircularImageView) rootView.findViewById(R.id.profilePicture); //makeMeRequest(); missionList.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent intent = new Intent(getActivity(), MissionDetailActivity_.class); intent.putExtra("title",missionsCopy.get(position).getString("title")); startActivity(intent); } }); return rootView; } @UiThread void setProgressDialog(boolean progress){ if (progress) { mFrameOverlay.setVisibility(View.VISIBLE); } else { mFrameOverlay.setVisibility(View.GONE); } } }
gpl-2.0
danielfm/obexftp-frontend
obexftp-frontend-core/src/test/java/net/sourceforge/obexftpfrontend/command/OBEXFTPCommandQueueEventTest.java
765
package net.sourceforge.obexftpfrontend.command; import org.jmock.Mockery; import org.junit.Test; import static org.junit.Assert.*; /** * OBEXFTPCommandQueueEvent test cases. * @author Daniel F. Martins */ public class OBEXFTPCommandQueueEventTest { private Mockery context = new Mockery(); @Test public void testCreate() { OBEXFTPCommand command = context.mock(OBEXFTPCommand.class); OBEXFTPCommandLifecycleEvent evt = new OBEXFTPCommandLifecycleEvent(command, "Some result", OBEXFTPCommandLifecycleEvent.ExecutionStatus.ADDED); assertSame(evt.getCommand(), command); assertEquals("Some result", evt.getResult()); assertEquals(OBEXFTPCommandLifecycleEvent.ExecutionStatus.ADDED, evt.getStatus()); } }
gpl-2.0
tunnelvisionlabs/goworks
go.project/src/org/tvl/goworks/project/testing/nodes/GoCallstackFrameNode.java
710
/* * Copyright (c) 2012 Sam Harwell, Tunnel Vision Laboratories LLC * All rights reserved. * * The source code of this document is proprietary work, and is not licensed for * distribution. For information about licensing, contact Sam Harwell at: * sam@tunnelvisionlabs.com */ package org.tvl.goworks.project.testing.nodes; import org.netbeans.modules.gsf.testrunner.api.CallstackFrameNode; /** * * @author Sam Harwell */ public class GoCallstackFrameNode extends CallstackFrameNode { public GoCallstackFrameNode(String frameInfo, String dispayName) { super(frameInfo, dispayName); } public GoCallstackFrameNode(String frameInfo) { super(frameInfo); } }
gpl-2.0
mihangram/Source
TMessagesProj/src/main/java/org/telegram/ui/Components/ChipSpan.java
1423
package org.telegram.ui.Components; import android.graphics.Paint; import android.graphics.Paint.FontMetricsInt; import android.graphics.drawable.Drawable; import android.text.style.ImageSpan; import org.telegram.messenger.AndroidUtilities; public class ChipSpan extends ImageSpan { public int uid; public ChipSpan(Drawable paramDrawable, int paramInt) { super(paramDrawable, paramInt); } public int getSize(Paint paramPaint, CharSequence paramCharSequence, int paramInt1, int paramInt2, Paint.FontMetricsInt paramFontMetricsInt) { Paint.FontMetricsInt localFontMetricsInt = paramFontMetricsInt; if (paramFontMetricsInt == null) { localFontMetricsInt = new Paint.FontMetricsInt(); } paramInt1 = super.getSize(paramPaint, paramCharSequence, paramInt1, paramInt2, localFontMetricsInt); paramInt2 = AndroidUtilities.dp(6.0F); int i = (localFontMetricsInt.bottom - localFontMetricsInt.top) / 2; localFontMetricsInt.top = (-i - paramInt2); localFontMetricsInt.bottom = (i - paramInt2); localFontMetricsInt.ascent = (-i - paramInt2); localFontMetricsInt.leading = 0; localFontMetricsInt.descent = (i - paramInt2); return paramInt1; } } /* Location: C:\Users\Armandl\Downloads\Compressed\dex2jar-2.0\classes-dex2jar.jar!\org\telegram\ui\Components\ChipSpan.class * Java compiler version: 6 (50.0) * JD-Core Version: 0.7.1 */
gpl-2.0
pmarches/bitcoop
unittest/bcoop/blocktracker/BlockTrackerAllTests.java
634
/** * <p>Title: BlockTrackerAllTests.java</p> * <p>Copyright: Copyright (c) 2005</p> * @author Philippe Marchesseault * @version 1.0 */ package bcoop.blocktracker; import junit.framework.Test; import junit.framework.TestSuite; /** * @author pmarches * */ public class BlockTrackerAllTests { public static Test suite() { TestSuite suite = new TestSuite("Test for bcoop.blocktracker"); //$JUnit-BEGIN$ suite.addTestSuite(BlockTrackerTest.class); suite.addTestSuite(BlockTrackerArchiverTest.class); suite.addTestSuite(TransactionHistoryTest.class); //$JUnit-END$ return suite; } }
gpl-2.0
Ruilx/TestJava
HelloComponent3.java
1591
import javax.swing.*; import java.awt.*; import java.awt.event.*; public class Jframe { public static void main( String args[] ){ System.out.println("Test JFrame..."); JFrame frame = new JFrame("HelloJava3"); frame.setSize(300, 250); frame.add( new HelloComponent3("我是吕鼎东!!来打我啊!!") ); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setVisible(true); } } class HelloComponent3 extends JComponent implements MouseMotionListener, ActionListener{ String theMessage; int messageX = 125, messageY = 95; JButton theButton; int colorIndex; static Color[] someColors = { Color.black, Color.red, Color.green, Color.blue, Color.magenta }; public HelloComponent3( String message ){ theMessage = message; theButton = new JButton("改变颜色"); setLayout( new FlowLayout() ); add( theButton ); theButton.addActionListener( this ); addMouseMotionListener( this ); } public void paintComponent( Graphics g ){ g.drawString(theMessage, messageX, messageY); } public void mouseDragged( MouseEvent e ){ messageX = e.getX(); messageY = e.getY(); repaint(); } public void mouseMoved( MouseEvent e ){ messageX = e.getX(); messageY = e.getY(); repaint(); } public void actionPerformed( ActionEvent e ){ if( e.getSource() == theButton ){ changeColor(); } } synchronized private void changeColor(){ if( ++colorIndex == someColors.length ){ colorIndex = 0; } setForeground( currentColor() ); repaint(); } synchronized private Color currentColor(){ return someColors[colorIndex]; } }
gpl-2.0
ckelsel/design
design/src/com/design/decorator/Soy.java
1119
/** * Copyright (C) 2015 KunMing Xie <ckelsel@hotmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package com.design.decorator; public class Soy extends CondimentDecorator { Beverage mBeverage; public Soy(Beverage beverage) { mBeverage = beverage; } @Override public String getDescprition() { return mBeverage.getDescprition() + " Soy"; } @Override public double cost() { return mBeverage.cost() + 0.3f; } }
gpl-2.0
hou80houzhu/rocserver
src/main/java/com/rocui/jmsger/base/result/ResultSet.java
2065
package com.rocui.jmsger.base.result; public class ResultSet { public static int RESULT_SUCCESS = 1; public static int RUSUTL_ERROR = 0; private Result result; private String routName; private String routType; public ResultSet() { this.result=new Result(); } public Result getResult(){ return this.result; } public ResultSet setTo(String to) { this.result.setTo(to); return this; } public ResultSet setCode(int code) { this.result.setCode(code); return this; } public ResultSet setData(Object data) { this.result.setData(data); return this; } public String getTo() { return this.result.getTo(); } public int getCode() { return this.result.getCode(); } public Object getData() { return this.result.getData(); } public String getRoutName() { return routName; } public ResultSet setRoutName(String routName) { this.routName = routName; return this; } public String getRoutType() { return routType; } public ResultSet setRoutType(String routType) { this.routType = routType; return this; } public ResultSet setService(String service){ this.result.setService(service); return this; } public ResultSet setSessionId(String sessionId){ this.result.setSessionId(sessionId); return this; } public ResultSet setGroupId(String groupId){ this.result.setGroupId(groupId); return this; } public ResultSet setCallbackIndex(String callbackIndex){ this.result.setCallbackIndex(callbackIndex); return this; } public ResultSet setOther(String other){ this.result.setOther(other); return this; } public ResultSet setFrom(String from){ this.result.setFrom(from); return this; } }
gpl-2.0
jmmut/opencga
opencga-lib/src/main/java/org/opencb/opencga/lib/common/TimeUtils.java
1140
package org.opencb.opencga.lib.common; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; import java.util.GregorianCalendar; public class TimeUtils { public static String getTime() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); return sdf.format(new Date()); } public static String getTimeMillis() { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS"); return sdf.format(new Date()); } public static Date add24HtoDate(Date date) { Calendar cal = new GregorianCalendar(); cal.setTime(date); cal.setTimeInMillis(date.getTime());// sumamos 24h a la fecha del login cal.add(Calendar.DATE, 1); return new Date(cal.getTimeInMillis()); } public static Date toDate(String dateStr) { Date now = null; try { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); now = sdf.parse(dateStr); } catch (ParseException e) { e.printStackTrace(); } return now; } }
gpl-2.0
SampleSizeShop/JavaStatistics
src/edu/cudenver/bios/power/test/paper/TestHotellingLawleyExactUnconditional.java
8954
/* * Java Statistics. A java library providing power/sample size estimation for * the general linear model. * * Copyright (C) 2010 Regents of the University of Colorado. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package edu.cudenver.bios.power.test.paper; import java.io.File; import junit.framework.TestCase; import org.apache.commons.math3.linear.Array2DRowRealMatrix; import org.apache.commons.math3.linear.MatrixUtils; import edu.cudenver.bios.matrix.FixedRandomMatrix; import edu.cudenver.bios.power.glmm.GLMMTestFactory.Test; import edu.cudenver.bios.power.parameters.GLMMPowerParameters; import edu.cudenver.bios.power.parameters.GLMMPowerParameters.PowerMethod; import edu.cudenver.bios.power.test.PowerChecker; import edu.cudenver.bios.power.test.ValidationReportBuilder; /** * Test case for exact unconditional power for the HLT. Values should match * exact unconditional power values from Table II in Glueck & Muller 2003. * * @author Sarah Kreidler * */ public class TestHotellingLawleyExactUnconditional extends TestCase { private static final String DATA_FILE = "data" + File.separator + "TestHotellingLawleyExactUnconditional.xml"; private static final String OUTPUT_FILE = "text" + File.separator + "results" + File.separator + "HotellingLawleyExactUnconditionalOutput.tex"; private static final String TITLE = "GLMM(F, g) Example 4. Unconditional power for the " + "Hotelling-Lawley Trace, using Davies algorithm"; private static final double MEAN = 9.75; private static final double VARIANCE = 1.0; private static final double[] ALPHA_LIST = {0.05}; private static final double[] SIGMA_SCALE_LIST = {1}; private static final String AUTHOR = "Sarah Kreidler"; private static final String STUDY_DESIGN_DESCRIPTION = "The study design in Example 4 is a three sample design with " + "a baseline covariate and four repeated measurements. We calculate " + "the unconditional power for a test of no difference between groups at each " + "time point, using the Hotelling-Lawley Trace test. " + "The exact distribution of the test statistic under the alternative hypothesis is obtained " + "using Davies' algorithm described in \n\n" + "\\hangindent2em\n\\hangafter=1\n Davies, R. B. (1980). " + "Algorithm AS 155: The Distribution of a Linear Combination " + "of Chi-Square Random Variables. \\emph{Applied Statistics}, " + "\\emph{29}(3), 323-333.\n\n" + "Unconditional power is calculated for the following combinations " + "of mean differences and per group sample sizes.\n\n" + "\\begin{enumerate}" + "\\item Per group sample size of 5, with beta scale values " + "0.4997025, 0.8075886, and 1.097641" + "\\item Per group sample size of 25, with beta scale values " + "0.1651525, 0.2623301, and 0.3508015" + "\\item Per group sample size of 50, with beta scale values " + "0.1141548, 0.1812892, and 0.2423835\n" + "\\end{enumerate}\n\n" + "The example is based on Table II from\n\n" + "\\hangindent2em\n\\hangafter=1\n Glueck, D. H., \\& Muller, K. E. (2003). " + "Adjusting power for a baseline covariate in linear models. \\emph{Statistics " + "in Medicine}, \\emph{22}(16), 2535-2551.\n\n"; private PowerChecker checker; public void setUp() { try { checker = new PowerChecker(DATA_FILE, true); } catch (Exception e) { System.err.println("Setup failed: " + e.getMessage()); fail(); } } /** * Compare the calculated HLT exact unconditional powers against simulation */ public void testPower() { // build the inputs double[] beta5 = { 0.4997025, 0.8075886, 1.097641}; GLMMPowerParameters params5 = buildValidMultivariateRandomInputs(beta5, 5); double[] beta25 = { 0.1651525, 0.2623301, 0.3508015 }; GLMMPowerParameters params25 = buildValidMultivariateRandomInputs(beta25, 25); double[] beta50 = { 0.1141548, 0.1812892, 0.2423835 }; GLMMPowerParameters params50 = buildValidMultivariateRandomInputs(beta50, 50); checker.checkPower(params5); checker.checkPower(params25); checker.checkPower(params50); // output the results try { // clear the beta scale list and per group N since this is described in the // study design section and may be confusing if we list all the beta scales // twice. params50.clearBetaScaleList(); params50.clearSampleSizeList(); ValidationReportBuilder reportBuilder = new ValidationReportBuilder(); reportBuilder.createValidationReportAsStdout(checker, TITLE, false); reportBuilder.createValidationReportAsLaTex( OUTPUT_FILE, TITLE, AUTHOR, STUDY_DESIGN_DESCRIPTION, params50, checker); } catch (Exception e) { System.err.println(e.getMessage()); } assertTrue(checker.isSASDeviationBelowTolerance()); checker.reset(); } /** * Builds matrices for a multivariate GLM with a baseline covariate * Note, this matrix set matches the values produced in Table II from Glueck&Muller */ private GLMMPowerParameters buildValidMultivariateRandomInputs(double[] betaScaleList, int repn) { GLMMPowerParameters params = new GLMMPowerParameters(); params.setNonCentralityCDFExact(true); // add unconditional power methods and median unconditional params.addPowerMethod(PowerMethod.UNCONDITIONAL_POWER); // add HLT as the statistical test params.addTest(Test.HOTELLING_LAWLEY_TRACE); // add alpha values for(double alpha: ALPHA_LIST) params.addAlpha(alpha); // create design matrix params.setDesignEssence(MatrixUtils.createRealIdentityMatrix(3)); // add sample size multipliers // for(int sampleSize: SAMPLE_SIZE_LIST) params.addSampleSize(sampleSize); params.addSampleSize(repn); // build sigma G matrix double[][] sigmaG = {{VARIANCE}}; params.setSigmaGaussianRandom(new Array2DRowRealMatrix(sigmaG)); // build sigma Y matrix double [][] sigmaY = {{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}}; params.setSigmaOutcome(new Array2DRowRealMatrix(sigmaY)); // build sigma YG double [][] sigmaYG = {{0.5},{0.5}, {0.5}, {0}}; params.setSigmaOutcomeGaussianRandom(new Array2DRowRealMatrix(sigmaYG)); // add sigma scale values for(double sigmaScale: SIGMA_SCALE_LIST) params.addSigmaScale(sigmaScale); // build beta matrix double [][] beta = {{1,0,0,0},{0,2,0,0},{0,0,0,0}}; double [][] betaRandom = {{1,1,1,1}}; params.setBeta(new FixedRandomMatrix(beta, betaRandom, false)); // add beta scale values for(double betaScale: betaScaleList) params.addBetaScale(betaScale); // build theta null matrix double [][] theta0 = {{0,0,0,0},{0,0,0,0}}; params.setTheta(new Array2DRowRealMatrix(theta0)); // build between subject contrast double [][] between = {{-1,1,0}, {-1,0,1}}; double[][] betweenRandom = {{0}, {0}}; params.setBetweenSubjectContrast(new FixedRandomMatrix(between, betweenRandom, true)); // build within subject contrast double [][] within = {{1,0,0,0},{0,1,0,0},{0,0,1,0},{0,0,0,1}}; params.setWithinSubjectContrast(new Array2DRowRealMatrix(within)); return params; } }
gpl-2.0
ssaenz/ActividadesDAW
modulo05/sesion05/src/modulo05/servlet/CochesManager.java
2076
package modulo05.servlet; import java.io.IOException; import java.util.Enumeration; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import modulo05.bean.CocheBean; import modulo05.database.DBManager; /** * Servlet implementation class CochesManager */ @WebServlet("/CochesManager") public class CochesManager extends HttpServlet { private static final long serialVersionUID = 1L; private static final String MATRICULA = "matricula"; private static final String NUMERO_PLAZAS = "numPlazas"; private static final String CIF_EMPRESA = "cif"; /** * @see HttpServlet#HttpServlet() */ public CochesManager() { super(); } @Override protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.service(request, response); String actionButton = request.getParameter("button"); if ("añadir".equals(actionButton)) { String matricula = request.getParameter(MATRICULA); int numPlazas = Integer.parseInt(request.getParameter(NUMERO_PLAZAS)); int cif = Integer.parseInt(request.getParameter(CIF_EMPRESA)); CocheBean coche = new CocheBean(); coche.setMatricula(matricula); coche.setCifEmpresa(cif); coche.setNumeroPlazas(numPlazas); DBManager.getInstance().createCoche(coche); } } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub } }
gpl-2.0
popovici-gabriel/projects
rx-samples/src/main/java/com/rx/samples/using/rx/UserService.java
528
package com.rx.samples.using.rx; import rx.Observer; import rx.functions.Action1; /** * User interface main contract * - add user */ public interface UserService { /** * Add user * * @param username SID * @param emailAddress JPMC email address */ void addUser(String username, String emailAddress); /** * Subscribe using a custom Observer * * @param subscriber {@link rx.Observer} subscriber */ void subsribeToUserEvents(Observer<UserEvent> subscriber); }
gpl-2.0
TheTypoMaster/Scaper
openjdk/langtools/test/tools/javah/6572945/T6572945.java
8898
/* * Copyright 2007 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ /* * @test * @bug 6572945 * @summary rewrite javah as an annotation processor, instead of as a doclet * @build TestClass1 TestClass2 TestClass3 * @run main T6572945 */ import java.io.*; import java.util.*; import com.sun.tools.javah.Main; public class T6572945 { static File testSrc = new File(System.getProperty("test.src", ".")); static File testClasses = new File(System.getProperty("test.classes", ".")); static boolean isWindows = System.getProperty("os.name").startsWith("Windows"); public static void main(String... args) throws IOException, InterruptedException { boolean ok = new T6572945().run(args); if (!ok) throw new Error("Test Failed"); } public boolean run(String[] args) throws IOException, InterruptedException { if (args.length == 1) jdk = new File(args[0]); test("-o", "jni.file.1", "-jni", "TestClass1"); test("-o", "jni.file.2", "-jni", "TestClass1", "TestClass2"); test("-d", "jni.dir.1", "-jni", "TestClass1", "TestClass2"); test("-o", "jni.file.3", "-jni", "TestClass3"); // The following tests are disabled because llni support has been // discontinued, and because bugs in old javah means that character // for character testing against output from old javah does not work. // In fact, the LLNI impl in new javah is actually better than the // impl in old javah because of a couple of significant bug fixes. // test("-o", "llni.file.1", "-llni", "TestClass1"); // test("-o", "llni.file.2", "-llni", "TestClass1", "TestClass2"); // test("-d", "llni.dir.1", "-llni", "TestClass1", "TestClass2"); // test("-o", "llni.file.3", "-llni", "TestClass3"); return (errors == 0); } void test(String... args) throws IOException, InterruptedException { String[] cp_args = new String[args.length + 2]; cp_args[0] = "-classpath"; cp_args[1] = testClasses.getPath(); System.arraycopy(args, 0, cp_args, 2, args.length); if (jdk != null) init(cp_args); File out = null; for (int i = 0; i < args.length; i++) { if (args[i].equals("-o")) { out = new File(args[++i]); break; } else if (args[i].equals("-d")) { out = new File(args[++i]); out.mkdirs(); break; } } try { System.out.println("test: " + Arrays.asList(cp_args)); // // Uncomment and use the following lines to execute javah via the // // command line -- for example, to run old javah and set up the golden files // List<String> cmd = new ArrayList<String>(); // File javaHome = new File(System.getProperty("java.home")); // if (javaHome.getName().equals("jre")) // javaHome = javaHome.getParentFile(); // File javah = new File(new File(javaHome, "bin"), "javah"); // cmd.add(javah.getPath()); // cmd.addAll(Arrays.asList(cp_args)); // ProcessBuilder pb = new ProcessBuilder(cmd); // pb.redirectErrorStream(true); // pb.start(); // Process p = pb.start(); // String line; // BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); // while ((line = in.readLine()) != null) // System.err.println(line); // in.close(); // int rc = p.waitFor(); // Use new javah PrintWriter err = new PrintWriter(System.err, true); int rc = Main.run(cp_args, err); if (rc != 0) { error("javah failed: rc=" + rc); return; } // The golden files use the LL suffix for long constants, which // is used on Linux and Solaris. On Windows, the suffix is i64, // so compare will update the golden files on the fly before the // final comparison. compare(new File(new File(testSrc, "gold"), out.getName()), out); } catch (Throwable t) { t.printStackTrace(); error("javah threw exception"); } } void init(String[] args) throws IOException, InterruptedException { String[] cmdArgs = new String[args.length + 1]; cmdArgs[0] = new File(new File(jdk, "bin"), "javah").getPath(); System.arraycopy(args, 0, cmdArgs, 1, args.length); System.out.println("init: " + Arrays.asList(cmdArgs)); ProcessBuilder pb = new ProcessBuilder(cmdArgs); pb.directory(new File(testSrc, "gold")); pb.redirectErrorStream(true); Process p = pb.start(); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while ((line = in.readLine()) != null) System.out.println("javah: " + line); int rc = p.waitFor(); if (rc != 0) error("javah: exit code " + rc); } /** Compare two directories. * @param f1 The golden directory * @param f2 The directory to be compared */ void compare(File f1, File f2) { compare(f1, f2, null); } /** Compare two files or directories * @param f1 The golden directory * @param f2 The directory to be compared * @param p An optional path identifying a file within the two directories */ void compare(File f1, File f2, String p) { File f1p = (p == null ? f1 : new File(f1, p)); File f2p = (p == null ? f2 : new File(f2, p)); System.out.println("compare " + f1p + " " + f2p); if (f1p.isDirectory() && f2p.isDirectory()) { Set<String> children = new HashSet<String>(); children.addAll(Arrays.asList(f1p.list())); children.addAll(Arrays.asList(f2p.list())); for (String c: children) { compare(f1, f2, new File(p, c).getPath()); // null-safe for p } } else if (f1p.isFile() && f2p.isFile()) { String s1 = read(f1p); if (isWindows) { // f1/s1 is the golden file // on Windows, long constants use the i64 suffix, not LL s1 = s1.replaceAll("( [0-9]+)LL\n", "$1i64\n"); } String s2 = read(f2p); if (!s1.equals(s2)) { System.out.println("File: " + f1p + "\n" + s1); System.out.println("File: " + f2p + "\n" + s2); error("Files differ: " + f1p + " " + f2p); } } else if (f1p.exists() && !f2p.exists()) error("Only in " + f1 + ": " + p); else if (f2p.exists() && !f1p.exists()) error("Only in " + f2 + ": " + p); else error("Files differ: " + f1p + " " + f2p); } private String read(File f) { try { BufferedReader in = new BufferedReader(new FileReader(f)); try { StringBuilder sb = new StringBuilder((int) f.length()); String line; while ((line = in.readLine()) != null) { sb.append(line); sb.append("\n"); } return sb.toString(); } finally { try { in.close(); } catch (IOException e) { } } } catch (IOException e) { error("error reading " + f + ": " + e); return ""; } } private void error(String msg) { System.out.println(msg); errors++; } private int errors; private File jdk; }
gpl-2.0
ridoo/SensorWebClient
sensorwebclient-ses-server/src/main/java/org/n52/server/ses/service/SesTimeseriesFeedServiceImpl.java
6786
/** * Copyright (C) 2012-2016 52°North Initiative for Geospatial Open Source * Software GmbH * * 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 publishedby the Free * Software Foundation. * * If the program is linked with libraries which are licensed under one of the * following licenses, the combination of the program with the linked library is * not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed under * the aforementioned licenses, is permitted by the copyright holders if the * distribution is compliant with both the GNU General Public License version 2 * and the aforementioned licenses. * * 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. */ package org.n52.server.ses.service; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import org.n52.client.service.SesTimeseriesFeedService; import org.n52.server.ses.SesConfig; import org.n52.server.ses.hibernate.HibernateUtil; import org.n52.server.ses.mail.MailSender; import org.n52.server.ses.util.SesParser; import org.n52.server.ses.util.SesServerUtil; import org.n52.shared.responses.SesClientResponse; import org.n52.shared.responses.SesClientResponseType; import org.n52.shared.serializable.pojos.TimeseriesFeed; import org.n52.shared.serializable.pojos.TimeseriesMetadata; import org.n52.shared.serializable.pojos.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class SesTimeseriesFeedServiceImpl implements SesTimeseriesFeedService { private static final Logger LOGGER = LoggerFactory.getLogger(SesTimeseriesFeedServiceImpl.class); private static SesParser parser; private static SesParser getParser(){ if (SesTimeseriesFeedServiceImpl.parser == null) { return new SesParser(SesConfig.serviceVersion, SesConfig.sesEndpoint); } return parser; } @Override public SesClientResponse getTimeseriesFeeds() throws Exception { try { LOGGER.debug("get registered timeseriesFeeds from DB"); List<TimeseriesFeed> timeseriesFeeds = HibernateUtil.getTimeseriesFeeds(); return new SesClientResponse(SesClientResponseType.REGISTERED_TIMESERIES_FEEDS, timeseriesFeeds); } catch (Exception e) { LOGGER.error("Exception occured on server side.", e); throw e; // last chance to log on server side } } @Override public void updateTimeseriesFeed(String timeseriesFeedId, boolean active) throws Exception { try { LOGGER.debug("updateTimeseriesFeed: {}, Active: {}", timeseriesFeedId, active); updateTimeseriesFeed(timeseriesFeedId, active); if (!active) { // sensor was deactivated // inform all subscriber ArrayList<User> userList = SesServerUtil.getUserBySensorID(timeseriesFeedId); // iterate over the user for (int i = 0; i < userList.size(); i++) { User user = userList.get(i); // inform user MailSender.sendSensorDeactivatedMail(user.geteMail(), timeseriesFeedId); } } } catch (Exception e) { LOGGER.error("Exception occured on server side.", e); throw e; // last chance to log on server side } } @Override public SesClientResponse getStations() throws Exception { try { LOGGER.debug("getStations"); ArrayList<TimeseriesMetadata> finalList = new ArrayList<TimeseriesMetadata>(); HashSet<TimeseriesMetadata> timeseriesMetadatas = new HashSet<TimeseriesMetadata>(); // DB request List<TimeseriesFeed> timeseriesFeeds = HibernateUtil.getActiveTimeseriesFeeds(); for (TimeseriesFeed timeseriesFeed : timeseriesFeeds) { timeseriesMetadatas.add(timeseriesFeed.getTimeseriesMetadata()); } finalList.addAll(timeseriesMetadatas); // TODO make FeedingMetadata comparable // Collections.sort(finalList); return new SesClientResponse(SesClientResponseType.STATIONS, finalList); } catch (Exception e) { LOGGER.error("Exception occured on server side.", e); throw e; // last chance to log on server side } } @Override public SesClientResponse getPhenomena(String timeseriesId) throws Exception { try { LOGGER.debug("getPhenomena for timeseriesId: " + timeseriesId); ArrayList<String> finalList = new ArrayList<String>(); ArrayList<String> unit = new ArrayList<String>(); ArrayList<String> phenomena = getParser().getPhenomena(timeseriesId); // TODO get the unit of measurement from internal/mapped id unit.add(getParser().getUnit(timeseriesId)); for (int i = 0; i < phenomena.size(); i++) { LOGGER.debug(phenomena.get(i)); finalList.add(phenomena.get(i)); } Collections.sort(finalList); return new SesClientResponse(SesClientResponseType.PHENOMENA, finalList, unit); } catch (Exception e) { LOGGER.error("Exception occured on server side.", e); throw e; // last chance to log on server side } } @Override public SesClientResponse deleteTimeseriesFeed(String timeseriesId) throws Exception { try { LOGGER.debug("delete timeseries feed: " + timeseriesId); if (HibernateUtil.deleteTimeseriesFeed(timeseriesId)) { return new SesClientResponse(SesClientResponseType.DELETE_SENSOR_OK); } throw new Exception("delete timeseries feed: " + timeseriesId + " " + "failed"); } catch (Exception e) { LOGGER.error("Exception occured on server side.", e); throw e; // last chance to log on server side } } }
gpl-2.0
deathspeeder/class-guard
apache-tomcat-7.0.53-src/java/org/apache/catalina/util/ExtensionValidator.java
16892
/* * 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.catalina.util; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.Locale; import java.util.NoSuchElementException; import java.util.StringTokenizer; import java.util.jar.JarInputStream; import java.util.jar.Manifest; import javax.naming.Binding; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.directory.DirContext; import org.apache.catalina.Context; import org.apache.naming.resources.Resource; import org.apache.tomcat.util.ExceptionUtils; import org.apache.tomcat.util.res.StringManager; /** * Ensures that all extension dependencies are resolved for a WEB application * are met. This class builds a master list of extensions available to an * application and then validates those extensions. * * See http://docs.oracle.com/javase/1.4.2/docs/guide/extensions/spec.html * for a detailed explanation of the extension mechanism in Java. * * @author Greg Murray * @author Justyna Horwat */ public final class ExtensionValidator { private static final org.apache.juli.logging.Log log= org.apache.juli.logging.LogFactory.getLog(ExtensionValidator.class); /** * The string resources for this package. */ private static final StringManager sm = StringManager.getManager("org.apache.catalina.util"); private static volatile ArrayList<Extension> containerAvailableExtensions = null; private static ArrayList<ManifestResource> containerManifestResources = new ArrayList<ManifestResource>(); // ----------------------------------------------------- Static Initializer /** * This static initializer loads the container level extensions that are * available to all web applications. This method scans all extension * directories available via the "java.ext.dirs" System property. * * The System Class-Path is also scanned for jar files that may contain * available extensions. */ static { // check for container level optional packages String systemClasspath = System.getProperty("java.class.path"); StringTokenizer strTok = new StringTokenizer(systemClasspath, File.pathSeparator); // build a list of jar files in the classpath while (strTok.hasMoreTokens()) { String classpathItem = strTok.nextToken(); if (classpathItem.toLowerCase(Locale.ENGLISH).endsWith(".jar")) { File item = new File(classpathItem); if (item.isFile()) { try { addSystemResource(item); } catch (IOException e) { log.error(sm.getString ("extensionValidator.failload", item), e); } } } } // add specified folders to the list addFolderList("java.ext.dirs"); } // --------------------------------------------------------- Public Methods /** * Runtime validation of a Web Application. * * This method uses JNDI to look up the resources located under a * <code>DirContext</code>. It locates Web Application MANIFEST.MF * file in the /META-INF/ directory of the application and all * MANIFEST.MF files in each JAR file located in the WEB-INF/lib * directory and creates an <code>ArrayList</code> of * <code>ManifestResorce<code> objects. These objects are then passed * to the validateManifestResources method for validation. * * @param dirContext The JNDI root of the Web Application * @param context The context from which the Logger and path to the * application * * @return true if all required extensions satisfied */ public static synchronized boolean validateApplication( DirContext dirContext, Context context) throws IOException { String appName = context.getName(); ArrayList<ManifestResource> appManifestResources = new ArrayList<ManifestResource>(); // If the application context is null it does not exist and // therefore is not valid if (dirContext == null) return false; // Find the Manifest for the Web Application InputStream inputStream = null; try { NamingEnumeration<Binding> wne = dirContext.listBindings("/META-INF/"); Binding binding = wne.nextElement(); if (binding.getName().toUpperCase(Locale.ENGLISH).equals("MANIFEST.MF")) { Resource resource = (Resource)dirContext.lookup ("/META-INF/" + binding.getName()); inputStream = resource.streamContent(); Manifest manifest = new Manifest(inputStream); inputStream.close(); inputStream = null; ManifestResource mre = new ManifestResource (sm.getString("extensionValidator.web-application-manifest"), manifest, ManifestResource.WAR); appManifestResources.add(mre); } } catch (NamingException nex) { // Application does not contain a MANIFEST.MF file } catch (NoSuchElementException nse) { // Application does not contain a MANIFEST.MF file } finally { if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } // Locate the Manifests for all bundled JARs NamingEnumeration<Binding> ne = null; // Primarily used for error reporting String jarName = null; try { ne = dirContext.listBindings("WEB-INF/lib/"); while ((ne != null) && ne.hasMoreElements()) { Binding binding = ne.nextElement(); jarName = binding.getName(); if (!jarName.toLowerCase(Locale.ENGLISH).endsWith(".jar")) { continue; } Object obj = dirContext.lookup("/WEB-INF/lib/" + jarName); if (!(obj instanceof Resource)) { // Probably a directory named xxx.jar - ignore it continue; } Resource resource = (Resource) obj; inputStream = resource.streamContent(); Manifest jmanifest = getManifest(inputStream); if (jmanifest != null) { ManifestResource mre = new ManifestResource(jarName, jmanifest, ManifestResource.APPLICATION); appManifestResources.add(mre); } } } catch (NamingException nex) { // Jump out of the check for this application because it // has no resources } catch (IOException ioe) { throw new IOException("Jar: " + jarName, ioe); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } return validateManifestResources(appName, appManifestResources); } /** * Checks to see if the given system JAR file contains a MANIFEST, and adds * it to the container's manifest resources. * * @param jarFile The system JAR whose manifest to add */ public static void addSystemResource(File jarFile) throws IOException { Manifest manifest = getManifest(new FileInputStream(jarFile)); if (manifest != null) { ManifestResource mre = new ManifestResource(jarFile.getAbsolutePath(), manifest, ManifestResource.SYSTEM); containerManifestResources.add(mre); } } // -------------------------------------------------------- Private Methods /** * Validates a <code>ArrayList</code> of <code>ManifestResource</code> * objects. This method requires an application name (which is the * context root of the application at runtime). * * <code>false</false> is returned if the extension dependencies * represented by any given <code>ManifestResource</code> objects * is not met. * * This method should also provide static validation of a Web Application * if provided with the necessary parameters. * * @param appName The name of the Application that will appear in the * error messages * @param resources A list of <code>ManifestResource</code> objects * to be validated. * * @return true if manifest resource file requirements are met */ private static boolean validateManifestResources(String appName, ArrayList<ManifestResource> resources) { boolean passes = true; int failureCount = 0; ArrayList<Extension> availableExtensions = null; Iterator<ManifestResource> it = resources.iterator(); while (it.hasNext()) { ManifestResource mre = it.next(); ArrayList<Extension> requiredList = mre.getRequiredExtensions(); if (requiredList == null) { continue; } // build the list of available extensions if necessary if (availableExtensions == null) { availableExtensions = buildAvailableExtensionsList(resources); } // load the container level resource map if it has not been built // yet if (containerAvailableExtensions == null) { containerAvailableExtensions = buildAvailableExtensionsList(containerManifestResources); } // iterate through the list of required extensions Iterator<Extension> rit = requiredList.iterator(); while (rit.hasNext()) { boolean found = false; Extension requiredExt = rit.next(); // check the application itself for the extension if (availableExtensions != null) { Iterator<Extension> ait = availableExtensions.iterator(); while (ait.hasNext()) { Extension targetExt = ait.next(); if (targetExt.isCompatibleWith(requiredExt)) { requiredExt.setFulfilled(true); found = true; break; } } } // check the container level list for the extension if (!found && containerAvailableExtensions != null) { Iterator<Extension> cit = containerAvailableExtensions.iterator(); while (cit.hasNext()) { Extension targetExt = cit.next(); if (targetExt.isCompatibleWith(requiredExt)) { requiredExt.setFulfilled(true); found = true; break; } } } if (!found) { // Failure log.info(sm.getString( "extensionValidator.extension-not-found-error", appName, mre.getResourceName(), requiredExt.getExtensionName())); passes = false; failureCount++; } } } if (!passes) { log.info(sm.getString( "extensionValidator.extension-validation-error", appName, failureCount + "")); } return passes; } /* * Build this list of available extensions so that we do not have to * re-build this list every time we iterate through the list of required * extensions. All available extensions in all of the * <code>MainfestResource</code> objects will be added to a * <code>HashMap</code> which is returned on the first dependency list * processing pass. * * The key is the name + implementation version. * * NOTE: A list is built only if there is a dependency that needs * to be checked (performance optimization). * * @param resources A list of <code>ManifestResource</code> objects * * @return HashMap Map of available extensions */ private static ArrayList<Extension> buildAvailableExtensionsList( ArrayList<ManifestResource> resources) { ArrayList<Extension> availableList = null; Iterator<ManifestResource> it = resources.iterator(); while (it.hasNext()) { ManifestResource mre = it.next(); ArrayList<Extension> list = mre.getAvailableExtensions(); if (list != null) { Iterator<Extension> values = list.iterator(); while (values.hasNext()) { Extension ext = values.next(); if (availableList == null) { availableList = new ArrayList<Extension>(); availableList.add(ext); } else { availableList.add(ext); } } } } return availableList; } /** * Return the Manifest from a jar file or war file * * @param inStream Input stream to a WAR or JAR file * @return The WAR's or JAR's manifest */ private static Manifest getManifest(InputStream inStream) throws IOException { Manifest manifest = null; JarInputStream jin = null; try { jin = new JarInputStream(inStream); manifest = jin.getManifest(); jin.close(); jin = null; } finally { if (jin != null) { try { jin.close(); } catch (Throwable t) { ExceptionUtils.handleThrowable(t); } } } return manifest; } /** * Add the JARs specified to the extension list. */ private static void addFolderList(String property) { // get the files in the extensions directory String extensionsDir = System.getProperty(property); if (extensionsDir != null) { StringTokenizer extensionsTok = new StringTokenizer(extensionsDir, File.pathSeparator); while (extensionsTok.hasMoreTokens()) { File targetDir = new File(extensionsTok.nextToken()); if (!targetDir.isDirectory()) { continue; } File[] files = targetDir.listFiles(); for (int i = 0; i < files.length; i++) { if (files[i].getName().toLowerCase(Locale.ENGLISH).endsWith(".jar") && files[i].isFile()) { try { addSystemResource(files[i]); } catch (IOException e) { log.error (sm.getString ("extensionValidator.failload", files[i]), e); } } } } } } }
gpl-2.0
qoswork/opennmszh
opennms-services/src/test/java/org/opennms/netmgt/poller/PollerTest.java
40167
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2006-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.poller; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import java.io.InputStream; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.Properties; import org.apache.log4j.Level; import org.junit.After; import org.junit.Before; import org.junit.Ignore; import org.junit.Test; import org.opennms.core.db.DataSourceFactory; import org.opennms.core.test.ConfigurationTestUtils; import org.opennms.core.test.MockLogAppender; import org.opennms.core.test.db.MockDatabase; import org.opennms.core.utils.Querier; import org.opennms.netmgt.EventConstants; import org.opennms.netmgt.capsd.JdbcCapsdDbSyncer; import org.opennms.netmgt.config.CollectdConfigFactory; import org.opennms.netmgt.config.DatabaseSchemaConfigFactory; import org.opennms.netmgt.config.OpennmsServerConfigFactory; import org.opennms.netmgt.config.poller.Package; import org.opennms.netmgt.dao.support.NullRrdStrategy; import org.opennms.netmgt.eventd.datablock.EventUtil; import org.opennms.netmgt.eventd.mock.EventAnticipator; import org.opennms.netmgt.eventd.mock.MockEventIpcManager; import org.opennms.netmgt.mock.MockElement; import org.opennms.netmgt.mock.MockEventUtil; import org.opennms.netmgt.mock.MockInterface; import org.opennms.netmgt.mock.MockNetwork; import org.opennms.netmgt.mock.MockNode; import org.opennms.netmgt.mock.MockOutageConfig; import org.opennms.netmgt.mock.MockPollerConfig; import org.opennms.netmgt.mock.MockService; import org.opennms.netmgt.mock.MockService.SvcMgmtStatus; import org.opennms.netmgt.mock.MockVisitor; import org.opennms.netmgt.mock.MockVisitorAdapter; import org.opennms.netmgt.mock.OutageAnticipator; import org.opennms.netmgt.mock.PollAnticipator; import org.opennms.netmgt.mock.TestCapsdConfigManager; import org.opennms.netmgt.model.PollStatus; import org.opennms.netmgt.model.events.EventUtils; import org.opennms.netmgt.poller.pollables.PollableNetwork; import org.opennms.netmgt.rrd.RrdUtils; import org.opennms.netmgt.xml.event.Event; import org.opennms.netmgt.xmlrpcd.OpenNMSProvisioner; import org.opennms.test.mock.MockUtil; import org.springframework.jdbc.core.JdbcTemplate; public class PollerTest { private static final String CAPSD_CONFIG = "\n" + "<capsd-configuration max-suspect-thread-pool-size=\"2\" max-rescan-thread-pool-size=\"3\"\n" + " delete-propagation-enabled=\"true\">\n" + " <protocol-plugin protocol=\"ICMP\" class-name=\"org.opennms.netmgt.capsd.plugins.LdapPlugin\"/>\n" + " <protocol-plugin protocol=\"SMTP\" class-name=\"org.opennms.netmgt.capsd.plugins.LdapPlugin\"/>\n" + " <protocol-plugin protocol=\"HTTP\" class-name=\"org.opennms.netmgt.capsd.plugins.LdapPlugin\"/>\n" + "</capsd-configuration>\n"; private Poller m_poller; private MockNetwork m_network; private MockDatabase m_db; private MockPollerConfig m_pollerConfig; private MockEventIpcManager m_eventMgr; private boolean m_daemonsStarted = false; private EventAnticipator m_anticipator; private OutageAnticipator m_outageAnticipator; private Level m_assertLevel; //private DemandPollDao m_demandPollDao; // // SetUp and TearDown // @Before public void setUp() throws Exception { m_assertLevel = Level.WARN; // System.setProperty("mock.logLevel", "DEBUG"); // System.setProperty("mock.debug", "true"); MockUtil.println("------------ Begin Test --------------------------"); MockLogAppender.setupLogging(); m_network = new MockNetwork(); m_network.setCriticalService("ICMP"); m_network.addNode(1, "Router"); m_network.addInterface("192.168.1.1"); m_network.addService("ICMP"); m_network.addService("SMTP"); m_network.addService("SNMP"); m_network.addInterface("192.168.1.2"); m_network.addService("ICMP"); m_network.addService("SMTP"); m_network.addNode(2, "Server"); m_network.addInterface("192.168.1.3"); m_network.addService("ICMP"); m_network.addService("HTTP"); m_network.addService("SMTP"); m_network.addService("SNMP"); m_network.addNode(3, "Firewall"); m_network.addInterface("192.168.1.4"); m_network.addService("SMTP"); m_network.addService("HTTP"); m_network.addInterface("192.168.1.5"); m_network.addService("SMTP"); m_network.addService("HTTP"); m_network.addNode(4, "DownNode"); m_network.addInterface("192.168.1.6"); m_network.addService("SNMP"); // m_network.addInterface("fe80:0000:0000:0000:0231:f982:0123:4567"); // m_network.addService("SNMP"); m_db = new MockDatabase(); m_db.populate(m_network); DataSourceFactory.setInstance(m_db); // DemandPollDao demandPollDao = new DemandPollDaoHibernate(m_db); // demandPollDao.setAllocateIdStmt(m_db // .getNextSequenceValStatement("demandPollNxtId")); // m_demandPollDao = demandPollDao; m_pollerConfig = new MockPollerConfig(m_network); m_pollerConfig.setNextOutageIdSql(m_db.getNextOutageIdStatement()); m_pollerConfig.setNodeOutageProcessingEnabled(true); m_pollerConfig.setCriticalService("ICMP"); m_pollerConfig.addPackage("TestPackage"); m_pollerConfig.addDowntime(1000L, 0L, -1L, false); m_pollerConfig.setDefaultPollInterval(1000L); m_pollerConfig.populatePackage(m_network); m_pollerConfig.addPackage("TestPkg2"); m_pollerConfig.addDowntime(1000L, 0L, -1L, false); m_pollerConfig.setDefaultPollInterval(2000L); m_pollerConfig.addService(m_network.getService(2, "192.168.1.3", "HTTP")); m_anticipator = new EventAnticipator(); m_outageAnticipator = new OutageAnticipator(m_db); m_eventMgr = new MockEventIpcManager(); m_eventMgr.setEventWriter(m_db); m_eventMgr.setEventAnticipator(m_anticipator); m_eventMgr.addEventListener(m_outageAnticipator); m_eventMgr.setSynchronous(false); QueryManager queryManager = new DefaultQueryManager(); queryManager.setDataSource(m_db); DefaultPollContext pollContext = new DefaultPollContext(); pollContext.setEventManager(m_eventMgr); pollContext.setLocalHostName("localhost"); pollContext.setName("Test.DefaultPollContext"); pollContext.setPollerConfig(m_pollerConfig); pollContext.setQueryManager(queryManager); PollableNetwork network = new PollableNetwork(pollContext); m_poller = new Poller(); m_poller.setDataSource(m_db); m_poller.setEventManager(m_eventMgr); m_poller.setNetwork(network); m_poller.setQueryManager(queryManager); m_poller.setPollerConfig(m_pollerConfig); m_poller.setPollOutagesConfig(m_pollerConfig); MockOutageConfig config = new MockOutageConfig(); config.setGetNextOutageID(m_db.getNextOutageIdStatement()); RrdUtils.setStrategy(new NullRrdStrategy()); // m_outageMgr = new OutageManager(); // m_outageMgr.setEventMgr(m_eventMgr); // m_outageMgr.setOutageMgrConfig(config); // m_outageMgr.setDbConnectionFactory(m_db); } @After public void tearDown() throws Exception { m_eventMgr.finishProcessingEvents(); stopDaemons(); sleep(200); if (m_assertLevel != null) { MockLogAppender.assertNotGreaterOrEqual(m_assertLevel); } m_db.drop(); MockUtil.println("------------ End Test --------------------------"); } // // Tests // @Test public void testIsRemotePackage() { Properties p = new Properties(); p.setProperty("org.opennms.netmgt.ConfigFileConstants", "ERROR"); MockLogAppender.setupLogging(p); Package pkg = new Package(); pkg.setName("SFO"); pkg.setRemote(true); Poller poller = new Poller(); assertFalse(poller.pollableServiceInPackage(null, null, pkg)); poller = null; } // public void testDemandPollService() { // DemandPoll demandPoll = new DemandPoll(); // demandPoll.setDescription("Test Poll"); // demandPoll.setRequestTime(new Date()); // demandPoll.setUserName("admin"); // // m_demandPollDao.save(demandPoll); // // assertNotNull(demandPoll.getId()); // // MockService httpService = m_network // .getService(2, "192.168.1.3", "HTTP"); // Event demandPollEvent = httpService.createDemandPollEvent(demandPoll.getId()); // // } @Test public void testNullInterfaceOnNodeDown() { // NODE processing = true; m_pollerConfig.setNodeOutageProcessingEnabled(true); MockNode node = m_network.getNode(2); MockService icmpService = m_network.getService(2, "192.168.1.3", "ICMP"); MockService smtpService = m_network.getService(2, "192.168.1.3", "SMTP"); MockService snmpService = m_network.getService(2, "192.168.1.3", "SNMP"); // start the poller startDaemons(); anticipateDown(node); icmpService.bringDown(); smtpService.bringDown(); snmpService.bringDown(); verifyAnticipated(10000); // node is down at this point boolean foundNodeDown = false; for (final Event event : m_anticipator.getAnticipatedEventsRecieved()) { if (EventConstants.NODE_DOWN_EVENT_UEI.equals(event.getUei())) { foundNodeDown = true; assertNull(event.getInterfaceAddress()); } } assertTrue(foundNodeDown); } @Test @Ignore public void testBug1564() { // NODE processing = true; m_pollerConfig.setNodeOutageProcessingEnabled(true); MockNode node = m_network.getNode(2); MockService icmpService = m_network.getService(2, "192.168.1.3", "ICMP"); MockService smtpService = m_network.getService(2, "192.168.1.3", "SMTP"); MockService snmpService = m_network.getService(2, "192.168.1.3", "SNMP"); // start the poller startDaemons(); // // Bring Down the HTTP service and expect nodeLostService Event // resetAnticipated(); anticipateDown(snmpService); // One service works fine snmpService.bringDown(); verifyAnticipated(10000); // Now we simulate the restart, the node // looses all three at the same time resetAnticipated(); anticipateDown(node); icmpService.bringDown(); smtpService.bringDown(); snmpService.bringDown(); verifyAnticipated(10000); anticipateDown(smtpService); verifyAnticipated(10000); anticipateDown(snmpService); verifyAnticipated(10000); // This is to simulate a restart, // where I turn off the node behaviour m_pollerConfig.setNodeOutageProcessingEnabled(false); anticipateUp(snmpService); snmpService.bringUp(); verifyAnticipated(10000); anticipateUp(smtpService); smtpService.bringUp(); verifyAnticipated(10000); // Another restart - let's see if this will work? m_pollerConfig.setNodeOutageProcessingEnabled(true); // So everything is down, now // SNMP will regain and SMTP will regain // will the node come up? smtpService.bringDown(); anticipateUp(smtpService); smtpService.bringUp(); verifyAnticipated(10000,true); anticipateUp(snmpService); snmpService.bringUp(); verifyAnticipated(10000); } @Test public void testBug709() { m_pollerConfig.setNodeOutageProcessingEnabled(true); MockNode node = m_network.getNode(2); MockService icmpService = m_network .getService(2, "192.168.1.3", "ICMP"); MockService httpService = m_network .getService(2, "192.168.1.3", "HTTP"); // start the poller startDaemons(); // // Bring Down the HTTP service and expect nodeLostService Event // resetAnticipated(); anticipateDown(httpService); // bring down the HTTP service httpService.bringDown(); verifyAnticipated(10000); // // Bring Down the ICMP (on the only interface on the node) now expect // nodeDown // only. // resetAnticipated(); anticipateDown(node); // bring down the ICMP service icmpService.bringDown(); // make sure the down events are received // verifyAnticipated(10000); sleep(5000); // // Bring up both the node and the httpService at the same time. Expect // both a nodeUp and a nodeRegainedService // resetAnticipated(); // the order matters here anticipateUp(httpService); anticipateUp(node); // bring up all the services on the node node.bringUp(); // make sure the down events are received verifyAnticipated(10000); } private void resetAnticipated() { m_anticipator.reset(); m_outageAnticipator.reset(); } @Test public void testNodeLostServiceWithReason() { m_pollerConfig.setNodeOutageProcessingEnabled(true); MockService svc = m_network.getService(1, "192.168.1.1", "ICMP"); Event e = svc.createDownEvent(); String reasonParm = "eventReason"; String val = EventUtil.getNamedParmValue("parm[" + reasonParm + "]", e); assertEquals("Service Not Responding.", val); } @Test public void testCritSvcStatusPropagation() { m_pollerConfig.setNodeOutageProcessingEnabled(true); MockNode node = m_network.getNode(1); anticipateDown(node); startDaemons(); bringDownCritSvcs(node); verifyAnticipated(8000); } @Test public void testInterfaceWithNoCriticalService() { m_pollerConfig.setNodeOutageProcessingEnabled(true); MockInterface iface = m_network.getInterface(3, "192.168.1.4"); MockService svc = iface.getService("SMTP"); MockService otherService = iface.getService("HTTP"); startDaemons(); anticipateDown(iface); iface.bringDown(); verifyAnticipated(8000); anticipateUp(iface); anticipateDown(otherService, true); svc.bringUp(); verifyAnticipated(8000); } // what about scheduled outages? @Test public void testDontPollDuringScheduledOutages() { long start = System.currentTimeMillis(); MockInterface iface = m_network.getInterface(1, "192.168.1.2"); m_pollerConfig.addScheduledOutage(m_pollerConfig.getPackage("TestPackage"), "TestOutage", start, start + 5000, iface.getIpAddr()); MockUtil.println("Begin Outage"); startDaemons(); long now = System.currentTimeMillis(); sleep(3000 - (now - start)); MockUtil.println("End Outage"); assertEquals(0, iface.getPollCount()); sleep(5000); assertTrue(0 < iface.getPollCount()); } // Test harness that tests any type of node, interface or element. private void testElementDeleted(MockElement element) { Event deleteEvent = element.createDeleteEvent(); m_pollerConfig.setNodeOutageProcessingEnabled(false); PollAnticipator poll = new PollAnticipator(); element.addAnticipator(poll); poll.anticipateAllServices(element); startDaemons(); // wait til after the first poll of the services poll.waitForAnticipated(1000L); // now delete the node and send a nodeDeleted event m_network.removeElement(element); m_eventMgr.sendEventToListeners(deleteEvent); // reset the poll count and wait to see if any polls on the removed // element happened m_network.resetInvalidPollCount(); // now ensure that no invalid polls have occurred sleep(3000); assertEquals("Received a poll for an element that doesn't exist", 0, m_network.getInvalidPollCount()); } // serviceDeleted: EventConstants.SERVICE_DELETED_EVENT_UEI @Test public void testServiceDeleted() { MockService svc = m_network.getService(1, "192.168.1.1", "SMTP"); testElementDeleted(svc); } // interfaceDeleted: EventConstants.INTERFACE_DELETED_EVENT_UEI @Test public void testInterfaceDeleted() { MockInterface iface = m_network.getInterface(1, "192.168.1.1"); testElementDeleted(iface); } // nodeDeleted: EventConstants.NODE_DELETED_EVENT_UEI @Test public void testNodeDeleted() { MockNode node = m_network.getNode(1); testElementDeleted(node); } // nodeLabelChanged: EventConstants.NODE_LABEL_CHANGED_EVENT_UEI @Test public void testNodeLabelChanged() { MockNode element = m_network.getNode(1); String newLabel = "NEW LABEL"; Event event = element.createNodeLabelChangedEvent(newLabel); m_pollerConfig.setNodeOutageProcessingEnabled(false); PollAnticipator poll = new PollAnticipator(); element.addAnticipator(poll); poll.anticipateAllServices(element); startDaemons(); // wait until after the first poll of the services poll.waitForAnticipated(1000L); assertEquals("Router", m_poller.getNetwork().getNode(1).getNodeLabel()); // now delete the node and send a nodeDeleted event element.setLabel(newLabel); m_eventMgr.sendEventToListeners(event); assertEquals(newLabel, m_poller.getNetwork().getNode(1).getNodeLabel()); } public void testOutagesClosedOnDelete(MockElement element) { startDaemons(); Event deleteEvent = element.createDeleteEvent(); // bring down so we create an outage in the outages table anticipateDown(element); element.bringDown(); verifyAnticipated(5000, false); m_outageAnticipator.anticipateOutageClosed(element, deleteEvent); // now delete the service m_eventMgr.sendEventToListeners(deleteEvent); m_network.removeElement(element); verifyAnticipated(5000); } @Test public void testServiceOutagesClosedOnDelete() { MockService element = m_network.getService(1, "192.168.1.1", "SMTP"); testOutagesClosedOnDelete(element); } @Test public void testInterfaceOutagesClosedOnDelete() { MockInterface element = m_network.getInterface(1, "192.168.1.1"); testOutagesClosedOnDelete(element); } @Test public void testNodeOutagesClosedOnDelete() { MockNode element = m_network.getNode(1); testOutagesClosedOnDelete(element); } // interfaceReparented: EventConstants.INTERFACE_REPARENTED_EVENT_UEI @Test public void testInterfaceReparented() throws Exception { m_assertLevel = null; m_pollerConfig.setNodeOutageProcessingEnabled(true); MockNode node1 = m_network.getNode(1); MockNode node2 = m_network.getNode(2); assertNotNull("Node 1 should have 192.168.1.1", node1.getInterface("192.168.1.1")); assertNotNull("Node 1 should have 192.168.1.2", node1.getInterface("192.168.1.2")); assertNull("Node 2 should not yet have 192.168.1.2", node2.getInterface("192.168.1.2")); assertNotNull("Node 2 should have 192.168.1.3", node2.getInterface("192.168.1.3")); MockInterface dotTwo = m_network.getInterface(1, "192.168.1.2"); MockInterface dotThree = m_network.getInterface(2, "192.168.1.3"); Event reparentEvent = MockEventUtil.createReparentEvent("Test", "192.168.1.2", 1, 2); // we are going to reparent to node 2 so when we bring down its only // current interface we expect an interface down not the whole node. anticipateDown(dotThree); startDaemons(); final int waitTime = 2000; final int verifyTime = 2000; sleep(waitTime); // move the reparented interface and send a reparented event dotTwo.moveTo(node2); m_db.reparentInterface(dotTwo.getIpAddr(), node1.getNodeId(), node2.getNodeId()); // send the reparent event to the daemons m_eventMgr.sendEventToListeners(reparentEvent); sleep(waitTime); // now bring down the other interface on the new node // System.err.println("Bring Down:"+node2Iface); dotThree.bringDown(); verifyAnticipated(verifyTime); resetAnticipated(); anticipateDown(node2); // System.err.println("Bring Down:"+reparentedIface); dotTwo.bringDown(); sleep(waitTime); verifyAnticipated(verifyTime); node1 = m_network.getNode(1); node2 = m_network.getNode(2); assertNotNull("Node 1 should still have 192.168.1.1", node1.getInterface("192.168.1.1")); assertNull("Node 1 should no longer have 192.168.1.2", node1.getInterface("192.168.1.2")); assertNotNull("Node 2 should now have 192.168.1.2", node2.getInterface("192.168.1.2")); assertNotNull("Node 2 should still have 192.168.1.3", node2.getInterface("192.168.1.3")); } // test to see that node lost/regained service events come in @Test public void testNodeOutageProcessingDisabled() throws Exception { m_pollerConfig.setNodeOutageProcessingEnabled(false); MockNode node = m_network.getNode(1); startDaemons(); resetAnticipated(); anticipateServicesDown(node); node.bringDown(); verifyAnticipated(10000); resetAnticipated(); anticipateServicesUp(node); node.bringUp(); verifyAnticipated(10000); } // test whole node down @Test public void testNodeOutageProcessingEnabled() throws Exception { m_pollerConfig.setNodeOutageProcessingEnabled(true); MockNode node = m_network.getNode(1); // start the poller startDaemons(); resetAnticipated(); anticipateDown(node); // brind down the node (duh) node.bringDown(); // make sure the correct events are recieved verifyAnticipated(10000); resetAnticipated(); anticipateUp(node); // bring the node back up node.bringUp(); // make sure the up events are received verifyAnticipated(10000); } @Test public void testNodeLostServiceIncludesReason() throws Exception { MockService element = m_network.getService(1, "192.168.1.1", "SMTP"); String expectedReason = "Oh No!! An Outage!!"; startDaemons(); resetAnticipated(); anticipateDown(element); MockUtil.println("Bringing down element: " + element); element.bringDown(expectedReason); MockUtil.println("Finished bringing down element: " + element); verifyAnticipated(8000); Collection<Event> receivedEvents = m_anticipator.getAnticipatedEventsRecieved(); assertEquals(1, receivedEvents.size()); Event event = receivedEvents.iterator().next(); assertEquals(expectedReason, EventUtils.getParm(event, EventConstants.PARM_LOSTSERVICE_REASON)); } @Test public void testNodeLostRegainedService() throws Exception { testElementDownUp(m_network.getService(1, "192.168.1.1", "SMTP")); } @Test public void testInterfaceDownUp() { testElementDownUp(m_network.getInterface(1, "192.168.1.1")); } @Test public void testNodeDownUp() { testElementDownUp(m_network.getNode(1)); } private void testElementDownUp(MockElement element) { startDaemons(); resetAnticipated(); anticipateDown(element); MockUtil.println("Bringing down element: " + element); element.bringDown(); MockUtil.println("Finished bringing down element: " + element); verifyAnticipated(5000); sleep(2000); resetAnticipated(); anticipateUp(element); MockUtil.println("Bringing up element: " + element); element.bringUp(); MockUtil.println("Finished bringing up element: " + element); verifyAnticipated(8000); } @Test public void testNoEventsOnNoOutages() throws Exception { testElementDownUp(m_network.getService(1, "192.168.1.1", "SMTP")); resetAnticipated(); verifyAnticipated(8000, true); } @Test public void testPolling() throws Exception { m_pollerConfig.setNodeOutageProcessingEnabled(false); // create a poll anticipator PollAnticipator anticipator = new PollAnticipator(); // register it with the interfaces services MockInterface iface = m_network.getInterface(1, "192.168.1.2"); iface.addAnticipator(anticipator); // // first ensure that polls are working while it is up // // anticipate three polls on all the interfaces services anticipator.anticipateAllServices(iface); anticipator.anticipateAllServices(iface); anticipator.anticipateAllServices(iface); // start the poller startDaemons(); // wait for the polls to occur while its up... 1 poll per second plus // overhead assertEquals(0, anticipator.waitForAnticipated(4500L).size()); } // test open outages for unmanaged services @Test public void testUnmangedWithOpenOutageAtStartup() { // before we start we need to initialize the database // create an outage for the service MockService svc = m_network.getService(1, "192.168.1.1", "SMTP"); MockInterface iface = m_network.getInterface(1, "192.168.1.2"); Event svcLostEvent = MockEventUtil.createNodeLostServiceEvent("Test", svc); m_db.writeEvent(svcLostEvent); createOutages(svc, svcLostEvent); Event ifaceDownEvent = MockEventUtil.createInterfaceDownEvent("Test", iface); m_db.writeEvent(ifaceDownEvent); createOutages(iface, ifaceDownEvent); // mark the service as unmanaged m_db.setServiceStatus(svc, 'U'); m_db.setInterfaceStatus(iface, 'U'); // assert that we have an open outage assertEquals(1, m_db.countOpenOutagesForService(svc)); assertEquals(1, m_db.countOutagesForService(svc)); assertEquals(iface.getServices().size(), m_db .countOutagesForInterface(iface)); assertEquals(iface.getServices().size(), m_db .countOpenOutagesForInterface(iface)); startDaemons(); // assert that we have no open outages assertEquals(0, m_db.countOpenOutagesForService(svc)); assertEquals(1, m_db.countOutagesForService(svc)); assertEquals(0, m_db.countOpenOutagesForInterface(iface)); assertEquals(iface.getServices().size(), m_db .countOutagesForInterface(iface)); } @Test public void testNodeGainedServiceWhileNodeDownAndServiceUp() { startDaemons(); MockNode node = m_network.getNode(4); MockService svc = m_network.getService(4, "192.168.1.6", "SNMP"); anticipateDown(node); node.bringDown(); verifyAnticipated(5000); resetAnticipated(); anticipateUp(node); anticipateDown(svc, true); MockService newSvc = m_network.addService(4, "192.168.1.6", "SMTP"); m_db.writeService(newSvc); Event e = MockEventUtil.createNodeGainedServiceEvent("Test", newSvc); m_eventMgr.sendEventToListeners(e); sleep(5000); System.err.println(m_db.getOutages()); verifyAnticipated(8000); } @Test public void testNodeGainedServiceWhileNodeDownAndServiceDown() { startDaemons(); MockNode node = m_network.getNode(4); MockService svc = m_network.getService(4, "192.168.1.6", "SNMP"); anticipateDown(node); node.bringDown(); verifyAnticipated(5000); resetAnticipated(); MockService newSvc = m_network.addService(4, "192.168.1.6", "SMTP"); m_db.writeService(newSvc); newSvc.bringDown(); Event e = MockEventUtil.createNodeGainedServiceEvent("Test", newSvc); m_eventMgr.sendEventToListeners(e); sleep(5000); System.err.println(m_db.getOutages()); verifyAnticipated(8000); anticipateUp(node); anticipateDown(svc, true); newSvc.bringUp(); verifyAnticipated(5000); } // test open outages for unmanaged services @Test public void testReparentCausesStatusChange() { m_pollerConfig.setNodeOutageProcessingEnabled(true); MockNode node1 = m_network.getNode(1); MockNode node2 = m_network.getNode(2); MockInterface dotOne = m_network.getInterface(1, "192.168.1.1"); MockInterface dotTwo = m_network.getInterface(1, "192.168.1.2"); MockInterface dotThree = m_network.getInterface(2, "192.168.1.3"); // // Plan to bring down both nodes except the reparented interface // the node owning the interface should be up while the other is down // after reparenting we should got the old owner go down while the other // comes up. // anticipateDown(node2); anticipateDown(dotOne); // bring down both nodes but bring iface back up node1.bringDown(); node2.bringDown(); dotTwo.bringUp(); Event reparentEvent = MockEventUtil.createReparentEvent("Test", "192.168.1.2", 1, 2); startDaemons(); verifyAnticipated(2000); m_db.reparentInterface(dotTwo.getIpAddr(), dotTwo.getNodeId(), node2 .getNodeId()); dotTwo.moveTo(node2); resetAnticipated(); anticipateDown(node1, true); anticipateUp(node2, true); anticipateDown(dotThree, true); m_eventMgr.sendEventToListeners(reparentEvent); verifyAnticipated(20000); } // send a nodeGainedService event: // EventConstants.NODE_GAINED_SERVICE_EVENT_UEI @Test public void testSendNodeGainedService() { m_pollerConfig.setNodeOutageProcessingEnabled(false); startDaemons(); testSendNodeGainedService("SMTP", "HTTP"); } @Test public void testSendNodeGainedServiceNodeOutages() { m_pollerConfig.setNodeOutageProcessingEnabled(true); startDaemons(); testSendNodeGainedService("SMTP", "HTTP"); } @Test public void testSendIPv6NodeGainedService() { m_pollerConfig.setNodeOutageProcessingEnabled(false); startDaemons(); testSendNodeGainedServices(99, "TestNode", "fe80:0000:0000:0000:0231:f982:0123:4567", new String[] { "SMTP", "HTTP" }); } @Test public void testSendIPv6NodeGainedServiceNodeOutages() { m_pollerConfig.setNodeOutageProcessingEnabled(true); startDaemons(); testSendNodeGainedServices(99, "TestNode", "fe80:0000:0000:0000:0231:f982:0123:4567", new String[] { "SMTP", "HTTP" }); } public void testSendNodeGainedService(String... svcNames) { testSendNodeGainedServices(99, "TestNode", "10.1.1.1", svcNames); } private void testSendNodeGainedServices(int nodeid, String nodeLabel, String ipAddr, String... svcNames) { assertNotNull(svcNames); assertTrue(svcNames.length > 0); MockNode node = m_network.addNode(nodeid, nodeLabel); m_db.writeNode(node); MockInterface iface = m_network.addInterface(nodeid, ipAddr); m_db.writeInterface(iface); List<MockService> services = new ArrayList<MockService>(); for(String svcName : svcNames) { MockService svc = m_network.addService(nodeid, ipAddr, svcName); m_db.writeService(svc); m_pollerConfig.addService(svc); services.add(svc); } MockVisitor gainSvcSender = new MockVisitorAdapter() { public void visitService(MockService svc) { Event event = MockEventUtil .createNodeGainedServiceEvent("Test", svc); m_eventMgr.sendEventToListeners(event); } }; node.visit(gainSvcSender); MockService svc1 = services.get(0); PollAnticipator anticipator = new PollAnticipator(); svc1.addAnticipator(anticipator); anticipator.anticipateAllServices(svc1); StringBuffer didNotOccur = new StringBuffer(); for (MockService service : anticipator.waitForAnticipated(10000)) { didNotOccur.append(service.toString()); } StringBuffer unanticipatedStuff = new StringBuffer(); for (MockService service : anticipator.unanticipatedPolls()) { unanticipatedStuff.append(service.toString()); } assertEquals(unanticipatedStuff.toString(), "", didNotOccur.toString()); anticipateDown(svc1); svc1.bringDown(); verifyAnticipated(10000); } @Test public void testNodeGainedDynamicService() throws Exception { m_pollerConfig.setNodeOutageProcessingEnabled(true); startDaemons(); TestCapsdConfigManager capsdConfig = new TestCapsdConfigManager(CAPSD_CONFIG); InputStream configStream = ConfigurationTestUtils.getInputStreamForConfigFile("opennms-server.xml"); OpennmsServerConfigFactory onmsSvrConfig = new OpennmsServerConfigFactory(configStream); configStream.close(); configStream = ConfigurationTestUtils.getInputStreamForConfigFile("database-schema.xml"); DatabaseSchemaConfigFactory.setInstance(new DatabaseSchemaConfigFactory(configStream)); configStream.close(); configStream = ConfigurationTestUtils.getInputStreamForResource(this, "/org/opennms/netmgt/capsd/collectd-configuration.xml"); CollectdConfigFactory collectdConfig = new CollectdConfigFactory(configStream, onmsSvrConfig.getServerName(), onmsSvrConfig.verifyServer()); configStream.close(); JdbcTemplate jdbcTemplate = new JdbcTemplate(m_db); JdbcCapsdDbSyncer syncer = new JdbcCapsdDbSyncer(); syncer.setJdbcTemplate(jdbcTemplate); syncer.setOpennmsServerConfig(onmsSvrConfig); syncer.setCapsdConfig(capsdConfig); syncer.setPollerConfig(m_pollerConfig); syncer.setCollectdConfig(collectdConfig); syncer.setNextSvcIdSql(m_db.getNextServiceIdStatement()); syncer.afterPropertiesSet(); OpenNMSProvisioner provisioner = new OpenNMSProvisioner(); provisioner.setPollerConfig(m_pollerConfig); provisioner.setCapsdConfig(capsdConfig); provisioner.setCapsdDbSyncer(syncer); provisioner.setEventManager(m_eventMgr); provisioner.addServiceDNS("MyDNS", 3, 100, 1000, 500, 3000, 53, "www.opennms.org"); assertNotNull("The service id for MyDNS is null", m_db .getServiceID("MyDNS")); MockUtil.println("The service id for MyDNS is: " + m_db.getServiceID("MyDNS").toString()); m_anticipator.reset(); testSendNodeGainedService("MyDNS", "HTTP"); } @Test public void testSuspendPollingResumeService() { MockService svc = m_network.getService(1, "192.168.1.2", "SMTP"); startDaemons(); sleep(2000); assertTrue(0 < svc.getPollCount()); m_eventMgr.sendEventToListeners(MockEventUtil .createSuspendPollingServiceEvent("Test", svc)); svc.resetPollCount(); sleep(5000); assertEquals(0, svc.getPollCount()); m_eventMgr.sendEventToListeners(MockEventUtil .createResumePollingServiceEvent("Test", svc)); sleep(2000); assertTrue(0 < svc.getPollCount()); } // // Utility methods // private void startDaemons() { // m_outageMgr.init(); m_poller.init(); // m_outageMgr.start(); m_poller.start(); m_daemonsStarted = true; } private void stopDaemons() { if (m_daemonsStarted) { m_poller.stop(); // m_outageMgr.stop(); m_daemonsStarted = false; } } private void sleep(long millis) { try { Thread.sleep(millis); } catch (final InterruptedException e) { } } private void verifyAnticipated(long millis) { verifyAnticipated(millis, true); } private void verifyAnticipated(long millis, boolean checkUnanticipated) { // make sure the down events are received MockEventUtil.printEvents("Events we're still waiting for: ", m_anticipator.waitForAnticipated(millis)); assertTrue("Expected events not forthcoming", m_anticipator.waitForAnticipated(0).isEmpty()); if (checkUnanticipated) { sleep(2000); MockEventUtil.printEvents("Unanticipated: ", m_anticipator.unanticipatedEvents()); assertEquals("Received unexpected events", 0, m_anticipator.unanticipatedEvents().size()); } sleep(1000); m_eventMgr.finishProcessingEvents(); assertEquals("Wrong number of outages opened", m_outageAnticipator.getExpectedOpens(), m_outageAnticipator.getActualOpens()); assertEquals("Wrong number of outages in outage table", m_outageAnticipator.getExpectedOutages(), m_outageAnticipator.getActualOutages()); assertTrue("Created outages don't match the expected outages", m_outageAnticipator.checkAnticipated()); } private void anticipateUp(MockElement element) { anticipateUp(element, false); } private void anticipateUp(MockElement element, boolean force) { if (force || !element.getPollStatus().equals(PollStatus.up())) { Event event = element.createUpEvent(); m_anticipator.anticipateEvent(event); m_outageAnticipator.anticipateOutageClosed(element, event); } } private void anticipateDown(MockElement element) { anticipateDown(element, false); } private void anticipateDown(MockElement element, boolean force) { if (force || !element.getPollStatus().equals(PollStatus.down())) { Event event = element.createDownEvent(); m_anticipator.anticipateEvent(event); m_outageAnticipator.anticipateOutageOpened(element, event); } } private void anticipateServicesUp(MockElement node) { MockVisitor eventCreator = new MockVisitorAdapter() { public void visitService(MockService svc) { anticipateUp(svc); } }; node.visit(eventCreator); } private void anticipateServicesDown(MockElement node) { MockVisitor eventCreator = new MockVisitorAdapter() { public void visitService(MockService svc) { anticipateDown(svc); } }; node.visit(eventCreator); } private void createOutages(MockElement element, final Event event) { MockVisitor outageCreater = new MockVisitorAdapter() { public void visitService(MockService svc) { if (svc.getMgmtStatus().equals(SvcMgmtStatus.ACTIVE)) { m_db.createOutage(svc, event); } } }; element.visit(outageCreater); } private void bringDownCritSvcs(MockElement element) { MockVisitor markCritSvcDown = new MockVisitorAdapter() { public void visitService(MockService svc) { if ("ICMP".equals(svc.getSvcName())) { svc.bringDown(); } } }; element.visit(markCritSvcDown); } class OutageChecker extends Querier { private Event m_lostSvcEvent; private Timestamp m_lostSvcTime; private MockService m_svc; private Event m_regainedSvcEvent; private Timestamp m_regainedSvcTime; OutageChecker(MockService svc, Event lostSvcEvent) throws Exception { this(svc, lostSvcEvent, null); } OutageChecker(MockService svc, Event lostSvcEvent, Event regainedSvcEvent) { super(m_db, "select * from outages where nodeid = ? and ipAddr = ? and serviceId = ?"); m_svc = svc; m_lostSvcEvent = lostSvcEvent; m_lostSvcTime = m_db.convertEventTimeToTimeStamp(m_lostSvcEvent .getTime()); m_regainedSvcEvent = regainedSvcEvent; if (m_regainedSvcEvent != null) m_regainedSvcTime = m_db .convertEventTimeToTimeStamp(m_regainedSvcEvent .getTime()); } public void processRow(ResultSet rs) throws SQLException { assertEquals(m_svc.getNodeId(), rs.getInt("nodeId")); assertEquals(m_svc.getIpAddr(), rs.getString("ipAddr")); assertEquals(m_svc.getId(), rs.getInt("serviceId")); assertEquals(m_lostSvcEvent.getDbid(), Integer.valueOf(rs.getInt("svcLostEventId"))); assertEquals(m_lostSvcTime, rs.getTimestamp("ifLostService")); assertEquals(getRegainedEventId(), rs .getObject("svcRegainedEventId")); assertEquals(m_regainedSvcTime, rs .getTimestamp("ifRegainedService")); } private Integer getRegainedEventId() { if (m_regainedSvcEvent == null) return null; return Integer.valueOf(m_regainedSvcEvent.getDbid()); } } // TODO: test multiple polling packages // TODO: test overlapping polling packages // TODO: test two packages both with the crit service and status propagation // TODO: how does unmanaging a node/iface/service work with the poller // TODO: test over lapping poll outages }
gpl-2.0
lanrat/AudioSnap
src/com/vorsk/audiosnap/FileMover_Unused.java
2771
package com.vorsk.audiosnap; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.InputStream; import com.dropbox.client2.DropboxAPI; import com.dropbox.client2.DropboxAPI.Entry; import com.dropbox.client2.android.AndroidAuthSession; import com.dropbox.client2.exception.DropboxException; import com.dropbox.client2.exception.DropboxUnlinkedException; import android.app.Activity; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; /** * Thread which can upload and download files from dropbox * decoder * * @author Ian Foster */ class FileMover_Unused extends AsyncTask<Object, String, Void> { private final String TAG = "File Mover"; public DropboxAPI<AndroidAuthSession> mDBApi; // Gui Var, there should be a better way to do this public Activity activity; public File file; public static enum Action {UPLOAD, DOWNLOAD}; public String uploadName; @Override protected Void doInBackground(Object... o) { // kinda ctor-ish, there must be another way of doing this //activity = (Activity) o[0]; //mDBApi = (DropboxAPI<AndroidAuthSession>) o[1]; //file = (File) o[2]; //String uploadName = (String) o[3]; Action action = (Action) o[0]; Log.d(TAG, "Thread started"); if (action == Action.UPLOAD){ upload(uploadName); }else if (action == Action.DOWNLOAD){ //Code here }else{ Log.w(TAG,"unknown action"); } return null; } private void upload(String path){ publishProgress("Uploading to dropbox"); InputStream inputStream = null; try { inputStream = new FileInputStream(file); } catch (FileNotFoundException e1) { publishProgress("Cannot Read File"); return; } try { Entry newEntry = mDBApi.putFile(path, inputStream, file.length(), null, null); Log.i("DbExampleLog", "The uploaded file's rev is: " + newEntry.rev); publishProgress("Upload Finished"); } catch (DropboxUnlinkedException e) { // User has unlinked, ask them to link again here. Log.e("DbExampleLog", "User has unlinked."); publishProgress("Your Dropbox accoutn is Unlinked!"); } catch (DropboxException e) { Log.e("DbExampleLog", "Something went wrong while uploading."); publishProgress("Unknown Error while Uploading"); } } protected void onPostExecute() { //this.showToast("Upload Finished"); } @Override protected void onProgressUpdate(String... s) { Log.i(TAG,s[0]); showToast(s[0]); } public void showToast(String msg) { Toast error = Toast.makeText(activity, msg, Toast.LENGTH_LONG); error.show(); } }
gpl-2.0
msmobility/silo
siloCore/src/main/java/de/tum/bgu/msm/data/dwelling/DwellingUsage.java
542
package de.tum.bgu.msm.data.dwelling; public enum DwellingUsage { GROUP_QUARTER_OR_DEFAULT, OWNED, RENTED, VACANT; public static DwellingUsage valueOf(int code) { switch (code) { case 0: return GROUP_QUARTER_OR_DEFAULT; case 1: return OWNED; case 2: return RENTED; case 3: return VACANT; default: throw new RuntimeException("Undefined dwelling usage code " + code); } } }
gpl-2.0
flyroom/PeerfactSimKOM_Clone
src/org/peerfact/impl/analyzer/visualization2d/controller/commands/LoadFromFile.java
2007
/* * Copyright (c) 2012-2013 Open Source Community - <http://www.peerfact.org> * Copyright (c) 2011-2012 University of Paderborn - UPB * Copyright (c) 2005-2011 KOM - Multimedia Communications Lab * * This file is part of PeerfactSim.KOM. * * PeerfactSim.KOM 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 * any later version. * * PeerfactSim.KOM 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 PeerfactSim.KOM. If not, see <http://www.gnu.org/licenses/>. * */ package org.peerfact.impl.analyzer.visualization2d.controller.commands; import javax.swing.JOptionPane; import org.peerfact.impl.analyzer.visualization2d.controller.Controller; import org.peerfact.impl.analyzer.visualization2d.ui.common.dialogs.RecordFileChooser; /** * Opens a file * * @author Leo Nobach <peerfact@kom.tu-darmstadt.de> * @author Kalman Graffi <info@peerfact.org> * * @version 08/18/2011 */ public class LoadFromFile implements Command { @Override public void execute() { if (Controller.getModel() != null && Controller.getModel().isUnsaved()) { switch (JOptionPane .showConfirmDialog( Controller.getUIMainWindow(), "The current visualization has not been saved, should it be saved now?", "Load recording", JOptionPane.YES_NO_CANCEL_OPTION)) { case JOptionPane.CANCEL_OPTION: return; case JOptionPane.NO_OPTION: break; case JOptionPane.YES_OPTION: new SaveToFile().execute(); } } RecordFileChooser fc = new RecordFileChooser(); if (fc.askForOpen()) { Controller.getModel().setUnsaved(false); } } }
gpl-2.0
erpragatisingh/androidTraining
Android_6_weekTraning/MEDIA_PLAYER/src/singhraman/media_player/PlayListActivity.java
1963
package singhraman.media_player; import java.util.ArrayList; import java.util.HashMap; import android.app.ListActivity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.AdapterView.OnItemClickListener; public class PlayListActivity extends ListActivity { // Songs list public ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>(); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.playlist); ArrayList<HashMap<String, String>> songsListData = new ArrayList<HashMap<String, String>>(); SongsManager plm = new SongsManager(); // get all songs from sdcard this.songsList = plm.getPlayList(); // looping through playlist for (int i = 0; i < songsList.size(); i++) { // creating new HashMap HashMap<String, String> song = songsList.get(i); // adding HashList to ArrayList songsListData.add(song); } // Adding menuItems to ListView ListAdapter adapter = new SimpleAdapter(this, songsListData, R.layout.activity_main, new String[] { "songTitle" }, new int[] { R.id.songTitle }); setListAdapter(adapter); // selecting single ListView item ListView lv = getListView(); // listening to single listitem click lv.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // getting listitem index int songIndex = position; // Starting new intent Intent in = new Intent(getApplicationContext(), MainActivity.class); // Sending songIndex to PlayerActivity in.putExtra("songIndex", songIndex); setResult(100, in); // Closing PlayListView finish(); } }); } }
gpl-2.0
wpy2016/TimeContrloller
app/src/main/java/com/wpy/faxianbei/sk/broadcast/LockBroadCast.java
194
package com.wpy.faxianbei.sk.broadcast; import android.app.admin.DeviceAdminReceiver; /** * Created by peiyuwang on 16-12-18. */ public class LockBroadCast extends DeviceAdminReceiver { }
gpl-2.0
RedditAndroidDev/Tamagotchi
Tamagotchi-android/src/com/redditandroiddevelopers/tamagotchi/MainActivity.java
3402
package com.redditandroiddevelopers.tamagotchi; import android.content.Context; import android.os.Bundle; import com.badlogic.gdx.backends.android.AndroidApplication; import com.badlogic.gdx.backends.android.AndroidApplicationConfiguration; import com.redditandroiddevelopers.tamagotchi.dao.CreatureDao; import com.redditandroiddevelopers.tamagotchi.dao.CreatureDatabase; import com.redditandroiddevelopers.tamagotchi.dao.CreatureEvolutionDao; import com.redditandroiddevelopers.tamagotchi.dao.CreatureRaiseTypeDao; import com.redditandroiddevelopers.tamagotchi.dao.CreatureStateDao; import com.redditandroiddevelopers.tamagotchi.dao.ExperienceActionDao; import com.redditandroiddevelopers.tamagotchi.dao.MedicineDao; import com.redditandroiddevelopers.tamagotchi.dao.SicknessDao; import com.redditandroiddevelopers.tamagotchi.mappers.CreatureEvolutionMapper; import com.redditandroiddevelopers.tamagotchi.mappers.CreatureMapper; import com.redditandroiddevelopers.tamagotchi.mappers.CreatureRaiseTypeMapper; import com.redditandroiddevelopers.tamagotchi.mappers.CreatureStateMapper; import com.redditandroiddevelopers.tamagotchi.mappers.ExperienceActionMapper; import com.redditandroiddevelopers.tamagotchi.mappers.MedicineMapper; import com.redditandroiddevelopers.tamagotchi.mappers.SicknessMapper; import com.redditandroiddevelopers.tamagotchi.model.Creature; import com.redditandroiddevelopers.tamagotchi.model.CreatureEvolution; import com.redditandroiddevelopers.tamagotchi.model.CreatureRaiseType; import com.redditandroiddevelopers.tamagotchi.model.CreatureState; import com.redditandroiddevelopers.tamagotchi.model.ExperienceAction; import com.redditandroiddevelopers.tamagotchi.model.Medicine; import com.redditandroiddevelopers.tamagotchi.model.Sickness; public class MainActivity extends AndroidApplication { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AndroidApplicationConfiguration cfg = new AndroidApplicationConfiguration(); cfg.useGL20 = false; TamagotchiConfiguration tcfg = new TamagotchiConfiguration(); initializeDatabase(tcfg); initialize(new TamagotchiGame(tcfg), cfg); } private void initializeDatabase(TamagotchiConfiguration config) { final Context context = getBaseContext(); config.creatureDao = new CreatureDao(new CreatureDatabase<Creature>( context), new CreatureMapper()); config.creatureEvolutionDao = new CreatureEvolutionDao( new CreatureDatabase<CreatureEvolution>( context), new CreatureEvolutionMapper()); config.creatureRaiseTypeDao = new CreatureRaiseTypeDao( new CreatureDatabase<CreatureRaiseType>( context), new CreatureRaiseTypeMapper()); config.creatureStateDao = new CreatureStateDao(new CreatureDatabase<CreatureState>( context), new CreatureStateMapper()); config.experienceActionDao = new ExperienceActionDao(new CreatureDatabase<ExperienceAction>( context), new ExperienceActionMapper()); config.medicineDao = new MedicineDao(new CreatureDatabase<Medicine>( context), new MedicineMapper()); config.sicknessDao = new SicknessDao(new CreatureDatabase<Sickness>( context), new SicknessMapper()); } }
gpl-2.0
RamiLego4Game/GalacticraftPixelGalaxy
src/main/java/com/ramilego/pixelgalaxy/PixelRecipes.java
26537
package com.ramilego.pixelgalaxy; import net.minecraft.init.Blocks; import net.minecraft.init.Items; import net.minecraft.item.ItemStack; import com.ramilego.pixelgalaxy.blocks.PixelGalaxyBlocks; import com.ramilego.pixelgalaxy.items.PixelGalaxyItems; import cpw.mods.fml.common.registry.GameRegistry; public class PixelRecipes { public static void registerCraftingRecipes(){ //Tools : //Pixelizer Sword GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelizerSword, 1), new Object[]{ " P ", " P ", " S ", 'P', PixelGalaxyItems.pixelizerIngot, 'S', PixelGalaxyItems.pixelWoodStickItem}); //Pixelizer Hoe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelizerHoe, 1), new Object[]{ "PP ", " S ", " S ", 'P', PixelGalaxyItems.pixelizerIngot, 'S', PixelGalaxyItems.pixelWoodStickItem }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelizerHoe, 1), new Object[]{ " PP", " S ", " S ", 'P', PixelGalaxyItems.pixelizerIngot, 'S', PixelGalaxyItems.pixelWoodStickItem }); //Pixelizer Pickaxe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelizerPickaxe, 1), new Object[]{ "PPP", " S ", " S ", 'P', PixelGalaxyItems.pixelizerIngot, 'S', PixelGalaxyItems.pixelWoodStickItem }); //Pixelizer Shovel GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelizerShovel, 1), new Object[]{ " P ", " S ", " S ", 'P', PixelGalaxyItems.pixelizerIngot, 'S', PixelGalaxyItems.pixelWoodStickItem }); //Pixelizer Axe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelizerAxe, 1), new Object[]{ " PP", " SP", " S ", 'P', PixelGalaxyItems.pixelizerIngot, 'S', PixelGalaxyItems.pixelWoodStickItem }); //Pixelizer Axe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelizerAxe, 1), new Object[]{ "PP ", "PS ", " S ", 'P', PixelGalaxyItems.pixelizerIngot, 'S', PixelGalaxyItems.pixelWoodStickItem }); //diamondPixel Sword GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.diamondPixelSword, 1), new Object[]{ " D ", " D ", " S ", 'D', PixelGalaxyItems.diamondPixel, 'S', PixelGalaxyItems.pixelWoodStickItem }); //diamondPixel Hoe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.diamondPixelHoe, 1), new Object[]{ "DD ", " S ", " S ", 'D', PixelGalaxyItems.diamondPixel, 'S', PixelGalaxyItems.pixelWoodStickItem }); //diamondPixel Hoe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.diamondPixelHoe, 1), new Object[]{ " DD", " S ", " S ", 'D', PixelGalaxyItems.diamondPixel, 'S', PixelGalaxyItems.pixelWoodStickItem }); //diamondPixel Pickaxe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.diamondPixelPickaxe, 1), new Object[]{ "DDD", " S ", " S ", 'D', PixelGalaxyItems.diamondPixel, 'S', PixelGalaxyItems.pixelWoodStickItem }); //diamondPixel Shovel GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.diamondPixelShovel, 1), new Object[]{ " D ", " S ", " S ", 'D', PixelGalaxyItems.diamondPixel, 'S', PixelGalaxyItems.pixelWoodStickItem }); //diamondPixel Axe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.diamondPixelAxe, 1), new Object[]{ " DD", " SD", " S ", 'D', PixelGalaxyItems.diamondPixel, 'S', PixelGalaxyItems.pixelWoodStickItem }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.diamondPixelAxe, 1), new Object[]{ "DD ", "DS ", " S ", 'D', PixelGalaxyItems.diamondPixel, 'S', PixelGalaxyItems.pixelWoodStickItem }); /*------------------------------------------------------------------------------------------------------------------------------------*/ //IronPixel Sword GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ironPixelSword, 1), new Object[]{ " D ", " D ", " S ", 'D', PixelGalaxyItems.ironPixelIngot, 'S', PixelGalaxyItems.pixelWoodStickItem }); //IronPixel Hoe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ironPixelHoe, 1), new Object[]{ "DD ", " S ", " S ", 'D', PixelGalaxyItems.ironPixelIngot, 'S', PixelGalaxyItems.pixelWoodStickItem }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ironPixelHoe, 1), new Object[]{ " DD", " S ", " S ", 'D', PixelGalaxyItems.ironPixelIngot, 'S', PixelGalaxyItems.pixelWoodStickItem }); //IronPixel Pickaxe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ironPixelPickaxe, 1), new Object[]{ "DDD", " S ", " S ", 'D', PixelGalaxyItems.ironPixelIngot, 'S', PixelGalaxyItems.pixelWoodStickItem }); //IronPixel Shovel GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ironPixelShovel, 1), new Object[]{ " D ", " S ", " S ", 'D', PixelGalaxyItems.ironPixelIngot, 'S', PixelGalaxyItems.pixelWoodStickItem }); //IronPixel Axe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ironPixelAxe, 1), new Object[]{ " DD", " SD", " S ", 'D', PixelGalaxyItems.ironPixelIngot, 'S', PixelGalaxyItems.pixelWoodStickItem }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ironPixelAxe, 1), new Object[]{ "DD ", "DS ", " S ", 'D', PixelGalaxyItems.ironPixelIngot, 'S', PixelGalaxyItems.pixelWoodStickItem }); //Armors: //Pixelizer Helmet GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelizerHelmet, 1), new Object[]{ "PPP", "P P", " ", 'P', PixelGalaxyItems.pixelizerIngot }); //Pixelizer Chestplate GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelizerChestplate, 1), new Object[]{ "P P", "PPP", "PPP", 'P', PixelGalaxyItems.pixelizerIngot }); //Pixelizer Legging GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelizerLeggings, 1), new Object[]{ "PPP", "P P", "P P", 'P', PixelGalaxyItems.pixelizerIngot }); //Pixelizer Boots GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelizerBoots, 1), new Object[]{ " ", "P P", "P P", 'P', PixelGalaxyItems.pixelizerIngot }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelizerBoots, 1), new Object[]{ "P P", "P P", " ", 'P', PixelGalaxyItems.pixelizerIngot }); /*-----------------------------------------------------------------------------------------------------------------------------------------*/ //DiamondPixel Helmet GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.diamondPixelHelmet, 1), new Object[]{ "DDD", "D D", " ", 'D', PixelGalaxyItems.diamondPixel }); //DiamondPixel Chestplate GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.diamondPixelChestplate, 1), new Object[]{ "D D", "DDD", "DDD", 'D', PixelGalaxyItems.diamondPixel }); //DiamondPixel Legging GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.diamondPixelLeggings, 1), new Object[]{ "DDD", "D D", "D D", 'D', PixelGalaxyItems.diamondPixel }); //DiamondPixel Boots GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.diamondPixelBoots, 1), new Object[]{ " ", "D D", "D D", 'D', PixelGalaxyItems.diamondPixel }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.diamondPixelBoots, 1), new Object[]{ "D D", "D D", " ", 'D', PixelGalaxyItems.diamondPixel }); //Pixelizer Block : GameRegistry.addRecipe(new ItemStack(PixelGalaxyBlocks.pixelizerBlock, 1), new Object[]{ "PPP", "PPP", "PPP", 'P', PixelGalaxyItems.pixelizerIngot }); //diamondPixel Block GameRegistry.addRecipe(new ItemStack(PixelGalaxyBlocks.pixelizerdiamondBlock, 1), new Object[]{ "DDD", "DDD", "DDD", 'D', PixelGalaxyItems.diamondPixel }); //diamondPixel Block GameRegistry.addRecipe(new ItemStack(PixelGalaxyBlocks.pixelIronBlock, 1), new Object[]{ "DDD", "DDD", "DDD", 'D', PixelGalaxyItems.ironPixelIngot }); //blueStone Block GameRegistry.addRecipe(new ItemStack(PixelGalaxyBlocks.GlowingBlueStoneBlock, 1), new Object[]{ "DDD", "DDD", "DDD", 'D', PixelGalaxyItems.blueStoneIngot }); //PixelCoal Block GameRegistry.addRecipe(new ItemStack(PixelGalaxyBlocks.pixelCoalBlocks, 1), new Object[]{ "DDD", "DDD", "DDD", 'D', PixelGalaxyItems.pixelCoal }); //Pixel Wood Block Level 0: GameRegistry.addRecipe(new ItemStack(PixelGalaxyBlocks.pixelWoodBlock, 1), new Object[]{ "WWW", "W W", "WWW", 'W', PixelGalaxyItems.pixelWoodItem }); //PixelRiceBread GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelRiceBread, 2), new Object[]{ "WWW", " ", " ", 'W', PixelGalaxyItems.pixelRice }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelRiceBread, 2), new Object[]{ " ", "WWW", " ", 'W', PixelGalaxyItems.pixelRice }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelRiceBread, 2), new Object[]{ " ", " ", "WWW", 'W', PixelGalaxyItems.pixelRice }); //PixelWheatBread GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelWheatBread, 1), new Object[]{ "WWW", " ", " ", 'W', PixelGalaxyItems.pixelWheat }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelWheatBread, 1), new Object[]{ " ", "WWW", " ", 'W', PixelGalaxyItems.pixelWheat }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelWheatBread, 1), new Object[]{ " ", " ", "WWW", 'W', PixelGalaxyItems.pixelWheat }); /*-----------------------------------------------------------------------------------------------------------------------------------------------------------------*/ //IronPixel Helmet GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ironPixelHelmet, 1), new Object[]{ "DDD", "D D", " ", 'D', PixelGalaxyItems.ironPixelIngot }); //IronPixel Chestplate GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ironPixelChestplate, 1), new Object[]{ "D D", "DDD", "DDD", 'D', PixelGalaxyItems.ironPixelIngot }); //IronPixel Legging GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ironPixelLeggings, 1), new Object[]{ "DDD", "D D", "D D", 'D', PixelGalaxyItems.ironPixelIngot }); //DiamondPixel Boots GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ironPixelBoots, 1), new Object[]{ " ", "D D", "D D", 'D', PixelGalaxyItems.ironPixelIngot }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ironPixelBoots, 1), new Object[]{ "D D", "D D", " ", 'D', PixelGalaxyItems.ironPixelIngot }); /*-----------------------------------------------------------------------------------------------------------------------------------------------------------------*/ //ChainPixel Helmet GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ChainPixelHelmet, 1), new Object[]{ "DDD", "D D", " ", 'D', PixelGalaxyItems.pixelChain }); //ChainPixel Chestplate GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ChainPixelChestplate, 1), new Object[]{ "D D", "DDD", "DDD", 'D', PixelGalaxyItems.pixelChain }); //ChainPixel Legging GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ChainPixelLeggings, 1), new Object[]{ "DDD", "D D", "D D", 'D', PixelGalaxyItems.pixelChain }); //ChainPixel Boots GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ChainPixelBoots, 1), new Object[]{ " ", "D D", "D D", 'D', PixelGalaxyItems.pixelChain }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.ChainPixelBoots, 1), new Object[]{ "D D", "D D", " ", 'D', PixelGalaxyItems.pixelChain }); /*-----------------------------------------------------------------------------------------------------------------------------------------------------------------*/ //GoldPixel Helmet GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelgold_helmet, 1), new Object[]{ "DDD", "D D", " ", 'D', PixelGalaxyItems.pixelgoldingot }); //GoldPixel Chestplate GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelgold_chestplate, 1), new Object[]{ "D D", "DDD", "DDD", 'D', PixelGalaxyItems.pixelgoldingot }); //GoldPixel Legging GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelgold_leggings, 1), new Object[]{ "DDD", "D D", "D D", 'D', PixelGalaxyItems.pixelgoldingot }); //GoldPixel Boots GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelgold_boots, 1), new Object[]{ " ", "D D", "D D", 'D', PixelGalaxyItems.pixelgoldingot }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelgold_boots, 1), new Object[]{ "D D", "D D", " ", 'D', PixelGalaxyItems.pixelgoldingot }); /*-----------------------------------------------------------------------------------------------------------------------------------------------------------------*/ //stonePixel Sword GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.stonePixelSword, 1), new Object[]{ " D ", " D ", " S ", 'D', PixelGalaxyBlocks.pixelCobblestoneStone, 'S', PixelGalaxyItems.pixelWoodStickItem }); //stonePixel Hoe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.stonePixelHoe, 1), new Object[]{ "DD ", " S ", " S ", 'D', PixelGalaxyBlocks.pixelCobblestoneStone, 'S', PixelGalaxyItems.pixelWoodStickItem }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.stonePixelHoe, 1), new Object[]{ " DD", " S ", " S ", 'D', PixelGalaxyBlocks.pixelCobblestoneStone, 'S', PixelGalaxyItems.pixelWoodStickItem }); //stonePixel Pickaxe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.stonePixelPickaxe, 1), new Object[]{ "DDD", " S ", " S ", 'D', PixelGalaxyBlocks.pixelCobblestoneStone, 'S', PixelGalaxyItems.pixelWoodStickItem }); //stonePixel Shovel GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.stonePixelShovel, 1), new Object[]{ " D ", " S ", " S ", 'D', PixelGalaxyBlocks.pixelCobblestoneStone, 'S', PixelGalaxyItems.pixelWoodStickItem }); //stonePixel Axe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.stonePixelAxe, 1), new Object[]{ " DD", " SD", " S ", 'D', PixelGalaxyBlocks.pixelCobblestoneStone, 'S', PixelGalaxyItems.pixelWoodStickItem }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.stonePixelAxe, 1), new Object[]{ "DD ", "DS ", " S ", 'D', PixelGalaxyBlocks.pixelCobblestoneStone, 'S', PixelGalaxyItems.pixelWoodStickItem }); /*-----------------------------------------------------------------------------------------------------------------------------------------------------------------*/ //PixelGold Sword GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelGoldSword, 1), new Object[]{ " D ", " D ", " S ", 'D', PixelGalaxyItems.pixelgoldingot, 'S', PixelGalaxyItems.pixelWoodStickItem }); //PixelGold Hoe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelGoldHoe, 1), new Object[]{ "DD ", " S ", " S ", 'D', PixelGalaxyItems.pixelgoldingot, 'S', PixelGalaxyItems.pixelWoodStickItem }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelGoldHoe, 1), new Object[]{ " DD", " S ", " S ", 'D', PixelGalaxyItems.pixelgoldingot, 'S', PixelGalaxyItems.pixelWoodStickItem }); //PixelGold Pickaxe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelGoldPickaxe, 1), new Object[]{ "DDD", " S ", " S ", 'D', PixelGalaxyItems.pixelgoldingot, 'S', PixelGalaxyItems.pixelWoodStickItem }); //PixelGold Shovel GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelGoldShovel, 1), new Object[]{ " D ", " S ", " S ", 'D', PixelGalaxyItems.pixelgoldingot, 'S', PixelGalaxyItems.pixelWoodStickItem }); //PixelGold Axe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelGoldAxe, 1), new Object[]{ " DD", " SD", " S ", 'D', PixelGalaxyItems.pixelgoldingot, 'S', PixelGalaxyItems.pixelWoodStickItem }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelGoldAxe, 1), new Object[]{ "DD ", "DS ", " S ", 'D', PixelGalaxyItems.pixelgoldingot, 'S', PixelGalaxyItems.pixelWoodStickItem }); /*-----------------------------------------------------------------------------------------------------------------------------------------------------------------*/ //woodPixel Sword GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.woodPixelSword, 1), new Object[]{ " D ", " D ", " S ", 'D', PixelGalaxyItems.pixelWoodItem, 'S', PixelGalaxyItems.pixelWoodStickItem }); //woodPixel Hoe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.woodPixelHoe, 1), new Object[]{ "DD ", " S ", " S ", 'D', PixelGalaxyItems.pixelWoodItem, 'S', PixelGalaxyItems.pixelWoodStickItem }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.woodPixelHoe, 1), new Object[]{ " DD", " S ", " S ", 'D', PixelGalaxyItems.pixelWoodItem, 'S', PixelGalaxyItems.pixelWoodStickItem }); //woodPixel Pickaxe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.woodPixelPickaxe, 1), new Object[]{ "DDD", " S ", " S ", 'D', PixelGalaxyItems.pixelWoodItem, 'S', PixelGalaxyItems.pixelWoodStickItem }); //woodPixel Shovel GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.woodPixelShovel, 1), new Object[]{ " D ", " S ", " S ", 'D', PixelGalaxyItems.pixelWoodItem, 'S', PixelGalaxyItems.pixelWoodStickItem }); //woodPixel Axe GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.woodPixelAxe, 1), new Object[]{ " DD", " SD", " S ", 'D', PixelGalaxyItems.pixelWoodItem, 'S', PixelGalaxyItems.pixelWoodStickItem }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.woodPixelAxe, 1), new Object[]{ "DD ", "DS ", " S ", 'D', PixelGalaxyItems.pixelWoodItem, 'S', PixelGalaxyItems.pixelWoodStickItem }); //beta Items and blocks //crafting table GameRegistry.addRecipe(new ItemStack(Blocks.crafting_table, 1), new Object[]{ "DD ", "DD ", " ", 'D', PixelGalaxyItems.pixelWoodItem, }); GameRegistry.addRecipe(new ItemStack(Blocks.crafting_table, 1), new Object[]{ " ", "DD ", "DD ", 'D', PixelGalaxyItems.pixelWoodItem, }); GameRegistry.addRecipe(new ItemStack(Blocks.crafting_table, 1), new Object[]{ " ", " DD", " DD", 'D', PixelGalaxyItems.pixelWoodItem, }); GameRegistry.addRecipe(new ItemStack(Blocks.crafting_table, 1), new Object[]{ " DD", " DD", " ", 'D', PixelGalaxyItems.pixelWoodItem, }); GameRegistry.addRecipe(new ItemStack(Blocks.furnace, 1), new Object[]{ "DDD", "D D", "DDD", 'D', PixelGalaxyBlocks.pixelCobblestoneStone, }); /*-----------------------------------------------------------------------------------------------------------------------------------------------------------------*/ //Bowl GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelbowl, 1), new Object[]{ " ", "B B", " B ", 'B', PixelGalaxyItems.pixelWoodItem, }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelbowl, 1), new Object[]{ "B B", " B ", " ", 'B', PixelGalaxyItems.pixelWoodItem, }); //pixelBeetRootsoup GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelbeetrootsoup, 1), new Object[]{ "BBB", "BBB", " H ", 'B', PixelGalaxyItems.pixelBeetroot, 'H', PixelGalaxyItems.pixelbowl, }); //pixelPotatoSoup GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelPotatoSoup, 1), new Object[]{ "BBB", "BBB", " H ", 'B', PixelGalaxyItems.pixelPotato, 'H', PixelGalaxyItems.pixelbowl, }); //pixelCarrotSoup GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelCarrotSoup, 1), new Object[]{ "BBB", "BBB", " H ", 'B', PixelGalaxyItems.pixelCarrot, 'H', PixelGalaxyItems.pixelbowl, }); //pixelPeaStew GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelPeaStew, 1), new Object[]{ "BBB", " R ", " H ", 'R', PixelGalaxyItems.pixelRice, 'B', PixelGalaxyItems.pixelPea, 'H', PixelGalaxyItems.pixelbowl, }); /*******************************************************************************************************************************************************/ //pIXELNitrogenDrink GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelNitrogenDrink, 1), new Object[]{ " ", " R ", " H ", 'R', PixelGalaxyBlocks.intensePixelNitrogen, 'H', PixelGalaxyItems.pixelBottle, }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelNitrogenDrink, 1), new Object[]{ " R ", " H ", " ", 'R', PixelGalaxyBlocks.intensePixelNitrogen, 'H', PixelGalaxyItems.pixelBottle, }); //pixel AppleJuice GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelAppleJuice, 1), new Object[]{ " ", " R ", " H ", 'R', PixelGalaxyItems.pixelApple, 'H', PixelGalaxyItems.pixelBottle, }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelAppleJuice, 1), new Object[]{ " R ", " H ", " ", 'R', PixelGalaxyItems.pixelApple, 'H', PixelGalaxyItems.pixelBottle, }); //pixel OrangeJuice GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelOrangeJuice, 1), new Object[]{ " ", " R ", " H ", 'R', PixelGalaxyItems.pixelOrange, 'H', PixelGalaxyItems.pixelBottle, }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelOrangeJuice, 1), new Object[]{ " R ", " H ", " ", 'R', PixelGalaxyItems.pixelOrange, 'H', PixelGalaxyItems.pixelBottle, }); /*------PixelStick--------------------------------------------------------------------------------------------------------------------------------------*/ GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelWoodStickItem, 4), new Object[]{ " ", "B ", "B ", 'B', PixelGalaxyItems.pixelWoodItem, }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelWoodStickItem, 4), new Object[]{ " ", " B ", " B ", 'B', PixelGalaxyItems.pixelWoodItem, }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelWoodStickItem, 4), new Object[]{ " ", " B", " B", 'B', PixelGalaxyItems.pixelWoodItem, }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelWoodStickItem, 4), new Object[]{ "B ", "B ", " ", 'B', PixelGalaxyItems.pixelWoodItem, }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelWoodStickItem, 4), new Object[]{ " B ", " B ", " ", 'B', PixelGalaxyItems.pixelWoodItem, }); GameRegistry.addRecipe(new ItemStack(PixelGalaxyItems.pixelWoodStickItem, 4), new Object[]{ " B", " B", " ", 'B', PixelGalaxyItems.pixelWoodItem, }); /*-----------------------------------------------------------------------------------------------------------------------------------------------------------------*/ GameRegistry.addShapelessRecipe(new ItemStack(PixelGalaxyItems.pixelizerIngot, 9), new Object[]{ PixelGalaxyBlocks.pixelizerBlock}); GameRegistry.addShapelessRecipe(new ItemStack(PixelGalaxyItems.diamondPixel, 9), new Object[]{ PixelGalaxyBlocks.pixelizerdiamondBlock}); GameRegistry.addShapelessRecipe(new ItemStack(PixelGalaxyItems.ironPixelIngot, 9), new Object[]{ PixelGalaxyBlocks.pixelIronBlock}); GameRegistry.addShapelessRecipe(new ItemStack(PixelGalaxyItems.blueStoneIngot, 9), new Object[]{ PixelGalaxyBlocks.GlowingBlueStoneBlock}); GameRegistry.addShapelessRecipe(new ItemStack(PixelGalaxyItems.pixelPumkinSeed, 4), new Object[]{ PixelGalaxyBlocks.pixelPumpkin}); GameRegistry.addShapelessRecipe(new ItemStack(PixelGalaxyItems.pixelCoal, 9), new Object[]{ PixelGalaxyBlocks.pixelCoalBlocks}); GameRegistry.addShapelessRecipe(new ItemStack(PixelGalaxyItems.pixelPeaSeed, 3), new Object[]{ PixelGalaxyItems.pixelPea}); } public static void registerSmeltingRecipes(){ GameRegistry.addSmelting(PixelGalaxyBlocks.pixelizerOre, new ItemStack(PixelGalaxyItems.pixelizerIngot, 1), 1.0F); GameRegistry.addSmelting(PixelGalaxyBlocks.pixelizerDiamondOre, new ItemStack(PixelGalaxyItems.diamondPixel, 1), 1.0F); GameRegistry.addSmelting(PixelGalaxyBlocks.pixelIronOre, new ItemStack(PixelGalaxyItems.ironPixelIngot, 1), 1.0F); GameRegistry.addSmelting(PixelGalaxyBlocks.pixelCobblestoneStone, new ItemStack(PixelGalaxyBlocks.pixelStone, 1), 0F); GameRegistry.addSmelting(PixelGalaxyItems.pixelWoodItem, new ItemStack(PixelGalaxyItems.pixelCharCoal, 1), 0F); GameRegistry.addSmelting(PixelGalaxyBlocks.pixelCoalOre, new ItemStack(PixelGalaxyItems.pixelCoal, 1), 0F); GameRegistry.addSmelting(PixelGalaxyItems.pixelPotato, new ItemStack(PixelGalaxyItems.pixelBakedPotato, 1), 0.35F); GameRegistry.addSmelting(PixelGalaxyItems.pixelRewPorkchop, new ItemStack(PixelGalaxyItems.pixelCookedPorkchop, 1), 0.35F); GameRegistry.addSmelting(PixelGalaxyItems.pixelbeefraw, new ItemStack(PixelGalaxyItems.pixelbeefcooked, 1), 0.35F); GameRegistry.addSmelting(PixelGalaxyItems.ironPixelIngot, new ItemStack(PixelGalaxyItems.pixelChain, 4), 0.35F); GameRegistry.addSmelting(PixelGalaxyBlocks.pixelGoldOre, new ItemStack(PixelGalaxyItems.pixelgoldingot, 1), 5.35F); } }
gpl-2.0
littcai/saap
saap/saap-common/src/main/java/com/litt/saap/core/model/CheckItem.java
1170
package com.litt.saap.core.model; import java.io.Serializable; /** * 复选项对象. * * <pre><b>描述:</b> * 在对象外封装一层选中状态,用于传递给上层 * </pre> * * <pre><b>修改记录:</b> * * </pre> * * @author <a href="mailto:littcai@hotmail.com">蔡源</a> * @since 2014年4月16日 * @version 1.0 */ public class CheckItem<T> implements Serializable { /** The Constant serialVersionUID. */ private static final long serialVersionUID = 1L; /** 是否选中. */ private boolean isChecked = false; private T obj; /** * @param obj */ public CheckItem(T obj) { this.obj = obj; } /** * @param isChecked * @param obj */ public CheckItem(boolean isChecked, T obj) { super(); this.isChecked = isChecked; this.obj = obj; } /** * @return the isChecked */ public boolean isChecked() { return isChecked; } /** * @param isChecked the isChecked to set */ public void setChecked(boolean isChecked) { this.isChecked = isChecked; } /** * @return the obj */ public T getObj() { return obj; } }
gpl-2.0
dmcennis/jMir
jMIR_2_4_developer/jLyrics/src/jlyrics/features/LinesPerSegmentVariance.java
3249
/* * LinesPerSegmentVariance.java * Version 1.0 * * Last modified on April 11, 2010. * McGill University */ package jlyrics.features; import ace.datatypes.FeatureDefinition; import jlyrics.datatypes.SongLyrics; /** * A feature extractor that extracts the variance of the number of lines per segment (e.g. verses, choruses, * etc.) in the text. Segments are assumed to be segmented by blank lines, and lines are segmented by line * breaks. Lines consisting only of line breaks are filtered out. This calculation does not include lines * consisting only of line breaks. * * @author Cory McKay */ public class LinesPerSegmentVariance extends LyricsFeatureExtractor { /* CONSTRUCTOR ******************************************************************************************/ /** * Basic constructor that sets the class's inherited fields. */ public LinesPerSegmentVariance() { // Specify descriptive metadata about the function String name = "Lines Per Segment Variance"; String description = "The variance of the number of lines per segments (e.g. verses, choruses, etc.) " + "in the text. Segments are assumed to be segmented by blank lines, and lines are segmented " + "by line breaks. Lines consisting only of line breaks are filtered out. This count does not " + "include lines consisting only of line breaks."; boolean is_sequential = false; int dimensions = 1; // Set the superclass's fields appropriately feature_description = new FeatureDefinition(name, description, is_sequential, dimensions); feature_dependencies = null; external_dependencies = null; } /* PUBLIC METHODS ***************************************************************************************/ /** * Extract this feature from given song lyrics. * * @param lyrics The lyrics to extract the feature from. * @param other_feature_values Ignored (not needed to calculate this feature). * @param external_information Ignored (not needed to calculate this feature). * @return The extracted feature value. Null if the feature cannot be extracted * from the given data. * @throws Exception Throws an informative exception if invalid data is provided. */ public double[] extractFeature(SongLyrics lyrics, double[][] other_feature_values, Object[][] external_information) throws Exception { // Throw an exception if no lyrics data is provided if (lyrics == null) throw new Exception("No lyrics data provided."); // Prepare the result and default it to 0 double[] result = new double[1]; result[0] = 0.0; // Return 0 if there are no words if (!lyrics.isLyricsAvailable()) return result; // Break into segments String[][] segments = lyrics.getSongSegments(); // Count the lines per segment int[] lines_per_segment = new int[segments.length]; for (int i = 0; i < segments.length; i++) lines_per_segment[i] = segments[i].length; // Calculate the variance double standard_deviation = mckay.utilities.staticlibraries.MathAndStatsMethods.getStandardDeviation(lines_per_segment); double variance = standard_deviation * standard_deviation; // Calculate the feature value result[0] = variance; // Return the result return result; } }
gpl-2.0
adriannovegil/apache-spark-benchmark
src/main/java/es/devcircus/apache/spark/benchmark/util/FileHelper.java
4877
/** * This file is part of Apache Spark Benchmark. * * Apache Spark Benchmark 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. * * Apache Spark Benchmark 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; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. */ package es.devcircus.apache.spark.benchmark.util; import es.devcircus.apache.spark.benchmark.util.config.ConfigurationManager; import java.io.*; import java.util.*; /** * * @author Adrian Novegil <adrian.novegil@gmail.com> */ public abstract class FileHelper { /** * The jar file / bin directory that contains this class */ public static final String CLASS_ROOT = new File(FileHelper.class.getProtectionDomain() .getCodeSource().getLocation().getFile()).getPath(); /** * The root of the benchmark directory */ public static final File ROOT_DIR = new File( ConfigurationManager.get("apache.benchmark.config.global.root.dir")); /** * Output result file (filled in addition to stdout results) */ public static final File RESULT_FILE = new File(ROOT_DIR + "/", "results.txt"); /** * Deletes the files and sub directories in a specified directory. * * @param dir an existing directory to delete its content */ public static void deleteDirContent(File dir) { for (File file : dir.listFiles()) { if (file.isDirectory()) { deleteDirContent(file); } file.delete(); } } /** * Calculates db disk space in a specified file or directory. * * @param file a file or a directory to check its disk space * @return the total disk space in bytes. */ static long getDiskSpace(File file) { long size = file.length(); if (file.isDirectory()) { for (File f : file.listFiles()) { String name = f.getName(); if (name.endsWith("old") || name.endsWith("log") || name.endsWith(".odr") || name.endsWith(".odb$")) { continue; // temporary/log files that can be ignored } size += getDiskSpace(f); } } return size; } /** * Gets all the JAR files in a specified directory. * * @param dir a directory of JAR (and other) files * @return the JAR files in that directory. */ static File[] getJarFiles(File dir) { return dir.listFiles( new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.toLowerCase().endsWith(".jar"); } } ); } /** * Adds the paths of specified JAR files to a list of paths. * * @param jarFiles the jar files * @param resultPathList list to be filled with JAR paths */ static void addJarFiles(File[] jarFiles, List<String> resultPathList) { if (jarFiles != null) { for (File jarFile : jarFiles) { resultPathList.add(jarFile.getAbsolutePath()); } } } /** * Writes a complete text file. * * @param text the text to be written * @param file the file to which to write */ public static void writeTextFile(String text, File file) { try { File dir = file.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } try (FileOutputStream out = new FileOutputStream(file)) { out.write(text.getBytes()); } } catch (IOException e) { throw new RuntimeException(e); } } /** * Appends a single text line to a text file. * * @param line a string to be written as a new text line * @param file the text file to append the line to */ public static void writeTextLine(String line, File file) { try { try (PrintWriter writer = new PrintWriter(new FileWriter(file, true))) { writer.println(line); } } catch (IOException e) { System.exit(1); } } }
gpl-2.0
ia-toki/judgels-play-commons
app/org/iatoki/judgels/play/services/impls/AbstractBaseJidCacheServiceImpl.java
2424
package org.iatoki.judgels.play.services.impls; import com.google.common.collect.ImmutableMap; import com.google.common.collect.Maps; import org.iatoki.judgels.play.models.daos.BaseJidCacheDao; import org.iatoki.judgels.play.models.entities.AbstractJidCacheModel; import org.iatoki.judgels.play.services.BaseJidCacheService; import java.util.List; import java.util.Map; public abstract class AbstractBaseJidCacheServiceImpl<M extends AbstractJidCacheModel> implements BaseJidCacheService<M> { private final BaseJidCacheDao<M> jidCacheDao; public AbstractBaseJidCacheServiceImpl(BaseJidCacheDao<M> jidCacheDao) { this.jidCacheDao = jidCacheDao; } @Override public final void putDisplayName(String jid, String displayName, String user, String ipAddress) { if (jidCacheDao.existsByJid(jid)) { editDisplayName(jid, displayName, user, ipAddress); } else { createDisplayName(jid, displayName, user, ipAddress); } } @Override public final String getDisplayName(String jid) { if (!jidCacheDao.existsByJid(jid)) { return jid; } else { M jidCacheModel = jidCacheDao.findByJid(jid); return jidCacheModel.displayName; } } @Override public final Map<String, String> getDisplayNames(List<String> jids) { List<M> entries = jidCacheDao.findByJids(jids); Map<String, String> displayNamesMap = Maps.newHashMap(); for (M entry : entries) { displayNamesMap.put(entry.jid, entry.displayName); } for (String jid : jids) { if (!displayNamesMap.containsKey(jid)) { displayNamesMap.put(jid, jid); } } return ImmutableMap.copyOf(displayNamesMap); } private void createDisplayName(String jid, String displayName, String user, String ipAddress) { M jidCacheModel = jidCacheDao.createJidCacheModel(); jidCacheModel.jid = jid; jidCacheModel.displayName = displayName; jidCacheDao.persist(jidCacheModel, user, ipAddress); } private void editDisplayName(String jid, String displayName, String user, String ipAddress) { M jidCacheModel = jidCacheDao.findByJid(jid); jidCacheModel.jid = jid; jidCacheModel.displayName = displayName; jidCacheDao.edit(jidCacheModel, user, ipAddress); } }
gpl-2.0
wangtaoenter/Books
Main/obsolete/j2me/src/org/zlibrary/ui/j2me/application/ZLJ2MEApplicationWindow.java
1869
/* * Copyright (C) 2007-2009 Geometer Plus <contact@geometerplus.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301, USA. */ package org.geometerplus.zlibrary.ui.j2me.application; import org.geometerplus.zlibrary.core.application.*; import org.geometerplus.zlibrary.core.view.ZLViewWidget; import org.geometerplus.zlibrary.ui.j2me.view.*; public class ZLJ2MEApplicationWindow extends ZLApplicationWindow { private final ZLCanvas myCanvas; public ZLJ2MEApplicationWindow(ZLApplication application, ZLCanvas canvas) { super(application); myCanvas = canvas; } protected void initMenu() { // TODO: implement } public void setToolbarItemState(ZLApplication.Toolbar.Item item, boolean visible, boolean enabled) { // TODO: implement } protected ZLViewWidget createViewWidget() { return new ZLJ2MEViewWidget(myCanvas); } public void addToolbarItem(ZLApplication.Toolbar.Item item) { // TODO: implement } public void close() { // TODO: implement } public void setCaption(String caption) { // TODO: implement } public void setFullscreen(boolean fullscreen) { // TODO: implement } public boolean isFullscreen() { // TODO: implement return false; } }
gpl-2.0
girnarsoft/DigitalDiary
src/com/girnar/online_digital_diary/ui/UpdateAccountInfoActivity.java
8505
package com.girnar.online_digital_diary.ui; import android.app.Activity; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.ArrayAdapter; import android.widget.AutoCompleteTextView; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.girnar.online_digital_diary.database.DbHelper; import com.girnar.online_digital_diary.interfaces.ImportantMethod; import com.girnar.online_digital_diary.util.Util; import com.google.analytics.tracking.android.EasyTracker; import com.google.analytics.tracking.android.Tracker; public class UpdateAccountInfoActivity extends Activity implements ImportantMethod, OnClickListener { private AutoCompleteTextView banks_name; private EditText account_no, location, holders_name; private DbHelper db = new DbHelper(this); private Button save; private Tracker tracker; LinearLayout back; // private LinearLayout linearLayout; private ImageView home; private String bank[] = { "Punjab National Bank", "State Bank Of Bikaner", "State Bank Of India", "Union Bank", "Allahabad Bank", "Andhra Bank", "Bank of Baroda", "Bank of India", "Bank of Maharashtra", "Canara Bank", "Central Bank of India", "Corporation Bank", "Dena Bank", "IDBI Bank", "Indian Bank", "Indian Overseas Bank", "Oriental Bank of Commerce", "Punjab and Sind Bank", "Syndicate Bank", "UCO Bank", "Union Bank of India", "United Bank of India", "Vijaya Bank", "Punjab & Sind Bank", "UCO_Bank", "ECGC", "State Bank of Bikaner & Jaipur", "State Bank of Hyderabad", "State Bank of Mysore", "State Bank of Patiala", "State Bank of Travancore", "State Bank of Saurashtra", "State bank of Indore", "Axis Bank", "Federal Bank", "Karnataka Bank", "South Indian Bank", "ABN Amro Bank", "HDFC Bank", "Karur Vysya Bank", "YES Bank", "Catholic Syrian Bank", "ICICI Bank", "Kotak Mahindra Bank", "IndusInd Bank", "Lakshmi Vilas Bank", "Dhanlaxmi Bank", "ING Vysya Bank", "Tamilnadu Mercantile Bank", "Development Credit Bank", "Abu Dhabi Commercial Bank", "Australia and New Zealand Bank", "Bank Internasional Indonesia", "Bank of America NA", "Bank of Bahrain and Kuwait", "Bank of Ceylon", "Bank of Nova Scotia", "Bank of Tokyo Mitsubishi UFJ", "Barclays Bank PLC", "BNP Paribas", "Calyon Bank", "Chinatrust Commercial Bank", "Citibank N.A.", "Credit Suisse", "Commonwealth Bank of Australia", "DBS Bank", "DCB Bank now RHB Bank", "Deutsche Bank AG", "FirstRand Bank", "HSBC", "JPMorgan Chase Bank", "Krung Thai Bank", "Mashreq Bank psc", "Mizuho Corporate Bank", "Royal Bank of Scotland", "Shinhan Bank", "Société Générale", "Sonali Bank", "Standard Chartered Bank", "State Bank of Mauritius", "UBS", "Woori Bank", "ABN AMRO Bank N.V. - Royal Bank of Scotland", "National Australia Bank" }; private int id; private String selected_bank_name, selected_holderName, selected_location, selected_acc_no; private TextView header_text; @SuppressWarnings("deprecation") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_other_info); // For hide Keyboard View view = (View) findViewById(R.id.addNewBankAccountInfoPage); Util.setupUI(view, this); EasyTracker.getInstance().setContext(getApplicationContext()); tracker = EasyTracker.getTracker(); tracker.trackView("Update Account Information Digital_Diary"); getIds(); addListener(); Util.addGoogleAds(this); db.open(); Intent intent = getIntent(); Bundle bundle = intent.getExtras(); id = bundle.getInt("id"); Cursor cursor = db.getInfoOtherMethod(id); db.close(); if (cursor != null) { // setData(new String[cursor.getCount()]); cursor.moveToFirst(); for (int i = 0; i < cursor.getCount(); i++) { selected_holderName = cursor.getString(0); selected_acc_no = cursor.getString(1); selected_bank_name = cursor.getString(2); selected_location = cursor.getString(3); holders_name.setText(selected_holderName); account_no.setText(selected_acc_no); // banks_name.set.setText(selected_bank_name); location.setText(selected_location); cursor.moveToNext(); } } ArrayAdapter<String> adapter = new ArrayAdapter<String>( getApplicationContext(), R.layout.custom_spinner, bank); banks_name.setAdapter(adapter); banks_name.setThreshold(1); banks_name.setText(selected_bank_name); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.update_account_info, menu); return true; } @Override public void onClick(View v) { // TODO Auto-generated method stub if (v == save) { boolean result = validate(); if (result) { databaseHelper(); Intent intent = new Intent(this, OtherListviewInfoActivity.class) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); this.overridePendingTransition( R.anim.layout_animation_row_right_from_left_side, R.anim.layout_animation_row_right_slide); finish(); } } else if (v == back) { Intent intent = new Intent(this, OtherListviewInfoActivity.class) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); this.overridePendingTransition( R.anim.layout_animation_row_right_from_left_side, R.anim.layout_animation_row_right_slide); finish(); } else if (v == home) { Util.homeAnimation(this); finish(); } } @Override public void onBackPressed() { // TODO Auto-generated method stub Intent intent = new Intent(this, OtherListviewInfoActivity.class) .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(intent); this.overridePendingTransition( R.anim.layout_animation_row_right_from_left_side, R.anim.layout_animation_row_right_slide); finish(); } /** * get the value from the database */ public void databaseHelper() { // // TODO Auto-generated method stub String account_no = this.account_no.getText().toString(); String holders_name = this.holders_name.getText().toString(); String banks_name = this.banks_name.getEditableText().toString(); String location = this.location.getText().toString(); db.open(); SharedPreferences preferences = PreferenceManager .getDefaultSharedPreferences(this); int id = preferences.getInt("id", 0); db.UpdateBankAccountInfo(this.id, holders_name, account_no, banks_name, location, id); db.close(); } @Override public void getIds() { // TODO Auto-generated method stub banks_name = (AutoCompleteTextView) findViewById(R.id.auto_bank_name_other_info); back = (LinearLayout) findViewById(R.id.linear_layout_img_bck); home = (ImageView) findViewById(R.id.img_home); save = (Button) findViewById(R.id.button_other_submit); account_no = (EditText) findViewById(R.id.edittext_other_account_no); holders_name = (EditText) findViewById(R.id.edittext_other_holders_name); location = (EditText) findViewById(R.id.edittext_other_location); header_text = (TextView) findViewById(R.id.header_text); header_text.setText("Update Information"); } @Override public void addListener() { // TODO Auto-generated method stub save.setOnClickListener(this); back.setOnClickListener(this); home.setOnClickListener(this); } @Override public boolean validate() { // TODO Auto-generated method stub if (account_no.getText().toString().length() == 0) { Toast.makeText(this, "Please fill account no.", Toast.LENGTH_SHORT) .show(); return false; } else if (holders_name.getText().toString().length() == 0) { Toast.makeText(this, "Please fill holder name", Toast.LENGTH_SHORT) .show(); return false; } else if (banks_name.getText().toString().length() == 0) { Toast.makeText(this, "Please fill bank name", Toast.LENGTH_SHORT) .show(); return false; } else if (location.getText().toString().length() == 0) { Toast.makeText(this, "Please fill location", Toast.LENGTH_SHORT) .show(); return false; } else { return true; } } }
gpl-2.0
BunnyWei/truffle-llvmir
graal/com.oracle.graal.compiler/src/com/oracle/graal/compiler/gen/DebugInfoBuilder.java
10696
/* * Copyright (c) 2011, 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. * * 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.oracle.graal.compiler.gen; import java.util.*; import java.util.Map.Entry; import com.oracle.graal.api.code.*; import com.oracle.graal.api.meta.*; import com.oracle.graal.compiler.common.*; import com.oracle.graal.debug.*; import com.oracle.graal.graph.*; import com.oracle.graal.lir.*; import com.oracle.graal.nodes.*; import com.oracle.graal.nodes.util.*; import com.oracle.graal.nodes.virtual.*; import com.oracle.graal.virtual.nodes.*; /** * Builds {@link LIRFrameState}s from {@link FrameState}s. */ public class DebugInfoBuilder { protected final NodeMap<Value> nodeOperands; public DebugInfoBuilder(NodeMap<Value> nodeOperands) { this.nodeOperands = nodeOperands; } protected final Map<VirtualObjectNode, VirtualObject> virtualObjects = Node.newMap(); protected final Map<VirtualObjectNode, EscapeObjectState> objectStates = Node.newIdentityMap(); public LIRFrameState build(FrameState topState, LabelRef exceptionEdge) { assert virtualObjects.size() == 0; assert objectStates.size() == 0; // collect all VirtualObjectField instances: FrameState current = topState; do { if (current.virtualObjectMappingCount() > 0) { for (EscapeObjectState state : current.virtualObjectMappings()) { if (!objectStates.containsKey(state.object())) { if (!(state instanceof MaterializedObjectState) || ((MaterializedObjectState) state).materializedValue() != state.object()) { objectStates.put(state.object(), state); } } } } current = current.outerFrameState(); } while (current != null); BytecodeFrame frame = computeFrameForState(topState); VirtualObject[] virtualObjectsArray = null; if (virtualObjects.size() != 0) { // fill in the VirtualObject values: // during this process new VirtualObjects might be discovered, so repeat until no more // changes occur. boolean changed; do { changed = false; Map<VirtualObjectNode, VirtualObject> virtualObjectsCopy = Node.newIdentityMap(virtualObjects); for (Entry<VirtualObjectNode, VirtualObject> entry : virtualObjectsCopy.entrySet()) { if (entry.getValue().getValues() == null) { VirtualObjectNode vobj = entry.getKey(); Value[] values = new Value[vobj.entryCount()]; if (values.length > 0) { changed = true; VirtualObjectState currentField = (VirtualObjectState) objectStates.get(vobj); assert currentField != null; int pos = 0; for (int i = 0; i < vobj.entryCount(); i++) { if (!currentField.values().get(i).isConstant() || currentField.values().get(i).asJavaConstant().getKind() != Kind.Illegal) { values[pos++] = toValue(currentField.values().get(i)); } else { assert currentField.values().get(i - 1).getKind() == Kind.Double || currentField.values().get(i - 1).getKind() == Kind.Long : vobj + " " + i + " " + currentField.values().get(i - 1); } } if (pos != vobj.entryCount()) { Value[] newValues = new Value[pos]; System.arraycopy(values, 0, newValues, 0, pos); values = newValues; } } entry.getValue().setValues(values); } } } while (changed); virtualObjectsArray = virtualObjects.values().toArray(new VirtualObject[virtualObjects.size()]); virtualObjects.clear(); } objectStates.clear(); assert frame.validateFormat(); return newLIRFrameState(exceptionEdge, frame, virtualObjectsArray); } protected LIRFrameState newLIRFrameState(LabelRef exceptionEdge, BytecodeFrame frame, VirtualObject[] virtualObjectsArray) { return new LIRFrameState(frame, virtualObjectsArray, exceptionEdge); } protected BytecodeFrame computeFrameForState(FrameState state) { try { assert state.bci != BytecodeFrame.INVALID_FRAMESTATE_BCI; assert state.bci != BytecodeFrame.UNKNOWN_BCI; assert state.bci != BytecodeFrame.BEFORE_BCI || state.locksSize() == 0; assert state.bci != BytecodeFrame.AFTER_BCI || state.locksSize() == 0; assert state.bci != BytecodeFrame.AFTER_EXCEPTION_BCI || state.locksSize() == 0; assert !(state.method().isSynchronized() && state.bci != BytecodeFrame.BEFORE_BCI && state.bci != BytecodeFrame.AFTER_BCI && state.bci != BytecodeFrame.AFTER_EXCEPTION_BCI) || state.locksSize() > 0; assert state.verify(); int numLocals = state.localsSize(); int numStack = state.stackSize(); int numLocks = state.locksSize(); Value[] values = new Value[numLocals + numStack + numLocks]; computeLocals(state, numLocals, values); computeStack(state, numLocals, numStack, values); computeLocks(state, values); BytecodeFrame caller = null; if (state.outerFrameState() != null) { caller = computeFrameForState(state.outerFrameState()); } return new BytecodeFrame(caller, state.method(), state.bci, state.rethrowException(), state.duringCall(), values, numLocals, numStack, numLocks); } catch (GraalInternalError e) { throw e.addContext("FrameState: ", state); } } protected void computeLocals(FrameState state, int numLocals, Value[] values) { for (int i = 0; i < numLocals; i++) { values[i] = computeLocalValue(state, i); } } protected Value computeLocalValue(FrameState state, int i) { return toValue(state.localAt(i)); } protected void computeStack(FrameState state, int numLocals, int numStack, Value[] values) { for (int i = 0; i < numStack; i++) { values[numLocals + i] = computeStackValue(state, i); } } protected Value computeStackValue(FrameState state, int i) { return toValue(state.stackAt(i)); } protected void computeLocks(FrameState state, Value[] values) { for (int i = 0; i < state.locksSize(); i++) { values[state.localsSize() + state.stackSize() + i] = computeLockValue(state, i); } } protected Value computeLockValue(FrameState state, int i) { return toValue(state.lockAt(i)); } private static final DebugMetric STATE_VIRTUAL_OBJECTS = Debug.metric("StateVirtualObjects"); private static final DebugMetric STATE_ILLEGALS = Debug.metric("StateIllegals"); private static final DebugMetric STATE_VARIABLES = Debug.metric("StateVariables"); private static final DebugMetric STATE_CONSTANTS = Debug.metric("StateConstants"); protected Value toValue(ValueNode value) { try { if (value instanceof VirtualObjectNode) { VirtualObjectNode obj = (VirtualObjectNode) value; EscapeObjectState state = objectStates.get(obj); if (state == null && obj.entryCount() > 0) { // null states occur for objects with 0 fields throw new GraalInternalError("no mapping found for virtual object %s", obj); } if (state instanceof MaterializedObjectState) { return toValue(((MaterializedObjectState) state).materializedValue()); } else { assert obj.entryCount() == 0 || state instanceof VirtualObjectState; VirtualObject vobject = virtualObjects.get(value); if (vobject == null) { vobject = VirtualObject.get(obj.type(), null, virtualObjects.size()); virtualObjects.put(obj, vobject); } STATE_VIRTUAL_OBJECTS.increment(); return vobject; } } else { // Remove proxies from constants so the constant can be directly embedded. ValueNode unproxied = GraphUtil.unproxify(value); if (unproxied instanceof ConstantNode) { STATE_CONSTANTS.increment(); return unproxied.asJavaConstant(); } else if (value != null) { STATE_VARIABLES.increment(); Value operand = nodeOperands.get(value); assert operand != null && (operand instanceof Variable || operand instanceof JavaConstant) : operand + " for " + value; return operand; } else { // return a dummy value because real value not needed STATE_ILLEGALS.increment(); return Value.ILLEGAL; } } } catch (GraalInternalError e) { throw e.addContext("toValue: ", value); } } }
gpl-2.0
cybershare/elseweb-v2
harvester/src/main/java/edu/utep/cybershare/elseweb/ontology/Format.java
665
package edu.utep.cybershare.elseweb.ontology; import java.util.Collection; import org.protege.owl.codegeneration.WrappedIndividual; import org.semanticweb.owlapi.model.OWLNamedIndividual; import org.semanticweb.owlapi.model.OWLOntology; /** * * <p> * Generated by Protege (http://protege.stanford.edu). <br> * Source Class: Format <br> * @version generated on Thu Feb 13 13:45:51 GMT-07:00 2014 by nick */ public interface Format extends WrappedIndividual { /* *************************************************** * Common interfaces */ OWLNamedIndividual getOwlIndividual(); OWLOntology getOwlOntology(); void delete(); }
gpl-2.0
TheTypoMaster/Scaper
openjdk/jaxws/drop_included/jaxws_src/src/com/sun/xml/internal/ws/util/CompletedFuture.java
2189
/* * Copyright 2005-2006 Sun Microsystems, Inc. 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. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ package com.sun.xml.internal.ws.util; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; /** * {@link Future} implementation that obtains an already available value. * * @author Kohsuke Kawaguchi * @author Jitendra Kotamraju */ public class CompletedFuture<T> implements Future<T> { private final T v; private final Throwable re; public CompletedFuture(T v, Throwable re) { this.v = v; this.re = re; } public boolean cancel(boolean mayInterruptIfRunning) { return false; } public boolean isCancelled() { return false; } public boolean isDone() { return true; } public T get() throws ExecutionException { if (re != null) { throw new ExecutionException(re); } return v; } public T get(long timeout, TimeUnit unit) throws ExecutionException { return get(); } }
gpl-2.0
MichaelChansn/RemoteControlSystem2.0_AndroidClient
src/com/ks/net/enums/MessageEnums.java
10875
package com.ks.net.enums; public class MessageEnums { public enum MessageType { HOST_NANME{ public byte getValue() { return (byte) 0x00; } }, EXIT{ public byte getValue() { return (byte) 0x02; } }, START_PIC { public byte getValue() { return (byte) 0x10; } }, STOP_PIC { public byte getValue() { return (byte) 0x11; } }, MOUSE_LEFT_DOWN { public byte getValue() { return (byte) 0x30; } }, MOUSE_LEFT_UP { public byte getValue() { return (byte) 0x31; } }, MOUSE_RIGHT_DOWN { public byte getValue() { return (byte) 0x32; } }, MOUSE_RIGHT_UP { public byte getValue() { return (byte) 0x33; } }, MOUSE_RIGHT_CLICK { public byte getValue() { return (byte) 0x36; } }, MOUSE_SET { public byte getValue() { return (byte) 0x3A; } }, MOUSE_LEFT_DOUBLE_CLICK { public byte getValue() { return (byte) 0x35; } }, MOUSE_LEFT_CLICK { public byte getValue() { return (byte) 0x34; } }, MOUSE_MOVE { public byte getValue() { return (byte) 0x39; } }, MOUSE_WHEEL { public byte getValue() { return (byte) 0x38; } }, KEY_DOWN{ public byte getValue() { return (byte) 0x20; } }, KEY_UP{ public byte getValue() { return (byte) 0x21; } }, TEXT{ public byte getValue() { return (byte) 0x70; } }, /**control PC funs*/ FUN_SHUTDOWN{ public byte getValue() { return (byte) 0x60; } }, FUN_RESTART{ public byte getValue() { return (byte) 0x61; } }, FUN_MANAGER{ public byte getValue() { return (byte) 0x62; } }, FUN_SLEEP{ public byte getValue() { return (byte) 0x63; } }, FUN_LOGOUT{ public byte getValue() { return (byte) 0x64; } }, FUN_LOCK{ public byte getValue() { return (byte) 0x65; } }, FUN_SHUTDOWN_TIME{ public byte getValue() { return (byte) 0x66; } }, FUN_SHUTDOWN_CANCEL{ public byte getValue() { return (byte) 0x67; } }, FUN_SHOW_DESKTOP{ public byte getValue() { return (byte) 0x68; } } ; public abstract byte getValue(); public static MessageType getMessageType(byte value) { MessageType ret = null; switch (value) { case 0x00: ret = MessageType.HOST_NANME; break; case 0x02: ret = MessageType.EXIT; break; case 0x36: ret = MessageType.MOUSE_RIGHT_CLICK; break; case 0x10: ret = MessageType.START_PIC; break; case 0x11: ret = MessageType.STOP_PIC; break; case 0x30: ret = MessageType.MOUSE_LEFT_DOWN; break; case 0x31: ret = MessageType.MOUSE_LEFT_UP; break; case 0x32: ret = MessageType.MOUSE_RIGHT_DOWN; break; case 0x33: ret = MessageType.MOUSE_RIGHT_UP; break; case 0x34: ret = MessageType.MOUSE_LEFT_CLICK; break; case 0x3A: ret = MessageType.MOUSE_SET; break; case 0x35: ret = MessageType.MOUSE_LEFT_DOUBLE_CLICK; break; case 0x39: ret = MessageType.MOUSE_MOVE; break; case 0x38: ret = MessageType.MOUSE_WHEEL; break; case 0x20: ret = MessageType.KEY_DOWN; break; case 0x21: ret = MessageType.KEY_UP; break; case 0x60: ret = MessageType.FUN_SHUTDOWN; break; case 0x61: ret = MessageType.FUN_RESTART; break; case 0x62: ret = MessageType.FUN_MANAGER; break; case 0x63: ret = MessageType.FUN_SLEEP; break; case 0x64: ret = MessageType.FUN_LOGOUT; break; case 0x65: ret = MessageType.FUN_LOCK; break; case 0x66: ret = MessageType.FUN_SHUTDOWN_TIME; break; case 0x67: ret = MessageType.FUN_SHUTDOWN_CANCEL; break; case 0x68: ret = MessageType.FUN_SHOW_DESKTOP; break; case 0x70: ret = MessageType.TEXT; break; default: break; } return ret; } } public enum SpecialKeys { NONE{ public byte getValue() { return (byte) 0xFF; } }, ENTER { public byte getValue() { return (byte) 0x00; } }, BACKSPACE { public byte getValue() { return (byte) 0x01; } }, SPACE { public byte getValue() { return (byte) 0x02; } }, ESC { public byte getValue() { return (byte) 0x03; } }, SHIFT { public byte getValue() { return (byte) 0x04; } }, CTRL { public byte getValue() { return (byte) 0x05; } }, ALT { public byte getValue() { return (byte) 0x06; } }, TAB { public byte getValue() { return (byte) 0x07; } }, WIN { public byte getValue() { return (byte) 0x08; } }, F1 { public byte getValue() { return (byte) 0x09; } }, F2 { public byte getValue() { return (byte) 0x0A; } }, F3 { public byte getValue() { return (byte) 0x0B; } }, F4 { public byte getValue() { return (byte) 0x0C; } }, F5 { public byte getValue() { return (byte) 0x0D; } }, F6 { public byte getValue() { return (byte) 0x0E; } }, F7 { public byte getValue() { return (byte) 0x0F; } }, F8 { public byte getValue() { return (byte) 0x10; } }, F9 { public byte getValue() { return (byte) 0x11; } }, F10 { public byte getValue() { return (byte) 0x12; } }, F11 { public byte getValue() { return (byte) 0x13; } }, F12 { public byte getValue() { return (byte) 0x14; } }, END { public byte getValue() { return (byte) 0x15; } }, HOME { public byte getValue() { return (byte) 0x16; } }, DEL { public byte getValue() { return (byte) 0x17; } }, PRTSC { public byte getValue() { return (byte) 0x18; } }, INSERT { public byte getValue() { return (byte) 0x19; } }, NUMLOCK { public byte getValue() { return (byte) 0x1A; } }, PAGEUP { public byte getValue() { return (byte) 0x1B; } }, PAGEDOWN { public byte getValue() { return (byte) 0x1C; } }, ARROW_UP { public byte getValue() { return (byte) 0x1D; } }, ARROW_DOWN { public byte getValue() { return (byte) 0x1E; } }, ARROW_LEFT { public byte getValue() { return (byte) 0x1F; } }, ARROW_RIGHT { public byte getValue() { return (byte) 0x20; } }, CAPSLOCK { public byte getValue() { return (byte) 0x21; } }, /**game control*/ GAME_UP{ public byte getValue() { return (byte) 0x22; } }, GAME_DOWN{ public byte getValue() { return (byte) 0x23; } }, GAME_LEFT{ public byte getValue() { return (byte) 0x24; } }, GAME_RIGHT{ public byte getValue() { return (byte) 0x25; } }, GAME_A{ public byte getValue() { return (byte) 0x26; } }, GAME_B { public byte getValue() { return (byte) 0x27; } }, GAME_C{ public byte getValue() { return (byte) 0x28; } }, GAME_D{ public byte getValue() { return (byte) 0x29; } }, GAME_START{ public byte getValue() { return (byte) 0x2A; } }, GAME_STOP{ public byte getValue() { return (byte) 0x2B; } }, GAME_OTHER1{ public byte getValue() { return (byte) 0x2C; } }, GAME_OTHER2{ public byte getValue() { return (byte) 0x2D; } }, GAME_OTHER3{ public byte getValue() { return (byte) 0x2E; } }, GAME_OTHER4{ public byte getValue() { return (byte) 0x2F; } }; public abstract byte getValue(); public static SpecialKeys getSpecialKeys(byte value) { SpecialKeys ret = null; switch (value) { case 0x00: ret = SpecialKeys.ENTER; break; case 0x01: ret = SpecialKeys.BACKSPACE; break; case 0x02: ret = SpecialKeys.SPACE; break; case 0x03: ret = SpecialKeys.ESC; break; case 0x04: ret = SpecialKeys.SHIFT; break; case 0x05: ret = SpecialKeys.CTRL; break; case 0x06: ret = SpecialKeys.ALT; break; case 0x07: ret = SpecialKeys.TAB; break; case 0x08: ret = SpecialKeys.WIN; break; case 0x09: ret = SpecialKeys.F1; break; case 0x0A: ret = SpecialKeys.F2; break; case 0x0B: ret = SpecialKeys.F3; break; case 0x0C: ret = SpecialKeys.F4; break; case 0x0D: ret = SpecialKeys.F5; break; case 0x0E: ret = SpecialKeys.F6; break; case 0x0F: ret = SpecialKeys.F7; break; case 0x10: ret = SpecialKeys.F8; break; case 0x11: ret = SpecialKeys.F9; break; case 0x12: ret = SpecialKeys.F10; break; case 0x13: ret = SpecialKeys.F11; break; case 0x14: ret = SpecialKeys.F12; break; case 0x15: ret = SpecialKeys.END; break; case 0x16: ret = SpecialKeys.HOME; break; case 0x17: ret = SpecialKeys.DEL; break; case 0x18: ret = SpecialKeys.PRTSC; break; case 0x19: ret = SpecialKeys.INSERT; break; case 0x1A: ret = SpecialKeys.NUMLOCK; break; case 0x1B: ret = SpecialKeys.PAGEUP; break; case 0x1C: ret = SpecialKeys.PAGEDOWN; break; case 0x1D: ret = SpecialKeys.ARROW_UP; break; case 0x1E: ret = SpecialKeys.ARROW_DOWN; break; case 0x1F: ret = SpecialKeys.ARROW_LEFT; break; case 0x20: ret = SpecialKeys.ARROW_RIGHT; break; case 0x21: ret = SpecialKeys.CAPSLOCK; break; case 0x22: ret =SpecialKeys.GAME_UP; break; case 0x23: ret = SpecialKeys.GAME_DOWN; break; case 0x24: ret = SpecialKeys.GAME_LEFT; break; case 0x25: ret = SpecialKeys.GAME_RIGHT; break; case 0x26: ret = SpecialKeys.GAME_A; break; case 0x27: ret = SpecialKeys.GAME_B; break; case 0x28: ret = SpecialKeys.GAME_C; break; case 0x29: ret = SpecialKeys.GAME_D; break; case 0x2A: ret = SpecialKeys.GAME_START; break; case 0x2B: ret = SpecialKeys.GAME_STOP; break; case 0x2C: ret = SpecialKeys.GAME_OTHER1; break; case 0x2D: ret = SpecialKeys.GAME_OTHER2; break; case 0x2E: ret = SpecialKeys.GAME_OTHER3; break; case 0x2F: ret = SpecialKeys.GAME_OTHER4; break; default: ret=SpecialKeys.NONE; break; } return ret; } } public static final String UDPSCANMESSAGE = "哥们,在不在啊?"; public static final String UDPSCANRETURN = "在啊,大哥,咋啦?"; public static final String NETSEPARATOR = "<##>";// 消息分隔符 public static final String UDPSEPARATOR = "-->>";// 消息分隔符 public static final String FINDNOSERVER = "find no server online"; }
gpl-2.0
vishwaAbhinav/OpenNMS
core/snmp/impl-snmp4j/src/main/java/org/opennms/netmgt/snmp/snmp4j/Snmp4JValue.java
10854
/******************************************************************************* * 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.snmp.snmp4j; import java.math.BigInteger; import java.net.InetAddress; import java.net.UnknownHostException; import org.apache.commons.lang.builder.EqualsBuilder; import org.opennms.netmgt.snmp.SnmpObjId; import org.opennms.netmgt.snmp.SnmpUtils; import org.opennms.netmgt.snmp.SnmpValue; import org.snmp4j.smi.Counter32; import org.snmp4j.smi.Counter64; import org.snmp4j.smi.Integer32; import org.snmp4j.smi.IpAddress; import org.snmp4j.smi.Null; import org.snmp4j.smi.OID; import org.snmp4j.smi.OctetString; import org.snmp4j.smi.Opaque; import org.snmp4j.smi.SMIConstants; import org.snmp4j.smi.TimeTicks; import org.snmp4j.smi.UnsignedInteger32; import org.snmp4j.smi.Variable; class Snmp4JValue implements SnmpValue { Variable m_value; Snmp4JValue(final Variable value) { if (value == null) { throw new NullPointerException("value attribute cannot be null"); } m_value = value; } Snmp4JValue(final int syntax, final byte[] bytes) { switch (syntax) { case SMIConstants.SYNTAX_INTEGER: { m_value = new Integer32(new BigInteger(bytes).intValue()); break; } case SMIConstants.SYNTAX_COUNTER32: { m_value = new Counter32(new BigInteger(bytes).longValue()); break; } case SMIConstants.SYNTAX_COUNTER64: { m_value = new Counter64(new BigInteger(bytes).longValue()); break; } case SMIConstants.SYNTAX_TIMETICKS: { m_value = new TimeTicks(new BigInteger(bytes).longValue()); break; } case SMIConstants.SYNTAX_UNSIGNED_INTEGER32: { m_value = new UnsignedInteger32(new BigInteger(bytes).longValue()); break; } case SMIConstants.SYNTAX_IPADDRESS: { try { m_value = new IpAddress(InetAddress.getByAddress(bytes)); } catch (final UnknownHostException e) { throw new IllegalArgumentException("unable to create InetAddress from bytes: "+e.getMessage()); } break; } case SMIConstants.SYNTAX_OBJECT_IDENTIFIER: { m_value = new OID(new String(bytes)); break; } case SMIConstants.SYNTAX_OCTET_STRING: { m_value = new OctetString(bytes); break; } case SMIConstants.SYNTAX_OPAQUE: { m_value = new Opaque(bytes); break; } case SMIConstants.SYNTAX_NULL: { m_value = new Null(); break; } default: throw new IllegalArgumentException("invalid syntax "+syntax); } if (m_value == null) { throw new IllegalArgumentException("value object created from syntax " + syntax + " is null"); } } public byte[] getBytes() { switch (m_value.getSyntax()) { case SMIConstants.SYNTAX_INTEGER: case SMIConstants.SYNTAX_COUNTER32: case SMIConstants.SYNTAX_COUNTER64: case SMIConstants.SYNTAX_TIMETICKS: case SMIConstants.SYNTAX_UNSIGNED_INTEGER32: return toBigInteger().toByteArray(); case SMIConstants.SYNTAX_IPADDRESS: return toInetAddress().getAddress(); case SMIConstants.SYNTAX_OBJECT_IDENTIFIER: return toSnmpObjId().toString().getBytes(); case SMIConstants.SYNTAX_OCTET_STRING: return ((OctetString)m_value).getValue(); case SMIConstants.SYNTAX_OPAQUE: return((Opaque)m_value).getValue(); case SMIConstants.SYNTAX_NULL: return new byte[0]; default: throw new IllegalArgumentException("cannot convert "+m_value+" to a byte array"); } } public int getType() { return m_value.getSyntax(); } public boolean isEndOfMib() { return m_value.getSyntax() == SMIConstants.EXCEPTION_END_OF_MIB_VIEW; } public boolean isNumeric() { switch (m_value.getSyntax()) { case SMIConstants.SYNTAX_INTEGER: case SMIConstants.SYNTAX_COUNTER32: case SMIConstants.SYNTAX_COUNTER64: case SMIConstants.SYNTAX_TIMETICKS: case SMIConstants.SYNTAX_UNSIGNED_INTEGER32: return true; default: return false; } } public int toInt() { switch (m_value.getSyntax()) { case SMIConstants.SYNTAX_COUNTER64: return (int)((Counter64)m_value).getValue(); case SMIConstants.SYNTAX_INTEGER: return ((Integer32)m_value).getValue(); case SMIConstants.SYNTAX_COUNTER32: case SMIConstants.SYNTAX_TIMETICKS: case SMIConstants.SYNTAX_UNSIGNED_INTEGER32: return (int)((UnsignedInteger32)m_value).getValue(); default: return Integer.parseInt(m_value.toString()); } } public long toLong() { switch (m_value.getSyntax()) { case SMIConstants.SYNTAX_COUNTER64: return ((Counter64)m_value).getValue(); case SMIConstants.SYNTAX_INTEGER: return ((Integer32)m_value).getValue(); case SMIConstants.SYNTAX_COUNTER32: case SMIConstants.SYNTAX_TIMETICKS: case SMIConstants.SYNTAX_UNSIGNED_INTEGER32: return ((UnsignedInteger32)m_value).getValue(); case SMIConstants.SYNTAX_OCTET_STRING: return (convertStringToLong()); default: return Long.parseLong(m_value.toString()); } } private long convertStringToLong() { return Double.valueOf(m_value.toString()).longValue(); } public String toDisplayString() { switch (m_value.getSyntax()) { case SMIConstants.SYNTAX_OBJECT_IDENTIFIER : return SnmpObjId.get(((OID)m_value).getValue()).toString(); case SMIConstants.SYNTAX_TIMETICKS : return Long.toString(toLong()); case SMIConstants.SYNTAX_OCTET_STRING : return toStringDottingCntrlChars(((OctetString)m_value).getValue()); default : return m_value.toString(); } } private String toStringDottingCntrlChars(final byte[] value) { final byte[] results = new byte[value.length]; for (int i = 0; i < value.length; i++) { results[i] = Character.isISOControl((char)value[i]) ? (byte)'.' : value[i]; } return new String(results); } public InetAddress toInetAddress() { switch (m_value.getSyntax()) { case SMIConstants.SYNTAX_IPADDRESS: return ((IpAddress)m_value).getInetAddress(); default: throw new IllegalArgumentException("cannot convert "+m_value+" to an InetAddress"); } } public String toHexString() { switch (m_value.getSyntax()) { case SMIConstants.SYNTAX_OCTET_STRING: return ((OctetString)m_value).toHexString().replaceAll(":", ""); default: throw new IllegalArgumentException("cannot convert "+m_value+" to a HexString"); } } public String toString() { return toDisplayString(); } public BigInteger toBigInteger() { switch (m_value.getSyntax()) { case SMIConstants.SYNTAX_COUNTER64: final Counter64 cnt = (Counter64)m_value; if (cnt.getValue() > 0) { return BigInteger.valueOf(cnt.getValue()); } else { return new BigInteger(cnt.toString()); } case SMIConstants.SYNTAX_INTEGER: return BigInteger.valueOf(((Integer32)m_value).getValue()); case SMIConstants.SYNTAX_COUNTER32: case SMIConstants.SYNTAX_TIMETICKS: case SMIConstants.SYNTAX_UNSIGNED_INTEGER32: return BigInteger.valueOf(((UnsignedInteger32)m_value).getValue()); default: return new BigInteger(m_value.toString()); } } public SnmpObjId toSnmpObjId() { switch (m_value.getSyntax()) { case SMIConstants.SYNTAX_OBJECT_IDENTIFIER: return SnmpObjId.get(((OID)m_value).getValue()); default: throw new IllegalArgumentException("cannot convert "+m_value+" to an SnmpObjId"); } } public boolean isDisplayable() { if (isNumeric()) { return true; } if (getType() == SnmpValue.SNMP_OBJECT_IDENTIFIER || getType() == SnmpValue.SNMP_IPADDRESS) { return true; } if (getType() == SnmpValue.SNMP_OCTET_STRING) { return SnmpUtils.allBytesDisplayable(getBytes()); } return false; } public boolean isNull() { return getType() == SnmpValue.SNMP_NULL; } public Variable getVariable() { return m_value; } public boolean isError() { switch (getType()) { case SnmpValue.SNMP_NO_SUCH_INSTANCE: case SnmpValue.SNMP_NO_SUCH_OBJECT: return true; default: return false; } } @Override public int hashCode() { if (m_value == null) return 5231; return m_value.hashCode(); } @Override public boolean equals(final Object obj) { if (obj == null) return false; if (obj == this) return true; if (obj.getClass() != getClass()) return false; final Snmp4JValue that = (Snmp4JValue)obj; return new EqualsBuilder() .append(this.m_value, that.m_value) .isEquals(); } }
gpl-2.0
niloc132/mauve-gwt
src/main/java/gnu/testlet/java/lang/AbstractMethodError/classInfo/isSynthetic.java
1653
// Test for method java.lang.AbstractMethodError.getClass().isSynthetic(Object) // Copyright (C) 2012 Pavel Tisnovsky <ptisnovs@redhat.com> // This file is part of Mauve. // Mauve 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. // Mauve 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 Mauve; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 51 Franklin Street, // Fifth Floor, Boston, MA 02110-1301 USA. // Tags: JDK1.5 package gnu.testlet.java.lang.AbstractMethodError.classInfo; import gnu.testlet.TestHarness; import gnu.testlet.Testlet; import java.lang.AbstractMethodError; /** * Test for method java.lang.AbstractMethodError.getClass().isSynthetic() */ public class isSynthetic implements Testlet { /** * Runs the test using the specified harness. * * @param harness the test harness (<code>null</code> not permitted). */ public void test(TestHarness harness) { // create instance of a class AbstractMethodError final Object o = new AbstractMethodError("AbstractMethodError"); // get a runtime class of an object "o" final Class c = o.getClass(); harness.check(!c.isSynthetic()); } }
gpl-2.0
ShimProfiler/SHIM
JikesRVMProbes/probe/HooverProbe.java
1161
package probe; import java.lang.reflect.*; public class HooverProbe implements Probe { private Method beginMethod; private Method endMethod; public void init() { try { Class harnessClass = Class.forName("org.mmtk.utility.PTGProfiler"); beginMethod = harnessClass.getMethod("harnessBegin"); endMethod = harnessClass.getMethod("harnessEnd"); } catch (Exception e) { throw new RuntimeException("Unable to find MMTk org.mmtk.utility.PTGProfiler.harnessBegin and/or org.mmtk.utility.PTGProfiler.harnessBegin", e); } } public void cleanup() {} public void begin(String benchmark, int iteration, boolean warmup) { if (warmup) return; try { beginMethod.invoke(null); } catch (Exception e) { throw new RuntimeException("Error running PTGProfiler.harnessBegin", e); } } public void end(String benchmark, int iteration, boolean warmup) { if (warmup) return; try { endMethod.invoke(null); } catch (Exception e) { throw new RuntimeException("Error running PTGProfiler.harnessEnd", e); } } public void report(String benchmark, int iteration, boolean warmup) {} }
gpl-2.0
kivensolo/UiUsingListView
app-bannerDemo/src/main/java/com/test/banner/ui/TouTiaoActivity.java
1246
package com.test.banner.ui; import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import com.google.android.material.snackbar.Snackbar; import com.test.banner.R; import com.test.banner.adapter.TopLineAdapter; import com.test.banner.bean.DataBean; import com.youth.banner.Banner; import com.youth.banner.transformer.ZoomOutPageTransformer; import com.youth.banner.util.LogUtils; import butterknife.BindView; import butterknife.ButterKnife; public class TouTiaoActivity extends AppCompatActivity { @BindView(R.id.banner) Banner banner; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_tou_tiao); ButterKnife.bind(this); //实现1号店和淘宝头条类似的效果 banner.setAdapter(new TopLineAdapter(DataBean.getTestData2())) .setOrientation(Banner.VERTICAL) .setPageTransformer(new ZoomOutPageTransformer()) .setOnBannerListener((data, position) -> { Snackbar.make(banner, ((DataBean) data).title, Snackbar.LENGTH_SHORT).show(); LogUtils.d("position:" + position); }); } }
gpl-2.0
mohlerm/hotspot_cached_profiles
test/compiler/jvmci/jdk.vm.ci.runtime.test/src/jdk/vm/ci/runtime/test/TypeUniverse.java
9844
/* * Copyright (c) 2013, 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. * * 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 jdk.vm.ci.runtime.test; import static java.lang.reflect.Modifier.isFinal; import static java.lang.reflect.Modifier.isStatic; import java.io.Serializable; import java.lang.reflect.Array; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.AbstractCollection; import java.util.AbstractList; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.IdentityHashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.Set; import java.util.TreeMap; import java.util.stream.Collectors; import jdk.vm.ci.meta.ConstantReflectionProvider; import jdk.vm.ci.meta.JavaConstant; import jdk.vm.ci.meta.MetaAccessProvider; import jdk.vm.ci.meta.ResolvedJavaField; import jdk.vm.ci.meta.ResolvedJavaType; import jdk.vm.ci.meta.TrustedInterface; import jdk.vm.ci.runtime.JVMCI; import org.junit.Test; import sun.misc.Unsafe; //JaCoCo Exclude /** * Context for type related tests. */ public class TypeUniverse { public static final Unsafe unsafe; public static final double JAVA_VERSION = Double.valueOf(System.getProperty("java.specification.version")); public static final MetaAccessProvider metaAccess = JVMCI.getRuntime().getHostJVMCIBackend().getMetaAccess(); public static final ConstantReflectionProvider constantReflection = JVMCI.getRuntime().getHostJVMCIBackend().getConstantReflection(); public static final Collection<Class<?>> classes = new HashSet<>(); public static final Set<ResolvedJavaType> javaTypes; public static final Map<Class<?>, Class<?>> arrayClasses = new HashMap<>(); private static List<ConstantValue> constants; public class InnerClass { } public static class InnerStaticClass { } public static final class InnerStaticFinalClass { } private class PrivateInnerClass { } protected class ProtectedInnerClass { } static { Unsafe theUnsafe = null; try { theUnsafe = Unsafe.getUnsafe(); } catch (Exception e) { try { Field theUnsafeField = Unsafe.class.getDeclaredField("theUnsafe"); theUnsafeField.setAccessible(true); theUnsafe = (Unsafe) theUnsafeField.get(null); } catch (Exception e1) { throw (InternalError) new InternalError("unable to initialize unsafe").initCause(e1); } } unsafe = theUnsafe; Class<?>[] initialClasses = {void.class, boolean.class, byte.class, short.class, char.class, int.class, float.class, long.class, double.class, Object.class, Class.class, boolean[].class, byte[].class, short[].class, char[].class, int[].class, float[].class, long[].class, double[].class, Object[].class, Class[].class, List[].class, boolean[][].class, byte[][].class, short[][].class, char[][].class, int[][].class, float[][].class, long[][].class, double[][].class, Object[][].class, Class[][].class, List[][].class, ClassLoader.class, String.class, Serializable.class, Cloneable.class, Test.class, TestMetaAccessProvider.class, List.class, Collection.class, Map.class, Queue.class, HashMap.class, LinkedHashMap.class, IdentityHashMap.class, AbstractCollection.class, AbstractList.class, ArrayList.class, TrustedInterface.class, InnerClass.class, InnerStaticClass.class, InnerStaticFinalClass.class, PrivateInnerClass.class, ProtectedInnerClass.class}; for (Class<?> c : initialClasses) { addClass(c); } javaTypes = Collections.unmodifiableSet(classes.stream().map(c -> metaAccess.lookupJavaType(c)).collect(Collectors.toSet())); } static class ConstantsUniverse { static final Object[] ARRAYS = classes.stream().map(c -> c != void.class && !c.isArray() ? Array.newInstance(c, 42) : null).filter(o -> o != null).collect(Collectors.toList()).toArray(); static final Object CONST1 = new ArrayList<>(); static final Object CONST2 = new ArrayList<>(); static final Object CONST3 = new IdentityHashMap<>(); static final Object CONST4 = new LinkedHashMap<>(); static final Object CONST5 = new TreeMap<>(); static final Object CONST6 = new ArrayDeque<>(); static final Object CONST7 = new LinkedList<>(); static final Object CONST8 = "a string"; static final Object CONST9 = 42; static final Object CONST10 = String.class; static final Object CONST11 = String[].class; } public static List<ConstantValue> constants() { if (constants == null) { List<ConstantValue> res = readConstants(JavaConstant.class); res.addAll(readConstants(ConstantsUniverse.class)); constants = res; } return constants; } public static class ConstantValue { public final String name; public final JavaConstant value; public final Object boxed; public ConstantValue(String name, JavaConstant value, Object boxed) { this.name = name; this.value = value; this.boxed = boxed; } @Override public String toString() { return name + "=" + value; } public String getSimpleName() { return name.substring(name.lastIndexOf('.') + 1); } } /** * Reads the value of all {@code static final} fields from a given class into an array of * {@link ConstantValue}s. */ public static List<ConstantValue> readConstants(Class<?> fromClass) { try { List<ConstantValue> res = new ArrayList<>(); for (Field field : fromClass.getDeclaredFields()) { if (isStatic(field.getModifiers()) && isFinal(field.getModifiers())) { ResolvedJavaField javaField = metaAccess.lookupJavaField(field); Object boxed = field.get(null); if (boxed instanceof JavaConstant) { res.add(new ConstantValue(javaField.format("%H.%n"), (JavaConstant) boxed, boxed)); } else { JavaConstant value = constantReflection.readConstantFieldValue(javaField, null); if (value != null) { res.add(new ConstantValue(javaField.format("%H.%n"), value, boxed)); if (boxed instanceof Object[]) { Object[] arr = (Object[]) boxed; for (int i = 0; i < arr.length; i++) { JavaConstant element = constantReflection.readArrayElement(value, i); if (element != null) { res.add(new ConstantValue(javaField.format("%H.%n[" + i + "]"), element, arr[i])); } } } } } } } return res; } catch (Exception e) { throw new AssertionError(e); } } public synchronized Class<?> getArrayClass(Class<?> componentType) { Class<?> arrayClass = arrayClasses.get(componentType); if (arrayClass == null) { arrayClass = Array.newInstance(componentType, 0).getClass(); arrayClasses.put(componentType, arrayClass); } return arrayClass; } public static int dimensions(Class<?> c) { if (c.getComponentType() != null) { return 1 + dimensions(c.getComponentType()); } return 0; } private static void addClass(Class<?> c) { if (classes.add(c)) { if (c.getSuperclass() != null) { addClass(c.getSuperclass()); } for (Class<?> sc : c.getInterfaces()) { addClass(sc); } for (Class<?> dc : c.getDeclaredClasses()) { addClass(dc); } for (Method m : c.getDeclaredMethods()) { addClass(m.getReturnType()); for (Class<?> p : m.getParameterTypes()) { addClass(p); } } if (c != void.class && dimensions(c) < 2) { Class<?> arrayClass = Array.newInstance(c, 0).getClass(); arrayClasses.put(c, arrayClass); addClass(arrayClass); } } } }
gpl-2.0
pablanco/taskManager
Android/FlexibleClient/src/com/artech/controls/grids/IGridAdapter.java
290
package com.artech.controls.grids; import com.artech.base.model.Entity; import com.artech.controllers.ViewData; import com.fedorvlasov.lazylist.ImageLoader; public interface IGridAdapter { ViewData getData(); Entity getEntity(int position); ImageLoader getImageLoader(); }
gpl-2.0
elBukkit/Dueling
src/main/java/me/KmanCrazy/dueling/ArenaType.java
110
package me.KmanCrazy.dueling; public enum ArenaType { FFA,SPLEEF,ONEVONE,TWOVTWO,THREEVTHREE,FOURVFOUR }
gpl-2.0
klaube/kata
marsRover/src/marsRover/Mars.java
125
package marsRover; public class Mars { public int getDimX() { return 10; } public int getDimY() { return 10; } }
gpl-2.0
php-coder/mystamps
src/main/java/ru/mystamps/web/support/spring/mvc/PatchRequest.java
1995
/* * Copyright (C) 2009-2022 Slava Semushin <slava.semushin@gmail.com> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package ru.mystamps.web.support.spring.mvc; import lombok.Getter; import lombok.Setter; import lombok.ToString; import org.apache.commons.lang3.StringUtils; import javax.validation.constraints.NotEmpty; import javax.validation.constraints.NotNull; import java.math.BigDecimal; // See for details: http://jsonpatch.com @Getter @Setter @ToString public class PatchRequest { public enum Operation { add, copy, move, remove, replace, test; } // @todo #785 Update series: add integration test for required "op" field @NotNull private Operation op; // @todo #785 Update series: add integration test for non-empty "path" field @NotEmpty private String path; // @todo #785 Update series: add integration test for non-empty "value" field @NotEmpty private String value; // @initBinder with StringTrimmerEditor() doesn't work with @RequestBody, so we do that manually // @todo #1447 Add test to ensure that catalog numbers are trimmed public void setValue(String value) { this.value = StringUtils.trimToNull(value); } public Integer integerValue() { return Integer.valueOf(value); } public BigDecimal bigDecimalValue() { return BigDecimalConverter.valueOf(value); } }
gpl-2.0
midaboghetich/netnumero
gen/com/numhero/client/model/datacargo/invoice/InvoiceListRequest_FieldSerializer.java
1865
package com.numhero.client.model.datacargo.invoice; @SuppressWarnings("deprecation") public class InvoiceListRequest_FieldSerializer { private static native com.numhero.shared.enums.InvoiceTypeEnum getInvoiceType(com.numhero.client.model.datacargo.invoice.InvoiceListRequest instance) /*-{ return instance.@com.numhero.client.model.datacargo.invoice.InvoiceListRequest::invoiceType; }-*/; private static native void setInvoiceType(com.numhero.client.model.datacargo.invoice.InvoiceListRequest instance, com.numhero.shared.enums.InvoiceTypeEnum value) /*-{ instance.@com.numhero.client.model.datacargo.invoice.InvoiceListRequest::invoiceType = value; }-*/; public static void deserialize(com.google.gwt.user.client.rpc.SerializationStreamReader streamReader, com.numhero.client.model.datacargo.invoice.InvoiceListRequest instance) throws com.google.gwt.user.client.rpc.SerializationException{ setInvoiceType(instance, (com.numhero.shared.enums.InvoiceTypeEnum) streamReader.readObject()); com.numhero.shared.datacargo.CommandRequest_FieldSerializer.deserialize(streamReader, instance); } public static native com.numhero.client.model.datacargo.invoice.InvoiceListRequest instantiate(com.google.gwt.user.client.rpc.SerializationStreamReader streamReader) throws com.google.gwt.user.client.rpc.SerializationException/*-{ return @com.numhero.client.model.datacargo.invoice.InvoiceListRequest::new()(); }-*/; public static void serialize(com.google.gwt.user.client.rpc.SerializationStreamWriter streamWriter, com.numhero.client.model.datacargo.invoice.InvoiceListRequest instance) throws com.google.gwt.user.client.rpc.SerializationException { streamWriter.writeObject(getInvoiceType(instance)); com.numhero.shared.datacargo.CommandRequest_FieldSerializer.serialize(streamWriter, instance); } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/jdk/test/java/io/Serializable/evolution/AddedField/ReadAddedField.java
3645
/* * Copyright 1997-1999 Sun Microsystems, Inc. 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 Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ /* * @bug 4088176 * @build WriteAddedField ReadAddedField * @run main ReadAddedField * * @summary Deserialize an evolved class with a new field, field type is new. * */ import java.io.*; class IncompatibleFieldClass implements Serializable { private static long serialVersionUID = 4L; int x = 5; }; class A implements Serializable { // Version 1.0 of class A. private static final long serialVersionUID = 1L; public int bar; } /** Test serial persistent fields w/o using Alternate API. */ class B implements Serializable { private static final long serialVersionUID = 2L; int bar; B() { bar = 4; } } /** Test serial persistent fields using Alternate API. * Also make sure that optional data to non-existent classes can be skipped. */ class C implements Serializable { private static final long serialVersionUID = 3L; int bar; C() { bar = 4; } private void readObject(ObjectInputStream s) throws IOException, ClassNotFoundException { s.defaultReadObject(); } private void writeObject(ObjectOutputStream s) throws IOException { s.defaultWriteObject(); } } public class ReadAddedField { public static void main(String args[]) throws IOException, ClassNotFoundException { File f = new File("tmp.ser"); ObjectInput in = new ObjectInputStream(new FileInputStream(f)); A a = (A)in.readObject(); if (a.bar != 4) throw new RuntimeException("a.bar does not equal 4, it equals " + a.bar); B b = (B)in.readObject(); if (b.bar != 4) throw new RuntimeException("b.bar does not equal 4, it equals " + b.bar); C c = (C)in.readObject(); if (c.bar != 4) throw new RuntimeException("c.bar does not equal 4, it equals " + c.bar); A aa = (A)in.readObject(); if (aa.bar != 4) throw new RuntimeException("a.bar does not equal 4, it equals " + aa.bar); B bb = (B)in.readObject(); if (bb.bar != 4) throw new RuntimeException("b.bar does not equal 4, it equals " + bb.bar); C cc = (C)in.readObject(); if (cc.bar != 4) throw new RuntimeException("c.bar does not equal 4, it equals " + cc.bar); in.close(); } }
gpl-2.0
mobile-event-processing/Asper
source/test/com/espertech/esper/regression/client/TestDeployOrder.java
9411
/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.regression.client; import com.espertech.esper.client.EPServiceProvider; import com.espertech.esper.client.EPServiceProviderManager; import com.espertech.esper.client.deploy.*; import com.espertech.esper.client.scopetest.EPAssertionUtil; import com.espertech.esper.support.client.SupportConfigFactory; import junit.framework.TestCase; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.Set; public class TestDeployOrder extends TestCase { private static final Log log = LogFactory.getLog(TestDeployOrder.class); private EPServiceProvider epService; private EPDeploymentAdmin deploymentAdmin; public void setUp() { epService = EPServiceProviderManager.getDefaultProvider(SupportConfigFactory.getConfiguration()); epService.initialize(); deploymentAdmin = epService.getEPAdministrator().getDeploymentAdmin(); } public void testOrder() throws Exception { Module moduleA = null; Module moduleB = null; Module moduleC = null; Module moduleD = null; Module moduleE = null; DeploymentOrder order = null; // Tree of 4 deep moduleA = getModule("A"); moduleB = getModule("B", "A"); moduleC = getModule("C", "A", "B", "D"); moduleD = getModule("D", "A", "B"); order = deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleC, moduleD, moduleB, moduleA}), new DeploymentOrderOptions()); assertOrder(new Module[] {moduleA, moduleB, moduleD, moduleC}, order); // Zero items order = deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {}), new DeploymentOrderOptions()); assertOrder(new Module[] {}, order); // 1 item moduleA = getModule("A"); order = deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleA}), new DeploymentOrderOptions()); assertOrder(new Module[] {moduleA}, order); // 2 item moduleA = getModule("A", "B"); moduleB = getModule("B"); order = deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleB, moduleA}), new DeploymentOrderOptions()); assertOrder(new Module[] {moduleB, moduleA}, order); // 3 item moduleB = getModule("B"); moduleC = getModule("C", "B"); moduleD = getModule("D"); order = deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleB, moduleC, moduleD}), new DeploymentOrderOptions()); assertOrder(new Module[] {moduleB, moduleC, moduleD}, order); order = deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleD, moduleC, moduleB}), new DeploymentOrderOptions()); assertOrder(new Module[] {moduleB, moduleD, moduleC}, order); // 2 trees of 2 deep moduleA = getModule("A", "B"); moduleB = getModule("B"); moduleC = getModule("C", "D"); moduleD = getModule("D"); order = deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleC, moduleB, moduleA, moduleD}), new DeploymentOrderOptions()); assertOrder(new Module[] {moduleB, moduleD, moduleC, moduleA}, order); // Tree of 5 deep moduleA = getModule("A", "C"); moduleB = getModule("B"); moduleC = getModule("C", "B"); moduleD = getModule("D", "C", "E"); moduleE = getModule("E"); order = deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleA, moduleB, moduleC, moduleD, moduleE}), new DeploymentOrderOptions()); assertOrder(new Module[] {moduleB, moduleC, moduleE, moduleA, moduleD}, order); order = deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleB, moduleE, moduleC, moduleA, moduleD}), new DeploymentOrderOptions()); assertOrder(new Module[] {moduleB, moduleE, moduleC, moduleA, moduleD}, order); order = deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleA, moduleD, moduleE, moduleC, moduleB}), new DeploymentOrderOptions()); assertOrder(new Module[] {moduleB, moduleE, moduleC, moduleA, moduleD}, order); // Tree with null names moduleA = getModule(null, "C", "A", "B", "D"); moduleB = getModule(null, "C"); moduleC = getModule("A"); moduleD = getModule("B", "A", "C"); moduleE = getModule("C"); DeploymentOrderOptions options = new DeploymentOrderOptions(); options.setCheckUses(false); order = deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleA, moduleB, moduleC, moduleD, moduleE}), options); assertOrder(new Module[] {moduleC, moduleE, moduleD, moduleA, moduleB}, order); assertFalse(deploymentAdmin.isDeployed("C")); // Tree with duplicate names moduleA = getModule("A", "C"); moduleB = getModule("B", "C"); moduleC = getModule("A", "B"); moduleD = getModule("D", "A"); moduleE = getModule("C"); order = deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleA, moduleB, moduleC, moduleD, moduleE}), options); assertOrder(new Module[] {moduleE, moduleB, moduleA, moduleC, moduleD}, order); } public void testCircular() throws Exception { // Circular 3 Module moduleB = getModule("B", "C"); Module moduleC = getModule("C", "D"); Module moduleD = getModule("D", "B"); try { deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleC, moduleD, moduleB}), new DeploymentOrderOptions()); fail(); } catch (DeploymentOrderException ex) { assertEquals("Circular dependency detected in module uses-relationships: module 'C' uses (depends on) module 'D' uses (depends on) module 'B'", ex.getMessage()); } // Circular 1 - this is allowed moduleB = getModule("B", "B"); DeploymentOrder order = deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleC, moduleD, moduleB}), new DeploymentOrderOptions()); assertOrder(new Module[] {moduleB, moduleD, moduleC, }, order); // Circular 2 moduleB = getModule("B", "C"); moduleC = getModule("C", "B"); try { deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleC, moduleB}), new DeploymentOrderOptions()); fail(); } catch (DeploymentOrderException ex) { assertEquals("Circular dependency detected in module uses-relationships: module 'C' uses (depends on) module 'B'", ex.getMessage()); } // turn off circular check DeploymentOrderOptions options = new DeploymentOrderOptions(); options.setCheckCircularDependency(false); order = deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleC, moduleB}), options); assertOrder(new Module[] {moduleB, moduleC}, order); } public void testUnresolvedUses() throws Exception { // Single module Module moduleB = getModule("B", "C"); try { deploymentAdmin.getDeploymentOrder(Arrays.asList(new Module[] {moduleB}), new DeploymentOrderOptions()); fail(); } catch (DeploymentOrderException ex) { assertEquals("Module-dependency not found as declared by module 'B' for uses-declaration 'C'", ex.getMessage()); } // multiple module Module[] modules = new Module[] {getModule("B", "C"), getModule("C", "D"), getModule("D", "x")}; try { deploymentAdmin.getDeploymentOrder(Arrays.asList(modules), new DeploymentOrderOptions()); fail(); } catch (DeploymentOrderException ex) { assertEquals("Module-dependency not found as declared by module 'D' for uses-declaration 'x'", ex.getMessage()); } // turn off uses-checks DeploymentOrderOptions options = new DeploymentOrderOptions(); options.setCheckUses(false); deploymentAdmin.getDeploymentOrder(Arrays.asList(modules), options); } private void assertOrder(Module[] ordered, DeploymentOrder order) { EPAssertionUtil.assertEqualsExactOrder(ordered, order.getOrdered().toArray()); } private Module getModule(String name, String... uses) { Set<String> usesSet = new HashSet<String>(); usesSet.addAll(Arrays.asList(uses)); return new Module(name, null, usesSet, Collections.EMPTY_SET, Collections.EMPTY_LIST, null); } }
gpl-2.0
ankitC/MapReduceFramework
src/common/FileIterator.java
1124
package common; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.Iterator; import java.util.NoSuchElementException; public class FileIterator implements Iterator<String> { private BufferedReader reader; private String line; public FileIterator(File file) throws IOException { this.reader = new BufferedReader(new FileReader(file)); line = reader.readLine(); } @Override public boolean hasNext() { return line != null; } @Override public String next() throws NoSuchElementException { if (line == null) throw new NoSuchElementException(); String next = line; try { line = reader.readLine(); if (line == null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } return next.split(" ")[1]; } @Override public void remove() { throw new UnsupportedOperationException( "Cannot remove" ); } }
gpl-2.0
masanobuimai/ideavim
test/org/jetbrains/plugins/ideavim/VimTestCase.java
6478
package org.jetbrains.plugins.ideavim; import com.intellij.ide.highlighter.JavaFileType; import com.intellij.openapi.application.PathManager; import com.intellij.openapi.editor.Caret; import com.intellij.openapi.editor.Editor; import com.intellij.openapi.fileTypes.PlainTextFileType; import com.intellij.openapi.project.Project; import com.intellij.testFramework.LightProjectDescriptor; import com.intellij.testFramework.PlatformTestCase; import com.intellij.testFramework.UsefulTestCase; import com.intellij.testFramework.fixtures.CodeInsightTestFixture; import com.intellij.testFramework.fixtures.IdeaProjectTestFixture; import com.intellij.testFramework.fixtures.IdeaTestFixtureFactory; import com.intellij.testFramework.fixtures.TestFixtureBuilder; import com.intellij.testFramework.fixtures.impl.LightTempDirTestFixtureImpl; import com.maddyhome.idea.vim.KeyHandler; import com.maddyhome.idea.vim.VimPlugin; import com.maddyhome.idea.vim.command.CommandState; import com.maddyhome.idea.vim.ex.ExOutputModel; import com.maddyhome.idea.vim.helper.EditorDataContext; import com.maddyhome.idea.vim.helper.RunnableHelper; import com.maddyhome.idea.vim.helper.StringHelper; import com.maddyhome.idea.vim.option.Options; import com.maddyhome.idea.vim.ui.ExEntryPanel; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.swing.*; import java.util.ArrayList; import java.util.List; /** * @author vlan */ public abstract class VimTestCase extends UsefulTestCase { private static final String ULTIMATE_MARKER_CLASS = "com.intellij.psi.css.CssFile"; protected CodeInsightTestFixture myFixture; public VimTestCase() { // Only in IntelliJ IDEA Ultimate Edition PlatformTestCase.initPlatformLangPrefix(); // XXX: IntelliJ IDEA Community and Ultimate 12+ //PlatformTestCase.initPlatformPrefix(ULTIMATE_MARKER_CLASS, "PlatformLangXml"); } @Override protected void setUp() throws Exception { super.setUp(); final IdeaTestFixtureFactory factory = IdeaTestFixtureFactory.getFixtureFactory(); final LightProjectDescriptor projectDescriptor = LightProjectDescriptor.EMPTY_PROJECT_DESCRIPTOR; final TestFixtureBuilder<IdeaProjectTestFixture> fixtureBuilder = factory.createLightFixtureBuilder(projectDescriptor); final IdeaProjectTestFixture fixture = fixtureBuilder.getFixture(); myFixture = IdeaTestFixtureFactory.getFixtureFactory().createCodeInsightFixture(fixture, new LightTempDirTestFixtureImpl(true)); myFixture.setUp(); myFixture.setTestDataPath(getTestDataPath()); KeyHandler.getInstance().fullReset(myFixture.getEditor()); Options.getInstance().resetAllOptions(); VimPlugin.getKey().resetKeyMappings(); } protected String getTestDataPath() { return PathManager.getHomePath() + "/community/plugins/ideavim/testData"; } @Override protected void tearDown() throws Exception { myFixture.tearDown(); myFixture = null; ExEntryPanel.getInstance().deactivate(false); super.tearDown(); } @NotNull protected Editor typeTextInFile(@NotNull final List<KeyStroke> keys, @NotNull String fileContents) { configureByText(fileContents); return typeText(keys); } @NotNull protected Editor configureByText(@NotNull String content) { myFixture.configureByText(PlainTextFileType.INSTANCE, content); return myFixture.getEditor(); } @NotNull protected Editor configureByJavaText(@NotNull String content) { myFixture.configureByText(JavaFileType.INSTANCE, content); return myFixture.getEditor(); } @NotNull protected Editor typeText(@NotNull final List<KeyStroke> keys) { final Editor editor = myFixture.getEditor(); final KeyHandler keyHandler = KeyHandler.getInstance(); final EditorDataContext dataContext = new EditorDataContext(editor); final Project project = myFixture.getProject(); RunnableHelper.runWriteCommand(project, new Runnable() { @Override public void run() { for (KeyStroke key : keys) { final ExEntryPanel exEntryPanel = ExEntryPanel.getInstance(); if (exEntryPanel.isActive()) { exEntryPanel.handleKey(key); } else { keyHandler.handleKey(editor, key, dataContext); } } } }, null, null); return editor; } @NotNull protected static List<KeyStroke> commandToKeys(@NotNull String command) { List<KeyStroke> keys = new ArrayList<KeyStroke>(); keys.addAll(StringHelper.parseKeys(":")); keys.addAll(StringHelper.stringToKeys(command)); keys.addAll(StringHelper.parseKeys("<Enter>")); return keys; } public void assertOffset(int... expectedOffsets) { final List<Caret> carets = myFixture.getEditor().getCaretModel().getAllCarets(); assertEquals("Wrong amount of carets", expectedOffsets.length, carets.size()); for (int i = 0; i < expectedOffsets.length; i++) { assertEquals(expectedOffsets[i], carets.get(i).getOffset()); } } public void assertMode(@NotNull CommandState.Mode expectedMode) { final CommandState.Mode mode = CommandState.getInstance(myFixture.getEditor()).getMode(); assertEquals(expectedMode, mode); } public void assertSelection(@Nullable String expected) { final String selected = myFixture.getEditor().getSelectionModel().getSelectedText(); assertEquals(expected, selected); } public void assertExOutput(@NotNull String expected) { final String actual = ExOutputModel.getInstance(myFixture.getEditor()).getText(); assertNotNull("No Ex output", actual); assertEquals(expected, actual); } public void assertPluginError(boolean isError) { assertEquals(isError, VimPlugin.isError()); } public void doTest(final List<KeyStroke> keys, String before, String after) { myFixture.configureByText(PlainTextFileType.INSTANCE, before); final Editor editor = myFixture.getEditor(); final KeyHandler keyHandler = KeyHandler.getInstance(); final EditorDataContext dataContext = new EditorDataContext(editor); final Project project = myFixture.getProject(); RunnableHelper.runWriteCommand(project, new Runnable() { @Override public void run() { for (KeyStroke key : keys) { keyHandler.handleKey(editor, key, dataContext); } } }, null, null); myFixture.checkResult(after); } }
gpl-2.0
felipewmartins/SICOBA
src/main/java/br/com/clairtonluz/sicoba/util/SendEmail.java
2539
package br.com.clairtonluz.sicoba.util; import br.com.clairtonluz.sicoba.config.Environment; import br.com.clairtonluz.sicoba.config.EnvironmentFactory; import com.sendgrid.*; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; /** * Created by clairton on 24/12/16. */ public class SendEmail { private SendEmail() { } public static void notificarAdmin(Exception e) { notificarAdmin(e.getMessage(), e); } public static void notificarAdmin(String subject, Exception e) { subject = String.format("[SICOBA][%s][ERROR] - %s", EnvironmentFactory.create().getEnv(), subject); String content = stackTraceAsString(e); sendToAdmin(subject, content); } public static void sendToAdmin(String subject, String content) { send(System.getenv("SICOBA_EMAIL_ADMIN"), subject, content); } public static void send(String to, String subject, String content) { send(System.getenv("SICOBA_EMAIL_SUPORTE"), to, subject, content); } public static void send(String from, String to, String subject, String content) { String env = EnvironmentFactory.create().getEnv(); if (Environment.PRODUCTION.equals(env) || Environment.QUALITY.equals(env)) { if (!Environment.PRODUCTION.equals(env)) { subject = String.format("[%s]%s", env, subject); } Email emailFrom = new Email(from); Email emailTo = new Email(to); Content content2 = new Content("text/plain", content); Mail mail = new Mail(emailFrom, subject, emailTo, content2); String sendgridApiKey = System.getenv("SENDGRID_API_KEY"); SendGrid sg = new SendGrid(sendgridApiKey); Request request = new Request(); try { request.method = Method.POST; request.endpoint = "mail/send"; request.body = mail.build(); Response response = sg.api(request); } catch (IOException e) { e.printStackTrace(); } } else { System.out.println(env); System.out.println(from); System.out.println(to); System.out.println(subject); System.out.println(content); } } private static String stackTraceAsString(Exception e) { StringWriter errors = new StringWriter(); e.printStackTrace(new PrintWriter(errors)); return errors.toString(); } }
gpl-2.0
kartoFlane/superluminal2
src/java/com/kartoflane/superluminal2/components/interfaces/Followable.java
1091
package com.kartoflane.superluminal2.components.interfaces; import java.util.Set; /** * Classes implementing this interface can be followed by classes implementing * the {@link Follower} interface.<br> * "Follow" in this case means that whenever the parent is moved, the * follower will move with it, at the offset specified by {@link Follower#setFollowOffset(int, int)} * * @author kartoFlane * */ public interface Followable extends Movable { /** @return a set containing all Followers of this object. */ public Set<Follower> getFollowers(); public boolean addFollower( Follower fol ); public boolean removeFollower( Follower fol ); /** @return the number of Followers currently following this object. */ public int getFollowerCount(); /** * Sets whether the Followable is currently active, ie. notifying its followers.<br> * True by default. */ public void setFollowActive( boolean active ); /** * @return whether the Followable is currently active, ie. notifying its followers.<br> * True by default. */ public boolean isFollowActive(); }
gpl-2.0
AntoineDelacroix/NewSuperProject-
org.eclipse.jface/src/org/eclipse/jface/action/MenuManager.java
30730
/******************************************************************************* * Copyright (c) 2000, 2015 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 * Remy Chi Jian Suen <remy.suen@gmail.com> - Bug 12116 [Contributions] widgets: MenuManager.setImageDescriptor() method needed * Lars Vogel <Lars.Vogel@gmail.com> - Bug 440252 * Andrey Loskutov <loskutov@gmx.de> - Bug 436225 *******************************************************************************/ package org.eclipse.jface.action; import java.util.ArrayList; import java.util.List; import org.eclipse.core.runtime.ListenerList; import org.eclipse.jface.internal.MenuManagerEventHelper; import org.eclipse.jface.resource.ImageDescriptor; import org.eclipse.jface.resource.JFaceResources; import org.eclipse.jface.resource.LocalResourceManager; import org.eclipse.swt.SWT; import org.eclipse.swt.events.MenuAdapter; import org.eclipse.swt.events.MenuEvent; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.Control; import org.eclipse.swt.widgets.CoolBar; import org.eclipse.swt.widgets.Decorations; import org.eclipse.swt.widgets.Item; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.MenuItem; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.ToolBar; /** * A menu manager is a contribution manager which realizes itself and its items * in a menu control; either as a menu bar, a sub-menu, or a context menu. * <p> * This class may be instantiated; it may also be subclassed. * </p> */ public class MenuManager extends ContributionManager implements IMenuManager { private static final String MANAGER_KEY = "org.eclipse.jface.action.MenuManager.managerKey"; //$NON-NLS-1$ /** * The menu id. */ private String id; /** * List of registered menu listeners (element type: <code>IMenuListener</code>). */ private ListenerList listeners = new ListenerList(); /** * The menu control; <code>null</code> before * creation and after disposal. */ private Menu menu = null; /** * The menu item widget; <code>null</code> before * creation and after disposal. This field is used * when this menu manager is a sub-menu. */ private MenuItem menuItem; /** * The text for a sub-menu. */ private String menuText; /** * The image for a sub-menu. */ private ImageDescriptor image; /** * A resource manager to remember all of the images that have been used by this menu. */ private LocalResourceManager imageManager; /** * The overrides for items of this manager */ private IContributionManagerOverrides overrides; /** * The parent contribution manager. */ private IContributionManager parent; /** * Indicates whether <code>removeAll</code> should be * called just before the menu is displayed. */ private boolean removeAllWhenShown = false; /** * Indicates this item is visible in its manager; <code>true</code> * by default. * @since 3.3 */ protected boolean visible = true; /** * allows a submenu to display a shortcut key. This is often used with the * QuickMenu command or action which can pop up a menu using the shortcut. */ private String definitionId = null; /** * Creates a menu manager. The text and id are <code>null</code>. * Typically used for creating a context menu, where it doesn't need to be referred to by id. */ public MenuManager() { this(null, null, null); } /** * Creates a menu manager with the given text. The id of the menu * is <code>null</code>. * Typically used for creating a sub-menu, where it doesn't need to be referred to by id. * * @param text the text for the menu, or <code>null</code> if none */ public MenuManager(String text) { this(text, null, null); } /** * Creates a menu manager with the given text and id. * Typically used for creating a sub-menu, where it needs to be referred to by id. * * @param text the text for the menu, or <code>null</code> if none * @param id the menu id, or <code>null</code> if it is to have no id */ public MenuManager(String text, String id) { this(text, null, id); } /** * Creates a menu manager with the given text, image, and id. * Typically used for creating a sub-menu, where it needs to be referred to by id. * * @param text the text for the menu, or <code>null</code> if none * @param image the image for the menu, or <code>null</code> if none * @param id the menu id, or <code>null</code> if it is to have no id * @since 3.4 */ public MenuManager(String text, ImageDescriptor image, String id) { this.menuText = text; this.image = image; this.id = id; } @Override public void addMenuListener(IMenuListener listener) { listeners.add(listener); } /** * Creates and returns an SWT context menu control for this menu, * and installs all registered contributions. * Does not create a new control if one already exists. * <p> * Note that the menu is not expected to be dynamic. * </p> * * @param parent the parent control * @return the menu control */ public Menu createContextMenu(Control parent) { if (!menuExist()) { menu = new Menu(parent); menu.setData(MANAGER_KEY, this); initializeMenu(); } return menu; } /** * Creates and returns an SWT menu bar control for this menu, * for use in the given <code>Decorations</code>, and installs all registered * contributions. Does not create a new control if one already exists. * * @param parent the parent decorations * @return the menu control * @since 2.1 */ public Menu createMenuBar(Decorations parent) { if (!menuExist()) { menu = new Menu(parent, SWT.BAR); menu.setData(MANAGER_KEY, this); update(false); } return menu; } /** * Creates and returns an SWT menu bar control for this menu, for use in the * given <code>Shell</code>, and installs all registered contributions. Does not * create a new control if one already exists. This implementation simply calls * the <code>createMenuBar(Decorations)</code> method * * @param parent the parent decorations * @return the menu control * @deprecated use <code>createMenuBar(Decorations)</code> instead. */ @Deprecated public Menu createMenuBar(Shell parent) { return createMenuBar((Decorations) parent); } /** * Disposes of this menu manager and frees all allocated SWT resources. Notifies all * contribution items of the dispose. Note that this method does not clean up references between * this menu manager and its associated contribution items. Use {@link #removeAll()} for that * purpose, but note that will not dispose the items. */ @Override public void dispose() { if (menuExist()) { menu.dispose(); } menu = null; if (menuItem != null) { menuItem.dispose(); menuItem = null; } disposeOldImages(); // remember items for disposal before removing them all IContributionItem[] items = getItems(); removeAll(); for (IContributionItem item : items) { item.dispose(); } markDirty(); parent = null; } @Override public void fill(Composite parent) { } @Override public void fill(CoolBar parent, int index) { } @Override public void fill(Menu parent, int index) { if (menuItem == null || menuItem.isDisposed()) { if (index >= 0) { menuItem = new MenuItem(parent, SWT.CASCADE, index); } else { menuItem = new MenuItem(parent, SWT.CASCADE); } String text = getMenuText(); if (text != null) { menuItem.setText(text); } if (image != null) { LocalResourceManager localManager = new LocalResourceManager( JFaceResources.getResources()); menuItem.setImage(localManager.createImage(image)); disposeOldImages(); imageManager = localManager; } if (!menuExist()) { menu = new Menu(parent); menu.setData(MANAGER_KEY, this); } menuItem.setMenu(menu); initializeMenu(); setDirty(true); } } @Override public void fill(ToolBar parent, int index) { } @Override public IMenuManager findMenuUsingPath(String path) { IContributionItem item = findUsingPath(path); if (item instanceof IMenuManager) { return (IMenuManager) item; } return null; } @Override public IContributionItem findUsingPath(String path) { String id = path; String rest = null; int separator = path.indexOf('/'); if (separator != -1) { id = path.substring(0, separator); rest = path.substring(separator + 1); } else { return super.find(path); } IContributionItem item = super.find(id); if (item instanceof IMenuManager) { IMenuManager manager = (IMenuManager) item; return manager.findUsingPath(rest); } return null; } /** * Notifies any menu listeners that a menu is about to show. * Only listeners registered at the time this method is called are notified. * * @param manager the menu manager * * @see IMenuListener#menuAboutToShow */ private void fireAboutToShow(IMenuManager manager) { Object[] listeners = this.listeners.getListeners(); for (Object listener : listeners) { ((IMenuListener) listener).menuAboutToShow(manager); } } /** * Notifies any menu listeners that a menu is about to hide. * Only listeners registered at the time this method is called are notified. * * @param manager the menu manager * */ private void fireAboutToHide(IMenuManager manager) { final Object[] listeners = this.listeners.getListeners(); for (final Object listener : listeners) { if (listener instanceof IMenuListener2) { final IMenuListener2 listener2 = (IMenuListener2) listener; listener2.menuAboutToHide(manager); } } } /** * Returns the menu id. The menu id is used when creating a contribution * item for adding this menu as a sub menu of another. * * @return the menu id */ @Override public String getId() { return id; } /** * Returns the SWT menu control for this menu manager. * * @return the menu control */ public Menu getMenu() { return menu; } /** * Returns the text shown in the menu, potentially with a shortcut * appended. * * @return the menu text */ public String getMenuText() { if (definitionId == null) { return menuText; } ExternalActionManager.ICallback callback = ExternalActionManager .getInstance().getCallback(); if (callback != null) { String shortCut = callback.getAcceleratorText(definitionId); if (shortCut == null) { return menuText; } return menuText + "\t" + shortCut; //$NON-NLS-1$ } return menuText; } /** * Returns the image for this menu as an image descriptor. * * @return the image, or <code>null</code> if this menu has no image * @since 3.4 */ public ImageDescriptor getImageDescriptor() { return image; } @Override public IContributionManagerOverrides getOverrides() { if (overrides == null) { if (parent == null) { overrides = new IContributionManagerOverrides() { @Override public Integer getAccelerator(IContributionItem item) { return null; } @Override public String getAcceleratorText(IContributionItem item) { return null; } @Override public Boolean getEnabled(IContributionItem item) { return null; } @Override public String getText(IContributionItem item) { return null; } @Override public Boolean getVisible(IContributionItem item) { return null; } }; } else { overrides = parent.getOverrides(); } super.setOverrides(overrides); } return overrides; } /** * Returns the parent contribution manager of this manger. * * @return the parent contribution manager * @since 2.0 */ public IContributionManager getParent() { return parent; } @Override public boolean getRemoveAllWhenShown() { return removeAllWhenShown; } /** * Notifies all listeners that this menu is about to appear. */ private void handleAboutToShow() { if (removeAllWhenShown) { removeAll(); } MenuManagerEventHelper.getInstance().showEventPreHelper(this); fireAboutToShow(this); MenuManagerEventHelper.getInstance().showEventPostHelper(this); update(false, false); } /** * Notifies all listeners that this menu is about to disappear. */ private void handleAboutToHide() { MenuManagerEventHelper.getInstance().hideEventPreHelper(this); fireAboutToHide(this); MenuManagerEventHelper.getInstance().hideEventPostHelper(this); } /** * Initializes the menu control. */ private void initializeMenu() { menu.addMenuListener(new MenuAdapter() { @Override public void menuHidden(MenuEvent e) { // ApplicationWindow.resetDescription(e.widget); handleAboutToHide(); } @Override public void menuShown(MenuEvent e) { handleAboutToShow(); } }); // Don't do an update(true) here, in case menu is never opened. // Always do it lazily in handleAboutToShow(). } @Override public boolean isDynamic() { return false; } /** * Returns whether this menu should be enabled or not. * Used to enable the menu item containing this menu when it is realized as a sub-menu. * <p> * The default implementation of this framework method * returns <code>true</code>. Subclasses may reimplement. * </p> * * @return <code>true</code> if enabled, and * <code>false</code> if disabled */ @Override public boolean isEnabled() { return true; } @Override public boolean isGroupMarker() { return false; } @Override public boolean isSeparator() { return false; } /** * Check if the contribution is item is a subsitute for ourselves * * @param item the contribution item * @return <code>true</code> if give item is a substitution for ourselves * @deprecated this method is no longer a part of the * {@link org.eclipse.jface.action.IContributionItem} API. */ @Deprecated public boolean isSubstituteFor(IContributionItem item) { return this.equals(item); } @Override public boolean isVisible() { if (!visible) { return false; // short circuit calculations in this case } if (removeAllWhenShown) { // we have no way of knowing if the menu has children return true; } // menus aren't visible if all of its children are invisible (or only contains visible separators). IContributionItem[] childItems = getItems(); boolean visibleChildren = false; for (int j = 0; j < childItems.length; j++) { if (isChildVisible(childItems[j]) && !childItems[j].isSeparator()) { visibleChildren = true; break; } } return visibleChildren; } /** * The <code>MenuManager</code> implementation of this <code>ContributionManager</code> method * also propagates the dirty flag up the parent chain. * * @since 3.1 */ @Override public void markDirty() { super.markDirty(); // Can't optimize by short-circuiting when the first dirty manager is encountered, // since non-visible children are not even processed. // That is, it's possible to have a dirty sub-menu under a non-dirty parent menu // even after the parent menu has been updated. // If items are added/removed in the sub-menu, we still need to propagate the dirty flag up, // even if the sub-menu is already dirty, since the result of isVisible() may change // due to the added/removed items. IContributionManager parent = getParent(); if (parent != null) { parent.markDirty(); } } /** * Returns whether the menu control is created * and not disposed. * * @return <code>true</code> if the control is created * and not disposed, <code>false</code> otherwise * @since 3.4 protected, was added in 3.1 as private method */ protected boolean menuExist() { return menu != null && !menu.isDisposed(); } @Override public void removeMenuListener(IMenuListener listener) { listeners.remove(listener); } @Override public void saveWidgetState() { } /** * Sets the overrides for this contribution manager * * @param newOverrides the overrides for the items of this manager * @since 2.0 */ @Override public void setOverrides(IContributionManagerOverrides newOverrides) { overrides = newOverrides; super.setOverrides(overrides); } @Override public void setParent(IContributionManager manager) { parent = manager; } @Override public void setRemoveAllWhenShown(boolean removeAll) { this.removeAllWhenShown = removeAll; } @Override public void setVisible(boolean visible) { this.visible = visible; } /** * Sets the action definition id of this action. This simply allows the menu * item text to include a short cut if available. It can be used to * notify a user of a key combination that will open a quick menu. * * @param definitionId * the command definition id * @since 3.4 */ public void setActionDefinitionId(String definitionId) { this.definitionId = definitionId; } @Override public void update() { updateMenuItem(); } /** * The <code>MenuManager</code> implementation of this <code>IContributionManager</code> * updates this menu, but not any of its submenus. * * @see #updateAll */ @Override public void update(boolean force) { update(force, false); } /** * Get all the items from the implementation's widget. * * @return the menu items * @since 3.4 */ protected Item[] getMenuItems() { if (menu != null) { return menu.getItems(); } return null; } /** * Get an item from the implementation's widget. * * @param index * of the item * @return the menu item * @since 3.4 */ protected Item getMenuItem(int index) { if (menu !=null) { return menu.getItem(index); } return null; } /** * Get the menu item count for the implementation's widget. * * @return the number of items * @since 3.4 */ protected int getMenuItemCount() { if (menu != null) { return menu.getItemCount(); } return 0; } /** * Call an <code>IContributionItem</code>'s fill method with the * implementation's widget. The default is to use the <code>Menu</code> * widget.<br> * <code>fill(Menu menu, int index)</code> * * @param ci * An <code>IContributionItem</code> whose <code>fill()</code> * method should be called. * @param index * The position the <code>fill()</code> method should start * inserting at. * @since 3.4 */ protected void doItemFill(IContributionItem ci, int index) { ci.fill(menu, index); } /** * Incrementally builds the menu from the contribution items. This method * leaves out double separators and separators in the first or last * position. * * @param force * <code>true</code> means update even if not dirty, and * <code>false</code> for normal incremental updating * @param recursive * <code>true</code> means recursively update all submenus, and * <code>false</code> means just this menu */ protected void update(boolean force, boolean recursive) { if (isDirty() || force) { if (menuExist()) { // clean contains all active items without double separators IContributionItem[] items = getItems(); List<IContributionItem> clean = new ArrayList<IContributionItem>(items.length); IContributionItem separator = null; for (IContributionItem item : items) { IContributionItem ci = item; if (!isChildVisible(ci)) { continue; } if (ci.isSeparator()) { // delay creation until necessary // (handles both adjacent separators, and separator at end) separator = ci; } else { if (separator != null) { if (clean.size() > 0) { clean.add(separator); } separator = null; } clean.add(ci); } } // remove obsolete (removed or non active) Item[] mi = getMenuItems(); for (Item element : mi) { Object data = element.getData(); if (data == null || !clean.contains(data)) { element.dispose(); } else if (data instanceof IContributionItem && ((IContributionItem) data).isDynamic() && ((IContributionItem) data).isDirty()) { element.dispose(); } } // add new mi = getMenuItems(); int srcIx = 0; int destIx = 0; for (IContributionItem src : clean) { IContributionItem dest; // get corresponding item in SWT widget if (srcIx < mi.length) { dest = (IContributionItem) mi[srcIx].getData(); } else { dest = null; } if (dest != null && src.equals(dest)) { srcIx++; destIx++; } else if (dest != null && dest.isSeparator() && src.isSeparator()) { mi[srcIx].setData(src); srcIx++; destIx++; } else { int start = getMenuItemCount(); doItemFill(src, destIx); int newItems = getMenuItemCount() - start; for (int i = 0; i < newItems; i++) { Item item = getMenuItem(destIx++); item.setData(src); } } // May be we can optimize this call. If the menu has just // been created via the call src.fill(fMenuBar, destIx) then // the menu has already been updated with update(true) // (see MenuManager). So if force is true we do it again. But // we can't set force to false since then information for the // sub sub menus is lost. if (recursive) { IContributionItem item = src; if (item instanceof SubContributionItem) { item = ((SubContributionItem) item).getInnerItem(); } if (item instanceof IMenuManager) { ((IMenuManager) item).updateAll(force); } } } // remove any old menu items not accounted for for (; srcIx < mi.length; srcIx++) { mi[srcIx].dispose(); } setDirty(false); } } else { // I am not dirty. Check if I must recursivly walk down the hierarchy. if (recursive) { IContributionItem[] items = getItems(); for (IContributionItem ci : items) { if (ci instanceof IMenuManager) { IMenuManager mm = (IMenuManager) ci; if (isChildVisible(mm)) { mm.updateAll(force); } } } } } updateMenuItem(); } @Override public void update(String property) { IContributionItem items[] = getItems(); for (IContributionItem item : items) { item.update(property); } if (menu != null && !menu.isDisposed() && menu.getParentItem() != null) { if (IAction.TEXT.equals(property)) { String text = getOverrides().getText(this); if (text == null) { text = getMenuText(); } if (text != null) { ExternalActionManager.ICallback callback = ExternalActionManager .getInstance().getCallback(); if (callback != null) { int index = text.indexOf('&'); if (index >= 0 && index < text.length() - 1) { char character = Character.toUpperCase(text .charAt(index + 1)); if (callback.isAcceleratorInUse(SWT.ALT | character) && isTopLevelMenu()) { if (index == 0) { text = text.substring(1); } else { text = text.substring(0, index) + text.substring(index + 1); } } } } menu.getParentItem().setText(text); } } else if (IAction.IMAGE.equals(property) && image != null) { LocalResourceManager localManager = new LocalResourceManager(JFaceResources .getResources()); menu.getParentItem().setImage(localManager.createImage(image)); disposeOldImages(); imageManager = localManager; } } } private boolean isTopLevelMenu() { if (menu != null && !menu.isDisposed() && menuItem != null && !menuItem.isDisposed()) { Menu parentMenu = menuItem.getParent(); return parentMenu != null && ((parentMenu.getStyle() & SWT.BAR) == SWT.BAR); } return false; } /** * Dispose any images allocated for this menu */ private void disposeOldImages() { if (imageManager != null) { imageManager.dispose(); imageManager = null; } } @Override public void updateAll(boolean force) { update(force, true); } /** * Updates the menu item for this sub menu. * The menu item is disabled if this sub menu is empty. * Does nothing if this menu is not a submenu. */ private void updateMenuItem() { /* * Commented out until proper solution to enablement of * menu item for a sub-menu is found. See bug 30833 for * more details. * if (menuItem != null && !menuItem.isDisposed() && menuExist()) { IContributionItem items[] = getItems(); boolean enabled = false; for (int i = 0; i < items.length; i++) { IContributionItem item = items[i]; enabled = item.isEnabled(); if(enabled) break; } // Workaround for 1GDDCN2: SWT:Linux - MenuItem.setEnabled() always causes a redraw if (menuItem.getEnabled() != enabled) menuItem.setEnabled(enabled); } */ // Partial fix for bug #34969 - diable the menu item if no // items in sub-menu (for context menus). if (menuItem != null && !menuItem.isDisposed() && menuExist()) { boolean enabled = removeAllWhenShown || menu.getItemCount() > 0; // Workaround for 1GDDCN2: SWT:Linux - MenuItem.setEnabled() always causes a redraw if (menuItem.getEnabled() != enabled) { // We only do this for context menus (for bug #34969) Menu topMenu = menu; while (topMenu.getParentMenu() != null) { topMenu = topMenu.getParentMenu(); } if ((topMenu.getStyle() & SWT.BAR) == 0) { menuItem.setEnabled(enabled); } } } } private boolean isChildVisible(IContributionItem item) { Boolean v = getOverrides().getVisible(item); if (v != null) { return v.booleanValue(); } return item.isVisible(); } /** * @param menuText The text (label) of the menu. * @since 3.10 */ public void setMenuText(String menuText) { this.menuText = menuText; } /** * @param imageDescriptor The image descriptor to set. * @since 3.10 */ public void setImageDescriptor(ImageDescriptor imageDescriptor) { this.image = imageDescriptor; } @Override public String toString() { return "MenuManager [" + (menuText != null ? "text=" + menuText + ", " : "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ + (id != null ? "id=" + id + ", " : "") + "visible=" + visible + "]"; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ } }
gpl-2.0
conansix/web-auth
src/main/java/cn/howardliu/web/auth/security/AccessDecisionManagerImpl.java
1880
package cn.howardliu.web.auth.security; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.security.access.AccessDecisionManager; import org.springframework.security.access.AccessDeniedException; import org.springframework.security.access.ConfigAttribute; import org.springframework.security.authentication.InsufficientAuthenticationException; import org.springframework.security.core.Authentication; import org.springframework.security.core.GrantedAuthority; import org.springframework.stereotype.Component; import java.util.Collection; /** * <br/>create at 16-2-25 * * @author liuxh * @since 1.0.0 */ @Component("accessDecisionManager") public class AccessDecisionManagerImpl implements AccessDecisionManager { private static final Logger logger = LoggerFactory.getLogger(AccessDecisionManagerImpl.class); @Override public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException { if (configAttributes == null) { return; } for (ConfigAttribute ca : configAttributes) { String needRole = ca.getAttribute(); logger.debug("The role needed is '{}'", needRole); //ga 为用户所被赋予的权限。 needRole 为访问相应的资源应该具有的权限。 for (GrantedAuthority ga : authentication.getAuthorities()) { if (needRole.equals(ga.getAuthority())) { return; } } } throw new AccessDeniedException("you don't allow to get content"); } @Override public boolean supports(ConfigAttribute attribute) { return true; } @Override public boolean supports(Class<?> clazz) { return true; } }
gpl-2.0
Blackhole16/Oberien
src/view/renderer/HUDRenderer.java
1258
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package view.renderer; import controller.State; import de.lessvoid.nifty.Nifty; import model.Model; import org.newdawn.slick.GameContainer; import org.newdawn.slick.Graphics; import org.newdawn.slick.Image; import org.newdawn.slick.SlickException; import org.newdawn.slick.geom.Point; import org.newdawn.slick.state.StateBasedGame; import view.huds.BuildHUD; import view.huds.MainHUD; import java.awt.*; public class HUDRenderer { private MainHUD mhud; private BuildHUD bhud; private Nifty nifty; public HUDRenderer(Font font, int width, Image[][] units, GameContainer gc) throws SlickException { mhud = new MainHUD(font, width); bhud = new BuildHUD(); bhud.init(gc, units); } public void draw(Graphics g, State state, StateBasedGame sbg, Model selected) { mhud.draw(g, state, sbg); bhud.draw(g, sbg, selected); } public void update(boolean mousePressed, Point mcoord) { bhud.update(mousePressed, mcoord); } public boolean isMouseEventAvailable() { return bhud.isMouseEventAvailable(); } public Model getSelectedModel() { return bhud.getSelectedModel(); } public void resetSelection() { bhud.resetSelection(); } }
gpl-2.0
deezzel/triary_main
Triary-ejb/src/java/control/serviceimplem/Generic.java
2041
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package control.serviceimplem; import control.IGeneric; import java.util.List; import javax.persistence.EntityManager; /** * * @author kate */ public abstract class Generic<T> implements IGeneric<T> { private Class<T> entityClass; public Generic(Class<T> entityClass) { this.entityClass = entityClass; } protected abstract EntityManager getEntityManager(); @Override public T find(Integer id) { return getEntityManager().find(entityClass, id); } @Override public void create(T entity) { getEntityManager().persist(entity); } @Override public void edit(T entity) { getEntityManager().merge(entity); } @Override public void remove(T entity) { getEntityManager().remove(getEntityManager().merge(entity)); } @Override public int count() { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); javax.persistence.criteria.Root<T> rt = cq.from(entityClass); cq.select(getEntityManager().getCriteriaBuilder().count(rt)); javax.persistence.Query q = getEntityManager().createQuery(cq); return ((Long) q.getSingleResult()).intValue(); } @Override public List<T> findAll() { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); return getEntityManager().createQuery(cq).getResultList(); } @Override public List<T> findRange(int[] range) { javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery(); cq.select(cq.from(entityClass)); javax.persistence.Query q = getEntityManager().createQuery(cq); q.setMaxResults(range[1] - range[0]); q.setFirstResult(range[0]); return q.getResultList(); } }
gpl-2.0
baratine/baratine
web/src/main/java/com/caucho/v5/http/protocol/OutHttpTcp.java
1764
/* * Copyright (c) 1998-2015 Caucho Technology -- all rights reserved * * This file is part of Baratine(TM) * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Baratine 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. * * Baratine 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, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Baratine; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.v5.http.protocol; import com.caucho.v5.io.WriteStream; import io.baratine.io.Buffer; /** * Writer for http response, called in the writer service. */ public interface OutHttpTcp { boolean canWrite(long sequence); /** * Writes the first buffer for a http response. The first buffer * will trigger the headers to be written. * * If the request is not the final request, free the buffer. * * @param buffer the temp buffer with data * @param length the length of the data in the buffer * @param isEnd true for the final result */ boolean write(WriteStream out, Buffer data, boolean isEnd); /** * Disconnect the connection */ void disconnect(WriteStream out); }
gpl-2.0
Corvu/dbeaver
plugins/org.jkiss.dbeaver.core/src/org/jkiss/dbeaver/ui/data/managers/StringValueManager.java
1908
/* * DBeaver - Universal Database Manager * Copyright (C) 2010-2016 Serge Rieder (serge@jkiss.org) * * 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. */ package org.jkiss.dbeaver.ui.data.managers; import org.jkiss.code.NotNull; import org.jkiss.dbeaver.DBException; import org.jkiss.dbeaver.ui.data.IValueController; import org.jkiss.dbeaver.ui.data.IValueEditor; import org.jkiss.dbeaver.ui.data.editors.StringInlineEditor; import org.jkiss.dbeaver.ui.dialogs.data.TextViewDialog; /** * String value manager */ public class StringValueManager extends BaseValueManager { @NotNull @Override public IValueController.EditType[] getSupportedEditTypes() { return new IValueController.EditType[] {IValueController.EditType.INLINE, IValueController.EditType.PANEL, IValueController.EditType.EDITOR}; } @Override public IValueEditor createEditor(@NotNull IValueController controller) throws DBException { switch (controller.getEditType()) { case INLINE: case PANEL: return new StringInlineEditor(controller); case EDITOR: return new TextViewDialog(controller); default: return null; } } }
gpl-2.0
akunft/fastr
com.oracle.truffle.r.test/src/com/oracle/truffle/r/test/library/stats/TestExternal_rbinom.java
1728
/* * Copyright (c) 2016, 2017, 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 com.oracle.truffle.r.test.library.stats; import org.junit.Test; import com.oracle.truffle.r.test.TestBase; public class TestExternal_rbinom extends TestBase { @Test public void testRbinom() { assertEval("set.seed(42); rbinom(10, 10, 0.5)"); assertEval("set.seed(42); rbinom('10', 10, 0.5)"); assertEval("set.seed(42); rbinom('aa', 10, 0.5)"); assertEval("set.seed(42); rbinom(10, 2:10, c(0.1, 0.5, 0.9))"); assertEval("set.seed(42); rbinom(1:10, 2:10, c(0.1, 0.5, 0.9))"); assertEval("set.seed(42); rbinom(c(1,2), 11:12, c(0.1, 0.5, 0.9))"); assertEval("set.seed(42); rbinom(1, 2, 3)"); } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest16696.java
2256
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark 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, version 2. * * The Benchmark 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 * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest16696") public class BenchmarkTest16696 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = request.getParameter("foo"); String bar = doSomething(param); try { javax.naming.directory.DirContext dc = org.owasp.benchmark.helpers.Utils.getDirContext(); dc.search("name", bar, new javax.naming.directory.SearchControls()); } catch (javax.naming.NamingException e) { throw new ServletException(e); } } // end doPost private static String doSomething(String param) throws ServletException, IOException { java.util.List<String> valuesList = new java.util.ArrayList<String>( ); valuesList.add("safe"); valuesList.add( param ); valuesList.add( "moresafe" ); valuesList.remove(0); // remove the 1st safe value String bar = valuesList.get(0); // get the param value return bar; } }
gpl-2.0
as-ideas/crowdsource
crowdsource-integrationtests/src/test/java/de/asideas/crowdsource/testsupport/selenium/WebDriverProvider.java
3758
package de.asideas.crowdsource.testsupport.selenium; import org.openqa.selenium.Dimension; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.logging.LogType; import org.openqa.selenium.logging.LoggingPreferences; import org.openqa.selenium.remote.CapabilityType; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.remote.RemoteWebDriver; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.io.File; import java.util.logging.Level; /** * Stateful! Holds WebDriver-Instance */ @Service public class WebDriverProvider { private final static Logger LOG = LoggerFactory.getLogger(WebDriverProvider.class); public static final int DESKTOP_WIDTH = 1280; public static final int MOBILE_WIDTH = 400; private static boolean IS_RECYCLED = false; private static RemoteWebDriver DRIVER_INSTANCE; public static void setIsRecycled(boolean isRecycled) { IS_RECYCLED = isRecycled; } @Value("${de.asideas.crowdsource.test.chrome.binary:unset}") private String chromeBinaryPath; public static void closeRecycledWebDriver() { IS_RECYCLED = false; closeWebDriver(); } /** * will close driver instance */ public static void closeWebDriver() { if (IS_RECYCLED) { return; } if (DRIVER_INSTANCE == null) { return; } // get handle of driver RemoteWebDriver driverHandle = DRIVER_INSTANCE; // break class reference DRIVER_INSTANCE = null; // close old driver try { if (driverHandle instanceof FirefoxDriver) { driverHandle.quit(); } else { driverHandle.close(); } } catch (Exception e) { LOG.warn("exception closing webdriver: {}", e.getMessage()); } } /** * @return {@link org.openqa.selenium.chrome.ChromeDriver} if binary specified, fallback to firefox */ public RemoteWebDriver provideDriver() { if (DRIVER_INSTANCE == null) { if (new File(chromeBinaryPath).exists()) { LOG.info("providing chromedriver"); System.setProperty("webdriver.chrome.driver", chromeBinaryPath); DesiredCapabilities capabilities = DesiredCapabilities.chrome(); enableLogging(capabilities); DRIVER_INSTANCE = new ChromeDriver(capabilities); } else { LOG.info("providing firefox driver as chromedriver-binary was not specified or does not resolve in file system."); DesiredCapabilities capabilities = DesiredCapabilities.firefox(); enableLogging(capabilities); DRIVER_INSTANCE = new FirefoxDriver(capabilities); } } DRIVER_INSTANCE.manage().window().setSize(new Dimension(DESKTOP_WIDTH, 800)); return DRIVER_INSTANCE; } public RemoteWebDriver provideMobileDriver() { RemoteWebDriver driver = provideDriver(); driver.manage().window().setSize(new Dimension(WebDriverProvider.MOBILE_WIDTH, 800)); return driver; } private void enableLogging(DesiredCapabilities capabilities) { LoggingPreferences loggingPreferences = new LoggingPreferences(); loggingPreferences.enable(LogType.BROWSER, Level.ALL); capabilities.setCapability(CapabilityType.LOGGING_PREFS, loggingPreferences); } public boolean hasActiveWebDriver() { return DRIVER_INSTANCE != null; } }
gpl-2.0
ZooMMX/Omoikane
main/src/omoikane/caja/business/domain/PartidaModel.java
3928
package omoikane.caja.business.domain; import javafx.beans.Observable; import javafx.beans.binding.Bindings; import javafx.beans.binding.NumberBinding; import javafx.beans.binding.ObjectBinding; import javafx.beans.property.*; import javafx.beans.property.adapter.JavaBeanObjectProperty; import javafx.beans.property.adapter.JavaBeanObjectPropertyBuilder; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import omoikane.caja.presentation.ImpuestoModel; import omoikane.entities.LegacyVentaDetalle; import omoikane.producto.Producto; import java.math.BigDecimal; import java.util.concurrent.Callable; /** * Clase de modelado, con el único propósito de servir como muestra y experimento * No es una clase de producción */ public class PartidaModel { private LongProperty id; private StringProperty concepto; private StringProperty codigo; private ObjectProperty<BigDecimal> cantidad; private ObjectProperty<BigDecimal> costo; private ObjectProperty<BigDecimal> precio; private ObjectProperty<BigDecimal> precioBase; private ObservableList<ImpuestoModel> impuestos; private ObjectProperty<BigDecimal> descuentosBase; private ObjectProperty<BigDecimal> porcDescuentosBase; private StringProperty importeString; private ObjectProperty<Producto> productoData; private LegacyVentaDetalle ventaDetalleEntity; private ObjectBinding<BigDecimal> subtotalBinding; private ReadOnlyObjectWrapper<BigDecimal> subtotalProperty; public PartidaModel() { id = new SimpleLongProperty(); concepto = new SimpleStringProperty(); codigo = new SimpleStringProperty(); cantidad = new SimpleObjectProperty<>(BigDecimal.ZERO); costo = new SimpleObjectProperty<>(); precio = new SimpleObjectProperty<>(BigDecimal.ZERO); precioBase = new SimpleObjectProperty<>(); impuestos = FXCollections.emptyObservableList(); descuentosBase = new SimpleObjectProperty<>(); porcDescuentosBase = new SimpleObjectProperty<>(); importeString = new SimpleStringProperty(); productoData = new SimpleObjectProperty<>(); // ---- Lógica del enlace de subtotal ---- // (cantidad * precio) --> subtotalBinding --> subtotalProperty subtotalBinding = Bindings.createObjectBinding( () -> { return cantidad.get().multiply(precio.get()); } , cantidad , precio ); subtotalProperty = new ReadOnlyObjectWrapper<>(); subtotalProperty.bind(subtotalBinding); } public ReadOnlyObjectProperty<BigDecimal> subtotalProperty() { return subtotalProperty.getReadOnlyProperty(); } public LongProperty getId() { return id; } public StringProperty getConcepto() { return concepto; } public StringProperty getCodigo() { return codigo; } public ObjectProperty<BigDecimal> getCantidad() { return cantidad; } public ObjectProperty<BigDecimal> getCosto() { return costo; } public ObjectProperty<BigDecimal> getPrecio() { return precio; } public ObjectProperty<BigDecimal> getPrecioBase() { return precioBase; } public ObservableList<ImpuestoModel> getImpuestos() { return impuestos; } public ObjectProperty<BigDecimal> getDescuentosBase() { return descuentosBase; } public ObjectProperty<BigDecimal> getPorcDescuentosBase() { return porcDescuentosBase; } public StringProperty getImporteString() { return importeString; } public ObjectProperty<Producto> getProductoData() { return productoData; } public LegacyVentaDetalle getVentaDetalleEntity() { return ventaDetalleEntity; } }
gpl-2.0
Heltrato/MHFC
src/main/java/com/heltrato/mhfc/entity/EntitiesMH.java
2606
package com.heltrato.mhfc.entity; import com.heltrato.mhfc.MainMH; import com.heltrato.mhfc.generator.LanguagesMH; import com.heltrato.mhfc.generator.LootTableMH; import net.minecraft.entity.EntityType; import net.minecraftforge.api.distmarker.Dist; import net.minecraftforge.api.distmarker.OnlyIn; import net.minecraftforge.registries.DeferredRegister; import net.minecraftforge.registries.ForgeRegistries; public class EntitiesMH { public static DeferredRegister<EntityType<?>> MOD_ENTITY = DeferredRegister.create(ForgeRegistries.ENTITIES, MainMH.MODID); static int TRACKINGRANGE = 80;// DEFAULT for Projectiles. static int UPDATEINTERVAL = 3;// DEFAULT for Projectiles. static boolean RECEIVEDUPDATES = true; // DEFAULT for Projectiles. // TODO PERHAPS MOVE THIS IN THEM ENTITY CLASS. //static EntityType<FelyneEntity> FELYNE_ENTITY_TYPE = EntityType.Builder.create(FelyneEntity::new, EntityClassification.CREATURE).size(0.4F, 0.4F).build("felyne"); //static RegistryObject<EntityType<FelyneEntity>> FELYNE_OBJECT = MOD_ENTITY.register("felyne",() -> FELYNE_ENTITY_TYPE); //static EntityType<PopoEntity> POPO_ENTITY_TYPE = EntityType.Builder.create(PopoEntity::new, EntityClassification.CREATURE).size(1.0F,1.0f).build("popo"); // RegistryObject<EntityType<PopoEntity>> POPO_OBJECT = MOD_ENTITY.register("popo", () -> POPO_ENTITY_TYPE); public static void addEntityLanguage(final LanguagesMH arg) { //arg.addEntityType(FELYNE_OBJECT, "Felyne"); //arg.addEntityType(POPO_OBJECT, "Popo"); } public static void addEntityLoot(final LootTableMH.AddEntityLoots arg) { //arg.registerLootTables(FELYNE_OBJECT, LootTable.builder()); //arg.registerLootTables(POPO_OBJECT, LootTable.builder()); } public static void addEntitySpawnPlacement() { //EntitySpawnPlacementRegistry.register(FELYNE_ENTITY_TYPE, PlacementType.ON_GROUND,Heightmap.Type.MOTION_BLOCKING_NO_LEAVES, FelyneEntity::canSpawnOn); //EntitySpawnPlacementRegistry.register(POPO_ENTITY_TYPE, PlacementType.ON_GROUND, Heightmap.Type.MOTION_BLOCKING_NO_LEAVES, PopoEntity::canSpawnOn); } @OnlyIn(Dist.CLIENT) public static void addEntityRenderer() { //RenderingRegistry.registerEntityRenderingHandler(FELYNE_ENTITY_TYPE, m -> new FelyneRenderer(m)); //RenderingRegistry.registerEntityRenderingHandler(POPO_ENTITY_TYPE, m -> new PopoRenderer(m, 2.0f)); } public static void addEntityAttributes(){ //GlobalEntityTypeAttributes.put(FELYNE_ENTITY_TYPE, FelyneEntity.registerAttributes().create()); //GlobalEntityTypeAttributes.put(POPO_ENTITY_TYPE, PopoEntity.registerAttributes().create()); } }
gpl-2.0
slevental/lm
src/main/java/lm/graph/Graph.java
260
package lm.graph; import java.util.Set; /** * Created by Stas on 1/5/15. */ public interface Graph { void addEdge(int from, int to); Set<Integer> getEdges(int from); boolean hasEdge(int from, int to); int vertexes(); int edges(); }
gpl-2.0
hdadler/sensetrace-src
com.ipv.sensetrace.RDFDatamanager/jena-2.11.0/jena-arq/src/main/java/com/hp/hpl/jena/sparql/sse/lang/parser/JavaCharStream.java
15529
/* Generated By:JavaCC: Do not edit this line. JavaCharStream.java Version 5.0 */ /* JavaCCOptions:STATIC=false,SUPPORT_CLASS_VISIBILITY_PUBLIC=true */ /** * 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 com.hp.hpl.jena.sparql.sse.lang.parser ; /** * An implementation of interface CharStream, where the stream is assumed to * contain only ASCII characters (with java-like unicode escape processing). */ public class JavaCharStream { /** Whether parser is static. */ public static final boolean staticFlag = false; static final int hexval(char c) throws java.io.IOException { switch(c) { case '0' : return 0; case '1' : return 1; case '2' : return 2; case '3' : return 3; case '4' : return 4; case '5' : return 5; case '6' : return 6; case '7' : return 7; case '8' : return 8; case '9' : return 9; case 'a' : case 'A' : return 10; case 'b' : case 'B' : return 11; case 'c' : case 'C' : return 12; case 'd' : case 'D' : return 13; case 'e' : case 'E' : return 14; case 'f' : case 'F' : return 15; } throw new java.io.IOException(); // Should never come here } /** Position in buffer. */ public int bufpos = -1; int bufsize; int available; int tokenBegin; protected int bufline[]; protected int bufcolumn[]; protected int column = 0; protected int line = 1; protected boolean prevCharIsCR = false; protected boolean prevCharIsLF = false; protected java.io.Reader inputStream; protected char[] nextCharBuf; protected char[] buffer; protected int maxNextCharInd = 0; protected int nextCharInd = -1; protected int inBuf = 0; protected int tabSize = 8; protected void setTabSize(int i) { tabSize = i; } protected int getTabSize(int i) { return tabSize; } protected void ExpandBuff(boolean wrapAround) { char[] newbuffer = new char[bufsize + 2048]; int newbufline[] = new int[bufsize + 2048]; int newbufcolumn[] = new int[bufsize + 2048]; try { if (wrapAround) { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); System.arraycopy(buffer, 0, newbuffer, bufsize - tokenBegin, bufpos); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); System.arraycopy(bufline, 0, newbufline, bufsize - tokenBegin, bufpos); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); System.arraycopy(bufcolumn, 0, newbufcolumn, bufsize - tokenBegin, bufpos); bufcolumn = newbufcolumn; bufpos += (bufsize - tokenBegin); } else { System.arraycopy(buffer, tokenBegin, newbuffer, 0, bufsize - tokenBegin); buffer = newbuffer; System.arraycopy(bufline, tokenBegin, newbufline, 0, bufsize - tokenBegin); bufline = newbufline; System.arraycopy(bufcolumn, tokenBegin, newbufcolumn, 0, bufsize - tokenBegin); bufcolumn = newbufcolumn; bufpos -= tokenBegin; } } catch (Throwable t) { throw new Error(t.getMessage()); } available = (bufsize += 2048); tokenBegin = 0; } protected void FillBuff() throws java.io.IOException { int i; if (maxNextCharInd == 4096) maxNextCharInd = nextCharInd = 0; try { if ((i = inputStream.read(nextCharBuf, maxNextCharInd, 4096 - maxNextCharInd)) == -1) { inputStream.close(); throw new java.io.IOException(); } else maxNextCharInd += i; return; } catch(java.io.IOException e) { if (bufpos != 0) { --bufpos; backup(0); } else { bufline[bufpos] = line; bufcolumn[bufpos] = column; } throw e; } } protected char ReadByte() throws java.io.IOException { if (++nextCharInd >= maxNextCharInd) FillBuff(); return nextCharBuf[nextCharInd]; } /** @return starting character for token. */ public char BeginToken() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; tokenBegin = bufpos; return buffer[bufpos]; } tokenBegin = 0; bufpos = -1; return readChar(); } protected void AdjustBuffSize() { if (available == bufsize) { if (tokenBegin > 2048) { bufpos = 0; available = tokenBegin; } else ExpandBuff(false); } else if (available > tokenBegin) available = bufsize; else if ((tokenBegin - available) < 2048) ExpandBuff(true); else available = tokenBegin; } protected void UpdateLineColumn(char c) { column++; if (prevCharIsLF) { prevCharIsLF = false; line += (column = 1); } else if (prevCharIsCR) { prevCharIsCR = false; if (c == '\n') { prevCharIsLF = true; } else line += (column = 1); } switch (c) { case '\r' : prevCharIsCR = true; break; case '\n' : prevCharIsLF = true; break; case '\t' : column--; column += (tabSize - (column % tabSize)); break; default : break; } bufline[bufpos] = line; bufcolumn[bufpos] = column; } /** Read a character. */ public char readChar() throws java.io.IOException { if (inBuf > 0) { --inBuf; if (++bufpos == bufsize) bufpos = 0; return buffer[bufpos]; } char c; if (++bufpos == available) AdjustBuffSize(); if ((buffer[bufpos] = c = ReadByte()) == '\\') { UpdateLineColumn(c); int backSlashCnt = 1; for (;;) // Read all the backslashes { if (++bufpos == available) AdjustBuffSize(); try { if ((buffer[bufpos] = c = ReadByte()) != '\\') { UpdateLineColumn(c); // found a non-backslash char. if ((c == 'u') && ((backSlashCnt & 1) == 1)) { if (--bufpos < 0) bufpos = bufsize - 1; break; } backup(backSlashCnt); return '\\'; } } catch(java.io.IOException e) { // We are returning one backslash so we should only backup (count-1) if (backSlashCnt > 1) backup(backSlashCnt-1); return '\\'; } UpdateLineColumn(c); backSlashCnt++; } // Here, we have seen an odd number of backslash's followed by a 'u' try { while ((c = ReadByte()) == 'u') ++column; buffer[bufpos] = c = (char)(hexval(c) << 12 | hexval(ReadByte()) << 8 | hexval(ReadByte()) << 4 | hexval(ReadByte())); column += 4; } catch(java.io.IOException e) { throw new Error("Invalid escape character at line " + line + " column " + column + "."); } if (backSlashCnt == 1) return c; else { backup(backSlashCnt - 1); return '\\'; } } else { UpdateLineColumn(c); return c; } } @Deprecated /** * @deprecated * @see #getEndColumn */ public int getColumn() { return bufcolumn[bufpos]; } @Deprecated /** * @deprecated * @see #getEndLine */ public int getLine() { return bufline[bufpos]; } /** Get end column. */ public int getEndColumn() { return bufcolumn[bufpos]; } /** Get end line. */ public int getEndLine() { return bufline[bufpos]; } /** @return column of token start */ public int getBeginColumn() { return bufcolumn[tokenBegin]; } /** @return line number of token start */ public int getBeginLine() { return bufline[tokenBegin]; } /** Retreat. */ public void backup(int amount) { inBuf += amount; if ((bufpos -= amount) < 0) bufpos += bufsize; } /** Constructor. */ public JavaCharStream(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; nextCharBuf = new char[4096]; } /** Constructor. */ public JavaCharStream(java.io.Reader dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public JavaCharStream(java.io.Reader dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn, int buffersize) { inputStream = dstream; line = startline; column = startcolumn - 1; if (buffer == null || buffersize != buffer.length) { available = bufsize = buffersize; buffer = new char[buffersize]; bufline = new int[buffersize]; bufcolumn = new int[buffersize]; nextCharBuf = new char[4096]; } prevCharIsLF = prevCharIsCR = false; tokenBegin = inBuf = maxNextCharInd = 0; nextCharInd = bufpos = -1; } /** Reinitialise. */ public void ReInit(java.io.Reader dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.Reader dstream) { ReInit(dstream, 1, 1, 4096); } /** Constructor. */ public JavaCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { this(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Constructor. */ public JavaCharStream(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { this(new java.io.InputStreamReader(dstream), startline, startcolumn, 4096); } /** Constructor. */ public JavaCharStream(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { this(dstream, encoding, startline, startcolumn, 4096); } /** Constructor. */ public JavaCharStream(java.io.InputStream dstream, int startline, int startcolumn) { this(dstream, startline, startcolumn, 4096); } /** Constructor. */ public JavaCharStream(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { this(dstream, encoding, 1, 1, 4096); } /** Constructor. */ public JavaCharStream(java.io.InputStream dstream) { this(dstream, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn, int buffersize) throws java.io.UnsupportedEncodingException { ReInit(encoding == null ? new java.io.InputStreamReader(dstream) : new java.io.InputStreamReader(dstream, encoding), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn, int buffersize) { ReInit(new java.io.InputStreamReader(dstream), startline, startcolumn, buffersize); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding, int startline, int startcolumn) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, int startline, int startcolumn) { ReInit(dstream, startline, startcolumn, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream, String encoding) throws java.io.UnsupportedEncodingException { ReInit(dstream, encoding, 1, 1, 4096); } /** Reinitialise. */ public void ReInit(java.io.InputStream dstream) { ReInit(dstream, 1, 1, 4096); } /** @return token image as String */ public String GetImage() { if (bufpos >= tokenBegin) return new String(buffer, tokenBegin, bufpos - tokenBegin + 1); else return new String(buffer, tokenBegin, bufsize - tokenBegin) + new String(buffer, 0, bufpos + 1); } /** @return suffix */ public char[] GetSuffix(int len) { char[] ret = new char[len]; if ((bufpos + 1) >= len) System.arraycopy(buffer, bufpos - len + 1, ret, 0, len); else { System.arraycopy(buffer, bufsize - (len - bufpos - 1), ret, 0, len - bufpos - 1); System.arraycopy(buffer, 0, ret, len - bufpos - 1, bufpos + 1); } return ret; } /** Set buffers back to null when finished. */ public void Done() { nextCharBuf = null; buffer = null; bufline = null; bufcolumn = null; } /** * Method to adjust line and column numbers for the start of a token. */ public void adjustBeginLineColumn(int newLine, int newCol) { int start = tokenBegin; int len; if (bufpos >= tokenBegin) { len = bufpos - tokenBegin + inBuf + 1; } else { len = bufsize - tokenBegin + bufpos + 1 + inBuf; } int i = 0, j = 0, k = 0; int nextColDiff = 0, columnDiff = 0; while (i < len && bufline[j = start % bufsize] == bufline[k = ++start % bufsize]) { bufline[j] = newLine; nextColDiff = columnDiff + bufcolumn[k] - bufcolumn[j]; bufcolumn[j] = newCol + columnDiff; columnDiff = nextColDiff; i++; } if (i < len) { bufline[j] = newLine++; bufcolumn[j] = newCol + columnDiff; while (i++ < len) { if (bufline[j = start % bufsize] != bufline[++start % bufsize]) bufline[j] = newLine++; else bufline[j] = newLine; } } line = bufline[j]; column = bufcolumn[j]; } } /* JavaCC - OriginalChecksum=252e61e16e221885b5b7879b56e1991b (do not edit this line) */
gpl-2.0
donatellosantoro/freESBee
freesbee/test/it/unibas/icar/freesbee/test/qualificazione/fruitore/TestQualificazione01Start.java
5481
package it.unibas.icar.freesbee.test.qualificazione.fruitore; import it.unibas.icar.freesbee.test.qualificazione.UtilTest; import junit.framework.Assert; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import org.apache.cxf.helpers.XMLUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; public class TestQualificazione01Start extends TestCase { // private org.apache.commons.logging.Log logger = org.apache.commons.logging.LogFactory.getLog(this.getClass()); private static final Logger logger = LoggerFactory.getLogger(TestQualificazione01Start.class.getName()); public void testQualificazione01() { AbstractPATest paTest = new TestPA("/messaggiFruitore/1.startRisposta.xml"); try { String indirizzoPD = "http://localhost:8192/PD/PD_QualificazionePDD/?FRUITORE=PAGenerica&TIPO_FRUITORE=SPC" + "&EROGATORE=CNIPA&TIPO_EROGATORE=SPC" + "&SERVIZIO=QualificazionePDD&TIPO_SERVIZIO=SPC" + "&AZIONE=start"; String richiesta = UtilTest.leggiMessaggio("/messaggiFruitore/1.startRichiesta.xml"); logger.info("RICHIESTA:\n" + richiesta); paTest.startServlet(); Document soapRichiesta = UtilTest.leggiSOAP(richiesta); Element soapElement = soapRichiesta.getDocumentElement(); NodeList headerElements = soapElement.getElementsByTagNameNS("http://schemas.xmlsoap.org/soap/envelope/", "Header"); if (headerElements.getLength() == 1) { Node headerEl = headerElements.item(0); soapElement.removeChild(headerEl); } String stringaRichiesta = XMLUtils.toString(soapRichiesta); String tokenSessione = UtilTest.trovaNodoString("/soapenv:Envelope/soapenv:Body/p891:richiesta_RichiestaRispostaSincrona_start/p891:TokenSessione", soapRichiesta); logger.info("TokenSessione: " + tokenSessione); String risposta = UtilTest.invia(indirizzoPD, stringaRichiesta); logger.info("RISPOSTA:\n" + risposta); Document soapRisposta = UtilTest.leggiSOAP(risposta); String rispostaOK = UtilTest.trovaNodoString("/soapenv:Envelope/soapenv:Body/p891:risposta_RichiestaRispostaSincrona_start/p891:Esito", soapRisposta); Assert.assertEquals("RISPOSTA_OK", rispostaOK); String token = UtilTest.trovaNodoString("/soapenv:Envelope/soapenv:Body/p891:risposta_RichiestaRispostaSincrona_start/p891:TokenSessione", soapRisposta); Assert.assertEquals(tokenSessione, token); } catch (Exception ex) { logger.info("ERRORE: " + ex); Assert.fail(ex.getLocalizedMessage()); } finally { paTest.stop(); } } private class TestPA extends AbstractPATest { public TestPA(String fileMessaggioRisposta) { super(fileMessaggioRisposta); } @Override public void verificaRichiesta(String stringaRichiesta) throws AssertionFailedError { Document soapRichiesta = UtilTest.leggiSOAP(stringaRichiesta); String expIntestazione = "/SOAP_ENV:Envelope/SOAP_ENV:Header/eGov_IT:Intestazione/eGov_IT:IntestazioneMessaggio"; String mittente = UtilTest.trovaNodoString(expIntestazione + "/eGov_IT:Mittente/eGov_IT:IdentificativoParte", soapRichiesta); TestQualificazione01Start.assertEquals("PAGenerica", mittente); String tipoMittente = UtilTest.trovaNodoString(expIntestazione + "/eGov_IT:Mittente/eGov_IT:IdentificativoParte/@tipo", soapRichiesta); TestQualificazione01Start.assertEquals("SPC", tipoMittente); String destinatario = UtilTest.trovaNodoString(expIntestazione + "/eGov_IT:Destinatario/eGov_IT:IdentificativoParte", soapRichiesta); TestQualificazione01Start.assertEquals("CNIPA", destinatario); String tipoDestinatario = UtilTest.trovaNodoString(expIntestazione + "/eGov_IT:Destinatario/eGov_IT:IdentificativoParte/@tipo", soapRichiesta); TestQualificazione01Start.assertEquals("SPC", tipoDestinatario); String servizio = UtilTest.trovaNodoString(expIntestazione + "/eGov_IT:Servizio ", soapRichiesta); TestQualificazione01Start.assertEquals("QualificazionePDD", servizio); String azione = UtilTest.trovaNodoString(expIntestazione + "/eGov_IT:Azione ", soapRichiesta); TestQualificazione01Start.assertEquals("start", azione); String identificatore = UtilTest.trovaNodoString(expIntestazione + "/eGov_IT:Messaggio/eGov_IT:Identificatore", soapRichiesta); TestQualificazione01Start.assertTrue(identificatore.startsWith("PAGenerica_PAGenericaSPCoopIT_")); String profiloCollaborazione = UtilTest.trovaNodoString(expIntestazione + "/eGov_IT:ProfiloCollaborazione", soapRichiesta); TestQualificazione01Start.assertEquals("EGOV_IT_ServizioSincrono", profiloCollaborazione); String token = UtilTest.trovaNodoString("/soapenv:Envelope/soapenv:Body/p891:richiesta_RichiestaRispostaSincrona_start/p891:TokenSessione", soapRichiesta); TestQualificazione01Start.assertEquals("1ab955960a3281e965c0393ad0071f1e", token); } } }
gpl-2.0
waps12b/IntroductionToAlgoritmProblemSolvingTechniques
Projects/DynamicArray/Java/DynamicArray.java
1536
import java.io.*; import java.util.*; import java.lang.*; public class DynamicArray<T> { public static final int INITIAL_CAPACITY = 16; private T[] array; // 내부 저장 공간 배열 private int capacity; // 내부 저장 공간의 실제 크기를 나타내는 변수 private int size; // 실제로 저장된 원소의 수를 나타내는 변수 public DynamicArray() { this.array = (T[]) (new Object[INITIAL_CAPACITY]); this.capacity = INITIAL_CAPACITY; this.size = 0; } /** * @TODO 배열에 존재하는 원소들을 사용해 초기화하는 생성자 구현 * * @param array */ public DynamicArray(T[] array) { } /** * @TODO 가장 뒤에 새로운 원소를 추가하는 메소드 구현 * * @param element */ public void add(T element) { } /** * @TODO 특정 인덱스에 위차한 원소를 삭제하는 메소드 구현. 삭제 후 뒤의 원소들은 모두 앞으로 한 칸씩 당긴다. * * @param index */ public void remove(int index) { } /** * @TODO 특정 인덱스에 위치한 원소를 반환하는 메소드 구현 * * @param index * @return */ public T get(int index) { return null; } /** * @TODO 특정 인덱스에 위치한 원소를 수정하는 메소드 구현 * * @param index * @param value */ public void set(int index, T value) { } /** * @TODO 현재 저장된 원소의 수를 반환하는 메소드 구현 * * @return */ public int size() { return -1; } }
gpl-2.0
h3xstream/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest00148.java
2140
/** * OWASP Benchmark Project v1.2 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://owasp.org/www-project-benchmark/">https://owasp.org/www-project-benchmark/</a>. * * The OWASP Benchmark 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, version 2. * * The OWASP Benchmark 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. * * @author Nick Sanidas * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet(value="/xss-00/BenchmarkTest00148") public class BenchmarkTest00148 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); String param = ""; if (request.getHeader("Referer") != null) { param = request.getHeader("Referer"); } // URL Decode the header value since req.getHeader() doesn't. Unlike req.getParameter(). param = java.net.URLDecoder.decode(param, "UTF-8"); String bar; // Simple if statement that assigns param to bar on true condition int num = 196; if ( (500/42) + num > 200 ) bar = param; else bar = "This should never happen"; response.setHeader("X-XSS-Protection", "0"); Object[] obj = { "a", bar }; response.getWriter().format("Formatted like: %1$s and %2$s.",obj); } }
gpl-2.0
Arquisoft/Trivial_i1b
Game/src/main/java/logic/Game.java
2183
package logic; import java.util.ArrayList; import java.util.List; import logic.DB.MongoQuestionManager; import logic.DB.MongoUserManager; import logic.board.Board; import logic.model.Die; import logic.model.Player; import logic.model.Statistics; import logic.model.User; import Model.Question; public class Game { private Board board; private List<Player> players; private Player activePlayer; public Game() { List<Question> questions = new MongoQuestionManager().getQuestions(); board = new Board(new QuestionSelector(questions)); players = new ArrayList<Player>(); } public Board getBoard() { return board; } public void addPlayer(Player player) { if (players.isEmpty()) { activePlayer = player; } players.add(player); } public Player nextPlayer() { for (int i = 0; i < players.size(); i++) { if (players.get(i).equals(activePlayer)) { if (i + 1 < players.size()) { activePlayer = players.get(i + 1); break; } else { activePlayer = players.get(0); break; } } } return activePlayer; } public boolean trueAnswer(Question question, int answer) { return question.getPositionTrue() == answer; } public User login(String username, String password) { User user = new MongoUserManager().getUser(username); if (user != null && user.getPassword().equals(password)) return user; return null; } public User register(String username, String email, String password) { User user = new User(username, password, email, new Statistics(0, 0, 0)); if (new MongoUserManager().saveUser(user)) return user; return null; } public List<Player> getPlayers() { return players; } public Player getActivePlayer() { return activePlayer; } public void changePositionPlayer(Player player, String string) { String[] position = string.split("_"); player.getPosition().setWalk(Integer.valueOf(position[0])); player.getPosition().setIndex(Integer.valueOf(position[1])); for (Player p : players) { if (player.getUsername().equals(p.getUsername())) p.setPosition(player.getPosition()); } } public void closeDatabase() { } public int throwDie() { return Die.drop(); } }
gpl-2.0
CEREMA/com.cerema.cloud
owncloud-android-library/src/com/cerema/cloud/lib/common/network/NetworkUtils.java
8440
/* ownCloud Android Library is available under MIT license * Copyright (C) 2014 ownCloud Inc. * * 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.cerema.cloud.lib.common.network; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.security.GeneralSecurityException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.cert.Certificate; import java.security.cert.CertificateException; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManager; import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; import org.apache.commons.httpclient.protocol.Protocol; import org.apache.http.conn.ssl.BrowserCompatHostnameVerifier; import org.apache.http.conn.ssl.X509HostnameVerifier; import android.content.Context; import com.cerema.cloud.lib.common.utils.Log_OC; public class NetworkUtils { final private static String TAG = NetworkUtils.class.getSimpleName(); /** Default timeout for waiting data from the server */ public static final int DEFAULT_DATA_TIMEOUT = 60000; /** Default timeout for establishing a connection */ public static final int DEFAULT_CONNECTION_TIMEOUT = 60000; /** Connection manager for all the OwnCloudClients */ private static MultiThreadedHttpConnectionManager mConnManager = null; private static Protocol mDefaultHttpsProtocol = null; private static AdvancedSslSocketFactory mAdvancedSslSocketFactory = null; private static X509HostnameVerifier mHostnameVerifier = null; /** * Registers or unregisters the proper components for advanced SSL handling. * @throws IOException */ public static void registerAdvancedSslContext(boolean register, Context context) throws GeneralSecurityException, IOException { Protocol pr = null; try { pr = Protocol.getProtocol("https"); if (pr != null && mDefaultHttpsProtocol == null) { mDefaultHttpsProtocol = pr; } } catch (IllegalStateException e) { // nothing to do here; really } boolean isRegistered = (pr != null && pr.getSocketFactory() instanceof AdvancedSslSocketFactory); if (register && !isRegistered) { Protocol.registerProtocol("https", new Protocol("https", getAdvancedSslSocketFactory(context), 443)); } else if (!register && isRegistered) { if (mDefaultHttpsProtocol != null) { Protocol.registerProtocol("https", mDefaultHttpsProtocol); } } } public static AdvancedSslSocketFactory getAdvancedSslSocketFactory(Context context) throws GeneralSecurityException, IOException { if (mAdvancedSslSocketFactory == null) { KeyStore trustStore = getKnownServersStore(context); AdvancedX509TrustManager trustMgr = new AdvancedX509TrustManager(trustStore); TrustManager[] tms = new TrustManager[] { trustMgr }; SSLContext sslContext = SSLContext.getInstance("TLS"); sslContext.init(null, tms, null); mHostnameVerifier = new BrowserCompatHostnameVerifier(); mAdvancedSslSocketFactory = new AdvancedSslSocketFactory(sslContext, trustMgr, mHostnameVerifier); } return mAdvancedSslSocketFactory; } private static String LOCAL_TRUSTSTORE_FILENAME = "knownServers.bks"; private static String LOCAL_TRUSTSTORE_PASSWORD = "password"; private static KeyStore mKnownServersStore = null; /** * Returns the local store of reliable server certificates, explicitly accepted by the user. * * Returns a KeyStore instance with empty content if the local store was never created. * * Loads the store from the storage environment if needed. * * @param context Android context where the operation is being performed. * @return KeyStore instance with explicitly-accepted server certificates. * @throws KeyStoreException When the KeyStore instance could not be created. * @throws IOException When an existing local trust store could not be loaded. * @throws NoSuchAlgorithmException When the existing local trust store was saved with an unsupported algorithm. * @throws CertificateException When an exception occurred while loading the certificates from the local trust store. */ private static KeyStore getKnownServersStore(Context context) throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException { if (mKnownServersStore == null) { //mKnownServersStore = KeyStore.getInstance("BKS"); mKnownServersStore = KeyStore.getInstance(KeyStore.getDefaultType()); File localTrustStoreFile = new File(context.getFilesDir(), LOCAL_TRUSTSTORE_FILENAME); Log_OC.d(TAG, "Searching known-servers store at " + localTrustStoreFile.getAbsolutePath()); if (localTrustStoreFile.exists()) { InputStream in = new FileInputStream(localTrustStoreFile); try { mKnownServersStore.load(in, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); } finally { in.close(); } } else { mKnownServersStore.load(null, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); // necessary to initialize an empty KeyStore instance } } return mKnownServersStore; } public static void addCertToKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore knownServers = getKnownServersStore(context); knownServers.setCertificateEntry(Integer.toString(cert.hashCode()), cert); FileOutputStream fos = null; try { fos = context.openFileOutput(LOCAL_TRUSTSTORE_FILENAME, Context.MODE_PRIVATE); knownServers.store(fos, LOCAL_TRUSTSTORE_PASSWORD.toCharArray()); } finally { fos.close(); } } static public MultiThreadedHttpConnectionManager getMultiThreadedConnManager() { if (mConnManager == null) { mConnManager = new MultiThreadedHttpConnectionManager(); mConnManager.getParams().setDefaultMaxConnectionsPerHost(5); mConnManager.getParams().setMaxTotalConnections(5); } return mConnManager; } public static boolean isCertInKnownServersStore(Certificate cert, Context context) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException { KeyStore knownServers = getKnownServersStore(context); Log_OC.d(TAG, "Certificate - HashCode: " + cert.hashCode() + " " + Boolean.toString(knownServers.isCertificateEntry(Integer.toString(cert.hashCode())))); return knownServers.isCertificateEntry(Integer.toString(cert.hashCode())); } }
gpl-2.0
siggouroglou/ergasia_restServerSide_java
src/main/java/gr/unipi/www/model/entity/Platform.java
1215
package gr.unipi.www.model.entity; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; /** * * @author siggouroglou@gmail.com */ @Entity @Table(schema = "web") public class Platform implements Serializable { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column private Integer id; @Column private String name; @ManyToMany(mappedBy = "platformList") private List<Student> studentList; public Platform() { this.id = null; this.name = ""; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<Student> getStudentList() { return studentList; } public void setStudentList(List<Student> studentList) { this.studentList = studentList; } }
gpl-2.0
jbright927/CoffeeFinder
foursquare-api-java-20140131/src/main/java/fi/foyt/foursquare/api/io/package-info.java
344
/* * FoursquareAPI - Foursquare API for Java * Copyright (C) 2008 - 2011 Antti Leppä / Foyt * http://www.foyt.fi * * License: * * Licensed under GNU Lesser General Public License Version 3 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html */ /** * Package containing IO operations */ package fi.foyt.foursquare.api.io;
gpl-2.0
clusterwork/ClusterWork
src/com/intel/wy/testcases/TestRetryChildStrategy.java
2593
package com.intel.wy.testcases; import java.io.FileWriter; import java.io.IOException; import com.intel.fangpei.logfactory.MonitorLog; import com.intel.fangpei.network.rpc.RpcClient; import com.intel.fangpei.process.MyChildStrategy2; import com.intel.fangpei.process.ProcessFactory; import com.intel.fangpei.task.NodeTaskTracker; import com.intel.fangpei.task.TaskRunner; import com.intel.fangpei.task.TaskStrategy; import com.intel.fangpei.terminal.Node; import com.intel.fangpei.util.ConfManager; public class TestRetryChildStrategy { /**��MyChildStrategy2�ĵ�54��"return true"�ij�"return false"�����дβ��������ظ���ӡ����1:1��1:5 * change <class>MyChilStrategy2<class> 54 line from "return true" to "return false", * run this demo will print twice from 1:1 to 1:5 * @param args * @throws Exception */ public static void main(String[] args) throws Exception { clean(); ConfManager.addResource(null); NodeTaskTracker tracker = new NodeTaskTracker(new MonitorLog()); TaskRunner tr1 = createTaskRunner(new String[]{"com.intel.developer.extend.myextend1"}); tracker.addNewTaskMonitorWithPriority(tr1, 0); // Node n = new Node(); // n.extendTask("com.intel.fangpei.process.MyChildStrategy2",new String[]{"com.intel.developer.extend.myextend1"}, 0); tryKillLastProcess(); } public static void clean(){ FileWriter fw; try { fw = new FileWriter("D:/myextend1.txt"); fw.write(" "); } catch (IOException e) { e.printStackTrace(); } } public static TaskRunner createTaskRunner(String[] s){ TaskRunner tr = new TaskRunner(); TaskStrategy strate = null; strate = new TaskStrategy(); //strate.addStrategy(tr.getDefaultStrategy(),s); strate.addStrategy(new MyChildStrategy2(),s); tr.setTaskStrategy(strate); return tr; } public static void tryKillLastProcess(){ try { Thread.sleep(3000); RpcClient client = RpcClient.getInstance(); int id = ProcessFactory.getProcessNum(); Object [] params = {id}; Thread.sleep(1000); client.execute("ChildHandler.setChildKilled", params); String function = "ChildHandler.iskilled"; boolean result = (Boolean) client.execute(function, params); System.out.println("--------------------------------------"); System.out.println("iskilled is "+result+""); System.out.println("--------------------------------------"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
gpl-2.0
eko-konnect/stop-the-bribe
StopTheBribe/src/org/ekokonnect/stopthebribe/SettingsActivity.java
2187
package org.ekokonnect.stopthebribe; import android.os.Bundle; import android.preference.EditTextPreference; import android.preference.Preference; import android.preference.PreferenceActivity; import android.preference.PreferenceCategory; import android.preference.PreferenceManager; import android.app.Activity; import android.content.SharedPreferences; import android.view.Menu; import android.widget.Toast; import com.ushahidi.android.app.Preferences; public class SettingsActivity extends PreferenceActivity{ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); addPreferencesFromResource(R.xml.pref_settings); for(int i=0;i<getPreferenceScreen().getPreferenceCount(); i++){ initSummary(getPreferenceScreen().getPreference(i)); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.settings, menu); return true; } private void showDefaultValue(Preference p){ //SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); Preferences.loadSettings(getApplicationContext()); if(p instanceof EditTextPreference){ EditTextPreference editPref = (EditTextPreference)p; //editPref.setDefaultValue(sharedPref.getString(editPref.getKey(), "Not Set")); if(editPref.getKey().equals("Firstname")){ editPref.setSummary(Preferences.firstname); } if(editPref.getKey().equals("Lastname")){ editPref.setSummary(Preferences.lastname); } if(editPref.getKey().equals("Email")){ editPref.setSummary(Preferences.email); } //editPref.setSummary(sharedPref.getString(editPref.getKey(), "Not Set")); //editPref.getEditText().setText(sharedPref.getString(editPref.getKey(), "Not Set")); } } private void initSummary(Preference p) { if (p instanceof PreferenceCategory) { PreferenceCategory cat = (PreferenceCategory) p; for (int i = 0; i < cat.getPreferenceCount(); i++) { initSummary(cat.getPreference(i)); } } else { showDefaultValue(p); } } }
gpl-2.0
Jacksson/mywms
server.app/los.inventory-ejb/src/de/linogistix/los/inventory/crud/ExtinguishOrderCRUDBean.java
834
/* * UserCRUDBean.java * * Created on 20.02.2007, 18:37:29 * * Copyright (c) 2006/2007 LinogistiX GmbH. All rights reserved. * * <a href="http://www.linogistix.com/">browse for licence information</a> * */ package de.linogistix.los.inventory.crud; import javax.ejb.EJB; import javax.ejb.Stateless; import org.mywms.service.BasicService; import de.linogistix.los.crud.BusinessObjectCRUDBean; import de.linogistix.los.inventory.model.ExtinguishOrder; import de.linogistix.los.inventory.service.ExtinguishOrderService; /** * @author trautm * */ @Stateless public class ExtinguishOrderCRUDBean extends BusinessObjectCRUDBean<ExtinguishOrder> implements ExtinguishOrderCRUDRemote { @EJB ExtinguishOrderService service; @Override protected BasicService<ExtinguishOrder> getBasicService() { return service; } }
gpl-2.0
Thomashuet/Biocham
gui/utils/OSXAdapter.java
23544
package fr.inria.contraintes.biocham.utils; /* File: OSXAdapter.java Abstract: Hooks existing preferences/about/quit functionality from an existing Java app into handlers for the Mac OS X application menu. Uses a Proxy object to dynamically implement the com.apple.eawt.ApplicationListener interface and register it with the com.apple.eawt.Application object. This allows the complete project to be both built and run on any platform without any stubs or placeholders. Useful for developers looking to implement Mac OS X features while supporting multiple platforms with minimal impact. Version: 2.0 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright (C) 2003-2007 Apple, Inc., All Rights Reserved */ import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * * Hooks existing preferences/about/quit functionality from an existing Java app into handlers for the Mac OS X application menu. Uses a Proxy object to dynamically implement the com.apple.eawt.ApplicationListener interface and register it with the com.apple.eawt.Application object. This allows the complete project to be both built and run on any platform without any stubs or placeholders. Useful for developers looking to implement Mac OS X features while supporting multiple platforms with minimal impact. * */ public class OSXAdapter implements InvocationHandler { protected Object targetObject; protected Method targetMethod; protected String proxySignature; public static boolean initialized1=false; public static boolean initialized2=false; static Object macOSXApplication; /** Pass this method an Object and Method equipped to perform application shutdown logic The method passed should return a boolean stating whether or not the quit should occur*/ public static void setQuitHandler(Object target, Method quitHandler) { Utils.debugMsg("OSXAdapter access the QUIT Menu"); setHandler(new OSXAdapter("handleQuit", target, quitHandler)); } /** Pass this method an Object and Method equipped to display application info They will be called when the About menu item is selected from the application menu*/ public static void setAboutHandler(Object target, Method aboutHandler) { boolean enableAboutMenu = (target != null && aboutHandler != null); if (enableAboutMenu) { Utils.debugMsg("OSXAdapter access the About Menu"); setHandler(new OSXAdapter("handleAbout", target, aboutHandler)); } /** If we're setting a handler, enable the About menu item by calling com.apple.eawt.Application reflectively*/ if(!initialized1){ try { Method enableAboutMethod = macOSXApplication.getClass().getDeclaredMethod("setEnabledAboutMenu", new Class[] { boolean.class }); Utils.debugMsg("OSXAdapter ENABLING ABOUT MENU!!!!!!!!!!!!!!!! on "+enableAboutMenu); Utils.debugMsg("macOSXApplication= "+macOSXApplication); enableAboutMethod.invoke(macOSXApplication, new Object[] { Boolean.TRUE }); initialized1=true; } catch (Exception ex) { Utils.debugMsg("OSXAdapter could not access the About Menu.\n"); ex.printStackTrace(); } } } /**Pass this method an Object and a Method equipped to display application options They will be called when the Preferences menu item is selected from the application menu*/ public static void setPreferencesHandler(Object target, Method prefsHandler) { boolean enablePrefsMenu = (target != null && prefsHandler != null); if (enablePrefsMenu) { Utils.debugMsg("OSXAdapter access the PREFF Menu"); setHandler(new OSXAdapter("handlePreferences", target, prefsHandler)); } // If we're setting a handler, enable the Preferences menu item by calling // com.apple.eawt.Application reflectively try { Method enablePrefsMethod = macOSXApplication.getClass().getDeclaredMethod("setEnabledPreferencesMenu", new Class[] { boolean.class }); enablePrefsMethod.invoke(macOSXApplication, new Object[] { Boolean.valueOf(enablePrefsMenu) }); } catch (Exception ex) { Utils.debugMsg("OSXAdapter could not access the About Menu"); ex.printStackTrace(); } } /** Pass this method an Object and a Method equipped to handle document events from the Finder Documents are registered with the Finder via the CFBundleDocumentTypes dictionary in the application bundle's Info.plist*/ public static void setFileHandler(Object target, Method fileHandler) { setHandler(new OSXAdapter("handleOpenFile", target, fileHandler) { // Override OSXAdapter.callTarget to send information on the // file to be opened public boolean callTarget(Object appleEvent) { if (appleEvent != null) { try { Utils.debugMsg("OSXAdapter access the OpenBiochamFile Menu"); Method getFilenameMethod = appleEvent.getClass().getDeclaredMethod("getFilename", (Class[])null); String filename = (String) getFilenameMethod.invoke(appleEvent, (Object[])null); this.targetMethod.invoke(this.targetObject, new Object[] { filename }); } catch (Exception ex) { ex.printStackTrace(); } } return true; } }); } /**setHandler creates a Proxy object from the passed OSXAdapter and adds it as an ApplicationListener*/ public static void setHandler(OSXAdapter adapter) { try { Class applicationClass = Class.forName("com.apple.eawt.Application"); if (macOSXApplication == null) { macOSXApplication = applicationClass.getConstructor((Class[])null).newInstance((Object[])null); } Utils.debugMsg("macOSXApplication in setHandler of method "+adapter.targetMethod.getName()+"= "+macOSXApplication); Class applicationListenerClass = Class.forName("com.apple.eawt.ApplicationListener"); Method addListenerMethod = applicationClass.getDeclaredMethod("addApplicationListener", new Class[] { applicationListenerClass }); // Create a proxy object around this handler that can be reflectively added as an Apple ApplicationListener Object osxAdapterProxy = Proxy.newProxyInstance(OSXAdapter.class.getClassLoader(), new Class[] { applicationListenerClass }, adapter); addListenerMethod.invoke(macOSXApplication, new Object[] { osxAdapterProxy }); } catch (ClassNotFoundException cnfe) { Utils.debugMsg("This version of Mac OS X does not support the Apple EAWT. ApplicationEvent handling has been disabled (" + cnfe + ")"); } catch (Exception ex) { // Likely a NoSuchMethodException or an IllegalAccessException loading/invoking eawt.Application methods Utils.debugMsg("Mac OS X Adapter could not talk to EAWT:"); ex.printStackTrace(); } } /** Each OSXAdapter has the name of the EAWT method it intends to listen for (handleAbout, for example), the Object that will ultimately perform the task, and the Method to be called on that Object*/ protected OSXAdapter(String proxySignature, Object target, Method handler) { this.proxySignature = proxySignature; this.targetObject = target; this.targetMethod = handler; } /** Override this method to perform any operations on the event that comes with the various callbacks See setFileHandler above for an example*/ public boolean callTarget(Object appleEvent) throws InvocationTargetException, IllegalAccessException { Object result = targetMethod.invoke(targetObject, (Object[])null); Utils.debugMsg("RESULT of calling target is: "+result); if (result == null) { return true; } return Boolean.valueOf(result.toString()).booleanValue(); } /** InvocationHandler implementation This is the entry point for our proxy object; it is called every time an ApplicationListener method is invoked*/ public Object invoke (Object proxy, Method method, Object[] args) throws Throwable { if (isCorrectMethod(method, args)) { boolean handled = callTarget(args[0]); Utils.debugMsg("******Invoking method: "+method.getName()+". Is it deja handled?="+handled+"************"); setApplicationEventHandled(args[0], handled); Utils.debugMsg("Invoking method: "+method.getName()); }else{ Utils.debugMsg("Invoking method: "+method.getName()+" doesn't has GOOD arguments!!!!!!!!!!!!!!!!"); } // All of the ApplicationListener methods are void; return null regardless of what happens return null; } /** Compare the method that was called to the intended method when the OSXAdapter instance was created (e.g. handleAbout, handleQuit, handleOpenFile, etc.)*/ protected boolean isCorrectMethod(Method method, Object[] args) { return (targetMethod != null && proxySignature.equals(method.getName()) && args.length == 1); } /** It is important to mark the ApplicationEvent as handled and cancel the default behavior This method checks for a boolean result from the proxy method and sets the event accordingly*/ protected void setApplicationEventHandled(Object event, boolean handled) { Utils.debugMsg("Invoking setApplicationEventHandled: event= "+event+", handled="+handled); if (event != null) { try { Method setHandledMethod = event.getClass().getDeclaredMethod("setHandled", new Class[] { boolean.class }); // If the target method returns a boolean, use that as a hint setHandledMethod.invoke(event, new Object[] { Boolean.valueOf(handled) }); } catch (Exception ex) { Utils.debugMsg("OSXAdapter was unable to handle an ApplicationEvent: " + event); ex.printStackTrace(); } } } } /*package fr.inria.contraintes.biocham; File: OSXAdapter.java Abstract: Hooks existing preferences/about/quit functionality from an existing Java app into handlers for the Mac OS X application menu. Uses a Proxy object to dynamically implement the com.apple.eawt.ApplicationListener interface and register it with the com.apple.eawt.Application object. This allows the complete project to be both built and run on any platform without any stubs or placeholders. Useful for developers looking to implement Mac OS X features while supporting multiple platforms with minimal impact. Version: 2.0 Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple Inc. ("Apple") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Apple software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Apple software. In consideration of your agreement to abide by the following terms, and subject to these terms, Apple grants you a personal, non-exclusive license, under Apple's copyrights in this original Apple software (the "Apple Software"), to use, reproduce, modify and redistribute the Apple Software, with or without modifications, in source and/or binary forms; provided that if you redistribute the Apple Software in its entirety and without modifications, you must retain this notice and the following text and disclaimers in all such redistributions of the Apple Software. Neither the name, trademarks, service marks or logos of Apple Inc. may be used to endorse or promote products derived from the Apple Software without specific prior written permission from Apple. Except as expressly stated in this notice, no other rights or licenses, express or implied, are granted by Apple herein, including but not limited to any patent rights that may be infringed by your derivative works or by other works in which the Apple Software may be incorporated. The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS. IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION, MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE), STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Copyright � 2003-2007 Apple, Inc., All Rights Reserved import java.lang.reflect.*; public class OSXAdapter implements InvocationHandler { protected Object targetObject; protected Method targetMethod; protected String proxySignature; static Object macOSXApplication; // Pass this method an Object and Method equipped to perform application shutdown logic // The method passed should return a boolean stating whether or not the quit should occur public static void setQuitHandler(Object target, Method quitHandler) { setHandler(new OSXAdapter("handleQuit", target, quitHandler)); } // Pass this method an Object and Method equipped to display application info // They will be called when the About menu item is selected from the application menu public static void setAboutHandler(Object target, Method aboutHandler) { boolean enableAboutMenu = (target != null && aboutHandler != null); if (enableAboutMenu) { setHandler(new OSXAdapter("handleAbout", target, aboutHandler)); } // If we're setting a handler, enable the About menu item by calling // com.apple.eawt.Application reflectively try { Method enableAboutMethod = macOSXApplication.getClass().getDeclaredMethod("setEnabledAboutMenu", new Class[] { boolean.class }); enableAboutMethod.invoke(macOSXApplication, new Object[] { Boolean.valueOf(enableAboutMenu) }); } catch (Exception ex) { System.err.println("OSXAdapter could not access the About Menu"); ex.printStackTrace(); } } // Pass this method an Object and a Method equipped to display application options // They will be called when the Preferences menu item is selected from the application menu public static void setPreferencesHandler(Object target, Method prefsHandler) { boolean enablePrefsMenu = (target != null && prefsHandler != null); if (enablePrefsMenu) { setHandler(new OSXAdapter("handlePreferences", target, prefsHandler)); } // If we're setting a handler, enable the Preferences menu item by calling // com.apple.eawt.Application reflectively try { Method enablePrefsMethod = macOSXApplication.getClass().getDeclaredMethod("setEnabledPreferencesMenu", new Class[] { boolean.class }); enablePrefsMethod.invoke(macOSXApplication, new Object[] { Boolean.valueOf(enablePrefsMenu) }); } catch (Exception ex) { System.err.println("OSXAdapter could not access the About Menu"); ex.printStackTrace(); } } // Pass this method an Object and a Method equipped to handle document events from the Finder // Documents are registered with the Finder via the CFBundleDocumentTypes dictionary in the // application bundle's Info.plist public static void setFileHandler(Object target, Method fileHandler) { setHandler(new OSXAdapter("handleOpenFile", target, fileHandler) { // Override OSXAdapter.callTarget to send information on the // file to be opened public boolean callTarget(Object appleEvent) { if (appleEvent != null) { try { Method getFilenameMethod = appleEvent.getClass().getDeclaredMethod("getFilename", (Class[])null); String filename = (String) getFilenameMethod.invoke(appleEvent, (Object[])null); this.targetMethod.invoke(this.targetObject, new Object[] { filename }); } catch (Exception ex) { } } return true; } }); } // setHandler creates a Proxy object from the passed OSXAdapter and adds it as an ApplicationListener public static void setHandler(OSXAdapter adapter) { try { Class applicationClass = Class.forName("com.apple.eawt.Application"); if (macOSXApplication == null) { macOSXApplication = applicationClass.getConstructor((Class[])null).newInstance((Object[])null); } Class applicationListenerClass = Class.forName("com.apple.eawt.ApplicationListener"); Method addListenerMethod = applicationClass.getDeclaredMethod("addApplicationListener", new Class[] { applicationListenerClass }); // Create a proxy object around this handler that can be reflectively added as an Apple ApplicationListener Object osxAdapterProxy = Proxy.newProxyInstance(OSXAdapter.class.getClassLoader(), new Class[] { applicationListenerClass }, adapter); addListenerMethod.invoke(macOSXApplication, new Object[] { osxAdapterProxy }); } catch (ClassNotFoundException cnfe) { System.err.println("This version of Mac OS X does not support the Apple EAWT. ApplicationEvent handling has been disabled (" + cnfe + ")"); } catch (Exception ex) { // Likely a NoSuchMethodException or an IllegalAccessException loading/invoking eawt.Application methods System.err.println("Mac OS X Adapter could not talk to EAWT:"); ex.printStackTrace(); } } // Each OSXAdapter has the name of the EAWT method it intends to listen for (handleAbout, for example), // the Object that will ultimately perform the task, and the Method to be called on that Object protected OSXAdapter(String proxySignature, Object target, Method handler) { this.proxySignature = proxySignature; this.targetObject = target; this.targetMethod = handler; } // Override this method to perform any operations on the event // that comes with the various callbacks // See setFileHandler above for an example public boolean callTarget(Object appleEvent) throws InvocationTargetException, IllegalAccessException { Object result = targetMethod.invoke(targetObject, (Object[])null); if (result == null) { return true; } return Boolean.valueOf(result.toString()).booleanValue(); } // InvocationHandler implementation // This is the entry point for our proxy object; it is called every time an ApplicationListener method is invoked public Object invoke (Object proxy, Method method, Object[] args) throws Throwable { if (isCorrectMethod(method, args)) { boolean handled = callTarget(args[0]); setApplicationEventHandled(args[0], handled); } // All of the ApplicationListener methods are void; return null regardless of what happens return null; } // Compare the method that was called to the intended method when the OSXAdapter instance was created // (e.g. handleAbout, handleQuit, handleOpenFile, etc.) protected boolean isCorrectMethod(Method method, Object[] args) { return (targetMethod != null && proxySignature.equals(method.getName()) && args.length == 1); } // It is important to mark the ApplicationEvent as handled and cancel the default behavior // This method checks for a boolean result from the proxy method and sets the event accordingly protected void setApplicationEventHandled(Object event, boolean handled) { if (event != null) { try { Method setHandledMethod = event.getClass().getDeclaredMethod("setHandled", new Class[] { boolean.class }); // If the target method returns a boolean, use that as a hint setHandledMethod.invoke(event, new Object[] { Boolean.valueOf(handled) }); } catch (Exception ex) { System.err.println("OSXAdapter was unable to handle an ApplicationEvent: " + event); ex.printStackTrace(); } } } } */
gpl-2.0
GChicha/IA_JGammon
src/jgam/net/Chatter.java
8036
/* * JGammon: A backgammon client written in Java * Copyright (C) 2005/06 Mattias Ulbrich * * JGammon includes: - playing over network * - plugin mechanism for graphical board implementations * - artificial intelligence player * - plugin mechanism for AI players * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package jgam.net; import java.awt.*; import java.awt.event.*; import java.io.*; import java.text.DateFormat; import java.util.*; import javax.swing.*; import javax.swing.border.Border; import javax.swing.text.*; import jgam.JGammon; /** * A simple chatter window that reacts on special messages send over the * connection and sends messages as well. * * @author Mattias Ulbrich */ public class Chatter extends JFrame implements ChannelListener { private static ResourceBundle msg = JGammon .getResources("jgam.msg.Chatter"); //$NON-NLS-1$ private BorderLayout borderLayout1 = new BorderLayout(); private JPanel jPanel2 = new JPanel(); private Border border1 = BorderFactory.createCompoundBorder(BorderFactory .createLineBorder(new Color(199, 199, 207), 3), BorderFactory .createEmptyBorder(5, 10, 5, 10)); private JTextField input = new JTextField(); private JScrollPane jScrollPane1 = new JScrollPane(); private Border border3 = BorderFactory.createLineBorder(new Color(199, 199, 207), 3); private JLabel jLabel1 = new JLabel(); private JButton send = new JButton(); private JTextPane output = new JTextPane(); private String remoteName, localName; private Writer writer; private NewMessageWindow messageWindow; public Chatter(String partner, String myName, Writer writer) { super(msg.getString("chatwith") + partner); //$NON-NLS-1$ this.remoteName = partner; this.localName = myName; this.writer = writer; try { jbInit(); pack(); } catch (Exception exception) { exception.printStackTrace(); } } private void jbInit() throws Exception { getContentPane().setLayout(borderLayout1); jScrollPane1.setBorder(border3); // input.setPreferredSize(new Dimension(220, 20)); jLabel1.setText(msg.getString("message")); //$NON-NLS-1$ send.setText(msg.getString("send")); //$NON-NLS-1$ getRootPane().setDefaultButton(send); send.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { send(); } }); jScrollPane1.setPreferredSize(new Dimension(350, 200)); output.setEditable(false); this.getContentPane().add(jPanel2, java.awt.BorderLayout.SOUTH); jPanel2.setBorder(border1); BorderLayout bl = new BorderLayout(10, 10); jPanel2.setLayout(bl); jPanel2.add(jLabel1, BorderLayout.WEST); jPanel2.add(input, BorderLayout.CENTER); jPanel2.add(send, BorderLayout.EAST); this.getContentPane().add(jScrollPane1, java.awt.BorderLayout.CENTER); jScrollPane1.getViewport().add(output); } public void receiveChannelMessage(int channel, String message) { if (channel != JGammonConnection.CHAT_CHANNEL) { return; } addMsg(message, true); if (!isVisible()) newMessageWindow(message); else toFront(); } public void newMessageWindow(String message) { if (messageWindow == null) { messageWindow = new NewMessageWindow(this, JGammon.jgammon() .getFrame()); } messageWindow.show(message); } public void send() { String msg = input.getText(); if (msg.length() == 0) { return; } try { writer.write(msg + "\n"); //$NON-NLS-1$ writer.flush(); addMsg(msg, false); } catch (IOException ex) { ex.printStackTrace(); } input.setText(""); //$NON-NLS-1$ } public void addMsg(final String message, boolean remote) { // insert text in the editor final SimpleAttributeSet norm = new SimpleAttributeSet(); if (remote) { StyleConstants.setForeground(norm, Color.blue); } SimpleAttributeSet bold = new SimpleAttributeSet(norm); StyleConstants.setBold(bold, true); final Document d = output.getStyledDocument(); final DateFormat df = DateFormat.getTimeInstance(DateFormat.SHORT); final String name = remote ? remoteName : localName; /* * bugfix: calling this function with the lock for this object causes * a deadlock. Instead: synchronize only the insert part with the document. */ try { synchronized(d) { d.insertString(d.getLength(), name + " (" + df.format(new Date()) + "): ", //$NON-NLS-1$ //$NON-NLS-2$ norm); d.insertString(d.getLength(), message + "\n", norm); //$NON-NLS-1$ } } catch (BadLocationException ex) { ex.printStackTrace(); } final Dimension size = output.getSize(); output.scrollRectToVisible(new Rectangle(0, size.height - 1, 1, size.height)); } } /** * In order to announnce a new message pop up a tooltip like frameless window. * */ class NewMessageWindow extends Window { ResourceBundle msg = JGammon.getResources("jgam.msg.Chatter"); //$NON-NLS-1$ JLabel label = new JLabel(); Chatter chatter; NewMessageWindow(Chatter chatter, Frame parent) { super(parent); this.chatter = chatter; JPanel p = new JPanel(new GridLayout(3, 1)); p.add(new JLabel(msg.getString("newchat"))); //$NON-NLS-1$ p.add(label); { JLabel clickhere = new JLabel(msg.getString("clickhere")); clickhere.setForeground(Color.blue); clickhere.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent e) { NewMessageWindow.this.chatter.setVisible(true); setVisible(false); } }); p.add(clickhere); } p.setBackground(UIManager.getColor("ToolTip.background")); //$NON-NLS-1$ p.setBorder(BorderFactory.createCompoundBorder(BorderFactory .createLineBorder(UIManager.getColor("ToolTip.foreround"), 1), //$NON-NLS-1$ BorderFactory.createEmptyBorder(15, 15, 15, 15))); p.addMouseListener(new MouseAdapter() { public void mouseClicked(MouseEvent ev) { setVisible(false); } }); add(p); } public void show(String message) { if (message.length() > 80) message = message.substring(0, 79) + "..."; label.setText(message); pack(); setLocationRelativeTo(getOwner()); setVisible(true); } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest03173.java
2455
/** * OWASP Benchmark Project v1.1 * * This file is part of the Open Web Application Security Project (OWASP) * Benchmark Project. For details, please see * <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>. * * The Benchmark 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, version 2. * * The Benchmark 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 * * @author Nick Sanidas <a href="https://www.aspectsecurity.com">Aspect Security</a> * @created 2015 */ package org.owasp.benchmark.testcode; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/BenchmarkTest03173") public class BenchmarkTest03173 extends HttpServlet { private static final long serialVersionUID = 1L; @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String param = request.getParameter("foo"); String bar; // Simple if statement that assigns constant to bar on true condition int i = 86; if ( (7*42) - i > 200 ) bar = "This_should_always_happen"; else bar = param; java.util.List<String> argList = new java.util.ArrayList<String>(); String osName = System.getProperty("os.name"); if (osName.indexOf("Windows") != -1) { argList.add("cmd.exe"); argList.add("/c"); } else { argList.add("sh"); argList.add("-c"); } argList.add("echo"); argList.add(bar); ProcessBuilder pb = new ProcessBuilder(argList); try { Process p = pb.start(); org.owasp.benchmark.helpers.Utils.printOSCommandResults(p); } catch (IOException e) { System.out.println("Problem executing cmdi - java.lang.ProcessBuilder(java.util.List) Test Case"); throw new ServletException(e); } } }
gpl-2.0
vlabatut/totalboumboum
resources/ai/org/totalboumboum/ai/v201314/ais/cetinozel/v1/criterion/Duree.java
4653
package org.totalboumboum.ai.v201314.ais.cetinozel.v1.criterion; import java.util.List; import org.totalboumboum.ai.v201314.adapter.agent.AiCriterionBoolean; import org.totalboumboum.ai.v201314.adapter.data.AiBlock; import org.totalboumboum.ai.v201314.adapter.data.AiBomb; import org.totalboumboum.ai.v201314.adapter.data.AiHero; import org.totalboumboum.ai.v201314.adapter.data.AiTile; import org.totalboumboum.ai.v201314.adapter.data.AiZone; import org.totalboumboum.ai.v201314.ais.cetinozel.v1.Agent; /** * Cette classe est un simple exemple de * critère binaire. Copiez-la, renommez-la, modifiez-la * pour l'adapter à vos besoin. * * @author Hakan Çetin * @author Yiğit Özel */ @SuppressWarnings("deprecation") public class Duree extends AiCriterionBoolean<Agent> { /** Nom de ce critère */ public static final String NAME = "Duree"; /** * Crée un nouveau critère binaire. * * @param ai * l'agent concerné. */ public Duree(Agent ai) { super(ai,NAME); ai.checkInterruption(); } ///////////////////////////////////////////////////////////////// // PROCESS ///////////////////////////////////// ///////////////////////////////////////////////////////////////// @Override public Boolean processValue(AiTile tile) { ai.checkInterruption(); boolean result = true; AiZone zone = tile.getZone(); AiHero hero; List<AiBlock> murs; List<AiBomb> bombs; hero=zone.getOwnHero(); int rangelimit=hero.getBombRangeLimit(); int colum=tile.getCol(); int line=tile.getRow(); long timeBeforeExpo; long timeAfterExpo; for(int c=0;c<=rangelimit;c++) { if((c+line)<zone.getHeight()-2) { bombs=zone.getTile(c+line,colum).getBombs(); murs=zone.getTile(c+line,colum).getBlocks(); if(!murs.isEmpty()) break; if(!bombs.isEmpty()) { if(bombs.get(0).getRange()>=c) { timeBeforeExpo=bombs.get(0).getNormalDuration()-bombs.get(0).getElapsedTime(); timeAfterExpo=timeBeforeExpo+bombs.get(0).getBurningDuration(); double temp=1000*(zone.getTileDistance(tile,zone.getTile(c+line, colum))*AiTile.getSize())/hero.getWalkingSpeed(); if(temp>-1000+ timeBeforeExpo && temp <1000+timeAfterExpo) { result=false; } } } } } if(result) { for(int c=0;c<=rangelimit;c++) { if((-c+line)>1) { bombs=zone.getTile(-c+line,colum).getBombs(); murs=zone.getTile(-c+line,colum).getBlocks(); if(!murs.isEmpty()) break; if(!bombs.isEmpty()) { if(bombs.get(0).getRange()>=c) { timeBeforeExpo=bombs.get(0).getNormalDuration()-bombs.get(0).getElapsedTime(); timeAfterExpo=timeBeforeExpo+bombs.get(0).getBurningDuration(); double temp=1000*(zone.getTileDistance(tile,zone.getTile(-c+line, colum))*AiTile.getSize())/hero.getWalkingSpeed(); if(temp>-1000+ timeBeforeExpo && temp <1000+timeAfterExpo) { result=false; } } } } } } if(result) { for(int d=0;d<=rangelimit;d++) { if((d+colum)<zone.getWidth()-2) { bombs=zone.getTile(line,d+colum).getBombs(); murs=zone.getTile(line,colum+d).getBlocks(); if(!murs.isEmpty()) break; if(!bombs.isEmpty()) { if(bombs.get(0).getRange()>=d) { timeBeforeExpo=bombs.get(0).getNormalDuration()-bombs.get(0).getElapsedTime(); timeAfterExpo=timeBeforeExpo+bombs.get(0).getBurningDuration(); double temp=1000*(zone.getTileDistance(tile,zone.getTile(line, d+colum))*AiTile.getSize())/hero.getWalkingSpeed(); if(temp>-1000 + timeBeforeExpo && temp <1000+timeAfterExpo) { result=false; } } } } } } if(result) { for(int d=0;d<=rangelimit;d++) { if((-d+colum)>1) { bombs=zone.getTile(line,-d+colum).getBombs(); murs=zone.getTile(line,-d+colum).getBlocks(); if(!murs.isEmpty()) break; if(!bombs.isEmpty()) { if(bombs.get(0).getRange()>=d) { timeBeforeExpo=bombs.get(0).getNormalDuration()-bombs.get(0).getElapsedTime(); timeAfterExpo=timeBeforeExpo+bombs.get(0).getBurningDuration(); double temp=1000*(zone.getTileDistance(tile,zone.getTile(line, colum-d))*AiTile.getSize())/hero.getWalkingSpeed(); if(temp>-1000 + timeBeforeExpo && temp <1000+timeAfterExpo) { result=false; } } } } } } return result; } }
gpl-2.0
adamfisk/littleshoot-client
common/turn/client/src/main/java/org/lastbamboo/common/turn/client/TcpTurnClient.java
18014
package org.lastbamboo.common.turn.client; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.Collection; import java.util.concurrent.atomic.AtomicBoolean; import org.apache.commons.lang.SystemUtils; import org.littleshoot.mina.common.ByteBuffer; import org.littleshoot.mina.common.CloseFuture; import org.littleshoot.mina.common.ConnectFuture; import org.littleshoot.mina.common.ExecutorThreadModel; import org.littleshoot.mina.common.IoFilter; import org.littleshoot.mina.common.IoFilterAdapter; import org.littleshoot.mina.common.IoFuture; import org.littleshoot.mina.common.IoFutureListener; import org.littleshoot.mina.common.IoHandler; import org.littleshoot.mina.common.IoService; import org.littleshoot.mina.common.IoServiceConfig; import org.littleshoot.mina.common.IoServiceListener; import org.littleshoot.mina.common.IoSession; import org.littleshoot.mina.common.RuntimeIOException; import org.littleshoot.mina.common.SimpleByteBufferAllocator; import org.littleshoot.mina.common.ThreadModel; import org.littleshoot.mina.filter.codec.ProtocolCodecFactory; import org.littleshoot.mina.filter.codec.ProtocolCodecFilter; import org.littleshoot.mina.filter.codec.ProtocolDecoderOutput; import org.littleshoot.mina.transport.socket.nio.SocketConnector; import org.littleshoot.mina.transport.socket.nio.SocketConnectorConfig; import org.lastbamboo.common.stun.stack.StunMessageDecoder; import org.lastbamboo.common.stun.stack.message.BindingRequest; import org.lastbamboo.common.stun.stack.message.StunMessage; import org.lastbamboo.common.stun.stack.message.StunMessageVisitorAdapter; import org.lastbamboo.common.stun.stack.message.attributes.turn.ConnectionStatus; import org.lastbamboo.common.stun.stack.message.turn.AllocateErrorResponse; import org.lastbamboo.common.stun.stack.message.turn.AllocateRequest; import org.lastbamboo.common.stun.stack.message.turn.AllocateSuccessResponse; import org.lastbamboo.common.stun.stack.message.turn.ConnectRequest; import org.lastbamboo.common.stun.stack.message.turn.ConnectionStatusIndication; import org.lastbamboo.common.stun.stack.message.turn.DataIndication; import org.littleshoot.util.CandidateProvider; import org.littleshoot.util.RuntimeIoException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * Class that handles all responsibilities of a TURN client. It does this in * a couple of ways. First, it opens a connection to the TURN server and * allocates a binding on the TURN server. Second, it decodes * Data Indication messages arriving from the TURN server. When it receives * a message, it creates sockets to the local HTTP server and forwards the * data (HTTP data) enclosed in the Data Indication to the local HTTP * server.<p> * * If this ever loses the connection to the TURN server, it notifies the * listener that maintains TURN connections. */ public class TcpTurnClient extends StunMessageVisitorAdapter<StunMessage> implements TurnClient, IoServiceListener { private final Logger m_log = LoggerFactory.getLogger(getClass()); private InetSocketAddress m_stunServerAddress; private IoSession m_ioSession; private InetSocketAddress m_relayAddress; private InetSocketAddress m_mappedAddress; private boolean m_receivedAllocateResponse; private final TurnClientListener m_turnClientListener; private final ProtocolCodecFactory m_dataCodecFactory; private int m_totalReadDataBytes; private int m_totalReadRawDataBytes; private final AtomicBoolean m_connected = new AtomicBoolean(false); private final SocketConnector m_connector = new SocketConnector(); private final CandidateProvider<InetSocketAddress> m_candidateProvider; /** * Creates a new TURN client with the default provider for server addresses. * * @param clientListener The listener for TURN client events. * @param codecFactory The codec factory. */ /* public TcpTurnClient(final TurnClientListener clientListener, final ProtocolCodecFactory codecFactory) { this(clientListener, new TurnServerCandidateProvider(), codecFactory); } */ /** * Creates a new TCP TURN client. * * @param clientListener The listener for TURN client events. * @param candidateProvider The class that provides TURN candidate * servers. * @param codecFactory The codec factory. */ public TcpTurnClient(final TurnClientListener clientListener, final CandidateProvider<InetSocketAddress> candidateProvider, final ProtocolCodecFactory codecFactory) { m_turnClientListener = clientListener; m_candidateProvider = candidateProvider; m_dataCodecFactory = codecFactory; // Configure the MINA buffers for optimal performance. ByteBuffer.setUseDirectBuffers(false); ByteBuffer.setAllocator(new SimpleByteBufferAllocator()); } public void connect() throws IOException { if (this.m_connected.get()) { throw new IllegalArgumentException("Already connected..."); } final Collection<InetSocketAddress> candidates = this.m_candidateProvider.getCandidates(); m_log.info("Attempting connections to: {}", candidates); for (final InetSocketAddress serverAddress : candidates) { connect(serverAddress, null); synchronized (this.m_connected) { try { this.m_connected.wait(30 * 1000); } catch (final InterruptedException e) { m_log.error("Interrupted while waiting", e); } } if (isConnected()) { m_log.debug("Connected to: {}", serverAddress); break; } } if (!isConnected()) { m_log.error("Could not connect or did not get allocate response"); close(); throw new IOException("Could not connect to any of: " + candidates); } } private void connect( final InetSocketAddress stunServerAddress, final InetSocketAddress localAddress) { final StunMessageDecoder decoder = new StunMessageDecoder(); final IoFilter turnFilter = new IoFilterAdapter() { @Override public void filterWrite(final NextFilter nextFilter, final IoSession session, final WriteRequest writeRequest) throws Exception { //m_log.debug("Filtering write: "+writeRequest.getMessage()); nextFilter.filterWrite(session, writeRequest); } @Override public void messageReceived( final NextFilter nextFilter, final IoSession session, final Object message) throws Exception { final ByteBuffer in = (ByteBuffer) message; final ProtocolDecoderOutput out = new ProtocolDecoderOutput() { public void flush() { } public void write(final Object msg) { final StunMessage stunMessage = (StunMessage) msg; stunMessage.accept(TcpTurnClient.this); } }; decoder.decode(session, in, out); } }; // If TURN is used with ICE, this will be a demultiplexing filter // between STUN and the media stream data. final ProtocolCodecFilter dataFilter = new ProtocolCodecFilter(m_dataCodecFactory); m_connector.getFilterChain().addLast("stunFilter", turnFilter); // This is really only used for the encoding. m_connector.getFilterChain().addLast("dataFilter", dataFilter); m_connector.addListener(this); //m_connectionListener = listener; m_stunServerAddress = stunServerAddress; final SocketConnectorConfig config = new SocketConnectorConfig(); // Java has weird issues with the new networking stack in Windows Vista. if (SystemUtils.IS_OS_WINDOWS_VISTA) { config.getSessionConfig().setKeepAlive(false); } else { config.getSessionConfig().setKeepAlive(true); } config.getSessionConfig().setReuseAddress(true); final ThreadModel threadModel = ExecutorThreadModel.getInstance("TCP-TURN-Client-"+hashCode()); config.setThreadModel(threadModel); //config.setThreadModel(ThreadModel.MANUAL); m_log.info("Connection to STUN server here: {}", m_stunServerAddress); final IoHandler ioHandler = new TurnClientIoHandler(this); final ConnectFuture connectFuture; if (localAddress == null) { connectFuture = m_connector.connect(m_stunServerAddress, ioHandler, config); } else { connectFuture = m_connector.connect(m_stunServerAddress, localAddress, ioHandler, config); } final IoFutureListener futureListener = new IoFutureListener() { public void operationComplete(final IoFuture ioFuture) { if (!ioFuture.isReady()) { m_log.warn("Future not ready?"); return; } try { m_ioSession = ioFuture.getSession(); } catch (final RuntimeIOException e) { // This seems to get thrown when we can't connect at all. m_log.warn("Could not connect to TURN server at: " + stunServerAddress, e); //m_connectionListener.connectionFailed(); return; } if (m_ioSession == null || !m_ioSession.isConnected()) { m_log.error("Could not create session"); throw new RuntimeIoException("Could not get session"); } // TODO: We should not need this. final TurnStunMessageMapper mapper = new TurnStunMessageMapperImpl(); m_ioSession.setAttribute("REMOTE_ADDRESS_MAP", mapper); final AllocateRequest msg = new AllocateRequest(); m_log.debug ("Sending allocate request to write handler..."); m_ioSession.write(msg); } }; connectFuture.addListener(futureListener); connectFuture.join(); } public void close() { m_log.debug("Closing TCP TURN client."); if (this.m_ioSession != null) { final CloseFuture closeFuture = this.m_ioSession.close(); closeFuture.join(); } } public void sendConnectRequest(final InetSocketAddress remoteAddress) { final ConnectRequest request = new ConnectRequest(remoteAddress); this.m_ioSession.write(request); } public InetSocketAddress getRelayAddress() { return this.m_relayAddress; } public InetSocketAddress getMappedAddress() { return this.m_mappedAddress; } @Override public StunMessage visitAllocateSuccessResponse( final AllocateSuccessResponse response) { // NOTE: This will get called many times for a single TURN session // between a client and a server because allocate requests are used // for keep-alives as well as the initial allocation. m_log.debug("Got successful allocate response: {}", response); // We need to set the relay address before notifying the // listener we're "connected". this.m_relayAddress = response.getRelayAddress(); this.m_mappedAddress = response.getMappedAddress(); this.m_receivedAllocateResponse = true; //this.m_connectionListener.connected(this.m_stunServerAddress); this.m_connected.set(true); synchronized (this.m_connected) { this.m_connected.notifyAll(); } return null; } @Override public StunMessage visitAllocateErrorResponse( final AllocateErrorResponse response) { m_log.warn("Received an Allocate Response error from the server: "+ response.getAttributes()); //this.m_connectionListener.connectionFailed(); this.m_ioSession.close(); return null; } @Override public StunMessage visitConnectionStatusIndication( final ConnectionStatusIndication indication) { m_log.debug("Visiting connection status message: {}", indication); final ConnectionStatus status = indication.getConnectionStatus(); final InetSocketAddress remoteAddress = indication.getRemoteAddress(); switch (status) { case CLOSED: m_log.debug("Got connection closed from: "+remoteAddress); this.m_turnClientListener.onRemoteAddressClosed(remoteAddress); break; case ESTABLISHED: m_log.debug("Connection established from: "+remoteAddress); // Create a local connection for the newly established session. this.m_turnClientListener.onRemoteAddressOpened(remoteAddress, this.m_ioSession); break; case LISTEN: m_log.debug("Got server listening for incoming data from: "+ remoteAddress); break; } return null; } @Override public StunMessage visitDataIndication(final DataIndication data) { m_log.debug("Visiting Data Indication message: {}", data); m_totalReadDataBytes += data.getTotalLength(); m_totalReadRawDataBytes += data.getData().length; final InetSocketAddress remoteAddress = data.getRemoteAddress(); try { m_turnClientListener.onData(remoteAddress, this.m_ioSession, data.getData()); } catch (final Exception e) { m_log.error("Could not process data: {}", data, e); } return null; } public void serviceActivated(final IoService service, final SocketAddress serviceAddress, final IoHandler handler, final IoServiceConfig config) { m_log.debug("Service activated..."); } public void serviceDeactivated(final IoService service, final SocketAddress serviceAddress, final IoHandler handler, final IoServiceConfig config) { m_log.debug("Service deactivated..."); } public void sessionCreated(final IoSession session) { m_log.debug("Session created..."); } public void sessionDestroyed(final IoSession session) { m_log.debug("Session destroyed..."); if (this.m_receivedAllocateResponse) { // We're disconnected, so set the allocate response flag to false // because the client's current connection, or lack thereof, has // not received a response. this.m_receivedAllocateResponse = false; this.m_connected.set(false); //this.m_connectionListener.disconnected(); } this.m_turnClientListener.close(); } public InetAddress getStunServerAddress() { return this.m_stunServerAddress.getAddress(); } public InetSocketAddress getHostAddress() { return (InetSocketAddress) this.m_ioSession.getLocalAddress(); } public InetSocketAddress getServerReflexiveAddress() { return getMappedAddress(); } public StunMessage write(final BindingRequest request, final InetSocketAddress remoteAddress) { // TODO We should just send the request to the server, // and we should combine the functionality of this class with the // functionality of TcpStunClient. // Or is this just handled by IceStunCheckers?? m_log.error("Unsupported!!!!!!!"); throw new IllegalStateException("Not implemented."); } public StunMessage write(final BindingRequest request, final InetSocketAddress remoteAddress, final long rto) { // See comment above. m_log.error("Unsupported!!!!!!!"); throw new IllegalStateException("Not implemented."); } public boolean isConnected() { return this.m_connected.get(); } public boolean hostPortMapped() { // We don't map ports for clients (only for classes that also accept // incoming connections). return false; } public void addIoServiceListener(final IoServiceListener serviceListener) { if (serviceListener == null) { throw new NullPointerException("Null listener"); } this.m_connector.addListener(serviceListener); } }
gpl-2.0
thammegowda/charliebot
src/main/java/org/alicebot/server/core/processor/IDProcessor.java
865
// Decompiled by Jad v1.5.8c. Copyright 2001 Pavel Kouznetsov. // Jad home page: http://www.geocities.com/kpdus/jad.html // Decompiler options: packimports(3) package org.alicebot.server.core.processor; import org.alicebot.server.core.parser.TemplateParser; import org.alicebot.server.core.parser.XMLNode; // Referenced classes of package org.alicebot.server.core.processor: // AIMLProcessor, AIMLProcessorException public class IDProcessor extends AIMLProcessor { public static final String label = "id"; public IDProcessor() { } public String process(int i, XMLNode xmlnode, TemplateParser templateparser) throws AIMLProcessorException { if (xmlnode.XMLType == 1) return templateparser.getUserID(); else throw new AIMLProcessorException("<id/> cannot have content!"); } }
gpl-2.0
rex-xxx/mt6572_x201
mediatek/frameworks/base/tests/net/tests/src/mediatek/net/libcore/support/Support_ASimpleWriter.java
4441
/* Copyright Statement: * * This software/firmware and related documentation ("MediaTek Software") are * protected under relevant copyright laws. The information contained herein is * confidential and proprietary to MediaTek Inc. and/or its licensors. Without * the prior written permission of MediaTek inc. and/or its licensors, any * reproduction, modification, use or disclosure of MediaTek Software, and * information contained herein, in whole or in part, shall be strictly * prohibited. * * MediaTek Inc. (C) 2010. All rights reserved. * * BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES * THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE") * RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER * ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL * WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR * NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH * RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, * INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES * TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. * RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO * OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK * SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE * RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR * STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S * ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE * RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE * MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE * CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE. * * The following software/firmware and/or related documentation ("MediaTek * Software") have been modified by MediaTek Inc. All revisions are subject to * any receiver's applicable license agreements with MediaTek Inc. */ package tests.support; import java.io.IOException; import java.io.Writer; /** * An implementation of {@code OutputStream} that should serve as the * underlying stream for classes to be tested. * In particular this implementation allows to have IOExecptions thrown on demand. * For simplicity of use and understanding all fields are public. */ public class Support_ASimpleWriter extends Writer { public static final int DEFAULT_BUFFER_SIZE = 32; public char[] buf; public int pos; public int size; // Set to true when exception is wanted: public boolean throwExceptionOnNextUse = false; public Support_ASimpleWriter() { this(DEFAULT_BUFFER_SIZE); } public Support_ASimpleWriter(boolean throwException) { this(DEFAULT_BUFFER_SIZE); throwExceptionOnNextUse = throwException; } public Support_ASimpleWriter(int bufferSize) { buf = new char[bufferSize]; pos = 0; size = bufferSize; } @Override public void close() throws IOException { if (throwExceptionOnNextUse) { throw new IOException("Exception thrown for testing purpose."); } } @Override public void flush() throws IOException { if (throwExceptionOnNextUse) { throw new IOException("Exception thrown for testing purpose."); } } @Override public void write(char[] src, int offset, int count) throws IOException { if (throwExceptionOnNextUse) { throw new IOException("Exception thrown for testing purpose."); } if (offset < 0 || count < 0 || (offset + count) > buf.length) { throw new IndexOutOfBoundsException(); } try { System.arraycopy(src, offset, buf, pos, count); pos += count; } catch (IndexOutOfBoundsException e) { pos = size; throw new IOException("Internal Buffer Overflow"); } } public byte[] toByteArray() { byte[] toReturn = new byte[pos]; System.arraycopy(buf, 0, toReturn, 0, pos); return toReturn; } public String toString() { return new String(buf, 0, pos); } }
gpl-2.0
taylor-project/taylor-picketlink-2.0.3
federation/picketlink-xmlsec-model/src/main/java/org/picketlink/identity/xmlsec/w3/xmldsig/SignatureValueType.java
2509
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.picketlink.identity.xmlsec.w3.xmldsig; /** * <p>Java class for SignatureValueType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="SignatureValueType"> * &lt;simpleContent> * &lt;extension base="&lt;http://www.w3.org/2001/XMLSchema>base64Binary"> * &lt;attribute name="Id" type="{http://www.w3.org/2001/XMLSchema}ID" /> * &lt;/extension> * &lt;/simpleContent> * &lt;/complexType> * </pre> * * */ public class SignatureValueType { protected byte[] value; protected String id; /** * Gets the value of the value property. * * @return * possible object is * byte[] */ public byte[] getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * byte[] */ public void setValue(byte[] value) { this.value = ((byte[]) value); } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
gpl-2.0
plgucm/practica3
src/maquinap/instrucciones/aritmeticas/Suma.java
979
package maquinap.instrucciones.aritmeticas; import java.util.Stack; import maquinap.MaquinaP; import maquinap.instrucciones.Instruccion; import maquinap.valor.Int; import maquinap.valor.Valor; public class Suma extends Instruccion { @Override public void ejecutar(MaquinaP maq) throws Exception { Stack<Valor<?>> pe = maq.getPilaEvaluacion(); if (pe.isEmpty()){ throw new Exception("SUMA -> faltan operandos"); } Valor<?> valor1 = pe.pop(); if (!(valor1.getValor() instanceof Integer)){ throw new Exception("SUMA -> segundo operando no de tipo entero"); } if (pe.isEmpty()){ throw new Exception("SUMA -> faltan operandos"); } Valor<?> valor2 = pe.pop(); if (!(valor2.getValor() instanceof Integer)){ throw new Exception("SUMA -> primer operando no de tipo entero"); } Int newValue = new Int((Integer)valor2.getValor()+(Integer)valor1.getValor()); maq.getPilaEvaluacion().push(newValue); maq.aumentarContadorPrograma(1); } }
gpl-2.0
taylor-project/taylor-picketlink-2.0.3
federation/picketlink-web/src/test/java/org/picketlink/test/identity/federation/web/mock/MockFilterChain.java
1527
/* * JBoss, Home of Professional Open Source. * Copyright 2008, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This 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 software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.picketlink.test.identity.federation.web.mock; import java.io.IOException; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; /** * Mock Filter Chain * @author Anil.Saldhana@redhat.com * @since Oct 8, 2009 */ public class MockFilterChain implements FilterChain { public void doFilter(ServletRequest arg0, ServletResponse arg1) throws IOException, ServletException { } }
gpl-2.0
cylong1016/NJULily
src/main/java/businesslogic/salebl/info/PromotionInfo_Sale.java
1792
package businesslogic.salebl.info; import java.rmi.RemoteException; import java.util.ArrayList; import po.CommodityItemPO; import vo.promotion.PromotionBargainVO; import vo.promotion.PromotionClientVO; import vo.promotion.PromotionCommodityVO; import vo.promotion.PromotionTotalVO; public interface PromotionInfo_Sale { /** * 查看是否有合适的商品的促销 * @deprecated 这个促销策略已经被我们狠心遗弃 * @param iD * @param commodityIDs * @author Zing * @version Dec 9, 2014 6:01:53 PM * @param commodityNumber * @throws RemoteException */ public ArrayList<PromotionCommodityVO> findFitPromotionCommodity(String iD, ArrayList<String> commodityIDs, ArrayList<Integer> commodityNumber) throws RemoteException; /** * 查看是否有合适的客户等级的促销 * @param iD * @param clientID * @author Zing * @version Dec 9, 2014 6:02:12 PM * @throws RemoteException */ public ArrayList<PromotionClientVO> findFitPromotionClient(String iD, String clientID) throws RemoteException; /** * 查看是否有合适的总价的促销 * @param iD * @param beforePrice * @author Zing * @version Dec 9, 2014 6:02:35 PM * @throws RemoteException */ public ArrayList<PromotionTotalVO> findFitPromotionTotal(String iD, double beforePrice) throws RemoteException; public ArrayList<PromotionBargainVO> showBargains() throws RemoteException; public PromotionBargainVO findBargains(String iD) throws RemoteException; /** * * @param ID * @return * @author Zing * @version Dec 30, 2014 7:22:39 PM */ public double getAllowance(String ID) throws RemoteException; public double getVoucher(String ID) throws RemoteException; public ArrayList<CommodityItemPO> getGifts(String ID) throws RemoteException; }
gpl-2.0
martijn00/Zipato
lib/impl/stubs/org/bouncycastle/crypto/params/ECKeyParameters.java
320
/** * * Classes for parameter objects for ciphers and generators. */ package org.bouncycastle.crypto.params; public class ECKeyParameters extends AsymmetricKeyParameter { protected ECKeyParameters(boolean isPrivate, ECDomainParameters params) { } public ECDomainParameters getParameters() { } }
gpl-2.0
aweinert/pwgen-android
src/com/alexweinert/pwgen/MainActivity.java
6608
package com.alexweinert.pwgen; import java.util.LinkedList; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Spinner; import android.widget.TextView; public class MainActivity extends Activity { private PasswordFactory passwordFactory; private static final int MUST_POSITION = 0; private static final int MAY_POSITION = 1; private static final int MUST_NOT_POSITION = 2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); this.setupReloadButtonHandler(); this.populateOptionSpinners(); this.setupSpinnerHandlers(); this.updatePasswordFactory(); this.createAndShowNewPassword(); } private void setupReloadButtonHandler() { this.findViewById(R.id.reloadButton).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { createAndShowNewPassword(); } }); } private void setupSpinnerHandlers() { for (Spinner spinner : this.getOptionSpinners()) { spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { updatePasswordFactory(); createAndShowNewPassword(); } @Override public void onNothingSelected(AdapterView<?> arg0) { // Does not happen in this context } }); } } private void updatePasswordFactory() { PasswordFactory newFactory = this.createPasswordFactory(); this.passwordFactory = newFactory; } private PasswordFactory createPasswordFactory() { PasswordFactory.Builder factoryBuilder = new PasswordFactory.Builder(new RandomGenerator()); this.configurePasswordFactoryBuilder(factoryBuilder); return factoryBuilder.create(); } private void configurePasswordFactoryBuilder(PasswordFactory.Builder builder) { this.configurePasswordFactoryBuilderLowercase(builder); this.configurePasswordFactoryBuilderUppercase(builder); this.configurePasswordFactoryBuilderDigits(builder); this.configurePasswordFactoryBuilderSymbols(builder); this.configurePasswordFactoryBuilderAmbiguous(builder); } private void configurePasswordFactoryBuilderLowercase(PasswordFactory.Builder builder) { int position = ((Spinner) this.findViewById(R.id.lowercaseSpinner)).getSelectedItemPosition(); if (position == MUST_POSITION) { builder.mustIncludeLowercase(); } else if (position == MAY_POSITION) { builder.mayIncludeLowercase(); } else if (position == MUST_NOT_POSITION) { builder.mustNotIncludeLowercase(); } } private void configurePasswordFactoryBuilderUppercase(PasswordFactory.Builder builder) { int position = ((Spinner) this.findViewById(R.id.uppercaseSpinner)).getSelectedItemPosition(); if (position == MUST_POSITION) { builder.mustIncludeUppercase(); } else if (position == MAY_POSITION) { builder.mayIncludeUppercase(); } else if (position == MUST_NOT_POSITION) { builder.mustNotIncludeUppercase(); } } private void configurePasswordFactoryBuilderDigits(PasswordFactory.Builder builder) { int position = ((Spinner) this.findViewById(R.id.digitsSpinner)).getSelectedItemPosition(); if (position == MUST_POSITION) { builder.mustIncludeDigits(); } else if (position == MAY_POSITION) { builder.mayIncludeDigits(); } else if (position == MUST_NOT_POSITION) { builder.mustNotIncludeDigits(); } } private void configurePasswordFactoryBuilderSymbols(PasswordFactory.Builder builder) { int position = ((Spinner) this.findViewById(R.id.symbolsSpinner)).getSelectedItemPosition(); if (position == MUST_POSITION) { builder.mustIncludeSymbols(); } else if (position == MAY_POSITION) { builder.mayIncludeSymbols(); } else if (position == MUST_NOT_POSITION) { builder.mustNotIncludeSymbols(); } } private void configurePasswordFactoryBuilderAmbiguous(PasswordFactory.Builder builder) { int position = ((Spinner) this.findViewById(R.id.ambiguousSpinner)).getSelectedItemPosition(); if (position == MUST_POSITION) { builder.mustIncludeAmbiguous(); } else if (position == MAY_POSITION) { builder.mayIncludeAmbiguous(); } else if (position == MUST_NOT_POSITION) { builder.mustNotIncludeAmbiguous(); } } private void createAndShowNewPassword() { String password = this.passwordFactory.getPassword(8); ((TextView) this.findViewById(R.id.passwordView)).setText(password); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } private void populateOptionSpinners() { // Taken from http://developer.android.com/guide/topics/ui/controls/spinner.html ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.optionChoices, android.R.layout.simple_spinner_item); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Use the same adapter for all spinners for (Spinner spinner : this.getOptionSpinners()) { spinner.setAdapter(adapter); } } private Iterable<Spinner> getOptionSpinners() { LinkedList<Spinner> returnValue = new LinkedList<Spinner>(); returnValue.add((Spinner) this.findViewById(R.id.lowercaseSpinner)); returnValue.add((Spinner) this.findViewById(R.id.uppercaseSpinner)); returnValue.add((Spinner) this.findViewById(R.id.digitsSpinner)); returnValue.add((Spinner) this.findViewById(R.id.symbolsSpinner)); returnValue.add((Spinner) this.findViewById(R.id.ambiguousSpinner)); return returnValue; } }
gpl-2.0
liyue80/GmailAssistant20
src/com/sun/mail/dsn/text_rfc822headers.java
6825
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 1997-2007 Sun Microsystems, Inc. All rights reserved. * * The contents of this file are subject to the terms of either the GNU * General Public License Version 2 only ("GPL") or the Common Development * and Distribution License("CDDL") (collectively, the "License"). You * may not use this file except in compliance with the License. You can obtain * a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html * or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific * language governing permissions and limitations under the License. * * When distributing the software, include this License Header Notice in each * file and include the License file at glassfish/bootstrap/legal/LICENSE.txt. * Sun designates this particular file as subject to the "Classpath" exception * as provided by Sun in the GPL Version 2 section of the License file that * accompanied this code. If applicable, add the following below the License * Header, with the fields enclosed by brackets [] replaced by your own * identifying information: "Portions Copyrighted [year] * [name of copyright owner]" * * Contributor(s): * * If you wish your version of this file to be governed by only the CDDL or * only the GPL Version 2, indicate your decision by adding "[Contributor] * elects to include this software in this distribution under the [CDDL or GPL * Version 2] license." If you don't indicate a single choice of license, a * recipient has the option to distribute your version of this file under * either the CDDL, the GPL Version 2 or to extend the choice of license to * its licensees as provided above. However, if you add GPL Version 2 code * and therefore, elected the GPL Version 2 license, then the option applies * only if the new code is made subject to such option by the copyright * holder. */ /* * @(#)text_rfc822headers.java 1.4 07/05/04 */ package com.sun.mail.dsn; import java.io.*; import java.awt.datatransfer.DataFlavor; import javax.activation.*; import javax.mail.*; import javax.mail.internet.*; /** * DataContentHandler for text/rfc822-headers. * * @version 1.4, 07/05/04 */ public class text_rfc822headers implements DataContentHandler { private static ActivationDataFlavor myDF = new ActivationDataFlavor( MessageHeaders.class, "text/rfc822-headers", "RFC822 headers"); private static ActivationDataFlavor myDFs = new ActivationDataFlavor( java.lang.String.class, "text/rfc822-headers", "RFC822 headers"); /** * Return the DataFlavors for this <code>DataContentHandler</code>. * * @return The DataFlavors */ public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { myDF, myDFs }; } /** * Return the Transfer Data of type DataFlavor from InputStream. * * @param df The DataFlavor * @param ds The DataSource corresponding to the data * @return String object */ public Object getTransferData(DataFlavor df, DataSource ds) throws IOException { // use myDF.equals to be sure to get ActivationDataFlavor.equals, // which properly ignores Content-Type parameters in comparison if (myDF.equals(df)) return getContent(ds); else if (myDFs.equals(df)) return getStringContent(ds); else return null; } public Object getContent(DataSource ds) throws IOException { try { return new MessageHeaders(ds.getInputStream()); } catch (MessagingException mex) { //System.out.println("Exception creating MessageHeaders: " + mex); throw new IOException("Exception creating MessageHeaders: " + mex); } } private Object getStringContent(DataSource ds) throws IOException { String enc = null; InputStreamReader is = null; try { enc = getCharset(ds.getContentType()); is = new InputStreamReader(ds.getInputStream(), enc); } catch (IllegalArgumentException iex) { /* * An unknown charset of the form ISO-XXX-XXX will cause * the JDK to throw an IllegalArgumentException. The * JDK will attempt to create a classname using this string, * but valid classnames must not contain the character '-', * and this results in an IllegalArgumentException, rather than * the expected UnsupportedEncodingException. Yikes. */ throw new UnsupportedEncodingException(enc); } int pos = 0; int count; char buf[] = new char[1024]; while ((count = is.read(buf, pos, buf.length - pos)) != -1) { pos += count; if (pos >= buf.length) { int size = buf.length; if (size < 256*1024) size += size; else size += 256*1024; char tbuf[] = new char[size]; System.arraycopy(buf, 0, tbuf, 0, pos); buf = tbuf; } } return new String(buf, 0, pos); } /** * Write the object to the output stream, using the specified MIME type. */ public void writeTo(Object obj, String type, OutputStream os) throws IOException { if (obj instanceof MessageHeaders) { MessageHeaders mh = (MessageHeaders)obj; try { mh.writeTo(os); } catch (MessagingException mex) { Exception ex = mex.getNextException(); if (ex instanceof IOException) throw (IOException)ex; else throw new IOException("Exception writing headers: " + mex); } return; } if (!(obj instanceof String)) throw new IOException("\"" + myDFs.getMimeType() + "\" DataContentHandler requires String object, " + "was given object of type " + obj.getClass().toString()); String enc = null; OutputStreamWriter osw = null; try { enc = getCharset(type); osw = new OutputStreamWriter(os, enc); } catch (IllegalArgumentException iex) { /* * An unknown charset of the form ISO-XXX-XXX will cause * the JDK to throw an IllegalArgumentException. The * JDK will attempt to create a classname using this string, * but valid classnames must not contain the character '-', * and this results in an IllegalArgumentException, rather than * the expected UnsupportedEncodingException. Yikes. */ throw new UnsupportedEncodingException(enc); } String s = (String)obj; osw.write(s, 0, s.length()); osw.flush(); } private String getCharset(String type) { try { ContentType ct = new ContentType(type); String charset = ct.getParameter("charset"); if (charset == null) // If the charset parameter is absent, use US-ASCII. charset = "us-ascii"; return MimeUtility.javaCharset(charset); } catch (Exception ex) { return null; } } }
gpl-2.0
Remper/hls
src/main/java/org/fbk/cit/hlt/parsers/hls/tags/media/DiscontinuitySequenceTag.java
1139
package org.fbk.cit.hlt.parsers.hls.tags.media; import org.fbk.cit.hlt.parsers.hls.tags.*; import org.fbk.cit.hlt.parsers.hls.exceptions.InvalidTagParameters; /** * #EXT-X-DISCONTINUITY-SEQUENCE */ @HLSTag(name="EXT-X-DISCONTINUITY-SEQUENCE") public class DiscontinuitySequenceTag implements Tag { protected int sequence; public DiscontinuitySequenceTag(String properties) throws InvalidTagParameters { if (!properties.matches("[0-9]+")) { throw new InvalidTagParameters(); } sequence = Integer.valueOf(properties); } @Override public String getName() { return "EXT-X-DISCONTINUITY-SEQUENCE"; } @Override public TagType getType() { return TagType.MEDIA_PLAYLIST; } @Override public int minVersion() { return 0; } @Override public boolean isOneTime() { return false; } @Override public boolean shouldBeFollowedByURI() { return false; } @Override public boolean shouldBeUnique() { return true; } public int getSequence() { return sequence; } }
gpl-2.0
gres147679/RedFISh
examples/Test.java
2609
import java.rmi.*; import java.io.File; import java.net.MalformedURLException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.io.InputStream; import java.io.FileInputStream; import java.io.OutputStream; import java.io.IOException; import java.io.FileNotFoundException; public class Test{ private static Integer BUF_SIZE = 2048; private static void copy(InputStream in, OutputStream out) throws IOException { System.out.println("using byte[] read/write"); byte[] b = new byte[BUF_SIZE]; int len; while ((len = in.read(b)) >= 0) { out.write(b, 0, len); } in.close(); out.close(); } public static Boolean uploadFile(FileServer server,String src, String dest) throws RemoteException{ try{ //copy (new FileInputStream(src), server.getOutputStream(new RMIFile(dest))); copy (new FileInputStream(src), server.owner); } catch(FileNotFoundException e){ System.out.println("El archivo especificado no existe:"); return false; } catch(IOException e){ System.out.println("Excepción no esperada de IO"); e.printStackTrace(); } return true; } public static Boolean downloadFile(FileServer server,String src, String dest) throws RemoteException{ try{ copy (server.getInputStream(new File(src)), new FileOutputStream(dest)); } catch(FileNotFoundException e){ System.out.println("El archivo especificado no existe:"); return false; } catch(IOException e){ System.out.println("Excepción no esperada de IO"); e.printStackTrace(); } return true; } public static void download(ServerInterf server, File src, File dest) throws IOException { } public static void main(String[] args) { try{ String url = "rmi://localhost:30226/FileServer"; FileServer server = (FileServer) Naming.lookup(url); File testFile = new File("prueba.txt"); long len = testFile.length(); long t; t = System.currentTimeMillis(); uploadFile(server,"prueba.txt", "download.tif"); //t = (System.currentTimeMillis() - t) / 1000; //System.out.println("download: " + (len / t / 1000000d) + " MB/s"); } catch(NotBoundException nbe){ System.out.println("Not bound"); System.exit(0); } catch(MalformedURLException mue){ System.out.println("Malformed"); System.exit(0); } catch(RemoteException re){ System.out.println("RemoteException"); re.printStackTrace(); System.exit(0); } } }
gpl-2.0
DrewG/mzmine2
src/main/java/net/sf/mzmine/modules/peaklistmethods/filtering/rowsfilter/RowsFilterTask.java
17610
/* * Copyright 2006-2015 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 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. * * MZmine 2 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 * MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA */ package net.sf.mzmine.modules.peaklistmethods.filtering.rowsfilter; import java.util.HashMap; import java.util.Iterator; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import com.google.common.collect.Range; import net.sf.mzmine.datamodel.Feature; import net.sf.mzmine.datamodel.IsotopePattern; import net.sf.mzmine.datamodel.MZmineProject; import net.sf.mzmine.datamodel.PeakIdentity; import net.sf.mzmine.datamodel.PeakList; import net.sf.mzmine.datamodel.PeakList.PeakListAppliedMethod; import net.sf.mzmine.datamodel.PeakListRow; import net.sf.mzmine.datamodel.RawDataFile; import net.sf.mzmine.datamodel.impl.SimpleFeature; import net.sf.mzmine.datamodel.impl.SimplePeakList; import net.sf.mzmine.datamodel.impl.SimplePeakListAppliedMethod; import net.sf.mzmine.datamodel.impl.SimplePeakListRow; import net.sf.mzmine.parameters.ParameterSet; import net.sf.mzmine.parameters.UserParameter; import net.sf.mzmine.taskcontrol.AbstractTask; import net.sf.mzmine.taskcontrol.TaskStatus; import net.sf.mzmine.util.PeakUtils; import net.sf.mzmine.util.RangeUtils; /** * Filters out peak list rows. */ public class RowsFilterTask extends AbstractTask { // Logger. private static final Logger LOG = Logger .getLogger(RowsFilterTask.class.getName()); // Peak lists. private final MZmineProject project; private final PeakList origPeakList; private PeakList filteredPeakList; // Processed rows counter private int processedRows, totalRows; // Parameters. private final ParameterSet parameters; /** * Create the task. * * @param list * peak list to process. * @param parameterSet * task parameters. */ public RowsFilterTask(final MZmineProject project, final PeakList list, final ParameterSet parameterSet) { // Initialize. this.project = project; parameters = parameterSet; origPeakList = list; filteredPeakList = null; processedRows = 0; totalRows = 0; } @Override public double getFinishedPercentage() { return totalRows == 0 ? 0.0 : (double) processedRows / (double) totalRows; } @Override public String getTaskDescription() { return "Filtering peak list rows"; } @Override public void run() { if (!isCanceled()) { try { setStatus(TaskStatus.PROCESSING); LOG.info("Filtering peak list rows"); // Filter the peak list. filteredPeakList = filterPeakListRows(origPeakList); if (!isCanceled()) { // Add new peaklist to the project project.addPeakList(filteredPeakList); // Remove the original peaklist if requested if (parameters .getParameter(RowsFilterParameters.AUTO_REMOVE) .getValue()) { project.removePeakList(origPeakList); } setStatus(TaskStatus.FINISHED); LOG.info("Finished peak list rows filter"); } } catch (Throwable t) { setErrorMessage(t.getMessage()); setStatus(TaskStatus.ERROR); LOG.log(Level.SEVERE, "Peak list row filter error", t); } } } /** * Filter the peak list rows. * * @param peakList * peak list to filter. * @return a new peak list with rows of the original peak list that pass the * filtering. */ private PeakList filterPeakListRows(final PeakList peakList) { // Create new peak list. final PeakList newPeakList = new SimplePeakList( peakList.getName() + ' ' + parameters .getParameter(RowsFilterParameters.SUFFIX).getValue(), peakList.getRawDataFiles()); // Copy previous applied methods. for (final PeakListAppliedMethod method : peakList .getAppliedMethods()) { newPeakList.addDescriptionOfAppliedTask(method); } // Add task description to peakList. newPeakList.addDescriptionOfAppliedTask(new SimplePeakListAppliedMethod( getTaskDescription(), parameters)); // Get parameters. final boolean onlyIdentified = parameters .getParameter(RowsFilterParameters.HAS_IDENTITIES).getValue(); final boolean filterByIdentityText = parameters .getParameter(RowsFilterParameters.IDENTITY_TEXT).getValue(); final boolean filterByCommentText = parameters .getParameter(RowsFilterParameters.COMMENT_TEXT).getValue(); final String groupingParameter = (String) parameters .getParameter(RowsFilterParameters.GROUPSPARAMETER).getValue(); final boolean filterByMinPeakCount = parameters .getParameter(RowsFilterParameters.MIN_PEAK_COUNT).getValue(); final boolean filterByMinIsotopePatternSize = parameters .getParameter(RowsFilterParameters.MIN_ISOTOPE_PATTERN_COUNT) .getValue(); final boolean filterByMzRange = parameters .getParameter(RowsFilterParameters.MZ_RANGE).getValue(); final boolean filterByRtRange = parameters .getParameter(RowsFilterParameters.RT_RANGE).getValue(); final boolean filterByDuration = parameters .getParameter(RowsFilterParameters.PEAK_DURATION).getValue(); final boolean filterByFWHM = parameters .getParameter(RowsFilterParameters.FWHM).getValue(); final boolean filterByMS2 = parameters .getParameter(RowsFilterParameters.MS2_Filter).getValue(); final String removeRowString = (String) parameters .getParameter(RowsFilterParameters.REMOVE_ROW).getValue(); Double minCount = parameters .getParameter(RowsFilterParameters.MIN_PEAK_COUNT) .getEmbeddedParameter().getValue(); final boolean renumber = parameters .getParameter(RowsFilterParameters.Reset_ID).getValue(); int rowsCount =0; boolean removeRow = false; if (removeRowString.equals(RowsFilterParameters.removeRowChoices[0])) removeRow = false; else removeRow = true; // Keep rows that don't match any criteria. Keep by default. boolean filterRowCriteriaFailed = false; // Handle < 1 values for minPeakCount if ((minCount == null) || (minCount < 1)) minCount = 1.0; // Round value down to nearest hole number int intMinCount = minCount.intValue(); // Filter rows. final PeakListRow[] rows = peakList.getRows(); totalRows = rows.length; for (processedRows = 0; !isCanceled() && processedRows < totalRows; processedRows++) { filterRowCriteriaFailed = false; final PeakListRow row = rows[processedRows]; final int peakCount = getPeakCount(row, groupingParameter); // Check number of peaks. if (filterByMinPeakCount) { if (peakCount < intMinCount) filterRowCriteriaFailed = true; } // Check identities. if (onlyIdentified) { if (row.getPreferredPeakIdentity() == null) filterRowCriteriaFailed = true; } // Check average m/z. if (filterByMzRange) { final Range<Double> mzRange = parameters .getParameter(RowsFilterParameters.MZ_RANGE) .getEmbeddedParameter().getValue(); if (!mzRange.contains(row.getAverageMZ())) filterRowCriteriaFailed = true; } // Check average RT. if (filterByRtRange) { final Range<Double> rtRange = parameters .getParameter(RowsFilterParameters.RT_RANGE) .getEmbeddedParameter().getValue(); if (!rtRange.contains(row.getAverageRT())) filterRowCriteriaFailed = true; } // Search peak identity text. if (filterByIdentityText) { if (row.getPreferredPeakIdentity() == null) filterRowCriteriaFailed = true; if (row.getPreferredPeakIdentity() != null) { final String searchText = parameters .getParameter(RowsFilterParameters.IDENTITY_TEXT) .getEmbeddedParameter().getValue().toLowerCase() .trim(); int numFailedIdentities = 0; PeakIdentity[] identities = row.getPeakIdentities(); for (int index = 0; !isCanceled() && index < identities.length; index++) { String rowText = identities[index].getName() .toLowerCase().trim(); if (!rowText.contains(searchText)) numFailedIdentities += 1; } if (numFailedIdentities == identities.length) filterRowCriteriaFailed = true; } } // Search peak comment text. if (filterByCommentText) { if (row.getComment() == null) filterRowCriteriaFailed = true; if (row.getComment() != null) { final String searchText = parameters .getParameter(RowsFilterParameters.COMMENT_TEXT) .getEmbeddedParameter().getValue().toLowerCase() .trim(); final String rowText = row.getComment().toLowerCase() .trim(); if (!rowText.contains(searchText)) filterRowCriteriaFailed = true; } } // Calculate average duration and isotope pattern count. int maxIsotopePatternSizeOnRow = 1; double avgDuration = 0.0; final Feature[] peaks = row.getPeaks(); for (final Feature p : peaks) { final IsotopePattern pattern = p.getIsotopePattern(); if (pattern != null && maxIsotopePatternSizeOnRow < pattern .getNumberOfDataPoints()) { maxIsotopePatternSizeOnRow = pattern .getNumberOfDataPoints(); } avgDuration += RangeUtils .rangeLength(p.getRawDataPointsRTRange()); } // Check isotope pattern count. if (filterByMinIsotopePatternSize) { final int minIsotopePatternSize = parameters .getParameter( RowsFilterParameters.MIN_ISOTOPE_PATTERN_COUNT) .getEmbeddedParameter().getValue(); if (maxIsotopePatternSizeOnRow < minIsotopePatternSize) filterRowCriteriaFailed = true; } // Check average duration. avgDuration /= peakCount; if (filterByDuration) { final Range<Double> durationRange = parameters .getParameter(RowsFilterParameters.PEAK_DURATION) .getEmbeddedParameter().getValue(); if (!durationRange.contains(avgDuration)) filterRowCriteriaFailed = true; } // Filter by FWHM range if (filterByFWHM) { final Range<Double> FWHMRange = parameters .getParameter(RowsFilterParameters.FWHM) .getEmbeddedParameter().getValue(); //If any of the peaks fail the FWHM criteria, Double FWHM_value = row.getBestPeak().getFWHM(); if (FWHM_value != null && !FWHMRange.contains(FWHM_value)) filterRowCriteriaFailed = true; } // Check ms2 filter . if (filterByMS2) { // iterates the peaks int failCounts =0; for (int i = 0; i<peakCount; i++ ) { if(row.getPeaks()[i].getMostIntenseFragmentScanNumber() <1) { failCounts++; //filterRowCriteriaFailed = true; //break; } } if (failCounts == peakCount){ filterRowCriteriaFailed = true; } } if (!filterRowCriteriaFailed && !removeRow){ // Only add the row if none of the criteria have failed. rowsCount ++; PeakListRow resetRow = copyPeakRow(row); if(renumber){ resetRow.setID(rowsCount); } newPeakList.addRow(resetRow); } if (filterRowCriteriaFailed && removeRow){ // Only remove rows that match *all* of the criteria, so add // rows that fail any of the criteria. rowsCount ++; PeakListRow resetRow = copyPeakRow(row); if(renumber){ resetRow.setID(rowsCount); } newPeakList.addRow(resetRow); } } return newPeakList; } /** * Create a copy of a peak list row. * * @param row * the row to copy. * @return the newly created copy. */ private static PeakListRow copyPeakRow(final PeakListRow row) { // Copy the peak list row. final PeakListRow newRow = new SimplePeakListRow(row.getID()); PeakUtils.copyPeakListRowProperties(row, newRow); // Copy the peaks. for (final Feature peak : row.getPeaks()) { final Feature newPeak = new SimpleFeature(peak); PeakUtils.copyPeakProperties(peak, newPeak); newRow.addPeak(peak.getDataFile(), newPeak); } return newRow; } private int getPeakCount(PeakListRow row, String groupingParameter) { if (groupingParameter.contains("Filtering by ")) { HashMap<String, Integer> groups = new HashMap<String, Integer>(); for (RawDataFile file : project.getDataFiles()) { UserParameter<?, ?> params[] = project.getParameters(); for (UserParameter<?, ?> p : params) { groupingParameter = groupingParameter .replace("Filtering by ", ""); if (groupingParameter.equals(p.getName())) { String parameterValue = String .valueOf(project.getParameterValue(p, file)); if (row.hasPeak(file)) { if (groups.containsKey(parameterValue)) { groups.put(parameterValue, groups.get(parameterValue) + 1); } else { groups.put(parameterValue, 1); } } else { groups.put(parameterValue, 0); } } } } Set<String> ref = groups.keySet(); Iterator<String> it = ref.iterator(); int min = Integer.MAX_VALUE; while (it.hasNext()) { String name = it.next(); int val = groups.get(name); if (val < min) { min = val; } } return min; } else { return row.getNumberOfPeaks(); } } }
gpl-2.0