repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
JustinCarrao/voogasalad-final
src/com/print_stack_trace/voogasalad/controller/guiElements/userInputTypes/level/LevelCameraY.java
1255
package com.print_stack_trace.voogasalad.controller.guiElements.userInputTypes.level; import com.print_stack_trace.voogasalad.controller.guiElements.gameObjects.GameObject; import com.print_stack_trace.voogasalad.controller.guiElements.gameObjects.LevelObject; import com.print_stack_trace.voogasalad.controller.guiElements.userInputTypes.CharacteristicController; import com.print_stack_trace.voogasalad.controller.popUpPanes.MessagePopUp; public class LevelCameraY extends CharacteristicController{ public LevelCameraY(String[] values, double width, double height, double x, double y, GameObject object) { super(values, width, height, x, y, object); // TODO Auto-generated constructor stub } @Override protected void populateDefaultText() { myTextBox.setText(((LevelObject)mySprite).getCharacteristics().getCameraStartPosition().getY()+""); } @Override protected void setCharacteristic(String newValue) { double newYValue = ((LevelObject)mySprite).getCharacteristics().getCameraStartPosition().getY(); try{ newYValue = Double.parseDouble(newValue); } catch(NumberFormatException e){ new MessagePopUp().showMessageDialog("Not A Number"); } ((LevelObject)mySprite).getCharacteristics().setCameraY(newYValue); } }
mit
vitruvianAnalogy/Corundum
Corundum Hub/org/corundummc/utils/interfaces/Matchable.java
1148
/** This code is property of the Corundum project managed under the Software Developers' Association of Arizona State University. * * Copying and use of this open-source code is permitted provided that the following requirements are met: * * - This code may not be used or distributed for private enterprise, including but not limited to personal or corporate profit. - Any products resulting from the copying, * use, or modification of this code may not claim endorsement by the Corundum project or any of its members or associates without written formal permission from the endorsing * party or parties. - This code may not be copied or used under any circumstances without the inclusion of this notice and mention of the contribution of the code by the * Corundum project. In source code form, this notice must be included as a comment as it is here; in binary form, proper documentation must be included with the final product * that includes this statement verbatim. * * @author REALDrummer */ package org.corundummc.utils.interfaces; public interface Matchable<T extends Matchable<T>> { public Object[] getSortPriorities(); }
mit
mumaoxi/android.iqv8
app/src/main/java/com/iqv8/yeequ/annotations/IActivity.java
403
package com.iqv8.yeequ.annotations; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Created by admin on 5/16/15. */ @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface IActivity { int value(); }
mit
naxmefy/PValidTest
src/main/java/me/nax/pvalid/model/fail/FailTyp.java
83
package me.nax.pvalid.model.fail; public enum FailTyp { INCLUSION, EXCLUSION }
mit
paraam/tr069-simulator
src/main/java/org/dslforum/cwmp_1_0/GYear.java
1269
package org.dslforum.cwmp_1_0; /** * Schema fragment(s) for this class: * <pre> * &lt;xs:complexType xmlns:ns="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xs="http://www.w3.org/2001/XMLSchema" name="gYear"> * &lt;xs:simpleContent> * &lt;xs:extension base="xs:string"> * &lt;xs:attributeGroup ref="ns:commonAttributes"/> * &lt;/xs:extension> * &lt;/xs:simpleContent> * &lt;/xs:complexType> * </pre> */ public class GYear { private String string; private CommonAttributes commonAttributes; /** * Get the extension value. * * @return value */ public String getString() { return string; } /** * Set the extension value. * * @param string */ public void setString(String string) { this.string = string; } /** * Get the 'commonAttributes' attributeGroup value. * * @return value */ public CommonAttributes getCommonAttributes() { return commonAttributes; } /** * Set the 'commonAttributes' attributeGroup value. * * @param commonAttributes */ public void setCommonAttributes(CommonAttributes commonAttributes) { this.commonAttributes = commonAttributes; } }
mit
jonaslu/SmipleJavaDataStructures
src/dynamicArray/DynamicArray.java
744
package dynamicArray; import java.util.stream.IntStream; public class DynamicArray<E> { private int size; private Object[] array; public DynamicArray() { this(2); } public DynamicArray(int initialSize) { this.size = initialSize; this.array = new Object[initialSize]; } public void set(int index, E object) { expandIfNecessary(index); array[index] = object; } private void expandIfNecessary(int index) { if (index >= size) { int newSize = index * 2; Object[] newArray = new Object[newSize]; IntStream.range(0, array.length).forEach(idx -> newArray[idx] = array[idx]); array = newArray; size = newSize; } } @SuppressWarnings("unchecked") public E get(int index) { return (E) array[index]; } }
mit
jrachiele/java-timeseries
math/src/test/java/com/github/signaflo/math/polynomial/interpolation/LinearInterpolationSpec.java
2133
/* * Copyright (c) 2017 Jacob Rachiele * * 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. * * Contributors: * * Jacob Rachiele */ package com.github.signaflo.math.polynomial.interpolation; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.*; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; public final class LinearInterpolationSpec { @Rule public ExpectedException exception = ExpectedException.none(); @Test public void whenTwoPointsSameExceptionThrown() { exception.expect(IllegalArgumentException.class); new LinearInterpolation(3.0, 3.0, 7.0, 10.0); } @Test public void whenFunctionValuesGivenFirstCoefficientCorrect() { LinearInterpolation interpolation = new LinearInterpolation(3.5, 5.0, 12.25, 25.0); assertThat(interpolation.a0(), is(equalTo(-17.5))); } @Test public void whenFunctionValuesGivenSecondCoefficientCorrect() { LinearInterpolation interpolation = new LinearInterpolation(3.5, 5.0, 12.25, 25.0); assertThat(interpolation.a1(), is(equalTo(8.5))); } }
mit
tetrisdaemon/imprint
src/main/java/org/scavenge/imprint/test/DatabaseBenchmark.java
4238
package org.scavenge.imprint.test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import java.util.ArrayList; import org.scavenge.imprint.database.ImprintDatabase; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DatabaseBenchmark { public static void benchmarkPlayerInteractInsert(Connection conn, int n) throws SQLException { PreparedStatement statement = conn.prepareStatement("INSERT INTO imprint.player_interacts " + "(`player_id`, " + "`xz`, " + "`y`, " + "`world_id`, " + "`item_id`, " + "`click_type`) VALUES (?, GeomFromText(?), ?, ?, ?, ?)"); int[] itemIds = new int[n]; int[] worldIds = new int[n]; int[] playerIds = new int[n]; int[] clickTypes = new int[n]; String[] points = new String[n]; int[] yCoords = new int[n]; for (int i = 0; i < n; ++i) { int itemId = (int) (Math.random() * 10000); int worldId = (int) (Math.random() * 5); int clickType = (int) (Math.random() * 4); int playerId = (int) (Math.random() * 10000); int x = (int) (Math.random() * 6000) - 3000; int z = (int) (Math.random() * 6000) - 3000; int y = (int) (Math.random() * 150); itemIds[i] = itemId; playerIds[i] = playerId; worldIds[i] = worldId; clickTypes[i] = clickType; points[i] = "POINT(" + x + " " + z + ")"; yCoords[i] = y; } long timingA = System.currentTimeMillis(); for (int i = 0; i < n; ++i) { statement.setInt(1, playerIds[i]); statement.setString(2, points[i]); statement.setInt(3, yCoords[i]); statement.setInt(4, worldIds[i]); statement.setInt(5, itemIds[i]); statement.setInt(6, clickTypes[i]); statement.executeUpdate(); } long timingB = System.currentTimeMillis(); System.out.println(n + " inserts lasted " + (timingB - timingA) + " ms"); } public static void benchmarkBlockBreakInsert(Connection conn, int n) throws SQLException { PreparedStatement statement = conn.prepareStatement("INSERT INTO imprint.block_breaks " + "(`block_id`, " + "`player_id`, " + "`type_id`, " + "`xz`, " + "`y`) VALUES (?, ?, ?, GeomFromText(?), ?)"); int[] blockIds = new int[n]; int[] playerIds = new int[n]; int[] typeIds = new int[n]; String[] points = new String[n]; int[] yCoords = new int[n]; for (int i = 0; i < n; ++i) { int blockId = (int) (Math.random() * 10000); int playerId = (int) (Math.random() * 10000); int typeId = (int) (Math.random() * 10); int x = (int) (Math.random() * 6000) - 3000; int z = (int) (Math.random() * 6000) - 3000; int y = (int) (Math.random() * 150); blockIds[i] = blockId; playerIds[i] = playerId; typeIds[i] = typeId; points[i] = "POINT(" + x + " " + z + ")"; yCoords[i] = y; } long timingA = System.currentTimeMillis(); for (int i = 0; i < n; ++i) { statement.setInt(1, blockIds[i]); statement.setInt(2, playerIds[i]); statement.setInt(3, typeIds[i]); statement.setString(4, points[i]); statement.setInt(5, yCoords[i]); statement.executeUpdate(); } long timingB = System.currentTimeMillis(); System.out.println(n + " inserts lasted " + (timingB - timingA) + " ms"); } public static void main(String[] args) { /*if (args.length == 0) return;*/ args[0] = "1000"; int nTimes = Integer.parseInt(args[0]); ImprintDatabase.getInstance().init(); ComboPooledDataSource src = ImprintDatabase.getInstance().getDataSource(); Connection conn = null; try { conn = src.getConnection(); benchmarkPlayerInteractInsert(conn, nTimes); } catch (SQLException e) { System.err.println("Acquiring connection failed."); e.printStackTrace(); } finally { try { if (conn != null) conn.close(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
mit
TakayukiHoshi1984/DeviceConnect-Android
dConnectSDK/dConnectLibStreaming/libmedia/src/main/java/org/deviceconnect/android/libmedia/streaming/rtsp/session/audio/AudioStream.java
1016
package org.deviceconnect.android.libmedia.streaming.rtsp.session.audio; import org.deviceconnect.android.libmedia.streaming.audio.AudioEncoder; import org.deviceconnect.android.libmedia.streaming.rtsp.session.MediaStream; public abstract class AudioStream extends MediaStream { /** * 音声を配信するポート番号を定義します. */ private static final int AUDIO_PORT = 5004; public AudioStream() { setDestinationPort(AUDIO_PORT); } /** * ミュートの設定を行います. * * @param mute ミュートにする場合はtrue、それ以外はfalse */ public abstract void setMute(boolean mute); /** * 音声用のエンコーダを取得します. * * @return 音声用のエンコーダ */ public abstract AudioEncoder getAudioEncoder(); @Override public boolean isHighPriority() { // Audio の場合は、スレッドを High にするので、trueを返却 return true; } }
mit
GPUdb/gpudb-api-java
api/src/main/java/com/gpudb/protocol/FilterByValueResponse.java
6292
/* * This file was autogenerated by the GPUdb schema processor. * * DO NOT EDIT DIRECTLY. */ package com.gpudb.protocol; import java.util.LinkedHashMap; import java.util.Map; import org.apache.avro.Schema; import org.apache.avro.SchemaBuilder; import org.apache.avro.generic.GenericData; import org.apache.avro.generic.IndexedRecord; /** * A set of results returned by {@link * com.gpudb.GPUdb#filterByValue(FilterByValueRequest)}. */ public class FilterByValueResponse implements IndexedRecord { private static final Schema schema$ = SchemaBuilder .record("FilterByValueResponse") .namespace("com.gpudb") .fields() .name("count").type().longType().noDefault() .name("info").type().map().values().stringType().noDefault() .endRecord(); /** * This method supports the Avro framework and is not intended to be called * directly by the user. * * @return the schema for the class. * */ public static Schema getClassSchema() { return schema$; } /** * Additional information. * <ul> * <li> {@link * com.gpudb.protocol.FilterByValueResponse.Info#QUALIFIED_VIEW_NAME * QUALIFIED_VIEW_NAME}: The fully qualified name of the view (i.e. * including the schema) * </ul> * The default value is an empty {@link Map}. * A set of string constants for the parameter {@code info}. */ public static final class Info { /** * The fully qualified name of the view (i.e. including the schema) */ public static final String QUALIFIED_VIEW_NAME = "qualified_view_name"; private Info() { } } private long count; private Map<String, String> info; /** * Constructs a FilterByValueResponse object with default parameters. */ public FilterByValueResponse() { } /** * * @return The number of records passing the value filter. * */ public long getCount() { return count; } /** * * @param count The number of records passing the value filter. * * @return {@code this} to mimic the builder pattern. * */ public FilterByValueResponse setCount(long count) { this.count = count; return this; } /** * * @return Additional information. * <ul> * <li> {@link * com.gpudb.protocol.FilterByValueResponse.Info#QUALIFIED_VIEW_NAME * QUALIFIED_VIEW_NAME}: The fully qualified name of the view (i.e. * including the schema) * </ul> * The default value is an empty {@link Map}. * */ public Map<String, String> getInfo() { return info; } /** * * @param info Additional information. * <ul> * <li> {@link * com.gpudb.protocol.FilterByValueResponse.Info#QUALIFIED_VIEW_NAME * QUALIFIED_VIEW_NAME}: The fully qualified name of the view * (i.e. including the schema) * </ul> * The default value is an empty {@link Map}. * * @return {@code this} to mimic the builder pattern. * */ public FilterByValueResponse setInfo(Map<String, String> info) { this.info = (info == null) ? new LinkedHashMap<String, String>() : info; return this; } /** * This method supports the Avro framework and is not intended to be called * directly by the user. * * @return the schema object describing this class. * */ @Override public Schema getSchema() { return schema$; } /** * This method supports the Avro framework and is not intended to be called * directly by the user. * * @param index the position of the field to get * * @return value of the field with the given index. * * @throws IndexOutOfBoundsException * */ @Override public Object get(int index) { switch (index) { case 0: return this.count; case 1: return this.info; default: throw new IndexOutOfBoundsException("Invalid index specified."); } } /** * This method supports the Avro framework and is not intended to be called * directly by the user. * * @param index the position of the field to set * @param value the value to set * * @throws IndexOutOfBoundsException * */ @Override @SuppressWarnings("unchecked") public void put(int index, Object value) { switch (index) { case 0: this.count = (Long)value; break; case 1: this.info = (Map<String, String>)value; break; default: throw new IndexOutOfBoundsException("Invalid index specified."); } } @Override public boolean equals(Object obj) { if( obj == this ) { return true; } if( (obj == null) || (obj.getClass() != this.getClass()) ) { return false; } FilterByValueResponse that = (FilterByValueResponse)obj; return ( ( this.count == that.count ) && this.info.equals( that.info ) ); } @Override public String toString() { GenericData gd = GenericData.get(); StringBuilder builder = new StringBuilder(); builder.append( "{" ); builder.append( gd.toString( "count" ) ); builder.append( ": " ); builder.append( gd.toString( this.count ) ); builder.append( ", " ); builder.append( gd.toString( "info" ) ); builder.append( ": " ); builder.append( gd.toString( this.info ) ); builder.append( "}" ); return builder.toString(); } @Override public int hashCode() { int hashCode = 1; hashCode = (31 * hashCode) + ((Long)this.count).hashCode(); hashCode = (31 * hashCode) + this.info.hashCode(); return hashCode; } }
mit
aaronblenkush/sailthru-java-client
src/main/com/sailthru/client/params/Stats.java
470
package com.sailthru.client.params; import com.sailthru.client.ApiAction; /** * * @author Prajwal Tuladhar <praj@sailthru.com> */ public abstract class Stats implements ApiParams { protected String stat; protected static final String MODE_BLAST = "blast"; protected static final String MODE_LIST = "list"; public Stats(String stat) { this.stat = stat; } public ApiAction getApiCall() { return ApiAction.blast; } }
mit
openhab/openhab2
bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/SomfyTahomaBindingConstants.java
20205
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.somfytahoma.internal; import java.util.*; import org.eclipse.jdt.annotation.NonNullByDefault; import org.openhab.core.thing.ThingTypeUID; /** * The {@link SomfyTahomaBindingConstants} class defines common constants, which are * used across the whole binding. * * @author Ondrej Pecta - Initial contribution */ @NonNullByDefault public class SomfyTahomaBindingConstants { public static final String BINDING_ID = "somfytahoma"; // Things // Bridge public static final ThingTypeUID THING_TYPE_BRIDGE = new ThingTypeUID(BINDING_ID, "bridge"); // Gateway public static final ThingTypeUID THING_TYPE_GATEWAY = new ThingTypeUID(BINDING_ID, "gateway"); // Roller Shutter public static final ThingTypeUID THING_TYPE_ROLLERSHUTTER = new ThingTypeUID(BINDING_ID, "rollershutter"); // Silent Roller Shutter public static final ThingTypeUID THING_TYPE_ROLLERSHUTTER_SILENT = new ThingTypeUID(BINDING_ID, "rollershutter_silent"); // Uno Roller Shutter public static final ThingTypeUID THING_TYPE_ROLLERSHUTTER_UNO = new ThingTypeUID(BINDING_ID, "rollershutter_uno"); // Screen public static final ThingTypeUID THING_TYPE_SCREEN = new ThingTypeUID(BINDING_ID, "screen"); // Venetian Blind public static final ThingTypeUID THING_TYPE_VENETIANBLIND = new ThingTypeUID(BINDING_ID, "venetianblind"); // Exterior Screen public static final ThingTypeUID THING_TYPE_EXTERIORSCREEN = new ThingTypeUID(BINDING_ID, "exteriorscreen"); // Exterior Venetian Blind public static final ThingTypeUID THING_TYPE_EXTERIORVENETIANBLIND = new ThingTypeUID(BINDING_ID, "exteriorvenetianblind"); // Garage Door public static final ThingTypeUID THING_TYPE_GARAGEDOOR = new ThingTypeUID(BINDING_ID, "garagedoor"); // Awning public static final ThingTypeUID THING_TYPE_AWNING = new ThingTypeUID(BINDING_ID, "awning"); // Actiongroup public static final ThingTypeUID THING_TYPE_ACTIONGROUP = new ThingTypeUID(BINDING_ID, "actiongroup"); // On Off public static final ThingTypeUID THING_TYPE_ONOFF = new ThingTypeUID(BINDING_ID, "onoff"); // Light public static final ThingTypeUID THING_TYPE_LIGHT = new ThingTypeUID(BINDING_ID, "light"); // DimmerLight public static final ThingTypeUID THING_TYPE_DIMMER_LIGHT = new ThingTypeUID(BINDING_ID, "dimmerlight"); // Light sensor public static final ThingTypeUID THING_TYPE_LIGHTSENSOR = new ThingTypeUID(BINDING_ID, "lightsensor"); // Smoke sensor public static final ThingTypeUID THING_TYPE_SMOKESENSOR = new ThingTypeUID(BINDING_ID, "smokesensor"); // Contact sensor public static final ThingTypeUID THING_TYPE_CONTACTSENSOR = new ThingTypeUID(BINDING_ID, "contactsensor"); // Occupancy sensor public static final ThingTypeUID THING_TYPE_OCCUPANCYSENSOR = new ThingTypeUID(BINDING_ID, "occupancysensor"); // Water sensor public static final ThingTypeUID THING_TYPE_WATERSENSOR = new ThingTypeUID(BINDING_ID, "watersensor"); // Humidity sensor public static final ThingTypeUID THING_TYPE_HUMIDITYSENSOR = new ThingTypeUID(BINDING_ID, "humiditysensor"); // Window public static final ThingTypeUID THING_TYPE_WINDOW = new ThingTypeUID(BINDING_ID, "window"); // Alarm public static final ThingTypeUID THING_TYPE_INTERNAL_ALARM = new ThingTypeUID(BINDING_ID, "internalalarm"); public static final ThingTypeUID THING_TYPE_EXTERNAL_ALARM = new ThingTypeUID(BINDING_ID, "externalalarm"); public static final ThingTypeUID THING_TYPE_MYFOX_ALARM = new ThingTypeUID(BINDING_ID, "myfoxalarm"); // Pod public static final ThingTypeUID THING_TYPE_POD = new ThingTypeUID(BINDING_ID, "pod"); // Heating system public static final ThingTypeUID THING_TYPE_VALVE_HEATING_SYSTEM = new ThingTypeUID(BINDING_ID, "valveheatingsystem"); public static final ThingTypeUID THING_TYPE_ZWAVE_HEATING_SYSTEM = new ThingTypeUID(BINDING_ID, "heatingsystem"); public static final ThingTypeUID THING_TYPE_ONOFF_HEATING_SYSTEM = new ThingTypeUID(BINDING_ID, "onoffheatingsystem"); public static final ThingTypeUID THING_TYPE_EXTERIOR_HEATING_SYSTEM = new ThingTypeUID(BINDING_ID, "exteriorheatingsystem"); // Door lock public static final ThingTypeUID THING_TYPE_DOOR_LOCK = new ThingTypeUID(BINDING_ID, "doorlock"); // Pergola public static final ThingTypeUID THING_TYPE_PERGOLA = new ThingTypeUID(BINDING_ID, "pergola"); // Window handle public static final ThingTypeUID THING_TYPE_WINDOW_HANDLE = new ThingTypeUID(BINDING_ID, "windowhandle"); // Temperature sensor public static final ThingTypeUID THING_TYPE_TEMPERATURESENSOR = new ThingTypeUID(BINDING_ID, "temperaturesensor"); // Gate public static final ThingTypeUID THING_TYPE_GATE = new ThingTypeUID(BINDING_ID, "gate"); // Curtains public static final ThingTypeUID THING_TYPE_CURTAIN = new ThingTypeUID(BINDING_ID, "curtain"); // Electricity sensor public static final ThingTypeUID THING_TYPE_ELECTRICITYSENSOR = new ThingTypeUID(BINDING_ID, "electricitysensor"); // Dock public static final ThingTypeUID THING_TYPE_DOCK = new ThingTypeUID(BINDING_ID, "dock"); // Siren public static final ThingTypeUID THING_TYPE_SIREN = new ThingTypeUID(BINDING_ID, "siren"); // Adjustable slats roller shutter public static final ThingTypeUID THING_TYPE_ADJUSTABLE_SLATS_ROLLERSHUTTER = new ThingTypeUID(BINDING_ID, "adjustableslatsrollershutter"); // MyFox Camera public static final ThingTypeUID THING_TYPE_MYFOX_CAMERA = new ThingTypeUID(BINDING_ID, "myfoxcamera"); // Thermostat public static final ThingTypeUID THING_TYPE_THERMOSTAT = new ThingTypeUID(BINDING_ID, "thermostat"); // List of all Channel ids public static final String RSSI = "rssi"; // Gateway public static final String STATUS = "status"; // Roller shutter, Awning, Screen, Blind, Garage door, Window, Curtain public static final String CONTROL = "control"; // Adjustable slats roller shutter public static final String ROCKER = "rocker"; // Silent roller shutter public static final String CONTROL_SILENT = "control_silent"; // Blind public static final String ORIENTATION = "orientation"; public static final String CLOSURE_AND_ORIENTATION = "closure_orientation"; // Action group public static final String EXECUTE_ACTION = "execute_action"; // OnOff, Light public static final String SWITCH = "switch"; // Dimmer Light public static final String LIGHT_INTENSITY = "light_intensity"; // Door lock public static final String LOCK = "lock"; public static final String OPEN = "open"; // Smoke sensor, Occupancy sensor, Contact sensor, Water sensor public static final String CONTACT = "contact"; public static final String SENSOR_DEFECT = "sensor_defect"; // Humidity sensor public static final String HUMIDITY = "humidity"; // Smoke sensor public static final String ALARM_CHECK = "alarm_check"; public static final String RADIO_BATTERY = "radio_battery"; public static final String SENSOR_BATTERY = "sensor_battery"; // Light sensor public static final String LUMINANCE = "luminance"; // Temperature sensor public static final String TEMPERATURE = "temperature"; // Alarm public static final String ALARM_COMMAND = "alarm_command"; public static final String ALARM_STATE = "alarm_state"; public static final String TARGET_ALARM_STATE = "target_alarm_state"; public static final String INTRUSION_CONTROL = "intrusion_control"; public static final String INTRUSION_STATE = "intrusion_state"; // Pod public static final String CYCLIC_BUTTON = "cyclic_button"; public static final String LIGHTING_LED_POD_MODE = "lighting_led_pod_mode"; // Heating system public static final String TARGET_TEMPERATURE = "target_temperature"; public static final String CURRENT_TEMPERATURE = "current_temperature"; public static final String CURRENT_STATE = "current_state"; public static final String BATTERY_LEVEL = "battery_level"; public static final String TARGET_HEATING_LEVEL = "target_heating_level"; public static final String HEATING_LEVEL = "heating_level"; // Thermostat public static final String HEATING_MODE = "heating_mode"; public static final String DEROGATION_ACTIVATION = "derogation_activation"; // Thermostat & Valve Heating system public static final String DEROGATED_TARGET_TEMPERATURE = "derogated_target_temperature"; public static final String DEROGATION_HEATING_MODE = "derogation_heating_mode"; // Valve heating system public static final String CURRENT_HEATING_MODE = "current_heating_mode"; public static final String OPEN_CLOSED_VALVE = "open_closed_valve"; public static final String OPERATING_MODE = "operating_mode"; // Window handle public static final String HANDLE_STATE = "handle_state"; // Gate public static final String GATE_STATE = "gate_state"; public static final String GATE_COMMAND = "gate_command"; public static final String GATE_POSITION = "gate_position"; // ElectricitySensor public static final String ENERGY_CONSUMPTION = "energy_consumption"; // Dock public static final String BATTERY_STATUS = "battery_status"; public static final String SIREN_STATUS = "siren_status"; public static final String SHORT_BIP = "short_beep"; public static final String LONG_BIP = "long_beep"; // Siren public static final String MEMORIZED_VOLUME = "memorized_volume"; public static final String ONOFF_STATE = "onoff"; public static final String BATTERY = "battery"; // Myfox Alarm public static final String MYFOX_ALARM_COMMAND = "myfox_alarm_command"; // Myfox Alarm & Camera public static final String CLOUD_STATUS = "cloud_status"; // Myfox Camera public static final String SHUTTER = "shutter"; // Constants public static final String TAHOMA_API_URL = "https://www.tahomalink.com/enduser-mobile-web/enduserAPI/"; public static final String TAHOMA_EVENTS_URL = TAHOMA_API_URL + "events/"; public static final String SETUP_URL = TAHOMA_API_URL + "setup/"; public static final String GATEWAYS_URL = SETUP_URL + "gateways/"; public static final String DEVICES_URL = SETUP_URL + "devices/"; public static final String REFRESH_URL = DEVICES_URL + "states/refresh"; public static final String EXEC_URL = TAHOMA_API_URL + "exec/"; public static final String DELETE_URL = EXEC_URL + "current/setup/"; public static final String TAHOMA_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36"; public static final int TAHOMA_TIMEOUT = 5; public static final String UNAUTHORIZED = "Not logged in"; public static final int TYPE_PERCENT = 1; public static final int TYPE_DECIMAL = 2; public static final int TYPE_STRING = 3; public static final int TYPE_BOOLEAN = 6; public static final String UNAVAILABLE = "unavailable"; public static final String AUTHENTICATION_CHALLENGE = "HTTP protocol violation: Authentication challenge without WWW-Authenticate header"; public static final String TOO_MANY_REQUESTS = "Too many requests, try again later"; public static final int SUSPEND_TIME = 120; public static final int RECONCILIATION_TIME = 600; // Commands public static final String COMMAND_MY = "my"; public static final String COMMAND_SET_CLOSURE = "setClosure"; public static final String COMMAND_SET_CLOSURE_ORIENTATION = "setClosureAndOrientation"; public static final String COMMAND_SET_DEPLOYMENT = "setDeployment"; public static final String COMMAND_SET_ORIENTATION = "setOrientation"; public static final String COMMAND_SET_CLOSURESPEED = "setClosureAndLinearSpeed"; public static final String COMMAND_SET_HEATINGLEVEL = "setHeatingLevel"; public static final String COMMAND_SET_PEDESTRIANPOSITION = "setPedestrianPosition"; public static final String COMMAND_SET_ROCKERPOSITION = "setRockerPosition"; public static final String COMMAND_SET_DEROGATION = "setDerogation"; public static final String COMMAND_UP = "up"; public static final String COMMAND_DOWN = "down"; public static final String COMMAND_OPEN = "open"; public static final String COMMAND_CLOSE = "close"; public static final String COMMAND_STOP = "stop"; public static final String COMMAND_OFF = "off"; public static final String COMMAND_CHECK_TRIGGER = "checkEventTrigger"; // States public static final String NAME_STATE = "core:NameState"; public static final String RSSI_LEVEL_STATE = "core:RSSILevelState"; public static final String STATUS_STATE = "core:StatusState"; public static final String ENERGY_CONSUMPTION_STATE = "core:ElectricEnergyConsumptionState"; public static final String CYCLIC_BUTTON_STATE = "core:CyclicButtonState"; public static final String BATTERY_STATUS_STATE = "internal:BatteryStatusState"; public static final String SLATE_ORIENTATION_STATE = "core:SlateOrientationState"; public static final String CLOSURE_OR_ROCKER_STATE = "core:ClosureOrRockerPositionState"; public static final String MYFOX_SHUTTER_STATUS_STATE = "myfox:ShutterStatusState"; public static final String TARGET_CLOSURE_STATE = "core:TargetClosureState"; public static final String WATER_DETECTION_STATE = "core:WaterDetectionState"; public static final String CLOUD_DEVICE_STATUS_STATE = "core:CloudDeviceStatusState"; public static final String BATTERY_LEVEL_STATE = "core:BatteryLevelState"; public static final String SIREN_STATUS_STATE = "internal:SirenStatusState"; public static final String TARGET_TEMPERATURE_STATE = "core:TargetTemperatureState"; public static final String TARGET_ROOM_TEMPERATURE_STATE = "core:TargetRoomTemperatureState"; public static final String SMOKE_STATE = "core:SmokeState"; public static final String SENSOR_DEFECT_STATE = "core:SensorDefectState"; public static final String RADIO_PART_BATTERY_STATE = "io:MaintenanceRadioPartBatteryState"; public static final String SENSOR_PART_BATTERY_STATE = "io:MaintenanceSensorPartBatteryState"; public static final String ZWAVE_SET_POINT_TYPE_STATE = "zwave:SetPointTypeState"; // supported uiClasses public static final String CLASS_ROLLER_SHUTTER = "RollerShutter"; public static final String CLASS_SCREEN = "Screen"; public static final String CLASS_VENETIAN_BLIND = "VenetianBlind"; public static final String CLASS_EXTERIOR_SCREEN = "ExteriorScreen"; public static final String CLASS_EXTERIOR_VENETIAN_BLIND = "ExteriorVenetianBlind"; public static final String CLASS_GARAGE_DOOR = "GarageDoor"; public static final String CLASS_AWNING = "Awning"; public static final String CLASS_ON_OFF = "OnOff"; public static final String CLASS_LIGHT = "Light"; public static final String CLASS_LIGHT_SENSOR = "LightSensor"; public static final String CLASS_SMOKE_SENSOR = "SmokeSensor"; public static final String CLASS_CONTACT_SENSOR = "ContactSensor"; public static final String CLASS_OCCUPANCY_SENSOR = "OccupancySensor"; public static final String CLASS_HUMIDITY_SENSOR = "HumiditySensor"; public static final String CLASS_WINDOW = "Window"; public static final String CLASS_ALARM = "Alarm"; public static final String CLASS_POD = "Pod"; public static final String CLASS_HEATING_SYSTEM = "HeatingSystem"; public static final String CLASS_EXTERIOR_HEATING_SYSTEM = "ExteriorHeatingSystem"; public static final String CLASS_DOOR_LOCK = "DoorLock"; public static final String CLASS_PERGOLA = "Pergola"; public static final String CLASS_WINDOW_HANDLE = "WindowHandle"; public static final String CLASS_TEMPERATURE_SENSOR = "TemperatureSensor"; public static final String CLASS_GATE = "Gate"; public static final String CLASS_CURTAIN = "Curtain"; public static final String CLASS_ELECTRICITY_SENSOR = "ElectricitySensor"; public static final String CLASS_DOCK = "Dock"; public static final String CLASS_SIREN = "Siren"; public static final String CLASS_ADJUSTABLE_SLATS_ROLLER_SHUTTER = "AdjustableSlatsRollerShutter"; public static final String CLASS_CAMERA = "Camera"; // unsupported uiClasses public static final String THING_PROTOCOL_GATEWAY = "ProtocolGateway"; public static final String THING_REMOTE_CONTROLLER = "RemoteController"; public static final String THING_NETWORK_COMPONENT = "NetworkComponent"; // Event states public static final String FAILED_EVENT = "FAILED"; public static final String COMPLETED_EVENT = "COMPLETED"; // supported thing types for discovery public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES_UIDS = new HashSet<>(Arrays.asList(THING_TYPE_GATEWAY, THING_TYPE_ROLLERSHUTTER, THING_TYPE_ROLLERSHUTTER_SILENT, THING_TYPE_SCREEN, THING_TYPE_VENETIANBLIND, THING_TYPE_EXTERIORSCREEN, THING_TYPE_EXTERIORVENETIANBLIND, THING_TYPE_GARAGEDOOR, THING_TYPE_AWNING, THING_TYPE_ACTIONGROUP, THING_TYPE_ONOFF, THING_TYPE_LIGHT, THING_TYPE_LIGHTSENSOR, THING_TYPE_SMOKESENSOR, THING_TYPE_CONTACTSENSOR, THING_TYPE_OCCUPANCYSENSOR, THING_TYPE_WINDOW, THING_TYPE_INTERNAL_ALARM, THING_TYPE_EXTERNAL_ALARM, THING_TYPE_POD, THING_TYPE_ZWAVE_HEATING_SYSTEM, THING_TYPE_ONOFF_HEATING_SYSTEM, THING_TYPE_DOOR_LOCK, THING_TYPE_PERGOLA, THING_TYPE_WINDOW_HANDLE, THING_TYPE_TEMPERATURESENSOR, THING_TYPE_GATE, THING_TYPE_CURTAIN, THING_TYPE_ELECTRICITYSENSOR, THING_TYPE_DOCK, THING_TYPE_SIREN, THING_TYPE_ADJUSTABLE_SLATS_ROLLERSHUTTER, THING_TYPE_MYFOX_CAMERA, THING_TYPE_ROLLERSHUTTER_UNO, THING_TYPE_WATERSENSOR, THING_TYPE_HUMIDITYSENSOR, THING_TYPE_MYFOX_ALARM, THING_TYPE_THERMOSTAT, THING_TYPE_DIMMER_LIGHT, THING_TYPE_EXTERIOR_HEATING_SYSTEM, THING_TYPE_VALVE_HEATING_SYSTEM)); // somfy gateways public static Map<Integer, String> gatewayTypes = new HashMap<Integer, String>() { { put(0, "VIRTUAL_KIZBOX"); put(2, "KIZBOX_V1"); put(15, "TAHOMA"); put(20, "VERISURE_ALARM_SYSTEM"); put(21, "KIZBOX_MINI"); put(24, "KIZBOX_V2"); put(25, "MYFOX_ALARM_SYSTEM"); put(27, "KIZBOX_MINI_VMBUS"); put(28, "KIZBOX_MINI_IO"); put(29, "TAHOMA_V2"); put(30, "KIZBOX_V2_3H"); put(31, "KIZBOX_V2_2H"); put(34, "CONNEXOON"); put(35, "JSW_CAMERA"); put(37, "KIZBOX_MINI_DAUGHTERBOARD"); put(38, "KIZBOX_MINI_DAUGHTERBOARD_ZWAVE"); put(39, "KIZBOX_MINI_DAUGHTERBOARD_ENOCEAN"); put(40, "KIZBOX_MINI_RAILDIN"); put(41, "TAHOMA_V2_RTS"); put(42, "KIZBOX_MINI_MODBUS"); put(43, "KIZBOX_MINI_OVP"); put(53, "CONNEXOON_RTS"); put(54, "OPENDOORS_LOCK_SYSTEM"); put(56, "CONNEXOON_RTS_JAPAN"); put(58, "HOME_PROTECT_SYSTEM"); put(62, "CONNEXOON_RTS_AUSTRALIA"); put(63, "THERMOSTAT_SOMFY_SYSTEM"); put(64, "BOX_ULTRA_LOW_COST_RTS"); put(65, "SMARTLY_MINI_DAUGHTERBOARD_ZWAVE"); put(66, "SMARTLY_MINIBOX_RAILDIN"); put(67, "TAHOMA_BEE"); put(72, "TAHOMA_RAIL_DIN"); put(77, "ELIOT"); put(88, "WISER"); } }; }
epl-1.0
groenda/LIMBO
dlim.generator/src/tools/descartes/dlim/UnivariateFunction.java
1544
/** */ package tools.descartes.dlim; /** * <!-- begin-user-doc --> A representation of the model object ' * <em><b>Univariate Function</b></em>'. <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link tools.descartes.dlim.UnivariateFunction#getFunction <em>Function * </em>}</li> * </ul> * </p> * * @see tools.descartes.dlim.DlimPackage#getUnivariateFunction() * @model abstract="true" * @generated */ public interface UnivariateFunction extends Function { /** * Returns the value of the '<em><b>Function</b></em>' containment * reference. <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Function</em>' containment reference isn't * clear, there really should be more of a description here... * </p> * <!-- end-user-doc --> * * @return the value of the '<em>Function</em>' containment reference. * @see #setFunction(Function) * @see tools.descartes.dlim.DlimPackage#getUnivariateFunction_Function() * @model containment="true" required="true" * @generated */ Function getFunction(); /** * Sets the value of the ' * {@link tools.descartes.dlim.UnivariateFunction#getFunction * <em>Function</em>}' containment reference. <!-- begin-user-doc --> <!-- * end-user-doc --> * * @param value * the new value of the '<em>Function</em>' containment * reference. * @see #getFunction() * @generated */ void setFunction(Function value); } // UnivariateFunction
epl-1.0
cdjackson/openhab2-addons
addons/binding/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/RFXComValueSelector.java
4780
/** * Copyright (c) 2010-2017 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.rfxcom; import org.eclipse.smarthome.core.items.Item; import org.eclipse.smarthome.core.library.items.ContactItem; import org.eclipse.smarthome.core.library.items.DateTimeItem; import org.eclipse.smarthome.core.library.items.DimmerItem; import org.eclipse.smarthome.core.library.items.NumberItem; import org.eclipse.smarthome.core.library.items.RollershutterItem; import org.eclipse.smarthome.core.library.items.StringItem; import org.eclipse.smarthome.core.library.items.SwitchItem; /** * Represents all valid value selectors which could be processed by RFXCOM * devices. * * @author Pauli Anttila - Initial contribution */ public enum RFXComValueSelector { RAW_MESSAGE(RFXComBindingConstants.CHANNEL_RAW_MESSAGE, StringItem.class), RAW_PAYLOAD(RFXComBindingConstants.CHANNEL_RAW_PAYLOAD, StringItem.class), SHUTTER(RFXComBindingConstants.CHANNEL_SHUTTER, RollershutterItem.class), COMMAND(RFXComBindingConstants.CHANNEL_COMMAND, SwitchItem.class), COMMAND_ID(RFXComBindingConstants.CHANNEL_COMMAND_ID, NumberItem.class), MOOD(RFXComBindingConstants.CHANNEL_MOOD, NumberItem.class), SIGNAL_LEVEL(RFXComBindingConstants.CHANNEL_SIGNAL_LEVEL, NumberItem.class), DIMMING_LEVEL(RFXComBindingConstants.CHANNEL_DIMMING_LEVEL, DimmerItem.class), UV(RFXComBindingConstants.CHANNEL_UV, NumberItem.class), TEMPERATURE(RFXComBindingConstants.CHANNEL_TEMPERATURE, NumberItem.class), HUMIDITY(RFXComBindingConstants.CHANNEL_HUMIDITY, NumberItem.class), HUMIDITY_STATUS(RFXComBindingConstants.CHANNEL_HUMIDITY_STATUS, StringItem.class), BATTERY_LEVEL(RFXComBindingConstants.CHANNEL_BATTERY_LEVEL, NumberItem.class), PRESSURE(RFXComBindingConstants.CHANNEL_PRESSURE, NumberItem.class), FORECAST(RFXComBindingConstants.CHANNEL_FORECAST, NumberItem.class), RAIN_RATE(RFXComBindingConstants.CHANNEL_RAIN_RATE, NumberItem.class), RAIN_TOTAL(RFXComBindingConstants.CHANNEL_RAIN_TOTAL, NumberItem.class), WIND_DIRECTION(RFXComBindingConstants.CHANNEL_WIND_DIRECTION, NumberItem.class), WIND_SPEED(RFXComBindingConstants.CHANNEL_WIND_SPEED, NumberItem.class), GUST(RFXComBindingConstants.CHANNEL_GUST, NumberItem.class), CHILL_FACTOR(RFXComBindingConstants.CHANNEL_CHILL_FACTOR, NumberItem.class), INSTANT_POWER(RFXComBindingConstants.CHANNEL_INSTANT_POWER, NumberItem.class), TOTAL_USAGE(RFXComBindingConstants.CHANNEL_TOTAL_USAGE, NumberItem.class), INSTANT_AMPS(RFXComBindingConstants.CHANNEL_INSTANT_AMPS, NumberItem.class), TOTAL_AMP_HOUR(RFXComBindingConstants.CHANNEL_TOTAL_AMP_HOUR, NumberItem.class), CHANNEL1_AMPS(RFXComBindingConstants.CHANNEL_CHANNEL1_AMPS, NumberItem.class), CHANNEL2_AMPS(RFXComBindingConstants.CHANNEL_CHANNEL2_AMPS, NumberItem.class), CHANNEL3_AMPS(RFXComBindingConstants.CHANNEL_CHANNEL3_AMPS, NumberItem.class), STATUS(RFXComBindingConstants.CHANNEL_STATUS, StringItem.class), MOTION(RFXComBindingConstants.CHANNEL_MOTION, SwitchItem.class), CONTACT(RFXComBindingConstants.CHANNEL_CONTACT, ContactItem.class), VOLTAGE(RFXComBindingConstants.CHANNEL_VOLTAGE, NumberItem.class), SET_POINT(RFXComBindingConstants.CHANNEL_SET_POINT, NumberItem.class), DATE_TIME(RFXComBindingConstants.CHANNEL_DATE_TIME, DateTimeItem.class), LOW_BATTERY(RFXComBindingConstants.CHANNEL_LOW_BATTERY, SwitchItem.class), CHIME_SOUND(RFXComBindingConstants.CHANNEL_CHIME_SOUND, NumberItem.class); private final String text; private Class<? extends Item> itemClass; private RFXComValueSelector(final String text, Class<? extends Item> itemClass) { this.text = text; this.itemClass = itemClass; } @Override public String toString() { return text; } public Class<? extends Item> getItemClass() { return itemClass; } /** * Procedure to convert selector string to value selector class. * * @param valueSelectorText * selector string e.g. RawData, Command, Temperature * @return corresponding selector value. */ public static RFXComValueSelector getValueSelector(String valueSelectorText) throws IllegalArgumentException { for (RFXComValueSelector c : RFXComValueSelector.values()) { if (c.text.equals(valueSelectorText)) { return c; } } throw new IllegalArgumentException("Not valid value selector"); } }
epl-1.0
epsilonlabs/haetae
org.eclipse.epsilon.haetae.eol.type/src/org/eclipse/epsilon/eol/visitor/resolution/type/naive/operationDefinitionHandler/CollectionIncludingAllHandler.java
14857
package org.eclipse.epsilon.eol.visitor.resolution.type.naive.operationDefinitionHandler; import java.util.ArrayList; import org.eclipse.emf.ecore.util.EcoreUtil; import org.eclipse.epsilon.eol.metamodel.AnyType; import org.eclipse.epsilon.eol.metamodel.CollectionType; import org.eclipse.epsilon.eol.metamodel.EolPackage; import org.eclipse.epsilon.eol.metamodel.Expression; import org.eclipse.epsilon.eol.metamodel.FeatureCallExpression; import org.eclipse.epsilon.eol.metamodel.MethodCallExpression; import org.eclipse.epsilon.eol.metamodel.OperationDefinition; import org.eclipse.epsilon.eol.metamodel.Type; import org.eclipse.epsilon.eol.problem.LogBook; import org.eclipse.epsilon.eol.problem.imessages.IMessage_TypeResolution; import org.eclipse.epsilon.eol.visitor.resolution.type.naive.operationDefinitionUtil.OperationDefinitionManager; import org.eclipse.epsilon.eol.visitor.resolution.type.naive.operationDefinitionUtil.StandardLibraryOperationDefinitionContainer; import org.eclipse.epsilon.eol.visitor.resolution.type.naive.util.TypeInferenceManager; import org.eclipse.epsilon.eol.visitor.resolution.type.naive.util.TypeUtil; public class CollectionIncludingAllHandler extends CollectionOperationDefinitionHandler{ @Override public boolean appliesTo(String name, Type contextType, ArrayList<Type> argTypes) { if (name.equals("includingAll") && argTypes.size() == 1 ) { if (contextType instanceof CollectionType) { return true; } else if (TypeUtil.getInstance().isInstanceofAnyType(contextType)) { if (TypeInferenceManager.getInstance().containsDynamicType((AnyType) contextType, EolPackage.eINSTANCE.getCollectionType())) { return true; } } else { return false; } } return false; } @Override public OperationDefinition handle( FeatureCallExpression featureCallExpression, Type contextType, ArrayList<Type> argTypes) { //get the manager StandardLibraryOperationDefinitionContainer manager = OperationDefinitionManager.getInstance().getStandardLibraryOperationDefinitionContainer(); //get the result OperationDefinition result = manager.getOperation(((MethodCallExpression) featureCallExpression).getMethod().getName(), argTypes); //if result is not null if (result != null) { //register result as it has been handled OperationDefinitionManager.getInstance().registerHandledOperationDefinition(result); //get the target Expression target = featureCallExpression.getTarget(); //if target is null, report and return if (target == null) { LogBook.getInstance().addError(featureCallExpression, IMessage_TypeResolution.OPERATION_REQUIRES_TARGET); return result; } //if target is collection type Type targetType = EcoreUtil.copy(target.getResolvedType()); //if target type is collection if (targetType instanceof CollectionType) { //get collection type and get content type CollectionType _targetType = (CollectionType) EcoreUtil.copy(targetType); Type contentType = _targetType.getContentType(); //get the arg type Type argType = argTypes.get(0); Type argContentType = null; //if argument is collection if (argType instanceof CollectionType) { CollectionType _argType = (CollectionType) EcoreUtil.copy(argType); argContentType = _argType.getContentType(); //if content type is any, add the argtype to the content type if (TypeUtil.getInstance().isInstanceofAnyType(contentType)) { AnyType _contentType = (AnyType) contentType; AnyType _argContentType = (AnyType) EcoreUtil.copy(argContentType); if (TypeUtil.getInstance().isInstanceofAnyType(argContentType)) { _contentType.getDynamicTypes().addAll(_argContentType.getDynamicTypes()); } else { _contentType.getDynamicTypes().add(_argContentType); } result.setReturnType(_targetType); } //if content type is not any, compare with the arg type (argtype is collection now, dont forget) else { if (TypeUtil.getInstance().isTypeEqualOrGeneric(argContentType, contentType)) { result.setReturnType(_targetType); return result; } else { LogBook.getInstance().addWarning(argType, IMessage_TypeResolution.bindMessage(IMessage_TypeResolution.POTENTIAL_TYPE_MISMATCH, contentType.getClass().getSimpleName())); result.setReturnType(_targetType); return result; } } } //if arg type is any else if (TypeUtil.getInstance().isInstanceofAnyType(argType)) { //get all dyn types that are of type collection if (TypeInferenceManager.getInstance().containsDynamicType((AnyType) argType, EolPackage.eINSTANCE.getCollectionType())) { ArrayList<Type> dynTypes = TypeInferenceManager.getInstance().getDynamicTypes((AnyType) argType, EolPackage.eINSTANCE.getCollectionType()); if (dynTypes.size() > 0) { boolean found = false; //for all the dynamic types for(Type t: dynTypes) { //cast to collection type and get the arg content type CollectionType collectionType2 = (CollectionType) t; argContentType = collectionType2.getContentType(); //if target content type is any, add to dynamic types if (TypeUtil.getInstance().isInstanceofAnyType(contentType)) { found = true; AnyType _contentType = (AnyType) contentType; AnyType _argContentType = (AnyType) EcoreUtil.copy(argContentType); if (TypeUtil.getInstance().isInstanceofAnyType(argContentType)) { _contentType.getDynamicTypes().addAll(_argContentType.getDynamicTypes()); } else { _contentType.getDynamicTypes().add(_argContentType); } } else { if (TypeUtil.getInstance().isTypeEqualOrGeneric(argContentType, contentType)) { found = true; } } } if (!found) { LogBook.getInstance().addWarning(argType, IMessage_TypeResolution.bindMessage(IMessage_TypeResolution.POTENTIAL_ARGUMENT_MISMATCH, "addAll(" + TypeUtil.getInstance().getTypeName(targetType) + ")")); result.setReturnType(_targetType); return result; } result.setReturnType(_targetType); return result; } else { LogBook.getInstance().addWarning(argType, IMessage_TypeResolution.bindMessage(IMessage_TypeResolution.POTENTIAL_ARGUMENT_MISMATCH, "addAll(" + TypeUtil.getInstance().getTypeName(targetType) + ")")); result.setReturnType(_targetType); return result; } } else { LogBook.getInstance().addWarning(argType, IMessage_TypeResolution.EXPRESSION_MAY_NOT_BE_COLLECTION_TYPE); result.setReturnType(_targetType); return result; } } else { LogBook.getInstance().addWarning(argType, IMessage_TypeResolution.EXPRESSION_MAY_NOT_BE_COLLECTION_TYPE); result.setReturnType(_targetType); return result; } } //if target is any type else if (TypeUtil.getInstance().isInstanceofAnyType(targetType)) { //get dynamic types that are collection ArrayList<Type> dynTypes = TypeInferenceManager.getInstance().getDynamicTypes((AnyType) targetType, EolPackage.eINSTANCE.getCollectionType()); //if no collection type found, report and return if (dynTypes.size() == 0) { LogBook.getInstance().addWarning(targetType, IMessage_TypeResolution.EXPRESSION_MAY_NOT_BE_COLLECTION_TYPE); return null; } else if (dynTypes.size() == 1) { //get collection type and get content type CollectionType _targetType = (CollectionType) EcoreUtil.copy(dynTypes.get(0)); Type contentType = _targetType.getContentType(); //get the arg type Type argType = argTypes.get(0); Type argContentType = null; //if argument is collection if (argType instanceof CollectionType) { CollectionType _argType = (CollectionType) EcoreUtil.copy(argType); argContentType = _argType.getContentType(); //if content type is any, add the argtype to the content type if (TypeUtil.getInstance().isInstanceofAnyType(contentType)) { AnyType _contentType = (AnyType) contentType; AnyType _argContentType = (AnyType) EcoreUtil.copy(argContentType); if (TypeUtil.getInstance().isInstanceofAnyType(argContentType)) { _contentType.getDynamicTypes().addAll(_argContentType.getDynamicTypes()); } else { _contentType.getDynamicTypes().add(_argContentType); } result.setReturnType(_targetType); } //if content type is not any, compare with the arg type (argtype is collection now, dont forget) else { if (TypeUtil.getInstance().isTypeEqualOrGeneric(argContentType, contentType)) { result.setReturnType(_targetType); return result; } else { LogBook.getInstance().addWarning(argType, IMessage_TypeResolution.bindMessage(IMessage_TypeResolution.POTENTIAL_TYPE_MISMATCH, contentType.getClass().getSimpleName())); result.setReturnType(_targetType); return result; } } } //if arg type is any else if (TypeUtil.getInstance().isInstanceofAnyType(argType)) { //get all dyn types that are of type collection if (TypeInferenceManager.getInstance().containsDynamicType((AnyType) argType, EolPackage.eINSTANCE.getCollectionType())) { ArrayList<Type> _dynTypes = TypeInferenceManager.getInstance().getDynamicTypes((AnyType) argType, EolPackage.eINSTANCE.getCollectionType()); if (_dynTypes.size() > 0) { boolean found = false; //for all the dynamic types for(Type t: _dynTypes) { //cast to collection type and get the arg content type CollectionType collectionType2 = (CollectionType) t; argContentType = collectionType2.getContentType(); //if target content type is any, add to dynamic types if (TypeUtil.getInstance().isInstanceofAnyType(contentType)) { found = true; AnyType _contentType = (AnyType) contentType; AnyType _argContentType = (AnyType) EcoreUtil.copy(argContentType); if (TypeUtil.getInstance().isInstanceofAnyType(argContentType)) { _contentType.getDynamicTypes().addAll(_argContentType.getDynamicTypes()); } else { _contentType.getDynamicTypes().add(_argContentType); } } else { if (TypeUtil.getInstance().isTypeEqualOrGeneric(argContentType, contentType)) { found = true; } } } if (!found) { LogBook.getInstance().addWarning(argType, IMessage_TypeResolution.bindMessage(IMessage_TypeResolution.POTENTIAL_ARGUMENT_MISMATCH, "addAll(" + TypeUtil.getInstance().getTypeName(targetType) + ")")); result.setReturnType(_targetType); return result; } result.setReturnType(_targetType); return result; } else { LogBook.getInstance().addWarning(argType, IMessage_TypeResolution.bindMessage(IMessage_TypeResolution.POTENTIAL_ARGUMENT_MISMATCH, "addAll(" + TypeUtil.getInstance().getTypeName(targetType) + ")")); result.setReturnType(_targetType); return result; } } else { LogBook.getInstance().addWarning(argType, IMessage_TypeResolution.EXPRESSION_MAY_NOT_BE_COLLECTION_TYPE); result.setReturnType(_targetType); return result; } } else { LogBook.getInstance().addWarning(argType, IMessage_TypeResolution.EXPRESSION_MAY_NOT_BE_COLLECTION_TYPE); result.setReturnType(_targetType); return result; } } //if found collection type else if (dynTypes.size() > 1) { Type _targetType = EcoreUtil.copy(targetType); Type argType = argTypes.get(0); //for all types found for(Type t: dynTypes) { //get collection type and get content type CollectionType __targetType = (CollectionType) t; Type contentType = __targetType.getContentType(); //get the arg type Type argContentType = null; if (argType instanceof CollectionType) { CollectionType _argType = (CollectionType) EcoreUtil.copy(argType); argContentType = _argType.getContentType(); //if content type is any, add the argtype to the content type if (TypeUtil.getInstance().isInstanceofAnyType(contentType)) { AnyType _contentType = (AnyType) contentType; if (TypeUtil.getInstance().isInstanceofAnyType(argContentType)) { AnyType _argContentType = (AnyType) argContentType; _contentType.getDynamicTypes().addAll(_argContentType.getDynamicTypes()); } else { _contentType.getDynamicTypes().add(argContentType); } } } else if (TypeUtil.getInstance().isInstanceofAnyType(argType)) { if (TypeInferenceManager.getInstance().containsDynamicType((AnyType) argType, EolPackage.eINSTANCE.getCollectionType())) { ArrayList<Type> _dynTypes = TypeInferenceManager.getInstance().getDynamicTypes((AnyType) argType, EolPackage.eINSTANCE.getCollectionType()); if (_dynTypes.size() > 0) { boolean found = false; for(Type _t: _dynTypes) { CollectionType __argType = (CollectionType) _t; argContentType = __argType.getContentType(); //if target content type is any, add to dynamic types if (TypeUtil.getInstance().isInstanceofAnyType(contentType)) { AnyType _contentType = (AnyType) contentType; if (TypeUtil.getInstance().isInstanceofAnyType(argContentType)) { AnyType _argContentType = (AnyType) argContentType; _contentType.getDynamicTypes().addAll(_argContentType.getDynamicTypes()); } else { _contentType.getDynamicTypes().add(argContentType); } found = true; } else { if (TypeUtil.getInstance().isTypeEqualOrGeneric(argContentType, contentType)) { found = true; } } } if (!found) { } } else { } } else { } } else { } } LogBook.getInstance().addWarning(argType, IMessage_TypeResolution.EXPRESSION_MAY_NOT_BE_COLLECTION_TYPE); result.setReturnType(_targetType); return result; } } else { LogBook.getInstance().addError(target, IMessage_TypeResolution.EXPRESSION_SHOULD_BE_COLLECTION_TYPE); Type targetTypeCopy = EcoreUtil.copy(targetType); result.setReturnType(targetTypeCopy); } } return result; } }
epl-1.0
openhab/openhab
bundles/binding/org.openhab.binding.rfxcom/src/main/java/org/openhab/binding/rfxcom/internal/messages/RFXComTemperatureMessage.java
6221
/** * Copyright (c) 2010-2020 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.rfxcom.internal.messages; import java.util.Arrays; import java.util.List; import javax.xml.bind.DatatypeConverter; import org.openhab.binding.rfxcom.RFXComValueSelector; import org.openhab.binding.rfxcom.internal.RFXComException; import org.openhab.core.library.items.NumberItem; import org.openhab.core.library.items.StringItem; import org.openhab.core.library.types.DecimalType; import org.openhab.core.library.types.StringType; import org.openhab.core.types.State; import org.openhab.core.types.Type; import org.openhab.core.types.UnDefType; /** * RFXCOM data class for temperature and humidity message. * * @author Pauli Anttila * @since 1.2.0 */ public class RFXComTemperatureMessage extends RFXComBaseMessage { public enum SubType { THR128_138_THC138(1), THC238_268_THN122_132_THWR288_THRN122_AW129_131(2), THWR800(3), RTHN318(4), LACROSSE_TX2_TX3_TX4_TX17(5), TS15C(6), VIKING_02811(7), LACROSSE_WS2300(8), RUBICSON(9), TFA_30_3133(10), WT0122(11), UNKNOWN(255); private final int subType; SubType(int subType) { this.subType = subType; } SubType(byte subType) { this.subType = subType; } public byte toByte() { return (byte) subType; } public static SubType fromByte(int input) { for (SubType c : SubType.values()) { if (c.subType == input) { return c; } } return SubType.UNKNOWN; } } private final static List<RFXComValueSelector> supportedValueSelectors = Arrays.asList(RFXComValueSelector.RAW_DATA, RFXComValueSelector.SIGNAL_LEVEL, RFXComValueSelector.BATTERY_LEVEL, RFXComValueSelector.TEMPERATURE); public SubType subType = SubType.UNKNOWN; public int sensorId = 0; public double temperature = 0; public byte signalLevel = 0; public byte batteryLevel = 0; public RFXComTemperatureMessage() { packetType = PacketType.TEMPERATURE; } public RFXComTemperatureMessage(byte[] data) { encodeMessage(data); } @Override public String toString() { String str = ""; str += super.toString(); str += "\n - Sub type = " + subType; str += "\n - Id = " + sensorId; str += "\n - Temperature = " + temperature; str += "\n - Signal level = " + signalLevel; str += "\n - Battery level = " + batteryLevel; return str; } @Override public void encodeMessage(byte[] data) { super.encodeMessage(data); subType = SubType.fromByte(super.subType); sensorId = (data[4] & 0xFF) << 8 | (data[5] & 0xFF); temperature = (short) ((data[6] & 0x7F) << 8 | (data[7] & 0xFF)) * 0.1; if ((data[6] & 0x80) != 0) { temperature = -temperature; } signalLevel = (byte) ((data[8] & 0xF0) >> 4); batteryLevel = (byte) (data[8] & 0x0F); } @Override public byte[] decodeMessage() { byte[] data = new byte[9]; data[0] = 0x08; data[1] = RFXComBaseMessage.PacketType.TEMPERATURE.toByte(); data[2] = subType.toByte(); data[3] = seqNbr; data[4] = (byte) ((sensorId & 0xFF00) >> 8); data[5] = (byte) (sensorId & 0x00FF); short temp = (short) Math.abs(temperature * 10); data[6] = (byte) ((temp >> 8) & 0xFF); data[7] = (byte) (temp & 0xFF); if (temperature < 0) { data[6] |= 0x80; } data[8] = (byte) (((signalLevel & 0x0F) << 4) | (batteryLevel & 0x0F)); return data; } @Override public String generateDeviceId() { return String.valueOf(sensorId); } @Override public State convertToState(RFXComValueSelector valueSelector) throws RFXComException { org.openhab.core.types.State state = UnDefType.UNDEF; if (valueSelector.getItemClass() == NumberItem.class) { if (valueSelector == RFXComValueSelector.SIGNAL_LEVEL) { state = new DecimalType(signalLevel); } else if (valueSelector == RFXComValueSelector.BATTERY_LEVEL) { state = new DecimalType(batteryLevel); } else if (valueSelector == RFXComValueSelector.TEMPERATURE) { state = new DecimalType(temperature); } else { throw new RFXComException("Can't convert " + valueSelector + " to NumberItem"); } } else if (valueSelector.getItemClass() == StringItem.class) { if (valueSelector == RFXComValueSelector.RAW_DATA) { state = new StringType(DatatypeConverter.printHexBinary(rawMessage)); } else { throw new RFXComException("Can't convert " + valueSelector + " to StringItem"); } } else { throw new RFXComException("Can't convert " + valueSelector + " to " + valueSelector.getItemClass()); } return state; } @Override public void convertFromState(RFXComValueSelector valueSelector, String id, Object subType, Type type, byte seqNumber) throws RFXComException { throw new RFXComException("Not supported"); } @Override public Object convertSubType(String subType) throws RFXComException { for (SubType s : SubType.values()) { if (s.toString().equals(subType)) { return s; } } throw new RFXComException("Unknown sub type " + subType); } @Override public List<RFXComValueSelector> getSupportedValueSelectors() throws RFXComException { return supportedValueSelectors; } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.javaee.dd.common/src/com/ibm/ws/javaee/dd/common/JMSConnectionFactory.java
2205
/******************************************************************************* * Copyright (c) 2014 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 *******************************************************************************/ package com.ibm.ws.javaee.dd.common; import java.util.List; /** * Represents &lt;jms-connection-factory>. */ public interface JMSConnectionFactory extends JNDIEnvironmentRef, Describable { /** * @return &lt;interface-name>, or null if unspecified */ String getInterfaceNameValue(); /** * @return &lt;class-name>, or null if unspecified */ String getClassNameValue(); /** * @return &lt;resource-adapter>, or null if unspecified */ String getResourceAdapter(); /** * @return &lt;user>, or null if unspecified */ String getUser(); /** * @return &lt;password>, or null if unspecified */ String getPassword(); /** * @return &lt;client-id>, or null if unspecified */ String getClientId(); /** * @return &lt;property> as a read-only list */ List<Property> getProperties(); /** * @return true if &lt;transactional> is specified * @see #isTransactional */ boolean isSetTransactional(); /** * @return &lt;transactional> if specified * @see #isSetTransactional */ boolean isTransactional(); /** * @return true if &lt;max-pool-size> is specified * @see #getMaxPoolSize */ boolean isSetMaxPoolSize(); /** * @return &lt;max-pool-size> if specified * @see #isSetMaxPoolSize */ int getMaxPoolSize(); /** * @return true if &lt;min-pool-size> is specified * @see #getMinPoolSize */ boolean isSetMinPoolSize(); /** * @return &lt;min-pool-size> if specified * @see #isSetMinPoolSize */ int getMinPoolSize(); }
epl-1.0
rlpark/rlpark
rlpark.plugin.rltoys/jvsrc/rlpark/plugin/rltoys/experiments/scheduling/pools/MemoryJobPool.java
712
package rlpark.plugin.rltoys.experiments.scheduling.pools; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import rlpark.plugin.rltoys.experiments.scheduling.interfaces.JobDoneEvent; import zephyr.plugin.core.api.signals.Listener; public class MemoryJobPool extends AbstractJobPool { protected final List<Runnable> jobs = new ArrayList<Runnable>(); public MemoryJobPool(JobPoolListener onAllJobDone, Listener<JobDoneEvent> onJobDone) { super(onAllJobDone, onJobDone); } @Override public void add(Runnable job) { checkHasBeenSubmitted(); jobs.add(job); } @Override protected Iterator<Runnable> createIterator() { return jobs.iterator(); } }
epl-1.0
marinmitev/smarthome
bundles/config/org.eclipse.smarthome.config.dispatch/src/main/java/org/eclipse/smarthome/config/dispatch/internal/ConfigDispatcher.java
12292
/** * Copyright (c) 2014-2015 openHAB UG (haftungsbeschraenkt) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.smarthome.config.dispatch.internal; import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE; import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE; import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.nio.file.Path; import java.nio.file.WatchEvent; import java.nio.file.WatchEvent.Kind; import java.nio.file.WatchService; import java.util.Dictionary; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Properties; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.StringUtils; import org.eclipse.smarthome.config.core.ConfigConstants; import org.eclipse.smarthome.core.service.AbstractWatchQueueReader; import org.eclipse.smarthome.core.service.AbstractWatchService; import org.osgi.service.cm.Configuration; import org.osgi.service.cm.ConfigurationAdmin; import org.osgi.service.cm.ManagedService; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class provides a mean to read any kind of configuration data from * config folder files and dispatch it to the different bundles using the {@link ConfigurationAdmin} service. * * <p> * The name of the configuration folder can be provided as a program argument "smarthome.configdir" (default is "conf"). * Configurations for OSGi services are kept in a subfolder that can be provided as a program argument * "smarthome.servicedir" (default is "services"). Any file in this folder with the extension .cfg will be processed. * </p> * * <p> * The format of the configuration file is similar to a standard property file, with the exception that the property * name can be prefixed by the service pid of the {@link ManagedService}: * </p> * <p> * &lt;service-pid&gt;:&lt;property&gt;=&lt;value&gt; * </p> * <p> * In case the pid does not contain any ".", the default service pid namespace is prefixed, which can be defined by the * program argument "smarthome.servicepid" (default is "org.eclipse.smarthome"). * </p> * <p> * If no pid is defined in the property line, the default pid namespace will be used together with the filename. E.g. if * you have a file "security.cfg", the pid that will be used is "org.eclipse.smarthome.security". * </p> * <p> * Last but not least, a pid can be defined in the first line of a cfg file by prefixing it with "pid:", e.g. * "pid: com.acme.smarthome.security". * * @author Kai Kreuzer - Initial contribution and API */ public class ConfigDispatcher extends AbstractWatchService { /** The program argument name for setting the service config directory path */ final static public String SERVICEDIR_PROG_ARGUMENT = "smarthome.servicedir"; /** The program argument name for setting the service pid namespace */ final static public String SERVICEPID_PROG_ARGUMENT = "smarthome.servicepid"; /** * The program argument name for setting the default services config file * name */ final static public String SERVICECFG_PROG_ARGUMENT = "smarthome.servicecfg"; /** The default folder name of the configuration folder of services */ final static public String SERVICES_FOLDER = "services"; /** The default namespace for service pids */ final static public String SERVICE_PID_NAMESPACE = "org.eclipse.smarthome"; /** The default services configuration filename */ final static public String SERVICE_CFG_FILE = "smarthome.cfg"; private static final String PID_MARKER = "pid:"; private final Logger logger = LoggerFactory.getLogger(ConfigDispatcher.class); private ConfigurationAdmin configAdmin; @Override public void activate() { super.activate(); readDefaultConfig(); readConfigs(); } @Override public void deactivate() { super.deactivate(); } protected void setConfigurationAdmin(ConfigurationAdmin configAdmin) { this.configAdmin = configAdmin; } protected void unsetConfigurationAdmin(ConfigurationAdmin configAdmin) { this.configAdmin = null; } /* * (non-Javadoc) * * @see * org.eclipse.smarthome.core.service.AbstractWatchService#getSourcePath() */ @Override protected String getSourcePath() { String progArg = System.getProperty(SERVICEDIR_PROG_ARGUMENT); if (progArg != null) { return ConfigConstants.getConfigFolder() + File.separator + progArg; } else { return ConfigConstants.getConfigFolder() + File.separator + SERVICES_FOLDER; } } /* * (non-Javadoc) * * @see * org.eclipse.smarthome.core.service.AbstractWatchService#watchSubDirectories * () */ @Override protected boolean watchSubDirectories() { return false; } /* * (non-Javadoc) * * @see * org.eclipse.smarthome.core.service.AbstractWatchService#registerDirecotry * (java.nio.file.Path) */ @Override protected void registerDirectory(Path subDir) throws IOException { subDir.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); } /* * (non-Javadoc) * * @see * org.eclipse.smarthome.core.service.AbstractWatchService#buildWatchQueueReader * (java.nio.file.WatchService, java.nio.file.Path) */ @Override protected AbstractWatchQueueReader buildWatchQueueReader(WatchService watchService, Path toWatch) { return new WatchQueueReader(watchService, toWatch); } private String getDefaultServiceConfigFile() { String progArg = System.getProperty(SERVICECFG_PROG_ARGUMENT); if (progArg != null) { return progArg; } else { return ConfigConstants.getConfigFolder() + File.separator + SERVICE_CFG_FILE; } } private void readDefaultConfig() { File defaultCfg = new File(getDefaultServiceConfigFile()); try { processConfigFile(defaultCfg); } catch (IOException e) { logger.warn("Could not process default config file '{}': {}", getDefaultServiceConfigFile(), e); } } private void readConfigs() { File dir = new File(getSourcePath()); if (dir.exists()) { File[] files = dir.listFiles(); for (File file : files) { try { processConfigFile(file); } catch (IOException e) { logger.warn("Could not process config file '{}': {}", file.getName(), e); } } } else { logger.debug("Configuration folder '{}' does not exist.", dir.toString()); } } private static String getServicePidNamespace() { String progArg = System.getProperty(SERVICEPID_PROG_ARGUMENT); if (progArg != null) { return progArg; } else { return SERVICE_PID_NAMESPACE; } } @SuppressWarnings({ "unchecked", "rawtypes" }) private void processConfigFile(File configFile) throws IOException, FileNotFoundException { if (configFile.isDirectory() || !configFile.getName().endsWith(".cfg")) { logger.debug("Ignoring file '{}'", configFile.getName()); return; } logger.debug("Processing config file '{}'", configFile.getName()); // we need to remember which configuration needs to be updated // because values have changed. Map<Configuration, Dictionary> configsToUpdate = new HashMap<Configuration, Dictionary>(); // also cache the already retrieved configurations for each pid Map<Configuration, Dictionary> configMap = new HashMap<Configuration, Dictionary>(); String pid; String filenameWithoutExt = StringUtils.substringBeforeLast(configFile.getName(), "."); if (filenameWithoutExt.contains(".")) { // it is a fully qualified namespace pid = filenameWithoutExt; } else { pid = getServicePidNamespace() + "." + filenameWithoutExt; } // configuration file contains a PID Marker List<String> lines = IOUtils.readLines(new FileInputStream(configFile)); if (lines.size() > 0 && lines.get(0).startsWith(PID_MARKER)) { pid = lines.get(0).substring(PID_MARKER.length()).trim(); } for (String line : lines) { String[] contents = parseLine(configFile.getPath(), line); // no valid configuration line, so continue if (contents == null) { continue; } if (contents[0] != null) { pid = contents[0]; // PID is not fully qualified, so prefix with namespace if (!pid.contains(".")) { pid = getServicePidNamespace() + "." + pid; } } String property = contents[1]; String value = contents[2]; Configuration configuration = configAdmin.getConfiguration(pid, null); if (configuration != null) { Dictionary configProperties = configMap.get(configuration); if (configProperties == null) { configProperties = configuration.getProperties() != null ? configuration.getProperties() : new Properties(); configMap.put(configuration, configProperties); } if (!value.equals(configProperties.get(property))) { configProperties.put(property, value); configsToUpdate.put(configuration, configProperties); } } } for (Entry<Configuration, Dictionary> entry : configsToUpdate.entrySet()) { entry.getKey().update(entry.getValue()); } } private String[] parseLine(final String filePath, final String line) { String trimmedLine = line.trim(); if (trimmedLine.startsWith("#") || trimmedLine.isEmpty()) { return null; } String pid = null; // no override of the pid String key = StringUtils.substringBefore(trimmedLine, "="); if (key.contains(":")) { pid = StringUtils.substringBefore(key, ":"); trimmedLine = trimmedLine.substring(pid.length() + 1); pid = pid.trim(); } if (!trimmedLine.isEmpty() && trimmedLine.substring(1).contains("=")) { String property = StringUtils.substringBefore(trimmedLine, "="); String value = trimmedLine.substring(property.length() + 1); return new String[] { pid, property.trim(), value.trim() }; } else { logger.warn("Could not parse line '{}'", line); return null; } } private class WatchQueueReader extends AbstractWatchQueueReader { public WatchQueueReader(WatchService watchService, Path dir) { super(watchService, dir); } @Override protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) { if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) { try { processConfigFile(new File(dir.toAbsolutePath() + File.separator + path.toString())); } catch (IOException e) { logger.warn("Could not process config file '{}': {}", path, e); } } } } }
epl-1.0
MikeJMajor/openhab2-addons-dlinksmarthome
bundles/org.openhab.binding.miio/src/main/java/org/openhab/binding/miio/internal/basic/StateDescriptionDTO.java
2417
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.miio.internal.basic; import java.math.BigDecimal; import java.util.List; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import com.google.gson.annotations.Expose; import com.google.gson.annotations.SerializedName; /** * Mapping properties from json for state descriptions * * @author Marcel Verpaalen - Initial contribution */ @NonNullByDefault public class StateDescriptionDTO { @SerializedName("minimum") @Expose @Nullable private BigDecimal minimum; @SerializedName("maximum") @Expose @Nullable private BigDecimal maximum; @SerializedName("step") @Expose @Nullable private BigDecimal step; @SerializedName("pattern") @Expose @Nullable private String pattern; @SerializedName("readOnly") @Expose @Nullable private Boolean readOnly; @SerializedName("options") @Expose @Nullable public List<OptionsValueListDTO> options = null; @Nullable public BigDecimal getMinimum() { return minimum; } public void setMinimum(BigDecimal minimum) { this.minimum = minimum; } @Nullable public BigDecimal getMaximum() { return maximum; } public void setMaximum(BigDecimal maximum) { this.maximum = maximum; } @Nullable public BigDecimal getStep() { return step; } public void setStep(BigDecimal step) { this.step = step; } @Nullable public String getPattern() { return pattern; } public void setPattern(String pattern) { this.pattern = pattern; } @Nullable public Boolean getReadOnly() { return readOnly; } public void setReadOnly(Boolean readOnly) { this.readOnly = readOnly; } @Nullable public List<OptionsValueListDTO> getOptions() { return options; } public void setOptions(List<OptionsValueListDTO> options) { this.options = options; } }
epl-1.0
ControlSystemStudio/cs-studio
thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/core/src/main/java/org/hibernate/tool/hbm2ddl/SchemaExportTask.java
7027
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Middleware LLC. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, 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 Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA * */ package org.hibernate.tool.hbm2ddl; import org.hibernate.HibernateException; import org.hibernate.cfg.Configuration; import org.hibernate.cfg.NamingStrategy; import org.hibernate.util.ArrayHelper; import org.hibernate.util.ReflectHelper; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.DirectoryScanner; import org.apache.tools.ant.Project; import org.apache.tools.ant.taskdefs.MatchingTask; import org.apache.tools.ant.types.FileSet; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Properties; /** * An Ant task for <tt>SchemaExport</tt>. * * <pre> * &lt;taskdef name="schemaexport" * classname="org.hibernate.tool.hbm2ddl.SchemaExportTask" * classpathref="class.path"/&gt; * * &lt;schemaexport * properties="${build.classes.dir}/hibernate.properties" * quiet="no" * text="no" * drop="no" * delimiter=";" * output="${build.dir}/schema-export.sql"&gt; * &lt;fileset dir="${build.classes.dir}"&gt; * &lt;include name="*.hbm.xml"/&gt; * &lt;/fileset&gt; * &lt;/schemaexport&gt; * </pre> * * @see SchemaExport * @author Rong C Ou */ public class SchemaExportTask extends MatchingTask { private List fileSets = new LinkedList(); private File propertiesFile = null; private File configurationFile = null; private File outputFile = null; private boolean quiet = false; private boolean text = false; private boolean drop = false; private boolean create = false; private boolean haltOnError = false; private String delimiter = null; private String namingStrategy = null; public void addFileset(FileSet set) { fileSets.add(set); } /** * Set a properties file * @param propertiesFile the properties file name */ public void setProperties(File propertiesFile) { if ( !propertiesFile.exists() ) { throw new BuildException("Properties file: " + propertiesFile + " does not exist."); } log("Using properties file " + propertiesFile, Project.MSG_DEBUG); this.propertiesFile = propertiesFile; } /** * Set a <literal>.cfg.xml</literal> file, which will be * loaded as a resource, from the classpath * @param configurationFile the path to the resource */ public void setConfig(File configurationFile) { this.configurationFile = configurationFile; } /** * Enable "quiet" mode. The schema will not be * written to standard out. * @param quiet true to enable quiet mode */ public void setQuiet(boolean quiet) { this.quiet = quiet; } /** * Enable "text-only" mode. The schema will not * be exported to the database. * @param text true to enable text-only mode */ public void setText(boolean text) { this.text = text; } /** * Enable "drop" mode. Database objects will be * dropped but not recreated. * @param drop true to enable drop mode */ public void setDrop(boolean drop) { this.drop = drop; } /** * Enable "create" mode. Database objects will be * created but not first dropped. * @param create true to enable create mode */ public void setCreate(boolean create) { this.create = create; } /** * Set the end of statement delimiter for the generated script * @param delimiter the delimiter */ public void setDelimiter(String delimiter) { this.delimiter = delimiter; } /** * Set the script output file * @param outputFile the file name */ public void setOutput(File outputFile) { this.outputFile = outputFile; } /** * Execute the task */ public void execute() throws BuildException { try { getSchemaExport( getConfiguration() ).execute(!quiet, !text, drop, create); } catch (HibernateException e) { throw new BuildException("Schema text failed: " + e.getMessage(), e); } catch (FileNotFoundException e) { throw new BuildException("File not found: " + e.getMessage(), e); } catch (IOException e) { throw new BuildException("IOException : " + e.getMessage(), e); } catch (Exception e) { throw new BuildException(e); } } private String[] getFiles() { List files = new LinkedList(); for ( Iterator i = fileSets.iterator(); i.hasNext(); ) { FileSet fs = (FileSet) i.next(); DirectoryScanner ds = fs.getDirectoryScanner( getProject() ); String[] dsFiles = ds.getIncludedFiles(); for (int j = 0; j < dsFiles.length; j++) { File f = new File(dsFiles[j]); if ( !f.isFile() ) { f = new File( ds.getBasedir(), dsFiles[j] ); } files.add( f.getAbsolutePath() ); } } return ArrayHelper.toStringArray(files); } private Configuration getConfiguration() throws Exception { Configuration cfg = new Configuration(); if (namingStrategy!=null) { cfg.setNamingStrategy( (NamingStrategy) ReflectHelper.classForName(namingStrategy).newInstance() ); } if (configurationFile != null) { cfg.configure( configurationFile ); } String[] files = getFiles(); for (int i = 0; i < files.length; i++) { String filename = files[i]; if ( filename.endsWith(".jar") ) { cfg.addJar( new File(filename) ); } else { cfg.addFile(filename); } } return cfg; } private SchemaExport getSchemaExport(Configuration cfg) throws HibernateException, IOException { Properties properties = new Properties(); properties.putAll( cfg.getProperties() ); if (propertiesFile == null) { properties.putAll( getProject().getProperties() ); } else { properties.load( new FileInputStream(propertiesFile) ); } cfg.setProperties(properties); return new SchemaExport(cfg) .setHaltOnError(haltOnError) .setOutputFile( outputFile.getPath() ) .setDelimiter(delimiter); } public void setNamingStrategy(String namingStrategy) { this.namingStrategy = namingStrategy; } public void setHaltonerror(boolean haltOnError) { this.haltOnError = haltOnError; } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.cdi.visibility_fat/fat/src/vistest/appClientLib/AppClientLibTargetBean.java
796
/******************************************************************************* * Copyright (c) 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 *******************************************************************************/ package vistest.appClientLib; import javax.enterprise.context.ApplicationScoped; import vistest.framework.TargetBean; import vistest.qualifiers.InAppClientLib; @ApplicationScoped @InAppClientLib public class AppClientLibTargetBean implements TargetBean { }
epl-1.0
dragon66/pixymeta-android
src/pixy/meta/adobe/UserMask.java
2159
/** * Copyright (C) 2014-2019 by Wen Yu. * 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 * * Any modifications to this file must keep this entire header intact. * * Change History - most recent changes go on top of previous changes * * UserMask.java - Adobe Photoshop Document Data Block LMsk * * Who Date Description * ==== ========= ================================================= * WY 28Jul2015 Initial creation */ package pixy.meta.adobe; import java.util.Arrays; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import pixy.io.ReadStrategy; public class UserMask extends DDBEntry { private int colorSpaceId; private int[] colors = new int[4]; private int opacity; private int flag; // Obtain a logger instance private static final Logger LOGGER = LoggerFactory.getLogger(UserMask.class); public UserMask(int size, byte[] data, ReadStrategy readStrategy) { super(DataBlockType.LMsk, size, data, readStrategy); read(); } public int[] getColors() { return colors.clone(); } public int getOpacity() { return opacity; } public int getFlag() { return flag; } public int getColorSpace() { return colorSpaceId; } public ColorSpaceID getColorSpaceID() { return ColorSpaceID.fromInt(colorSpaceId); } public void print() { super.print(); LOGGER.info("Color space: {}", getColorSpaceID()); LOGGER.info("Color values: {}", Arrays.toString(colors)); LOGGER.info("Opacity: {}", opacity); LOGGER.info("Flag: {}", flag); } private void read() { int i = 0; colorSpaceId = readStrategy.readShort(data, i); i += 2; colors[0] = readStrategy.readUnsignedShort(data, i); i += 2; colors[1] = readStrategy.readUnsignedShort(data, i); i += 2; colors[2] = readStrategy.readUnsignedShort(data, i); i += 2; colors[3] = readStrategy.readUnsignedShort(data, i); i += 2; opacity = readStrategy.readShort(data, i); i += 2; flag = data[i]&0xff; // 128 } }
epl-1.0
cdietrich/xtext-languageserver-example
org.xtext.example.mydsl/src/org/xtext/example/mydsl/scoping/MyDslScopeProvider.java
329
/* * generated by Xtext 2.23.0 */ package org.xtext.example.mydsl.scoping; /** * This class contains custom scoping description. * * See https://www.eclipse.org/Xtext/documentation/303_runtime_concepts.html#scoping * on how and when to use it. */ public class MyDslScopeProvider extends AbstractMyDslScopeProvider { }
epl-1.0
acshea/edgware
fabric.lib/src/fabric/client/services/IClientNotificationServices.java
1305
/* * (C) Copyright IBM Corp. 2010 * * LICENSE: Eclipse Public License v1.0 * http://www.eclipse.org/legal/epl-v10.html */ package fabric.client.services; /** * Interface for classes providing Fabric notification services to clients. */ public interface IClientNotificationServices { /** Copyright notice. */ public static final String copyrightNotice = "(C) Copyright IBM Corp. 2010"; /* * Interface constants */ /* * Interface methods */ /** * Registers a client handler Fabric notification messages received for the specified correlation ID. * * @param correlationID * the correlation ID. * * @param handler * the notification handler. * * @return the previously registered handler, or <code>null</code> if there was not one. */ public IClientNotificationHandler registerNotificationHandler(String correlationID, IClientNotificationHandler handler); /** * De-registers a client handler to handle Fabric notification messages received for the specified correlation ID. * * @param correlationID * the correlation ID. * * @return the previously registered handler, or <code>null</code> if there was not one. */ public IClientNotificationHandler deregisterNotificationHandler(String correlationID); }
epl-1.0
MikeJMajor/openhab2-addons-dlinksmarthome
bundles/org.openhab.binding.knx/src/main/java/org/openhab/binding/knx/internal/client/DeviceInfoClient.java
1290
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.knx.internal.client; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.jdt.annotation.Nullable; import tuwien.auto.calimero.IndividualAddress; /** * Client to retrieve further information about KNX devices. * * @author Simon Kaufmann - initial contribution and API * */ @NonNullByDefault public interface DeviceInfoClient { byte @Nullable [] readDeviceDescription(IndividualAddress address, int descType, boolean authenticate, long timeout); byte @Nullable [] readDeviceMemory(IndividualAddress address, int startAddress, int bytes, boolean authenticate, long timeout); byte @Nullable [] readDeviceProperties(IndividualAddress address, final int interfaceObjectIndex, final int propertyId, final int start, final int elements, boolean authenticate, long timeout); public boolean isConnected(); }
epl-1.0
zsmartsystems/com.zsmartsystems.zigbee
com.zsmartsystems.zigbee/src/main/java/com/zsmartsystems/zigbee/transaction/package-info.java
1478
/** * This package supports ZigBee transactions within the framework. * <p> * The diagram below shows the general flow from the application sending a transaction to the * {@link ZigBeeTransactionManager}, into the {@link ZigBeeTransactionQueue}, and the interaction with the * {@link ZigBeeTransportTransmit} and {@link ZigBeeTransportRecieve} classes. * <p> * <img src="./doc-files/ZigBeeTransactionOverview.png" width="100%"> * <p> * The {@link ZigBeeTransactionManager} manages the overall transaction process. It acts as the central configuration * interface for configuring the transaction subsystem, and handles sending and receiving of commands. It gets * transactions from the different queues, selecting a queue randomly, and enforces an overall maximum number of * transactions that can be outstanding. * <p> * The {@link ZigBeeTransactionQueue} handles the transactions for a single queue. A queue is established for each node, * along with broadcasts and multicast message queues. The {@link ZigBeeTransactionQueue} enforces the maximum number of * outstanding messages for this queue, and ensures a minimum delay between each subsequent transaction release. The * {@link ZigBeeTransactionQueue} is notified of all completed transactions so it can add failed transactions back in * the queue if retries are required. * <p> * The {@link ZigBeeTransactionProfile} is used to configure the queues. */ package com.zsmartsystems.zigbee.transaction;
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.org.apache.cxf.cxf.api.2.6.2/src/org/apache/cxf/wsdl/TDefinitions.java
9651
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.1-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2019.06.20 at 10:40:54 AM CDT // package org.apache.cxf.wsdl; import java.util.ArrayList; import java.util.List; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlElementRefs; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.CollapsedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.w3c.dom.Element; import com.ibm.websphere.ras.annotation.Trivial; /** * <p>Java class for tDefinitions complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="tDefinitions"> * &lt;complexContent> * &lt;extension base="{http://schemas.xmlsoap.org/wsdl/}tExtensibleDocumented"> * &lt;sequence minOccurs="0"> * &lt;group ref="{http://schemas.xmlsoap.org/wsdl/}anyTopLevelOptionalElement"/> * &lt;choice maxOccurs="unbounded" minOccurs="0"> * &lt;group ref="{http://schemas.xmlsoap.org/wsdl/}anyTopLevelOptionalElement"/> * &lt;any processContents='lax' namespace='##other'/> * &lt;/choice> * &lt;/sequence> * &lt;attribute name="targetNamespace" type="{http://www.w3.org/2001/XMLSchema}anyURI" /> * &lt;attribute name="name" type="{http://www.w3.org/2001/XMLSchema}NCName" /> * &lt;anyAttribute processContents='lax' namespace='##other'/> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "tDefinitions", propOrder = { "_import", "types", "message", "portType", "binding", "service", "importOrTypesOrMessage" }) @Trivial public class TDefinitions extends TExtensibleDocumented { @XmlElement(name = "import") protected TImport _import; protected TTypes types; protected TMessage message; protected TPortType portType; protected TBinding binding; protected TService service; @XmlElementRefs({ @XmlElementRef(name = "service", namespace = "http://schemas.xmlsoap.org/wsdl/", type = JAXBElement.class), @XmlElementRef(name = "types", namespace = "http://schemas.xmlsoap.org/wsdl/", type = JAXBElement.class), @XmlElementRef(name = "message", namespace = "http://schemas.xmlsoap.org/wsdl/", type = JAXBElement.class), @XmlElementRef(name = "binding", namespace = "http://schemas.xmlsoap.org/wsdl/", type = JAXBElement.class), @XmlElementRef(name = "import", namespace = "http://schemas.xmlsoap.org/wsdl/", type = JAXBElement.class), @XmlElementRef(name = "portType", namespace = "http://schemas.xmlsoap.org/wsdl/", type = JAXBElement.class) }) @XmlAnyElement(lax = true) protected List<Object> importOrTypesOrMessage; @XmlAttribute(name = "targetNamespace") @XmlSchemaType(name = "anyURI") protected String targetNamespace; @XmlAttribute(name = "name") @XmlJavaTypeAdapter(CollapsedStringAdapter.class) @XmlSchemaType(name = "NCName") protected String name; /** * Gets the value of the import property. * * @return * possible object is * {@link TImport } * */ public TImport getImport() { return _import; } /** * Sets the value of the import property. * * @param value * allowed object is * {@link TImport } * */ public void setImport(TImport value) { this._import = value; } public boolean isSetImport() { return (this._import!= null); } /** * Gets the value of the types property. * * @return * possible object is * {@link TTypes } * */ public TTypes getTypes() { return types; } /** * Sets the value of the types property. * * @param value * allowed object is * {@link TTypes } * */ public void setTypes(TTypes value) { this.types = value; } public boolean isSetTypes() { return (this.types!= null); } /** * Gets the value of the message property. * * @return * possible object is * {@link TMessage } * */ public TMessage getMessage() { return message; } /** * Sets the value of the message property. * * @param value * allowed object is * {@link TMessage } * */ public void setMessage(TMessage value) { this.message = value; } public boolean isSetMessage() { return (this.message!= null); } /** * Gets the value of the portType property. * * @return * possible object is * {@link TPortType } * */ public TPortType getPortType() { return portType; } /** * Sets the value of the portType property. * * @param value * allowed object is * {@link TPortType } * */ public void setPortType(TPortType value) { this.portType = value; } public boolean isSetPortType() { return (this.portType!= null); } /** * Gets the value of the binding property. * * @return * possible object is * {@link TBinding } * */ public TBinding getBinding() { return binding; } /** * Sets the value of the binding property. * * @param value * allowed object is * {@link TBinding } * */ public void setBinding(TBinding value) { this.binding = value; } public boolean isSetBinding() { return (this.binding!= null); } /** * Gets the value of the service property. * * @return * possible object is * {@link TService } * */ public TService getService() { return service; } /** * Sets the value of the service property. * * @param value * allowed object is * {@link TService } * */ public void setService(TService value) { this.service = value; } public boolean isSetService() { return (this.service!= null); } /** * Gets the value of the importOrTypesOrMessage property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the importOrTypesOrMessage property. * * <p> * For example, to add a new item, do as follows: * <pre> * getImportOrTypesOrMessage().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link JAXBElement }{@code <}{@link TService }{@code >} * {@link Object } * {@link JAXBElement }{@code <}{@link TTypes }{@code >} * {@link JAXBElement }{@code <}{@link TMessage }{@code >} * {@link JAXBElement }{@code <}{@link TBinding }{@code >} * {@link Element } * {@link JAXBElement }{@code <}{@link TImport }{@code >} * {@link JAXBElement }{@code <}{@link TPortType }{@code >} * * */ public List<Object> getImportOrTypesOrMessage() { if (importOrTypesOrMessage == null) { importOrTypesOrMessage = new ArrayList<Object>(); } return this.importOrTypesOrMessage; } public boolean isSetImportOrTypesOrMessage() { return ((this.importOrTypesOrMessage!= null)&&(!this.importOrTypesOrMessage.isEmpty())); } public void unsetImportOrTypesOrMessage() { this.importOrTypesOrMessage = null; } /** * Gets the value of the targetNamespace property. * * @return * possible object is * {@link String } * */ public String getTargetNamespace() { return targetNamespace; } /** * Sets the value of the targetNamespace property. * * @param value * allowed object is * {@link String } * */ public void setTargetNamespace(String value) { this.targetNamespace = value; } public boolean isSetTargetNamespace() { return (this.targetNamespace!= null); } /** * Gets the value of the name property. * * @return * possible object is * {@link String } * */ public String getName() { return name; } /** * Sets the value of the name property. * * @param value * allowed object is * {@link String } * */ public void setName(String value) { this.name = value; } public boolean isSetName() { return (this.name!= null); } }
epl-1.0
ollie314/che-plugins
plugin-docker/che-plugin-docker-machine/src/main/java/org/eclipse/che/plugin/docker/machine/DockerInstanceProvider.java
23586
/******************************************************************************* * Copyright (c) 2012-2016 Codenvy, S.A. * 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: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.plugin.docker.machine; import com.google.common.base.Strings; import com.google.common.collect.Maps; import com.google.common.collect.ObjectArrays; import com.google.common.collect.Sets; import com.google.inject.Inject; import org.eclipse.che.api.core.NotFoundException; import org.eclipse.che.api.core.model.machine.MachineState; import org.eclipse.che.api.core.model.machine.Recipe; import org.eclipse.che.api.core.util.FileCleaner; import org.eclipse.che.api.core.util.LineConsumer; import org.eclipse.che.api.core.util.SystemInfo; import org.eclipse.che.api.machine.server.exception.InvalidRecipeException; import org.eclipse.che.api.machine.server.exception.MachineException; import org.eclipse.che.api.machine.server.exception.SnapshotException; import org.eclipse.che.api.machine.server.spi.Instance; import org.eclipse.che.api.machine.server.spi.InstanceKey; import org.eclipse.che.api.machine.server.spi.InstanceProvider; import org.eclipse.che.commons.annotation.Nullable; import org.eclipse.che.commons.env.EnvironmentContext; import org.eclipse.che.commons.lang.IoUtil; import org.eclipse.che.commons.lang.NameGenerator; import org.eclipse.che.plugin.docker.client.DockerConnector; import org.eclipse.che.plugin.docker.client.DockerConnectorConfiguration; import org.eclipse.che.plugin.docker.client.DockerFileException; import org.eclipse.che.plugin.docker.client.Dockerfile; import org.eclipse.che.plugin.docker.client.DockerfileParser; import org.eclipse.che.plugin.docker.client.ProgressLineFormatterImpl; import org.eclipse.che.plugin.docker.client.ProgressMonitor; import org.eclipse.che.plugin.docker.client.json.ContainerConfig; import org.eclipse.che.plugin.docker.client.json.HostConfig; import org.eclipse.che.plugin.docker.machine.node.DockerNode; import org.eclipse.che.plugin.docker.machine.node.WorkspaceFolderPathProvider; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Named; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; import java.nio.file.Files; import java.util.Collections; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.stream.Collectors; import static com.google.common.base.Strings.isNullOrEmpty; /** * Docker implementation of {@link InstanceProvider} * * @author andrew00x * @author Alexander Garagatyi */ public class DockerInstanceProvider implements InstanceProvider { private static final Logger LOG = LoggerFactory.getLogger(DockerInstanceProvider.class); private final DockerConnector docker; private final DockerInstanceStopDetector dockerInstanceStopDetector; private final WorkspaceFolderPathProvider workspaceFolderPathProvider; private final boolean doForcePullOnBuild; private final Set<String> supportedRecipeTypes; private final DockerMachineFactory dockerMachineFactory; private final Map<String, String> devMachineContainerLabels; private final Map<String, String> commonMachineContainerLabels; private final Map<String, Map<String, String>> devMachinePortsToExpose; private final Map<String, Map<String, String>> commonMachinePortsToExpose; private final String[] devMachineSystemVolumes; private final String[] commonMachineSystemVolumes; private final String[] devMachineEnvVariables; private final String[] commonMachineEnvVariables; private final String[] allMachinesExtraHosts; private final String projectFolderPath; @Inject public DockerInstanceProvider(DockerConnector docker, DockerConnectorConfiguration dockerConnectorConfiguration, DockerMachineFactory dockerMachineFactory, DockerInstanceStopDetector dockerInstanceStopDetector, @Named("machine.docker.dev_machine.machine_servers") Set<ServerConf> devMachineServers, @Named("machine.docker.machine_servers") Set<ServerConf> allMachinesServers, @Named("machine.docker.dev_machine.machine_volumes") Set<String> devMachineSystemVolumes, @Named("machine.docker.machine_volumes") Set<String> allMachinesSystemVolumes, @Nullable @Named("machine.docker.machine_extra_hosts") String allMachinesExtraHosts, WorkspaceFolderPathProvider workspaceFolderPathProvider, @Named("che.machine.projects.internal.storage") String projectFolderPath, @Named("machine.docker.pull_image") boolean doForcePullOnBuild, @Named("machine.docker.dev_machine.machine_env") Set<String> devMachineEnvVariables, @Named("machine.docker.machine_env") Set<String> allMachinesEnvVariables) throws IOException { this.docker = docker; this.dockerMachineFactory = dockerMachineFactory; this.dockerInstanceStopDetector = dockerInstanceStopDetector; this.workspaceFolderPathProvider = workspaceFolderPathProvider; this.doForcePullOnBuild = doForcePullOnBuild; this.supportedRecipeTypes = Collections.singleton("Dockerfile"); this.projectFolderPath = projectFolderPath; if (SystemInfo.isWindows()) { allMachinesSystemVolumes = escapePaths(allMachinesSystemVolumes); devMachineSystemVolumes = escapePaths(devMachineSystemVolumes); } this.commonMachineSystemVolumes = allMachinesSystemVolumes.toArray(new String[allMachinesEnvVariables.size()]); final Set<String> devMachineVolumes = Sets.newHashSetWithExpectedSize(allMachinesSystemVolumes.size() + devMachineSystemVolumes.size()); devMachineVolumes.addAll(allMachinesSystemVolumes); devMachineVolumes.addAll(devMachineSystemVolumes); this.devMachineSystemVolumes = devMachineVolumes.toArray(new String[devMachineVolumes.size()]); this.devMachinePortsToExpose = Maps.newHashMapWithExpectedSize(allMachinesServers.size() + devMachineServers.size()); this.commonMachinePortsToExpose = Maps.newHashMapWithExpectedSize(allMachinesServers.size()); this.devMachineContainerLabels = Maps.newHashMapWithExpectedSize(2 * allMachinesServers.size() + 2 * devMachineServers.size()); this.commonMachineContainerLabels = Maps.newHashMapWithExpectedSize(2 * allMachinesServers.size()); for (ServerConf serverConf : devMachineServers) { devMachinePortsToExpose.put(serverConf.getPort(), Collections.<String, String>emptyMap()); devMachineContainerLabels.put("che:server:" + serverConf.getPort() + ":ref", serverConf.getRef()); devMachineContainerLabels.put("che:server:" + serverConf.getPort() + ":protocol", serverConf.getProtocol()); } for (ServerConf serverConf : allMachinesServers) { commonMachinePortsToExpose.put(serverConf.getPort(), Collections.<String, String>emptyMap()); devMachinePortsToExpose.put(serverConf.getPort(), Collections.<String, String>emptyMap()); commonMachineContainerLabels.put("che:server:" + serverConf.getPort() + ":ref", serverConf.getRef()); devMachineContainerLabels.put("che:server:" + serverConf.getPort() + ":ref", serverConf.getRef()); commonMachineContainerLabels.put("che:server:" + serverConf.getPort() + ":protocol", serverConf.getProtocol()); devMachineContainerLabels.put("che:server:" + serverConf.getPort() + ":protocol", serverConf.getProtocol()); } allMachinesEnvVariables = filterEmptyAndNullValues(allMachinesEnvVariables); devMachineEnvVariables = filterEmptyAndNullValues(devMachineEnvVariables); this.commonMachineEnvVariables = allMachinesEnvVariables.toArray(new String[allMachinesEnvVariables.size()]); final HashSet<String> envVariablesForDevMachine = Sets.newHashSetWithExpectedSize(allMachinesEnvVariables.size() + devMachineEnvVariables.size()); envVariablesForDevMachine.addAll(allMachinesEnvVariables); envVariablesForDevMachine.addAll(devMachineEnvVariables); this.devMachineEnvVariables = envVariablesForDevMachine.toArray(new String[envVariablesForDevMachine.size()]); // always add the docker host String dockerHost = DockerInstanceMetadata.CHE_HOST.concat(":").concat(dockerConnectorConfiguration.getDockerHostIp()); if (isNullOrEmpty(allMachinesExtraHosts)) { this.allMachinesExtraHosts = new String[] {dockerHost}; } else { this.allMachinesExtraHosts = ObjectArrays.concat(allMachinesExtraHosts.split(","), dockerHost); } } /** * Escape paths for Windows system with boot@docker according to rules given here : * https://github.com/boot2docker/boot2docker/blob/master/README.md#virtualbox-guest-additions * * @param paths * set of paths to escape * @return set of escaped path */ protected Set<String> escapePaths(Set<String> paths) { return paths.stream().map(this::escapePath).collect(Collectors.toSet()); } /** * Escape path for Windows system with boot@docker according to rules given here : * https://github.com/boot2docker/boot2docker/blob/master/README.md#virtualbox-guest-additions * * @param path * path to escape * @return escaped path */ protected String escapePath(String path) { String esc; if (path.indexOf(":") == 1) { //check and replace only occurrence of ":" after disk label on Windows host (e.g. C:/) // but keep other occurrences it can be marker for docker mount volumes // (e.g. /path/dir/from/host:/name/of/dir/in/container ) esc = path.replaceFirst(":", "").replace('\\', '/'); esc = Character.toLowerCase(esc.charAt(0)) + esc.substring(1); //letter of disk mark must be lower case } else { esc = path.replace('\\', '/'); } if (!esc.startsWith("/")) { esc = "/" + esc; } return esc; } @Override public String getType() { return "docker"; } @Override public Set<String> getRecipeTypes() { return supportedRecipeTypes; } @Override public Instance createInstance(Recipe recipe, MachineState machineState, LineConsumer creationLogsOutput) throws MachineException { final Dockerfile dockerfile = parseRecipe(recipe); final String machineContainerName = generateContainerName(machineState.getWorkspaceId(), machineState.getName()); final String machineImageName = "eclipse-che/" + machineContainerName; buildImage(dockerfile, creationLogsOutput, machineImageName); return createInstance(machineContainerName, machineState, machineImageName, creationLogsOutput); } @Override public Instance createInstance(InstanceKey instanceKey, MachineState machineState, LineConsumer creationLogsOutput) throws NotFoundException, MachineException { final DockerInstanceKey dockerInstanceKey = new DockerInstanceKey(instanceKey); pullImage(dockerInstanceKey, creationLogsOutput); final String machineContainerName = generateContainerName(machineState.getWorkspaceId(), machineState.getName()); final String machineImageName = "eclipse-che/" + machineContainerName; final String fullNameOfPulledImage = dockerInstanceKey.getFullName(); try { // tag image with generated name to allow sysadmin recognize it docker.tag(fullNameOfPulledImage, machineImageName, null); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); throw new MachineException("Can't create machine from snapshot."); } try { // remove unneeded tag docker.removeImage(fullNameOfPulledImage, false); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); } return createInstance(machineContainerName, machineState, machineImageName, creationLogsOutput); } private Dockerfile parseRecipe(Recipe recipe) throws InvalidRecipeException { final Dockerfile dockerfile = getDockerFile(recipe); if (dockerfile.getImages().isEmpty()) { throw new InvalidRecipeException("Unable build docker based machine, Dockerfile found but it doesn't contain base image."); } return dockerfile; } private Dockerfile getDockerFile(Recipe recipe) throws InvalidRecipeException { if (recipe.getScript() == null) { throw new InvalidRecipeException("Unable build docker based machine, recipe isn't set or doesn't provide Dockerfile and " + "no Dockerfile found in the list of files attached to this builder."); } try { return DockerfileParser.parse(recipe.getScript()); } catch (DockerFileException e) { LOG.debug(e.getLocalizedMessage(), e); throw new InvalidRecipeException(String.format("Unable build docker based machine. %s", e.getMessage())); } } private void buildImage(Dockerfile dockerfile, final LineConsumer creationLogsOutput, String imageName) throws MachineException { File workDir = null; try { // build docker image workDir = Files.createTempDirectory(null).toFile(); final File dockerfileFile = new File(workDir, "Dockerfile"); dockerfile.writeDockerfile(dockerfileFile); final List<File> files = new LinkedList<>(); //noinspection ConstantConditions Collections.addAll(files, workDir.listFiles()); final ProgressLineFormatterImpl progressLineFormatter = new ProgressLineFormatterImpl(); final ProgressMonitor progressMonitor = currentProgressStatus -> { try { creationLogsOutput.writeLine(progressLineFormatter.format(currentProgressStatus)); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); } }; docker.buildImage(imageName, progressMonitor, null, doForcePullOnBuild, files.toArray(new File[files.size()])); } catch (IOException | InterruptedException e) { throw new MachineException(e.getMessage(), e); } finally { if (workDir != null) { FileCleaner.addFile(workDir); } } } private void pullImage(DockerInstanceKey dockerInstanceKey, final LineConsumer creationLogsOutput) throws MachineException { if (dockerInstanceKey.getRepository() == null) { throw new MachineException("Machine creation failed. Snapshot state is invalid. Please, contact support."); } try { final ProgressLineFormatterImpl progressLineFormatter = new ProgressLineFormatterImpl(); docker.pull(dockerInstanceKey.getRepository(), dockerInstanceKey.getTag(), dockerInstanceKey.getRegistry(), currentProgressStatus -> { try { creationLogsOutput.writeLine(progressLineFormatter.format(currentProgressStatus)); } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); } }); } catch (IOException | InterruptedException e) { throw new MachineException(e.getLocalizedMessage(), e); } } // TODO rework in accordance with v2 docker registry API @Override public void removeInstanceSnapshot(InstanceKey instanceKey) throws SnapshotException { // use registry API directly because docker doesn't have such API yet // https://github.com/docker/docker-registry/issues/45 final DockerInstanceKey dockerInstanceKey = new DockerInstanceKey(instanceKey); String registry = dockerInstanceKey.getRegistry(); String repository = dockerInstanceKey.getRepository(); if (registry == null || repository == null) { throw new SnapshotException("Snapshot removing failed. Snapshot attributes are not valid"); } StringBuilder sb = new StringBuilder("http://");// TODO make possible to use https here sb.append(registry).append("/v1/repositories/"); sb.append(repository); sb.append("/");// do not remove! Doesn't work without this slash try { final HttpURLConnection conn = (HttpURLConnection)new URL(sb.toString()).openConnection(); try { conn.setConnectTimeout(30 * 1000); conn.setRequestMethod("DELETE"); // fixme add auth header for secured registry // conn.setRequestProperty("Authorization", authHeader); final int responseCode = conn.getResponseCode(); if ((responseCode / 100) != 2) { InputStream in = conn.getErrorStream(); if (in == null) { in = conn.getInputStream(); } LOG.error(IoUtil.readAndCloseQuietly(in)); throw new SnapshotException("Internal server error occurs. Can't remove snapshot"); } } finally { conn.disconnect(); } } catch (IOException e) { LOG.error(e.getLocalizedMessage(), e); } } private Instance createInstance(String containerName, MachineState machineState, String imageName, LineConsumer outputConsumer) throws MachineException { try { final Map<String, String> labels; final Map<String, Map<String, String>> portsToExpose; final String[] volumes; final String[] env; if (machineState.isDev()) { labels = devMachineContainerLabels; portsToExpose = devMachinePortsToExpose; final String projectFolderVolume = String.format("%s:%s", workspaceFolderPathProvider.getPath(machineState.getWorkspaceId()), projectFolderPath); volumes = ObjectArrays.concat(devMachineSystemVolumes, SystemInfo.isWindows() ? escapePath(projectFolderVolume) : projectFolderVolume); String[] vars = {DockerInstanceMetadata.CHE_WORKSPACE_ID + '=' + machineState.getWorkspaceId(), DockerInstanceMetadata.USER_TOKEN + '=' + EnvironmentContext.getCurrent().getUser().getToken()}; env = ObjectArrays.concat(devMachineEnvVariables, vars, String.class); } else { labels = commonMachineContainerLabels; portsToExpose = commonMachinePortsToExpose; volumes = commonMachineSystemVolumes; env = commonMachineEnvVariables; } final HostConfig hostConfig = new HostConfig().withBinds(volumes) .withExtraHosts(allMachinesExtraHosts) .withPublishAllPorts(true) .withMemorySwap(-1) .withMemory((long)machineState.getLimits().getRam() * 1024 * 1024); final ContainerConfig config = new ContainerConfig().withImage(imageName) .withLabels(labels) .withExposedPorts(portsToExpose) .withHostConfig(hostConfig) .withEnv(env); final String containerId = docker.createContainer(config, containerName).getId(); docker.startContainer(containerId, null); final DockerNode node = dockerMachineFactory.createNode(machineState.getWorkspaceId(), containerId); if (machineState.isDev()) { node.bindWorkspace(); } dockerInstanceStopDetector.startDetection(containerId, machineState.getId()); return dockerMachineFactory.createInstance(machineState, containerId, imageName, node, outputConsumer); } catch (IOException e) { throw new MachineException(e); } } String generateContainerName(String workspaceId, String displayName) { String userName = EnvironmentContext.getCurrent().getUser().getName(); final String containerName = userName + '_' + workspaceId + '_' + displayName + '_'; // removing all not allowed characters + generating random name suffix return NameGenerator.generate(containerName.replaceAll("[^a-zA-Z0-9_-]+", ""), 5); } /** * Returns set that contains all non empty and non nullable values from specified set */ protected Set<String> filterEmptyAndNullValues(Set<String> paths) { return paths.stream() .filter(path -> !Strings.isNullOrEmpty(path)) .collect(Collectors.toSet()); } }
epl-1.0
OpenLiberty/open-liberty
dev/com.ibm.ws.request.timing.servlet/src/com/ibm/ws/request/timing/servlet/internal/package-info.java
688
/******************************************************************************* * Copyright (c) 2019 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 *******************************************************************************/ @TraceOptions(traceGroup = "requestTiming") package com.ibm.ws.request.timing.servlet.internal; import com.ibm.websphere.ras.annotation.TraceOptions;
epl-1.0
tavalin/openhab2-addons
addons/binding/org.openhab.binding.leapmotion/src/main/java/org/openhab/binding/leapmotion/internal/LeapMotionDimmerProfile.java
3594
/** * Copyright (c) 2010-2018 by the respective copyright holders. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.openhab.binding.leapmotion.internal; import java.math.BigDecimal; import org.eclipse.jdt.annotation.NonNullByDefault; import org.eclipse.smarthome.core.library.types.OnOffType; import org.eclipse.smarthome.core.library.types.PercentType; import org.eclipse.smarthome.core.thing.profiles.ProfileCallback; import org.eclipse.smarthome.core.thing.profiles.ProfileContext; import org.eclipse.smarthome.core.thing.profiles.ProfileTypeUID; import org.eclipse.smarthome.core.thing.profiles.TriggerProfile; import org.eclipse.smarthome.core.types.State; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The {@link LeapMotionDimmerProfile} class implements the behavior when being linked to a Dimmer item. * It supports two modes: Either the dim level is determined by the number of shown fingers or by the height of the hand * over the controller. * * @author Kai Kreuzer - Initial contribution */ @NonNullByDefault public class LeapMotionDimmerProfile implements TriggerProfile { static final int MAX_HEIGHT = 400; // in mm over controller private static final String MODE = "mode"; private final Logger logger = LoggerFactory.getLogger(LeapMotionDimmerProfile.class); private ProfileCallback callback; private BigDecimal lastState = BigDecimal.ZERO; private boolean fingerMode = false; public LeapMotionDimmerProfile(ProfileCallback callback, ProfileContext profileContext) { this.callback = callback; fingerMode = "fingers".equals(profileContext.getConfiguration().get(MODE)); } @Override public ProfileTypeUID getProfileTypeUID() { return LeapMotionProfileFactory.UID_DIMMER; } @Override public void onStateUpdateFromItem(State state) { PercentType currentState = state.as(PercentType.class); if (currentState != null) { lastState = currentState.toBigDecimal(); } } @Override public void onTriggerFromHandler(String event) { if (event.equals(LeapMotionBindingConstants.GESTURE_TAP)) { callback.sendCommand(lastState.equals(BigDecimal.ZERO) ? OnOffType.ON : OnOffType.OFF); } else if (event.startsWith(LeapMotionBindingConstants.GESTURE_FINGERS)) { int fingers = Integer .valueOf(Character.toString(event.charAt(LeapMotionBindingConstants.GESTURE_FINGERS.length()))); if (fingerMode) { // the brightness is determined by the number of shown fingers, 20% for each. callback.sendCommand(new PercentType(fingers * 20)); } else if (fingers == 5) { // the brightness is determined by the height of the palm over the sensor, where higher means brighter try { int height = Integer .valueOf(event.substring(LeapMotionBindingConstants.GESTURE_FINGERS.length() + 2)); height = Math.min(100 * height / MAX_HEIGHT, 100); // don't use values over 100 callback.sendCommand(new PercentType(height)); } catch (NumberFormatException e) { logger.error("Found illegal format of finger event: {}", event, e); } } } } }
epl-1.0
MikeJMajor/openhab2-addons-dlinksmarthome
bundles/org.openhab.binding.evohome/src/main/java/org/openhab/binding/evohome/internal/configuration/EvohomeTemperatureControlSystemConfiguration.java
663
/** * Copyright (c) 2010-2021 Contributors to the openHAB project * * See the NOTICE file(s) distributed with this work for additional * information. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License 2.0 which is available at * http://www.eclipse.org/legal/epl-2.0 * * SPDX-License-Identifier: EPL-2.0 */ package org.openhab.binding.evohome.internal.configuration; /** * Contains the configuration of the binding. * * @author Jasper van Zuijlen - Initial contribution * */ public class EvohomeTemperatureControlSystemConfiguration { public String id; public String name; }
epl-1.0
RandallDW/Aruba_plugin
plugins/org.python.pydev.debug/src_console/org/python/pydev/debug/newconsole/PydevConsoleCompletionProcessor.java
5255
/** * Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved. * Licensed under the terms of the Eclipse Public License (EPL). * Please see the license.txt included with this distribution for details. * Any modifications to this file must keep this entire header intact. */ package org.python.pydev.debug.newconsole; import org.eclipse.jface.text.ITextViewer; import org.eclipse.jface.text.contentassist.ContentAssistEvent; import org.eclipse.jface.text.contentassist.ICompletionListener; import org.eclipse.jface.text.contentassist.ICompletionProposal; import org.eclipse.jface.text.contentassist.IContextInformation; import org.eclipse.jface.text.contentassist.IContextInformationValidator; import org.python.pydev.core.log.Log; import org.python.pydev.editor.codecompletion.CompletionError; import org.python.pydev.editor.codecompletion.PyCodeCompletionPreferencesPage; import org.python.pydev.editor.codecompletion.PyContentAssistant; import org.python.pydev.editor.codecompletion.PyContextInformationValidator; import org.python.pydev.editor.codecompletion.PythonCompletionProcessor; import org.python.pydev.shared_interactive_console.console.IScriptConsoleShell; import org.python.pydev.shared_interactive_console.console.ui.IScriptConsoleViewer; import org.python.pydev.shared_ui.content_assist.AbstractCompletionProcessorWithCycling; /** * Gathers completions for the pydev console. * * @author fabioz */ public class PydevConsoleCompletionProcessor extends AbstractCompletionProcessorWithCycling implements ICompletionListener { /** * This is the class that manages the context information (validates it and * changes its presentation). */ private PyContextInformationValidator contextInformationValidator; private IScriptConsoleShell interpreterShell; private String errorMessage = null; private int lastActivationCount = -1; public PydevConsoleCompletionProcessor(IScriptConsoleShell interpreterShell, PyContentAssistant pyContentAssistant) { super(pyContentAssistant); pyContentAssistant.addCompletionListener(this); this.interpreterShell = interpreterShell; } @Override public char[] getContextInformationAutoActivationCharacters() { return null; } @Override public char[] getCompletionProposalAutoActivationCharacters() { return PythonCompletionProcessor.getStaticCompletionProposalAutoActivationCharacters(); } /** * Get the completions (and cycle the completion mode if needed). */ @Override public ICompletionProposal[] computeCompletionProposals(ITextViewer v, int offset) { //cycle if we're in a new activation for requests (a second ctrl+space or //a new request) boolean cycleRequest; if (lastActivationCount == -1) { //new request: don't cycle lastActivationCount = this.contentAssistant.lastActivationCount; cycleRequest = false; updateStatus(); } else { //we already had a request (so, we may cycle or not depending on the activation count) cycleRequest = this.contentAssistant.lastActivationCount != lastActivationCount; } if (cycleRequest) { lastActivationCount = this.contentAssistant.lastActivationCount; doCycle(); updateStatus(); } IScriptConsoleViewer viewer = (IScriptConsoleViewer) v; try { if (!PyCodeCompletionPreferencesPage.useCodeCompletion()) { return new ICompletionProposal[0]; } String commandLine = viewer.getCommandLine(); int cursorPosition = offset - viewer.getCommandLineOffset(); return interpreterShell.getCompletions(viewer, commandLine, cursorPosition, offset, this.whatToShow); } catch (Exception e) { Log.log(e); CompletionError completionError = new CompletionError(e); this.errorMessage = completionError.getErrorMessage(); //Make the error visible to the user! return new ICompletionProposal[] { completionError }; } } @Override public IContextInformation[] computeContextInformation(ITextViewer v, int offset) { return null; } @Override public IContextInformationValidator getContextInformationValidator() { if (contextInformationValidator == null) { contextInformationValidator = new PyContextInformationValidator(); } return contextInformationValidator; } /** * @return an error message that happened while getting the completions */ @Override public String getErrorMessage() { String msg = errorMessage; errorMessage = null; return msg; } @Override public void assistSessionEnded(ContentAssistEvent event) { } @Override public void assistSessionStarted(ContentAssistEvent event) { this.lastActivationCount = -1; //we have to start with templates because it'll start already cycling. startCycle(); } @Override public void selectionChanged(ICompletionProposal proposal, boolean smartToggle) { } }
epl-1.0
pplatek/furnace
test-harness/arquillian/core/src/main/java/org/jboss/forge/arquillian/impl/ShrinkWrapUtil.java
4247
/* * Copyright 2014 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.arquillian.impl; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.URL; import java.util.Map; import java.util.Map.Entry; import org.jboss.forge.furnace.util.Streams; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ArchivePath; import org.jboss.shrinkwrap.api.Filter; import org.jboss.shrinkwrap.api.Node; import org.jboss.shrinkwrap.api.asset.Asset; import org.jboss.shrinkwrap.api.exporter.ZipExporter; import org.jboss.shrinkwrap.descriptor.api.Descriptor; public final class ShrinkWrapUtil { private ShrinkWrapUtil() { } /** * Export an {@link Archive} to a {@link File} * * @param archive Archive to export */ public static void toFile(File target, final Archive<?> archive) { try { archive.as(ZipExporter.class).exportTo(target, true); } catch (Exception e) { throw new RuntimeException("Could not export deployment to file [" + target.getAbsolutePath() + "]", e); } } public static void unzip(File baseDir, Archive<?> archive) { try { Map<ArchivePath, Node> content = archive.getContent(new Filter<ArchivePath>() { @Override public boolean include(ArchivePath object) { return object.get().endsWith(".jar"); } }); for (Entry<ArchivePath, Node> entry : content.entrySet()) { ArchivePath path = entry.getKey(); File target = new File(baseDir.getAbsolutePath() + "/" + path.get().replaceFirst("/lib/", "")); target.mkdirs(); target.delete(); target.createNewFile(); Node node = entry.getValue(); Asset asset = node.getAsset(); FileOutputStream fos = null; InputStream is = null; try { fos = new FileOutputStream(target); is = asset.openStream(); Streams.write(is, fos); } finally { Streams.closeQuietly(is); Streams.closeQuietly(fos); } } } catch (Exception e) { throw new RuntimeException(e); } } /** * Creates a tmp folder and exports the file. Returns the URL for that file location. * * @param archive Archive to export * @return */ public static URL toURL(final Archive<?> archive) { // create a random named temp file, then delete and use it as a directory try { File root = File.createTempFile("arquillian", archive.getName()); root.delete(); root.mkdirs(); File deployment = new File(root, archive.getName()); deployment.deleteOnExit(); archive.as(ZipExporter.class).exportTo(deployment, true); return deployment.toURI().toURL(); } catch (Exception e) { throw new RuntimeException("Could not export deployment to temp", e); } } public static URL toURL(final Descriptor descriptor) { // create a random named temp file, then delete and use it as a directory try { File root = File.createTempFile("arquillian", descriptor.getDescriptorName()); root.delete(); root.mkdirs(); File deployment = new File(root, descriptor.getDescriptorName()); deployment.deleteOnExit(); FileOutputStream stream = new FileOutputStream(deployment); try { descriptor.exportTo(stream); } finally { try { stream.close(); } catch (Exception e) { throw new RuntimeException(e); } } return deployment.toURI().toURL(); } catch (Exception e) { throw new RuntimeException("Could not export deployment to temp", e); } } }
epl-1.0
debrief/limpet
info.limpet.stackedcharts.model/src/info/limpet/stackedcharts/model/AxisScale.java
5030
/** */ package info.limpet.stackedcharts.model; import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> A representation of the literals of the enumeration '<em><b>Axis * Scale</b></em>', and utility methods for working with them. <!-- end-user-doc --> <!-- * begin-model-doc --> List of styles of axis <!-- end-model-doc --> * * @see info.limpet.stackedcharts.model.StackedchartsPackage#getAxisScale() * @model * @generated */ public enum AxisScale implements Enumerator { /** * The '<em><b>Linear</b></em>' literal object. <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #LINEAR_VALUE * @generated * @ordered */ LINEAR(0, "Linear", "Linear"), /** * The '<em><b>Log</b></em>' literal object. <!-- begin-user-doc --> <!-- end-user-doc --> * * @see #LOG_VALUE * @generated * @ordered */ LOG(0, "Log", "Log"); /** * The '<em><b>Linear</b></em>' literal value. <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Linear</b></em>' literal object isn't clear, there really should be * more of a description here... * </p> * <!-- end-user-doc --> * * @see #LINEAR * @model name="Linear" * @generated * @ordered */ public static final int LINEAR_VALUE = 0; /** * The '<em><b>Log</b></em>' literal value. <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>Log</b></em>' literal object isn't clear, there really should be more * of a description here... * </p> * <!-- end-user-doc --> * * @see #LOG * @model name="Log" * @generated * @ordered */ public static final int LOG_VALUE = 0; /** * An array of all the '<em><b>Axis Scale</b></em>' enumerators. <!-- begin-user-doc --> <!-- * end-user-doc --> * * @generated */ private static final AxisScale[] VALUES_ARRAY = new AxisScale[] {LINEAR, LOG,}; /** * A public read-only list of all the '<em><b>Axis Scale</b></em>' enumerators. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated */ public static final List<AxisScale> VALUES = Collections.unmodifiableList( Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Axis Scale</b></em>' literal with the specified literal value. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @param literal * the literal. * @return the matching enumerator or <code>null</code>. * @generated */ public static AxisScale get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { AxisScale result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Axis Scale</b></em>' literal with the specified name. <!-- begin-user-doc * --> <!-- end-user-doc --> * * @param name * the name. * @return the matching enumerator or <code>null</code>. * @generated */ public static AxisScale getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { AxisScale result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Axis Scale</b></em>' literal with the specified integer value. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @param value * the integer value. * @return the matching enumerator or <code>null</code>. * @generated */ public static AxisScale get(int value) { switch (value) { case LINEAR_VALUE: return LINEAR; } return null; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ private final int value; /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ private final String name; /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ private final String literal; /** * Only this class can construct instances. <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ private AxisScale(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public int getValue() { return value; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public String getName() { return name; } /** * <!-- begin-user-doc --> <!-- end-user-doc --> * * @generated */ public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. <!-- * begin-user-doc --> <!-- end-user-doc --> * * @generated */ @Override public String toString() { return literal; } } // AxisScale
epl-1.0
k33g/golo-lang
src/main/java/org/eclipse/golo/compiler/ir/Block.java
4435
/* * Copyright (c) 2012-2017 Institut National des Sciences Appliquées de Lyon (INSA-Lyon) * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html */ package org.eclipse.golo.compiler.ir; import java.util.LinkedList; import java.util.List; import java.util.Optional; import org.eclipse.golo.compiler.parser.GoloASTNode; import static java.util.Collections.unmodifiableList; import static org.eclipse.golo.compiler.ir.Builders.*; import static java.util.Objects.requireNonNull; public final class Block extends ExpressionStatement { private final List<GoloStatement> statements = new LinkedList<>(); private ReferenceTable referenceTable; private boolean hasReturn = false; Block(ReferenceTable referenceTable) { super(); this.referenceTable = referenceTable; } public static Block emptyBlock() { return new Block(new ReferenceTable()); } public static Block of(Object block) { if (block == null) { return emptyBlock(); } if (block instanceof Block) { return (Block) block; } throw cantConvert("Block", block); } @Override public Block ofAST(GoloASTNode n) { super.ofAST(n); return this; } public void merge(Block other) { for (GoloStatement innerStatement : other.getStatements()) { this.addStatement(innerStatement); } } public ReferenceTable getReferenceTable() { return referenceTable; } @Override public Optional<ReferenceTable> getLocalReferenceTable() { return Optional.of(referenceTable); } public Block ref(Object referenceTable) { if (referenceTable instanceof ReferenceTable) { setReferenceTable((ReferenceTable) referenceTable); return this; } throw new IllegalArgumentException("not a reference table"); } public void setReferenceTable(ReferenceTable referenceTable) { this.referenceTable = requireNonNull(referenceTable); } public void internReferenceTable() { this.referenceTable = referenceTable.flatDeepCopy(true); } public List<GoloStatement> getStatements() { return unmodifiableList(statements); } public Block add(Object statement) { this.addStatement(toGoloStatement(statement)); return this; } private void updateStateWith(GoloStatement statement) { referenceTable.updateFrom(statement); makeParentOf(statement); checkForReturns(statement); } public void addStatement(GoloStatement statement) { statements.add(statement); updateStateWith(statement); } public void prependStatement(GoloStatement statement) { statements.add(0, statement); updateStateWith(statement); } private void setStatement(int idx, GoloStatement statement) { statements.set(idx, statement); updateStateWith(statement); } private void checkForReturns(GoloStatement statement) { if (statement instanceof ReturnStatement || statement instanceof ThrowStatement) { hasReturn = true; } else if (statement instanceof ConditionalBranching) { hasReturn = hasReturn || ((ConditionalBranching) statement).returnsFromBothBranches(); } } public boolean hasReturn() { return hasReturn; } public int size() { return statements.size(); } public boolean hasOnlyReturn() { return statements.size() == 1 && statements.get(0) instanceof ReturnStatement && !((ReturnStatement) statements.get(0)).isReturningVoid(); } @Override public String toString() { return "{" + statements.toString() + "}"; } public boolean isEmpty() { return statements.isEmpty(); } @Override public void accept(GoloIrVisitor visitor) { visitor.visitBlock(this); } @Override public void walk(GoloIrVisitor visitor) { for (LocalReference ref : referenceTable.ownedReferences()) { ref.accept(visitor); } for (GoloStatement statement : statements) { statement.accept(visitor); } } @Override protected void replaceElement(GoloElement original, GoloElement newElement) { if (statements.contains(original) && newElement instanceof GoloStatement) { setStatement(statements.indexOf(original), (GoloStatement) newElement); } else { throw cantReplace(original, newElement); } } }
epl-1.0
adida/importUsers2OpenLM
src/main/java/org/datacontract/schemas/_2004/_07/openlm_server_services_datacontracts/RouterPortStatistics.java
7697
package org.datacontract.schemas._2004._07.openlm_server_services_datacontracts; import org.datacontract.schemas._2004._07.openlm_shared.SlimDateTime; import org.datacontract.schemas._2004._07.openlm_shared_public.RouterListenerPortProtocol; import org.datacontract.schemas._2004._07.openlm_shared_public.RouterListenerPortStatus; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.*; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for RouterPortStatistics complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="RouterPortStatistics"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="DenialsInInterval" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="ErrorMsg" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="PortProtocolReported" type="{http://schemas.datacontract.org/2004/07/OpenLM.Shared.Public.Enums}RouterListenerPortProtocol" minOccurs="0"/> * &lt;element name="PortReported" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="PortStatus" type="{http://schemas.datacontract.org/2004/07/OpenLM.Shared.Public.Enums}RouterListenerPortStatus" minOccurs="0"/> * &lt;element name="RouteInInterval" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;element name="Timestamp" type="{http://schemas.datacontract.org/2004/07/OpenLM.Shared.VO}SlimDateTime" minOccurs="0"/> * &lt;element name="TimestampUTC" type="{http://www.w3.org/2001/XMLSchema}dateTime" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "RouterPortStatistics", propOrder = { "denialsInInterval", "errorMsg", "portProtocolReported", "portReported", "portStatus", "routeInInterval", "timestamp", "timestampUTC" }) public class RouterPortStatistics { @XmlElement(name = "DenialsInInterval") protected Integer denialsInInterval; @XmlElementRef(name = "ErrorMsg", namespace = "http://schemas.datacontract.org/2004/07/OpenLM.Server.Services.DataContracts.Router", type = JAXBElement.class, required = false) protected JAXBElement<String> errorMsg; @XmlElement(name = "PortProtocolReported") @XmlSchemaType(name = "string") protected RouterListenerPortProtocol portProtocolReported; @XmlElement(name = "PortReported") protected Integer portReported; @XmlElement(name = "PortStatus") @XmlSchemaType(name = "string") protected RouterListenerPortStatus portStatus; @XmlElement(name = "RouteInInterval") protected Integer routeInInterval; @XmlElementRef(name = "Timestamp", namespace = "http://schemas.datacontract.org/2004/07/OpenLM.Server.Services.DataContracts.Router", type = JAXBElement.class, required = false) protected JAXBElement<SlimDateTime> timestamp; @XmlElement(name = "TimestampUTC") @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar timestampUTC; /** * Gets the value of the denialsInInterval property. * * @return * possible object is * {@link Integer } * */ public Integer getDenialsInInterval() { return denialsInInterval; } /** * Sets the value of the denialsInInterval property. * * @param value * allowed object is * {@link Integer } * */ public void setDenialsInInterval(Integer value) { this.denialsInInterval = value; } /** * Gets the value of the errorMsg property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public JAXBElement<String> getErrorMsg() { return errorMsg; } /** * Sets the value of the errorMsg property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link String }{@code >} * */ public void setErrorMsg(JAXBElement<String> value) { this.errorMsg = value; } /** * Gets the value of the portProtocolReported property. * * @return * possible object is * {@link RouterListenerPortProtocol } * */ public RouterListenerPortProtocol getPortProtocolReported() { return portProtocolReported; } /** * Sets the value of the portProtocolReported property. * * @param value * allowed object is * {@link RouterListenerPortProtocol } * */ public void setPortProtocolReported(RouterListenerPortProtocol value) { this.portProtocolReported = value; } /** * Gets the value of the portReported property. * * @return * possible object is * {@link Integer } * */ public Integer getPortReported() { return portReported; } /** * Sets the value of the portReported property. * * @param value * allowed object is * {@link Integer } * */ public void setPortReported(Integer value) { this.portReported = value; } /** * Gets the value of the portStatus property. * * @return * possible object is * {@link RouterListenerPortStatus } * */ public RouterListenerPortStatus getPortStatus() { return portStatus; } /** * Sets the value of the portStatus property. * * @param value * allowed object is * {@link RouterListenerPortStatus } * */ public void setPortStatus(RouterListenerPortStatus value) { this.portStatus = value; } /** * Gets the value of the routeInInterval property. * * @return * possible object is * {@link Integer } * */ public Integer getRouteInInterval() { return routeInInterval; } /** * Sets the value of the routeInInterval property. * * @param value * allowed object is * {@link Integer } * */ public void setRouteInInterval(Integer value) { this.routeInInterval = value; } /** * Gets the value of the timestamp property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link SlimDateTime }{@code >} * */ public JAXBElement<SlimDateTime> getTimestamp() { return timestamp; } /** * Sets the value of the timestamp property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link SlimDateTime }{@code >} * */ public void setTimestamp(JAXBElement<SlimDateTime> value) { this.timestamp = value; } /** * Gets the value of the timestampUTC property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getTimestampUTC() { return timestampUTC; } /** * Sets the value of the timestampUTC property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setTimestampUTC(XMLGregorianCalendar value) { this.timestampUTC = value; } }
gpl-2.0
klst-com/metasfresh
de.metas.swat/de.metas.swat.base/src/main/java/de/metas/adempiere/model/ITableColumnPathElement.java
1014
package de.metas.adempiere.model; /* * #%L * de.metas.swat.base * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ public interface ITableColumnPathElement { public String getTableName(); public String getColumnName(); public String getParentTableName(); public String getParentColumnName(); public String getParentColumnSQL(); }
gpl-2.0
ayuzhanin/cornell-spf-scala
src/main/java/edu/cornell/cs/nlp/spf/mr/language/type/ArrayType.java
2371
/******************************************************************************* * Copyright (C) 2011 - 2015 Yoav Artzi, All rights reserved. * <p> * 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 any later version. * <p> * 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. * <p> * 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.cornell.cs.nlp.spf.mr.language.type; /** * Type of an array for a given base type. * * @author Yoav Artzi */ public class ArrayType extends Type { public static final String ARRAY_SUFFIX = "[]"; private static final long serialVersionUID = 888739870983897365L; private final Type baseType; private final Type parent; ArrayType(String name, Type baseType, Type parent) { super(name); this.parent = parent; this.baseType = baseType; } public Type getBaseType() { return baseType; } @Override public Type getDomain() { return null; } @Override public Type getRange() { return this; } @Override public boolean isArray() { return true; } @Override public boolean isComplex() { return baseType.isComplex(); } @Override public boolean isExtending(Type other) { if (other == null) { return false; } if (this.equals(other)) { return true; } else if (other.isArray()) { // An array A extends and array B, if the A.basetype extends // B.basetype return this.baseType.isExtending(((ArrayType) other).getBaseType()); } else { return parent == null ? false : parent.isExtending(other); } } @Override public boolean isExtendingOrExtendedBy(Type other) { return other != null && (this.isExtending(other) || other.isExtending(this)); } @Override public String toString() { return baseType.toString() + ARRAY_SUFFIX; } }
gpl-2.0
wikimedia/wikidata-query-blazegraph
blazegraph-colt/src/main/java/cern/colt/function/IntDoubleProcedure.java
1445
package cern.colt.function; /* Copyright (c) 1999 CERN - European Organization for Nuclear Research. Permission to use, copy, modify, distribute and sell this software and its documentation for any purpose is hereby granted without fee, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. CERN makes no representations about the suitability of this software for any purpose. It is provided "as is" without expressed or implied warranty. */ /** * Interface that represents a procedure object: a procedure that takes * two arguments and does not return a value. */ public interface IntDoubleProcedure { /** * Applies a procedure to two arguments. * Optionally can return a boolean flag to inform the object calling the procedure. * * <p>Example: forEach() methods often use procedure objects. * To signal to a forEach() method whether iteration should continue normally or terminate (because for example a matching element has been found), * a procedure can return <tt>false</tt> to indicate termination and <tt>true</tt> to indicate continuation. * * @param first first argument passed to the procedure. * @param second second argument passed to the procedure. * @return a flag to inform the object calling the procedure. */ abstract public boolean apply(int first, double second); }
gpl-2.0
petergeneric/j2ssh
src/main/java/com/sshtools/j2ssh/forwarding/ForwardingClient.java
28230
/* * SSHTools - Java SSH2 API * * Copyright (C) 2002-2003 Lee David Painter and Contributors. * * Contributions made by: * * Brett Smith * Richard Pernavas * Erwin Bolwidt * * 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.sshtools.j2ssh.forwarding; import com.sshtools.j2ssh.configuration.SshConnectionProperties; import com.sshtools.j2ssh.connection.Channel; import com.sshtools.j2ssh.connection.ChannelFactory; import com.sshtools.j2ssh.connection.ConnectionProtocol; import com.sshtools.j2ssh.connection.InvalidChannelException; import com.sshtools.j2ssh.io.ByteArrayReader; import com.sshtools.j2ssh.io.ByteArrayWriter; import com.sshtools.j2ssh.util.StartStopState; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import java.io.IOException; import java.net.Socket; import java.net.SocketPermission; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Vector; /** * * * @author $author$ * @version $Revision: 1.37 $ */ public class ForwardingClient implements ChannelFactory { private static Log log = LogFactory.getLog(ForwardingClient.class); /** */ public final static String REMOTE_FORWARD_REQUEST = "tcpip-forward"; /** */ public final static String REMOTE_FORWARD_CANCEL_REQUEST = "cancel-tcpip-forward"; private ConnectionProtocol connection; private List channelTypes = new Vector(); private Map localForwardings = new HashMap(); private Map remoteForwardings = new HashMap(); private XDisplay xDisplay; private ForwardingConfiguration x11ForwardingConfiguration; /** * Creates a new ForwardingClient object. * * @param connection * * @throws IOException */ public ForwardingClient(ConnectionProtocol connection) throws IOException { this.connection = connection; //channelTypes.add(ForwardingSocketChannel.REMOTE_FORWARDING_CHANNEL); connection.addChannelFactory(ForwardingSocketChannel.REMOTE_FORWARDING_CHANNEL, this); connection.addChannelFactory(ForwardingSocketChannel.X11_FORWARDING_CHANNEL, this); } /** * * * @return */ public List getChannelType() { return channelTypes; } /** * * * @param localDisplay */ public void enableX11Forwarding(XDisplay localDisplay) { xDisplay = localDisplay; x11ForwardingConfiguration = new ForwardingConfiguration("x11", "", 0, xDisplay.getHost(), xDisplay.getPort()); } /** * * * @return */ public ForwardingConfiguration getX11ForwardingConfiguration() { return x11ForwardingConfiguration; } /** * * * @return */ public boolean hasActiveConfigurations() { // First check the size if ((localForwardings.size() == 0) && (remoteForwardings.size() == 0)) { return false; } Iterator it = localForwardings.values().iterator(); while (it.hasNext()) { if (((ForwardingConfiguration) it.next()).getState().getValue() == StartStopState.STARTED) { return true; } } it = remoteForwardings.values().iterator(); while (it.hasNext()) { if (((ForwardingConfiguration) it.next()).getState().getValue() == StartStopState.STARTED) { return true; } } return false; } public void synchronizeConfiguration(SshConnectionProperties properties) { ForwardingConfiguration fwd = null; if (properties.getLocalForwardings().size() > 0) { for (Iterator it = properties.getLocalForwardings().values() .iterator(); it.hasNext();) { try { fwd = (ForwardingConfiguration) it.next(); fwd = addLocalForwarding(fwd); if (properties.getForwardingAutoStartMode()) { startLocalForwarding(fwd.getName()); } } catch (Throwable ex) { log.warn((("Failed to start local forwarding " + fwd) != null) ? fwd.getName() : "", ex); } } } if (properties.getRemoteForwardings().size() > 0) { for (Iterator it = properties.getRemoteForwardings().values() .iterator(); it.hasNext();) { try { fwd = (ForwardingConfiguration) it.next(); addRemoteForwarding(fwd); if (properties.getForwardingAutoStartMode()) { startRemoteForwarding(fwd.getName()); } } catch (Throwable ex) { log.warn((("Failed to start remote forwarding " + fwd) != null) ? fwd.getName() : "", ex); } } } } /** * * * @return */ public boolean hasActiveForwardings() { // First check the size if ((localForwardings.size() == 0) && (remoteForwardings.size() == 0)) { return false; } Iterator it = localForwardings.values().iterator(); while (it.hasNext()) { if (((ForwardingConfiguration) it.next()).getActiveForwardingSocketChannels() .size() > 0) { return true; } } it = remoteForwardings.values().iterator(); while (it.hasNext()) { if (((ForwardingConfiguration) it.next()).getActiveForwardingSocketChannels() .size() > 0) { return true; } } return false; } /** * * * @param addressToBind * @param portToBind * * @return * * @throws ForwardingConfigurationException */ public ForwardingConfiguration getLocalForwardingByAddress( String addressToBind, int portToBind) throws ForwardingConfigurationException { Iterator it = localForwardings.values().iterator(); ForwardingConfiguration config; while (it.hasNext()) { config = (ForwardingConfiguration) it.next(); if (config.getAddressToBind().equals(addressToBind) && (config.getPortToBind() == portToBind)) { return config; } } throw new ForwardingConfigurationException( "The configuration does not exist"); } /** * * * @param name * * @return * * @throws ForwardingConfigurationException */ public ForwardingConfiguration getLocalForwardingByName(String name) throws ForwardingConfigurationException { if (!localForwardings.containsKey(name)) { throw new ForwardingConfigurationException( "The configuraiton does not exist!"); } return (ForwardingConfiguration) localForwardings.get(name); } /** * * * @param name * * @return * * @throws ForwardingConfigurationException */ public ForwardingConfiguration getRemoteForwardingByName(String name) throws ForwardingConfigurationException { if (!remoteForwardings.containsKey(name)) { throw new ForwardingConfigurationException( "The configuraiton does not exist!"); } return (ForwardingConfiguration) remoteForwardings.get(name); } /** * * * @return */ public Map getLocalForwardings() { return localForwardings; } /** * * * @return */ public Map getRemoteForwardings() { return remoteForwardings; } /** * * * @param addressToBind * @param portToBind * * @return * * @throws ForwardingConfigurationException */ public ForwardingConfiguration getRemoteForwardingByAddress( String addressToBind, int portToBind) throws ForwardingConfigurationException { Iterator it = remoteForwardings.values().iterator(); ForwardingConfiguration config; while (it.hasNext()) { config = (ForwardingConfiguration) it.next(); if (config.getAddressToBind().equals(addressToBind) && (config.getPortToBind() == portToBind)) { return config; } } throw new ForwardingConfigurationException( "The configuration does not exist"); } /** * * * @param name * * @throws ForwardingConfigurationException */ public void removeLocalForwarding(String name) throws ForwardingConfigurationException { if (!localForwardings.containsKey(name)) { throw new ForwardingConfigurationException( "The name is not a valid forwarding configuration"); } ForwardingListener listener = (ForwardingListener) localForwardings.get(name); if (listener.isRunning()) { stopLocalForwarding(name); } localForwardings.remove(name); } /** * * * @param name * * @throws IOException * @throws ForwardingConfigurationException */ public void removeRemoteForwarding(String name) throws IOException, ForwardingConfigurationException { if (!remoteForwardings.containsKey(name)) { throw new ForwardingConfigurationException( "The name is not a valid forwarding configuration"); } ForwardingListener listener = (ForwardingListener) remoteForwardings.get(name); if (listener.isRunning()) { stopRemoteForwarding(name); } remoteForwardings.remove(name); } /** * * * @param uniqueName * @param addressToBind * @param portToBind * @param hostToConnect * @param portToConnect * * @return * * @throws ForwardingConfigurationException */ public ForwardingConfiguration addLocalForwarding(String uniqueName, String addressToBind, int portToBind, String hostToConnect, int portToConnect) throws ForwardingConfigurationException { // Check that the name does not exist if (localForwardings.containsKey(uniqueName)) { throw new ForwardingConfigurationException( "The configuration name already exists!"); } // Check that the address to bind and port are not already being used Iterator it = localForwardings.values().iterator(); ForwardingConfiguration config; while (it.hasNext()) { config = (ForwardingConfiguration) it.next(); if (config.getAddressToBind().equals(addressToBind) && (config.getPortToBind() == portToBind)) { throw new ForwardingConfigurationException( "The address and port are already in use"); } } // Check the security mananger SecurityManager manager = System.getSecurityManager(); if (manager != null) { try { manager.checkPermission(new SocketPermission(addressToBind + ":" + String.valueOf(portToBind), "accept,listen")); } catch (SecurityException e) { throw new ForwardingConfigurationException( "The security manager has denied listen permision on " + addressToBind + ":" + String.valueOf(portToBind)); } } // Create the configuration object ForwardingConfiguration cf = new ClientForwardingListener(uniqueName, connection, addressToBind, portToBind, hostToConnect, portToConnect); localForwardings.put(uniqueName, cf); return cf; } /** * * * @param fwd * * @return * * @throws ForwardingConfigurationException */ public ForwardingConfiguration addLocalForwarding( ForwardingConfiguration fwd) throws ForwardingConfigurationException { return addLocalForwarding(fwd.getName(), fwd.getAddressToBind(), fwd.getPortToBind(), fwd.getHostToConnect(), fwd.getPortToConnect()); /* // Check that the name does not exist if (localForwardings.containsKey(fwd.getName())) { throw new ForwardingConfigurationException( "The configuration name already exists!"); } // Check that the address to bind and port are not already being used Iterator it = localForwardings.values().iterator(); ForwardingConfiguration config; while (it.hasNext()) { config = (ForwardingConfiguration) it.next(); if (config.getAddressToBind().equals(fwd.getAddressToBind()) && (config.getPortToBind() == fwd.getPortToBind())) { throw new ForwardingConfigurationException( "The address and port are already in use"); } } // Check the security mananger SecurityManager manager = System.getSecurityManager(); if (manager != null) { try { manager.checkPermission(new SocketPermission(fwd .getAddressToBind() + ":" + String.valueOf(fwd.getPortToBind()), "accept,listen")); } catch (SecurityException e) { throw new ForwardingConfigurationException( "The security manager has denied listen permision on " + fwd.getAddressToBind() + ":" + String.valueOf(fwd.getPortToBind())); } } // Create the configuration object localForwardings.put(fwd.getName(), new ClientForwardingListener(fwd.getName(), connection, fwd.getAddressToBind(), fwd.getPortToBind(), fwd.getHostToConnect(), fwd.getPortToConnect()));*/ } /** * * * @param uniqueName * @param addressToBind * @param portToBind * @param hostToConnect * @param portToConnect * * @throws ForwardingConfigurationException */ public void addRemoteForwarding(String uniqueName, String addressToBind, int portToBind, String hostToConnect, int portToConnect) throws ForwardingConfigurationException { // Check that the name does not exist if (remoteForwardings.containsKey(uniqueName)) { throw new ForwardingConfigurationException( "The remote forwaring configuration name already exists!"); } // Check that the address to bind and port are not already being used Iterator it = remoteForwardings.values().iterator(); ForwardingConfiguration config; while (it.hasNext()) { config = (ForwardingConfiguration) it.next(); if (config.getAddressToBind().equals(addressToBind) && (config.getPortToBind() == portToBind)) { throw new ForwardingConfigurationException( "The remote forwarding address and port are already in use"); } } // Check the security mananger SecurityManager manager = System.getSecurityManager(); if (manager != null) { try { manager.checkPermission(new SocketPermission(hostToConnect + ":" + String.valueOf(portToConnect), "connect")); } catch (SecurityException e) { throw new ForwardingConfigurationException( "The security manager has denied connect permision on " + hostToConnect + ":" + String.valueOf(portToConnect)); } } // Create the configuration object remoteForwardings.put(uniqueName, new ForwardingConfiguration(uniqueName, addressToBind, portToBind, hostToConnect, portToConnect)); } /** * * * @param fwd * * @throws ForwardingConfigurationException */ public void addRemoteForwarding(ForwardingConfiguration fwd) throws ForwardingConfigurationException { // Check that the name does not exist if (remoteForwardings.containsKey(fwd.getName())) { throw new ForwardingConfigurationException( "The remote forwaring configuration name already exists!"); } // Check that the address to bind and port are not already being used Iterator it = remoteForwardings.values().iterator(); ForwardingConfiguration config; while (it.hasNext()) { config = (ForwardingConfiguration) it.next(); if (config.getAddressToBind().equals(fwd.getAddressToBind()) && (config.getPortToBind() == fwd.getPortToBind())) { throw new ForwardingConfigurationException( "The remote forwarding address and port are already in use"); } } // Check the security mananger SecurityManager manager = System.getSecurityManager(); if (manager != null) { try { manager.checkPermission(new SocketPermission(fwd.getHostToConnect() + ":" + String.valueOf(fwd.getPortToConnect()), "connect")); } catch (SecurityException e) { throw new ForwardingConfigurationException( "The security manager has denied connect permision on " + fwd.getHostToConnect() + ":" + String.valueOf(fwd.getPortToConnect())); } } // Create the configuration object remoteForwardings.put(fwd.getName(), fwd); } /** * * * @param channelType * @param requestData * * @return * * @throws InvalidChannelException */ public Channel createChannel(String channelType, byte[] requestData) throws InvalidChannelException { if (channelType.equals(ForwardingSocketChannel.X11_FORWARDING_CHANNEL)) { if (xDisplay == null) { throw new InvalidChannelException( "Local display has not been set for X11 forwarding."); } try { ByteArrayReader bar = new ByteArrayReader(requestData); String originatingHost = bar.readString(); int originatingPort = (int) bar.readInt(); log.debug("Creating socket to " + x11ForwardingConfiguration.getHostToConnect() + "/" + x11ForwardingConfiguration.getPortToConnect()); Socket socket = new Socket(x11ForwardingConfiguration.getHostToConnect(), x11ForwardingConfiguration.getPortToConnect()); // Create the channel adding it to the active channels ForwardingSocketChannel channel = x11ForwardingConfiguration.createForwardingSocketChannel(channelType, x11ForwardingConfiguration.getHostToConnect(), x11ForwardingConfiguration.getPortToConnect(), originatingHost, originatingPort); channel.bindSocket(socket); channel.addEventListener(x11ForwardingConfiguration.monitor); return channel; } catch (IOException ioe) { throw new InvalidChannelException(ioe.getMessage()); } } if (channelType.equals( ForwardingSocketChannel.REMOTE_FORWARDING_CHANNEL)) { try { ByteArrayReader bar = new ByteArrayReader(requestData); String addressBound = bar.readString(); int portBound = (int) bar.readInt(); String originatingHost = bar.readString(); int originatingPort = (int) bar.readInt(); ForwardingConfiguration config = getRemoteForwardingByAddress(addressBound, portBound); Socket socket = new Socket(config.getHostToConnect(), config.getPortToConnect()); /*Socket socket = new Socket(); socket.connect(new InetSocketAddress( config.getHostToConnect(), config.getPortToConnect()));*/ // Create the channel adding it to the active channels ForwardingSocketChannel channel = config.createForwardingSocketChannel(channelType, config.getHostToConnect(), config.getPortToConnect(), originatingHost, originatingPort); channel.bindSocket(socket); channel.addEventListener(config.monitor); return channel; } catch (ForwardingConfigurationException fce) { throw new InvalidChannelException( "No valid forwarding configuration was available for the request address"); } catch (IOException ioe) { throw new InvalidChannelException(ioe.getMessage()); } } throw new InvalidChannelException( "The server can only request a remote forwarding channel or an" + "X11 forwarding channel"); } /** * * * @param uniqueName * * @throws ForwardingConfigurationException */ public void startLocalForwarding(String uniqueName) throws ForwardingConfigurationException { if (!localForwardings.containsKey(uniqueName)) { throw new ForwardingConfigurationException( "The name is not a valid forwarding configuration"); } try { ForwardingListener listener = (ForwardingListener) localForwardings.get(uniqueName); listener.start(); } catch (IOException ex) { throw new ForwardingConfigurationException(ex.getMessage()); } } /** * * * @throws IOException * @throws ForwardingConfigurationException */ public void startX11Forwarding() throws IOException, ForwardingConfigurationException { if (x11ForwardingConfiguration == null) { throw new ForwardingConfigurationException( "X11 forwarding hasn't been enabled."); } ByteArrayWriter baw = new ByteArrayWriter(); baw.writeString(x11ForwardingConfiguration.getAddressToBind()); baw.writeInt(x11ForwardingConfiguration.getPortToBind()); x11ForwardingConfiguration.getState().setValue(StartStopState.STARTED); if (log.isDebugEnabled()) { log.info("X11 forwarding started"); log.debug("Address to bind: " + x11ForwardingConfiguration.getAddressToBind()); log.debug("Port to bind: " + String.valueOf(x11ForwardingConfiguration.getPortToBind())); log.debug("Host to connect: " + x11ForwardingConfiguration.hostToConnect); log.debug("Port to connect: " + x11ForwardingConfiguration.portToConnect); } else { log.info("Request for X11 rejected."); } } /** * * * @param name * * @throws IOException * @throws ForwardingConfigurationException */ public void startRemoteForwarding(String name) throws IOException, ForwardingConfigurationException { if (!remoteForwardings.containsKey(name)) { throw new ForwardingConfigurationException( "The name is not a valid forwarding configuration"); } ForwardingConfiguration config = (ForwardingConfiguration) remoteForwardings.get(name); ByteArrayWriter baw = new ByteArrayWriter(); baw.writeString(config.getAddressToBind()); baw.writeInt(config.getPortToBind()); connection.sendGlobalRequest(REMOTE_FORWARD_REQUEST, true, baw.toByteArray()); remoteForwardings.put(name, config); config.getState().setValue(StartStopState.STARTED); log.info("Remote forwarding configuration '" + name + "' started"); if (log.isDebugEnabled()) { log.debug("Address to bind: " + config.getAddressToBind()); log.debug("Port to bind: " + String.valueOf(config.getPortToBind())); log.debug("Host to connect: " + config.hostToConnect); log.debug("Port to connect: " + config.portToConnect); } } /** * * * @param uniqueName * * @throws ForwardingConfigurationException */ public void stopLocalForwarding(String uniqueName) throws ForwardingConfigurationException { if (!localForwardings.containsKey(uniqueName)) { throw new ForwardingConfigurationException( "The name is not a valid forwarding configuration"); } ForwardingListener listener = (ForwardingListener) localForwardings.get(uniqueName); listener.stop(); log.info("Local forwarding configuration " + uniqueName + "' stopped"); } /** * * * @param name * * @throws IOException * @throws ForwardingConfigurationException */ public void stopRemoteForwarding(String name) throws IOException, ForwardingConfigurationException { if (!remoteForwardings.containsKey(name)) { throw new ForwardingConfigurationException( "The remote forwarding configuration does not exist"); } ForwardingConfiguration config = (ForwardingConfiguration) remoteForwardings.get(name); ByteArrayWriter baw = new ByteArrayWriter(); baw.writeString(config.getAddressToBind()); baw.writeInt(config.getPortToBind()); connection.sendGlobalRequest(REMOTE_FORWARD_CANCEL_REQUEST, true, baw.toByteArray()); config.getState().setValue(StartStopState.STOPPED); log.info("Remote forwarding configuration '" + name + "' stopped"); } public class ClientForwardingListener extends ForwardingListener { public ClientForwardingListener(String name, ConnectionProtocol connection, String addressToBind, int portToBind, String hostToConnect, int portToConnect) { super(name, connection, addressToBind, portToBind, hostToConnect, portToConnect); } public ForwardingSocketChannel createChannel(String hostToConnect, int portToConnect, Socket socket) throws ForwardingConfigurationException { return createForwardingSocketChannel(ForwardingSocketChannel.LOCAL_FORWARDING_CHANNEL, hostToConnect, portToConnect, /*( (InetSocketAddress) socket. getRemoteSocketAddress()).getAddress() .getHostAddress()*/ socket.getInetAddress().getHostAddress(), /*( (InetSocketAddress) socket. getRemoteSocketAddress()).getPort()*/ socket.getPort()); } } }
gpl-2.0
debian-pkg-android-tools/android-platform-libcore
ojluni/src/main/java/java/util/EnumSet.java
17724
/* * Copyright (C) 2014 The Android Open Source Project * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util; /** * A specialized {@link Set} implementation for use with enum types. All of * the elements in an enum set must come from a single enum type that is * specified, explicitly or implicitly, when the set is created. Enum sets * are represented internally as bit vectors. This representation is * extremely compact and efficient. The space and time performance of this * class should be good enough to allow its use as a high-quality, typesafe * alternative to traditional <tt>int</tt>-based "bit flags." Even bulk * operations (such as <tt>containsAll</tt> and <tt>retainAll</tt>) should * run very quickly if their argument is also an enum set. * * <p>The iterator returned by the <tt>iterator</tt> method traverses the * elements in their <i>natural order</i> (the order in which the enum * constants are declared). The returned iterator is <i>weakly * consistent</i>: it will never throw {@link ConcurrentModificationException} * and it may or may not show the effects of any modifications to the set that * occur while the iteration is in progress. * * <p>Null elements are not permitted. Attempts to insert a null element * will throw {@link NullPointerException}. Attempts to test for the * presence of a null element or to remove one will, however, function * properly. * * <P>Like most collection implementations, <tt>EnumSet</tt> is not * synchronized. If multiple threads access an enum set concurrently, and at * least one of the threads modifies the set, it should be synchronized * externally. This is typically accomplished by synchronizing on some * object that naturally encapsulates the enum set. If no such object exists, * the set should be "wrapped" using the {@link Collections#synchronizedSet} * method. This is best done at creation time, to prevent accidental * unsynchronized access: * * <pre> * Set&lt;MyEnum&gt; s = Collections.synchronizedSet(EnumSet.noneOf(MyEnum.class)); * </pre> * * <p>Implementation note: All basic operations execute in constant time. * They are likely (though not guaranteed) to be much faster than their * {@link HashSet} counterparts. Even bulk operations execute in * constant time if their argument is also an enum set. * * <p>This class is a member of the * <a href="{@docRoot}openjdk-redirect.html?v=8&path=/technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @author Josh Bloch * @since 1.5 * @see EnumMap * @serial exclude */ public abstract class EnumSet<E extends Enum<E>> extends AbstractSet<E> implements Cloneable, java.io.Serializable { /** * The class of all the elements of this set. */ final Class<E> elementType; /** * All of the values comprising T. (Cached for performance.) */ final Enum[] universe; private static Enum[] ZERO_LENGTH_ENUM_ARRAY = new Enum[0]; EnumSet(Class<E>elementType, Enum[] universe) { this.elementType = elementType; this.universe = universe; } /** * Creates an empty enum set with the specified element type. * * @param elementType the class object of the element type for this enum * set * @throws NullPointerException if <tt>elementType</tt> is null */ public static <E extends Enum<E>> EnumSet<E> noneOf(Class<E> elementType) { Enum[] universe = getUniverse(elementType); if (universe == null) throw new ClassCastException(elementType + " not an enum"); if (universe.length <= 64) return new RegularEnumSet<>(elementType, universe); else return new JumboEnumSet<>(elementType, universe); } /** * Creates an enum set containing all of the elements in the specified * element type. * * @param elementType the class object of the element type for this enum * set * @throws NullPointerException if <tt>elementType</tt> is null */ public static <E extends Enum<E>> EnumSet<E> allOf(Class<E> elementType) { EnumSet<E> result = noneOf(elementType); result.addAll(); return result; } /** * Adds all of the elements from the appropriate enum type to this enum * set, which is empty prior to the call. */ abstract void addAll(); /** * Creates an enum set with the same element type as the specified enum * set, initially containing the same elements (if any). * * @param s the enum set from which to initialize this enum set * @throws NullPointerException if <tt>s</tt> is null */ public static <E extends Enum<E>> EnumSet<E> copyOf(EnumSet<E> s) { return s.clone(); } /** * Creates an enum set initialized from the specified collection. If * the specified collection is an <tt>EnumSet</tt> instance, this static * factory method behaves identically to {@link #copyOf(EnumSet)}. * Otherwise, the specified collection must contain at least one element * (in order to determine the new enum set's element type). * * @param c the collection from which to initialize this enum set * @throws IllegalArgumentException if <tt>c</tt> is not an * <tt>EnumSet</tt> instance and contains no elements * @throws NullPointerException if <tt>c</tt> is null */ public static <E extends Enum<E>> EnumSet<E> copyOf(Collection<E> c) { if (c instanceof EnumSet) { return ((EnumSet<E>)c).clone(); } else { if (c.isEmpty()) throw new IllegalArgumentException("Collection is empty"); Iterator<E> i = c.iterator(); E first = i.next(); EnumSet<E> result = EnumSet.of(first); while (i.hasNext()) result.add(i.next()); return result; } } /** * Creates an enum set with the same element type as the specified enum * set, initially containing all the elements of this type that are * <i>not</i> contained in the specified set. * * @param s the enum set from whose complement to initialize this enum set * @throws NullPointerException if <tt>s</tt> is null */ public static <E extends Enum<E>> EnumSet<E> complementOf(EnumSet<E> s) { EnumSet<E> result = copyOf(s); result.complement(); return result; } /** * Creates an enum set initially containing the specified element. * * Overloadings of this method exist to initialize an enum set with * one through five elements. A sixth overloading is provided that * uses the varargs feature. This overloading may be used to create * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * * @param e the element that this set is to contain initially * @throws NullPointerException if <tt>e</tt> is null * @return an enum set initially containing the specified element */ public static <E extends Enum<E>> EnumSet<E> of(E e) { EnumSet<E> result = noneOf(e.getDeclaringClass()); result.add(e); return result; } /** * Creates an enum set initially containing the specified elements. * * Overloadings of this method exist to initialize an enum set with * one through five elements. A sixth overloading is provided that * uses the varargs feature. This overloading may be used to create * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @throws NullPointerException if any parameters are null * @return an enum set initially containing the specified elements */ public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2) { EnumSet<E> result = noneOf(e1.getDeclaringClass()); result.add(e1); result.add(e2); return result; } /** * Creates an enum set initially containing the specified elements. * * Overloadings of this method exist to initialize an enum set with * one through five elements. A sixth overloading is provided that * uses the varargs feature. This overloading may be used to create * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @param e3 another element that this set is to contain initially * @throws NullPointerException if any parameters are null * @return an enum set initially containing the specified elements */ public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3) { EnumSet<E> result = noneOf(e1.getDeclaringClass()); result.add(e1); result.add(e2); result.add(e3); return result; } /** * Creates an enum set initially containing the specified elements. * * Overloadings of this method exist to initialize an enum set with * one through five elements. A sixth overloading is provided that * uses the varargs feature. This overloading may be used to create * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @param e3 another element that this set is to contain initially * @param e4 another element that this set is to contain initially * @throws NullPointerException if any parameters are null * @return an enum set initially containing the specified elements */ public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4) { EnumSet<E> result = noneOf(e1.getDeclaringClass()); result.add(e1); result.add(e2); result.add(e3); result.add(e4); return result; } /** * Creates an enum set initially containing the specified elements. * * Overloadings of this method exist to initialize an enum set with * one through five elements. A sixth overloading is provided that * uses the varargs feature. This overloading may be used to create * an enum set initially containing an arbitrary number of elements, but * is likely to run slower than the overloadings that do not use varargs. * * @param e1 an element that this set is to contain initially * @param e2 another element that this set is to contain initially * @param e3 another element that this set is to contain initially * @param e4 another element that this set is to contain initially * @param e5 another element that this set is to contain initially * @throws NullPointerException if any parameters are null * @return an enum set initially containing the specified elements */ public static <E extends Enum<E>> EnumSet<E> of(E e1, E e2, E e3, E e4, E e5) { EnumSet<E> result = noneOf(e1.getDeclaringClass()); result.add(e1); result.add(e2); result.add(e3); result.add(e4); result.add(e5); return result; } /** * Creates an enum set initially containing the specified elements. * This factory, whose parameter list uses the varargs feature, may * be used to create an enum set initially containing an arbitrary * number of elements, but it is likely to run slower than the overloadings * that do not use varargs. * * @param first an element that the set is to contain initially * @param rest the remaining elements the set is to contain initially * @throws NullPointerException if any of the specified elements are null, * or if <tt>rest</tt> is null * @return an enum set initially containing the specified elements */ @SafeVarargs public static <E extends Enum<E>> EnumSet<E> of(E first, E... rest) { EnumSet<E> result = noneOf(first.getDeclaringClass()); result.add(first); for (E e : rest) result.add(e); return result; } /** * Creates an enum set initially containing all of the elements in the * range defined by the two specified endpoints. The returned set will * contain the endpoints themselves, which may be identical but must not * be out of order. * * @param from the first element in the range * @param to the last element in the range * @throws NullPointerException if {@code from} or {@code to} are null * @throws IllegalArgumentException if {@code from.compareTo(to) > 0} * @return an enum set initially containing all of the elements in the * range defined by the two specified endpoints */ public static <E extends Enum<E>> EnumSet<E> range(E from, E to) { if (from.compareTo(to) > 0) throw new IllegalArgumentException(from + " > " + to); EnumSet<E> result = noneOf(from.getDeclaringClass()); result.addRange(from, to); return result; } /** * Adds the specified range to this enum set, which is empty prior * to the call. */ abstract void addRange(E from, E to); /** * Returns a copy of this set. * * @return a copy of this set */ public EnumSet<E> clone() { try { return (EnumSet<E>) super.clone(); } catch(CloneNotSupportedException e) { throw new AssertionError(e); } } /** * Complements the contents of this enum set. */ abstract void complement(); /** * Throws an exception if e is not of the correct type for this enum set. */ final void typeCheck(E e) { Class eClass = e.getClass(); if (eClass != elementType && eClass.getSuperclass() != elementType) throw new ClassCastException(eClass + " != " + elementType); } /** * Returns all of the values comprising E. * The result is uncloned, cached, and shared by all callers. */ private static <E extends Enum<E>> E[] getUniverse(Class<E> elementType) { // Android-changed: Use JavaLangAccess directly instead of going via // SharedSecrets. return java.lang.JavaLangAccess.getEnumConstantsShared(elementType); } /** * This class is used to serialize all EnumSet instances, regardless of * implementation type. It captures their "logical contents" and they * are reconstructed using public static factories. This is necessary * to ensure that the existence of a particular implementation type is * an implementation detail. * * @serial include */ private static class SerializationProxy <E extends Enum<E>> implements java.io.Serializable { /** * The element type of this enum set. * * @serial */ private final Class<E> elementType; /** * The elements contained in this enum set. * * @serial */ private final Enum[] elements; SerializationProxy(EnumSet<E> set) { elementType = set.elementType; elements = set.toArray(ZERO_LENGTH_ENUM_ARRAY); } private Object readResolve() { EnumSet<E> result = EnumSet.noneOf(elementType); for (Enum e : elements) result.add((E)e); return result; } private static final long serialVersionUID = 362491234563181265L; } Object writeReplace() { return new SerializationProxy<>(this); } // readObject method for the serialization proxy pattern // See Effective Java, Second Ed., Item 78. private void readObject(java.io.ObjectInputStream stream) throws java.io.InvalidObjectException { throw new java.io.InvalidObjectException("Proxy required"); } }
gpl-2.0
iammyr/Benchmark
src/main/java/org/owasp/benchmark/testcode/BenchmarkTest09029.java
2605
/** * 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 Dave Wichers <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("/BenchmarkTest09029") public class BenchmarkTest09029 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 = ""; java.util.Enumeration<String> headerNames = request.getHeaderNames(); if (headerNames.hasMoreElements()) { param = headerNames.nextElement(); // just grab first element } String bar = new Test().doSomething(param); String sql = "SELECT * from USERS where USERNAME='foo' and PASSWORD='"+ bar +"'"; try { java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement(); statement.execute( sql, new String[] { "username", "password" } ); } catch (java.sql.SQLException e) { throw new ServletException(e); } } // end doPost private class Test { public 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; } } // end innerclass Test } // end DataflowThruInnerClass
gpl-2.0
netroby/hotspot9
test/gc/g1/TestShrinkAuxiliaryData10.java
1858
/* * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /** * @test TestShrinkAuxiliaryData10 * @bug 8038423 8061715 * @summary Checks that decommitment occurs for JVM with different * G1ConcRSLogCacheSize and ObjectAlignmentInBytes options values * @requires vm.gc=="G1" | vm.gc=="null" * @library /testlibrary /../../test/lib * @modules java.base/sun.misc * java.management * @build com.oracle.java.testlibrary.* sun.hotspot.WhiteBox * @build TestShrinkAuxiliaryData TestShrinkAuxiliaryData10 * @run main ClassFileInstaller sun.hotspot.WhiteBox * sun.hotspot.WhiteBox$WhiteBoxPermission * @run driver/timeout=720 TestShrinkAuxiliaryData10 */ public class TestShrinkAuxiliaryData10 { public static void main(String[] args) throws Exception { new TestShrinkAuxiliaryData(10).test(); } }
gpl-2.0
klst-com/metasfresh
de.metas.adempiere.adempiere/base/src/main/java/org/adempiere/ad/ui/spi/TabCalloutAdapter.java
1214
package org.adempiere.ad.ui.spi; import org.adempiere.ad.callout.api.ICalloutRecord; import com.google.common.base.MoreObjects; /** * Implement what you want extension of {@link ITabCallout}. * * Developers are highly advised to extend this one instead of implementing {@link ITabCallout}. * * @author tsa * */ public abstract class TabCalloutAdapter implements ITabCallout { @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .addValue((this instanceof IStatefulTabCallout) ? "STATEFUL" : null) .toString(); } @Override public void onIgnore(final ICalloutRecord calloutRecord) { // nothing } @Override public void onNew(final ICalloutRecord calloutRecord) { // nothing } @Override public void onSave(final ICalloutRecord calloutRecord) { // nothing } @Override public void onDelete(final ICalloutRecord calloutRecord) { // nothing } @Override public void onRefresh(final ICalloutRecord calloutRecord) { // nothing } @Override public void onRefreshAll(final ICalloutRecord calloutRecord) { // nothing } @Override public void onAfterQuery(final ICalloutRecord calloutRecord) { // nothing } }
gpl-2.0
drcrane/fred
src/freenet/node/DarknetPeerNode.java
61774
package freenet.node; import static java.util.concurrent.TimeUnit.DAYS; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashSet; import java.util.zip.DeflaterOutputStream; import java.util.zip.InflaterInputStream; import freenet.client.DefaultMIMETypes; import freenet.io.comm.DMT; import freenet.io.comm.DisconnectedException; import freenet.io.comm.FreenetInetAddress; import freenet.io.comm.Message; import freenet.io.comm.NotConnectedException; import freenet.io.comm.Peer; import freenet.io.comm.PeerParseException; import freenet.io.comm.ReferenceSignatureVerificationException; import freenet.io.comm.RetrievalException; import freenet.io.xfer.BulkReceiver; import freenet.io.xfer.BulkTransmitter; import freenet.io.xfer.PartiallyReceivedBulk; import freenet.keys.FreenetURI; import freenet.l10n.NodeL10n; import freenet.node.useralerts.AbstractUserAlert; import freenet.node.useralerts.BookmarkFeedUserAlert; import freenet.node.useralerts.DownloadFeedUserAlert; import freenet.node.useralerts.N2NTMUserAlert; import freenet.node.useralerts.UserAlert; import freenet.support.Base64; import freenet.support.HTMLNode; import freenet.support.IllegalBase64Exception; import freenet.support.Logger; import freenet.support.Logger.LogLevel; import freenet.support.SimpleFieldSet; import freenet.support.SizeUtil; import freenet.support.api.HTTPUploadedFile; import freenet.support.api.RandomAccessBuffer; import freenet.support.io.BucketTools; import freenet.support.io.ByteArrayRandomAccessBuffer; import freenet.support.io.FileUtil; import freenet.support.io.FileRandomAccessBuffer; public class DarknetPeerNode extends PeerNode { /** Name of this node */ String myName; /** True if this peer is not to be connected with */ private boolean isDisabled; /** True if we don't send handshake requests to this peer, but will connect if we receive one */ private boolean isListenOnly; /** True if we send handshake requests to this peer in infrequent bursts */ private boolean isBurstOnly; /** True if we want to ignore the source port of the node's sent packets. * This is normally set when dealing with an Evil Corporate Firewall which rewrites the port on outgoing * packets but does not redirect incoming packets destined to the rewritten port. * What it does is this: If we have an address with the same IP but a different port, to the detectedPeer, * we use that instead. */ private boolean ignoreSourcePort; /** True if we want to allow LAN/localhost addresses. */ private boolean allowLocalAddresses; /** Extra peer data file numbers */ private LinkedHashSet<Integer> extraPeerDataFileNumbers; /** Private comment on the peer for /friends/ page */ private String privateDarknetComment; /** Private comment on the peer for /friends/ page's extra peer data file number */ private int privateDarknetCommentFileNumber; /** Queued-to-send N2NM extra peer data file numbers */ private LinkedHashSet<Integer> queuedToSendN2NMExtraPeerDataFileNumbers; private FRIEND_TRUST trustLevel; private FRIEND_VISIBILITY ourVisibility; private FRIEND_VISIBILITY theirVisibility; private static boolean logMINOR; public enum FRIEND_TRUST { LOW, NORMAL, HIGH; private static final FRIEND_TRUST[] valuesBackwards; static { final FRIEND_TRUST[] values = values(); valuesBackwards = new FRIEND_TRUST[values.length]; for(int i=0;i<values.length;i++) valuesBackwards[i] = values[values.length-i-1]; } public static FRIEND_TRUST[] valuesBackwards() { return valuesBackwards.clone(); } public boolean isDefaultValue() { return equals(FRIEND_TRUST.NORMAL); } } public enum FRIEND_VISIBILITY { YES((short)0), // Visible NAME_ONLY((short)1), // Only the name is visible, but other friends can ask for a connection NO((short)2); // Not visible to our other friends at all /** The codes are persistent and used to communicate between nodes, so they must not change. * Which is why we are not using ordinal(). */ final short code; FRIEND_VISIBILITY(short code) { this.code = code; } public boolean isStricterThan(FRIEND_VISIBILITY theirVisibility) { if(theirVisibility == null) return true; // Higher number = more strict. return theirVisibility.code < code; } public static FRIEND_VISIBILITY getByCode(short code) { for(FRIEND_VISIBILITY f : values()) { if(f.code == code) return f; } return null; } public boolean isDefaultValue() { return equals(FRIEND_VISIBILITY.YES); } } /** * Create a darknet PeerNode from a SimpleFieldSet * @param fs The SimpleFieldSet to parse * @param node2 The running Node we are part of. * @param trust If this is a new node, we will use this parameter to set the initial trust level. */ public DarknetPeerNode(SimpleFieldSet fs, Node node2, NodeCrypto crypto, PeerManager peers, boolean fromLocal, OutgoingPacketMangler mangler, FRIEND_TRUST trust, FRIEND_VISIBILITY visibility2) throws FSParseException, PeerParseException, ReferenceSignatureVerificationException { super(fs, node2, crypto, peers, fromLocal, false, mangler, false); logMINOR = Logger.shouldLog(LogLevel.MINOR, this); String name = fs.get("myName"); if(name == null) throw new FSParseException("No name"); myName = name; if(fromLocal) { SimpleFieldSet metadata = fs.subset("metadata"); isDisabled = metadata.getBoolean("isDisabled", false); isListenOnly = metadata.getBoolean("isListenOnly", false); isBurstOnly = metadata.getBoolean("isBurstOnly", false); disableRouting = disableRoutingHasBeenSetLocally = metadata.getBoolean("disableRoutingHasBeenSetLocally", false); ignoreSourcePort = metadata.getBoolean("ignoreSourcePort", false); allowLocalAddresses = metadata.getBoolean("allowLocalAddresses", false); String s = metadata.get("trustLevel"); if(s != null) { trustLevel = FRIEND_TRUST.valueOf(s); } else { trustLevel = node.securityLevels.getDefaultFriendTrust(); System.err.println("Assuming friend ("+name+") trust is opposite of friend seclevel: "+trustLevel); } s = metadata.get("ourVisibility"); if(s != null) { ourVisibility = FRIEND_VISIBILITY.valueOf(s); } else { System.err.println("Assuming friend ("+name+") wants to be invisible"); node.createVisibilityAlert(); ourVisibility = FRIEND_VISIBILITY.NO; } s = metadata.get("theirVisibility"); if(s != null) { theirVisibility = FRIEND_VISIBILITY.valueOf(s); } else { theirVisibility = FRIEND_VISIBILITY.NO; } } else { if(trust == null) throw new IllegalArgumentException(); trustLevel = trust; ourVisibility = visibility2; } // Setup the private darknet comment note privateDarknetComment = ""; privateDarknetCommentFileNumber = -1; // Setup the extraPeerDataFileNumbers extraPeerDataFileNumbers = new LinkedHashSet<Integer>(); // Setup the queuedToSendN2NMExtraPeerDataFileNumbers queuedToSendN2NMExtraPeerDataFileNumbers = new LinkedHashSet<Integer>(); } /** * * Normally this is the address that packets have been received from from this node. * However, if ignoreSourcePort is set, we will search for a similar address with a different port * number in the node reference. */ @Override public synchronized Peer getPeer(){ Peer detectedPeer = super.getPeer(); if(ignoreSourcePort) { FreenetInetAddress addr = detectedPeer == null ? null : detectedPeer.getFreenetAddress(); int port = detectedPeer == null ? -1 : detectedPeer.getPort(); if(nominalPeer == null) return detectedPeer; for(Peer p : nominalPeer) { if(p.getPort() != port && p.getFreenetAddress().equals(addr)) { return p; } } } return detectedPeer; } /** * @return True, if we are disconnected and it has been a * sufficient time period since we last sent a handshake * attempt. */ @Override public boolean shouldSendHandshake() { synchronized(this) { if(isDisabled) return false; if(isListenOnly) return false; if(!super.shouldSendHandshake()) return false; } return true; } @Override protected synchronized boolean innerProcessNewNoderef(SimpleFieldSet fs, boolean forARK, boolean forDiffNodeRef, boolean forFullNodeRef) throws FSParseException { boolean changedAnything = super.innerProcessNewNoderef(fs, forARK, forDiffNodeRef, forFullNodeRef); String name = fs.get("myName"); if(name == null && forFullNodeRef) throw new FSParseException("No name in full noderef"); if(name != null && !name.equals(myName)) { changedAnything = true; myName = name; } return changedAnything; } @Override public synchronized SimpleFieldSet exportFieldSet() { SimpleFieldSet fs = super.exportFieldSet(); fs.putSingle("myName", getName()); return fs; } @Override public synchronized SimpleFieldSet exportMetadataFieldSet(long now) { SimpleFieldSet fs = super.exportMetadataFieldSet(now); if(isDisabled) fs.putSingle("isDisabled", "true"); if(isListenOnly) fs.putSingle("isListenOnly", "true"); if(isBurstOnly) fs.putSingle("isBurstOnly", "true"); if(ignoreSourcePort) fs.putSingle("ignoreSourcePort", "true"); if(allowLocalAddresses) fs.putSingle("allowLocalAddresses", "true"); if(disableRoutingHasBeenSetLocally) fs.putSingle("disableRoutingHasBeenSetLocally", "true"); fs.putSingle("trustLevel", trustLevel.name()); fs.putSingle("ourVisibility", ourVisibility.name()); if(theirVisibility != null) fs.putSingle("theirVisibility", theirVisibility.name()); return fs; } public synchronized String getName() { return myName; } @Override protected synchronized int getPeerNodeStatus(long now, long backedOffUntilRT, long backedOffUntilBulk, boolean overPingThreshold, boolean noLoadStats) { if(isDisabled) { return PeerManager.PEER_NODE_STATUS_DISABLED; } int status = super.getPeerNodeStatus(now, backedOffUntilRT, backedOffUntilBulk, overPingThreshold, noLoadStats); if(status == PeerManager.PEER_NODE_STATUS_CONNECTED || status == PeerManager.PEER_NODE_STATUS_CLOCK_PROBLEM || status == PeerManager.PEER_NODE_STATUS_ROUTING_BACKED_OFF || status == PeerManager.PEER_NODE_STATUS_CONN_ERROR || status == PeerManager.PEER_NODE_STATUS_TOO_NEW || status == PeerManager.PEER_NODE_STATUS_TOO_OLD || status == PeerManager.PEER_NODE_STATUS_ROUTING_DISABLED || status == PeerManager.PEER_NODE_STATUS_DISCONNECTING || status == PeerManager.PEER_NODE_STATUS_NO_LOAD_STATS) return status; if(isListenOnly) return PeerManager.PEER_NODE_STATUS_LISTEN_ONLY; if(isBurstOnly) return PeerManager.PEER_NODE_STATUS_LISTENING; return status; } public void enablePeer() { synchronized(this) { isDisabled = false; } setPeerNodeStatus(System.currentTimeMillis()); node.peers.writePeersDarknetUrgent(); } public void disablePeer() { synchronized(this) { isDisabled = true; } if(isConnected()) { forceDisconnect(); } stopARKFetcher(); setPeerNodeStatus(System.currentTimeMillis()); node.peers.writePeersDarknetUrgent(); } @Override public synchronized boolean isDisabled() { return isDisabled; } public void setListenOnly(boolean setting) { synchronized(this) { isListenOnly = setting; } if(setting && isBurstOnly()) { setBurstOnly(false); } if(setting) { stopARKFetcher(); } setPeerNodeStatus(System.currentTimeMillis()); node.peers.writePeersDarknetUrgent(); } public synchronized boolean isListenOnly() { return isListenOnly; } public void setBurstOnly(boolean setting) { synchronized(this) { isBurstOnly = setting; } if(setting && isListenOnly()) { setListenOnly(false); } long now = System.currentTimeMillis(); if(!setting) { synchronized(this) { sendHandshakeTime = now; // don't keep any long handshake delays we might have had under BurstOnly } } setPeerNodeStatus(now); node.peers.writePeersDarknetUrgent(); } public void setIgnoreSourcePort(boolean setting) { synchronized(this) { ignoreSourcePort = setting; } } /** * Change the routing status of a peer * * @param shouldRoute * @param localRequest (true everywhere but in NodeDispatcher) */ public void setRoutingStatus(boolean shouldRoute, boolean localRequest) { synchronized(this) { if(localRequest) disableRoutingHasBeenSetLocally = !shouldRoute; else disableRoutingHasBeenSetRemotely = !shouldRoute; disableRouting = disableRoutingHasBeenSetLocally || disableRoutingHasBeenSetRemotely; } if(localRequest) { Message msg = DMT.createRoutingStatus(shouldRoute); try { sendAsync(msg, null, node.nodeStats.setRoutingStatusCtr); } catch(NotConnectedException e) { // ok } } setPeerNodeStatus(System.currentTimeMillis()); node.peers.writePeersDarknetUrgent(); } @Override public boolean isIgnoreSource() { return ignoreSourcePort; } @Override public boolean isBurstOnly() { synchronized(this) { if(isBurstOnly) return true; } return super.isBurstOnly(); } @Override public boolean allowLocalAddresses() { synchronized(this) { if(allowLocalAddresses) return true; } return super.allowLocalAddresses(); } public void setAllowLocalAddresses(boolean setting) { synchronized(this) { allowLocalAddresses = setting; } node.peers.writePeersDarknetUrgent(); } public boolean readExtraPeerData() { String extraPeerDataDirPath = node.getExtraPeerDataDir(); File extraPeerDataPeerDir = new File(extraPeerDataDirPath+File.separator+getIdentityString()); if(!extraPeerDataPeerDir.exists()) { return false; } if(!extraPeerDataPeerDir.isDirectory()) { Logger.error(this, "Extra peer data directory for peer not a directory: "+extraPeerDataPeerDir.getPath()); return false; } File[] extraPeerDataFiles = extraPeerDataPeerDir.listFiles(); if(extraPeerDataFiles == null) { return false; } boolean gotError = false; boolean readResult = false; for (File extraPeerDataFile : extraPeerDataFiles) { Integer fileNumber; try { fileNumber = Integer.valueOf(extraPeerDataFile.getName()); } catch (NumberFormatException e) { gotError = true; continue; } synchronized(extraPeerDataFileNumbers) { extraPeerDataFileNumbers.add(fileNumber); } readResult = readExtraPeerDataFile(extraPeerDataFile, fileNumber.intValue()); if(!readResult) { gotError = true; } } return !gotError; } public boolean rereadExtraPeerDataFile(int fileNumber) { if(logMINOR) Logger.minor(this, "Rereading peer data file "+fileNumber+" for "+shortToString()); String extraPeerDataDirPath = node.getExtraPeerDataDir(); File extraPeerDataPeerDir = new File(extraPeerDataDirPath+File.separator+getIdentityString()); if(!extraPeerDataPeerDir.exists()) { Logger.error(this, "Extra peer data directory for peer does not exist: "+extraPeerDataPeerDir.getPath()); return false; } if(!extraPeerDataPeerDir.isDirectory()) { Logger.error(this, "Extra peer data directory for peer not a directory: "+extraPeerDataPeerDir.getPath()); return false; } File extraPeerDataFile = new File(extraPeerDataDirPath+File.separator+getIdentityString()+File.separator+fileNumber); if(!extraPeerDataFile.exists()) { Logger.error(this, "Extra peer data file for peer does not exist: "+extraPeerDataFile.getPath()); return false; } return readExtraPeerDataFile(extraPeerDataFile, fileNumber); } public boolean readExtraPeerDataFile(File extraPeerDataFile, int fileNumber) { if(logMINOR) Logger.minor(this, "Reading "+extraPeerDataFile+" : "+fileNumber+" for "+shortToString()); boolean gotError = false; if(!extraPeerDataFile.exists()) { if(logMINOR) Logger.minor(this, "Does not exist"); return false; } Logger.normal(this, "extraPeerDataFile: "+extraPeerDataFile.getPath()); FileInputStream fis; try { fis = new FileInputStream(extraPeerDataFile); } catch (FileNotFoundException e1) { Logger.normal(this, "Extra peer data file not found: "+extraPeerDataFile.getPath()); return false; } InputStreamReader isr; try { isr = new InputStreamReader(fis, "UTF-8"); } catch (UnsupportedEncodingException e) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e); } BufferedReader br = new BufferedReader(isr); SimpleFieldSet fs = null; try { // Read in the single SimpleFieldSet fs = new SimpleFieldSet(br, false, true); } catch (EOFException e3) { // End of file, fine } catch (IOException e4) { Logger.error(this, "Could not read extra peer data file: "+e4, e4); } finally { try { br.close(); } catch (IOException e5) { Logger.error(this, "Ignoring "+e5+" caught reading "+extraPeerDataFile.getPath(), e5); } } if(fs == null) { Logger.normal(this, "Deleting corrupt (too short?) file: "+extraPeerDataFile); deleteExtraPeerDataFile(fileNumber); return true; } boolean parseResult = false; try { parseResult = parseExtraPeerData(fs, extraPeerDataFile, fileNumber); if(!parseResult) { gotError = true; } } catch (FSParseException e2) { Logger.error(this, "Could not parse extra peer data: "+e2+ '\n' +fs.toString(),e2); gotError = true; } return !gotError; } private boolean parseExtraPeerData(SimpleFieldSet fs, File extraPeerDataFile, int fileNumber) throws FSParseException { String extraPeerDataTypeString = fs.get("extraPeerDataType"); int extraPeerDataType = -1; try { extraPeerDataType = Integer.parseInt(extraPeerDataTypeString); } catch (NumberFormatException e) { Logger.error(this, "NumberFormatException parsing extraPeerDataType ("+extraPeerDataTypeString+") in file "+extraPeerDataFile.getPath()); return false; } if(extraPeerDataType == Node.EXTRA_PEER_DATA_TYPE_N2NTM) { node.handleNodeToNodeTextMessageSimpleFieldSet(fs, this, fileNumber); return true; } else if(extraPeerDataType == Node.EXTRA_PEER_DATA_TYPE_PEER_NOTE) { String peerNoteTypeString = fs.get("peerNoteType"); int peerNoteType = -1; try { peerNoteType = Integer.parseInt(peerNoteTypeString); } catch (NumberFormatException e) { Logger.error(this, "NumberFormatException parsing peerNoteType ("+peerNoteTypeString+") in file "+extraPeerDataFile.getPath()); return false; } if(peerNoteType == Node.PEER_NOTE_TYPE_PRIVATE_DARKNET_COMMENT) { synchronized(this) { try { privateDarknetComment = Base64.decodeUTF8(fs.get("privateDarknetComment")); } catch (IllegalBase64Exception e) { Logger.error(this, "Bad Base64 encoding when decoding a private darknet comment SimpleFieldSet", e); return false; } privateDarknetCommentFileNumber = fileNumber; } return true; } Logger.error(this, "Read unknown peer note type '"+peerNoteType+"' from file "+extraPeerDataFile.getPath()); return false; } else if(extraPeerDataType == Node.EXTRA_PEER_DATA_TYPE_QUEUED_TO_SEND_N2NM) { boolean sendSuccess = false; int type = fs.getInt("n2nType"); if(isConnected()) { Message n2nm; if(fs.get("extraPeerDataType") != null) { fs.removeValue("extraPeerDataType"); } if(fs.get("senderFileNumber") != null) { fs.removeValue("senderFileNumber"); } fs.putOverwrite("senderFileNumber", String.valueOf(fileNumber)); if(fs.get("sentTime") != null) { fs.removeValue("sentTime"); } fs.putOverwrite("sentTime", Long.toString(System.currentTimeMillis())); try { n2nm = DMT.createNodeToNodeMessage(type, fs.toString().getBytes("UTF-8")); } catch (UnsupportedEncodingException e) { Logger.error(this, "UnsupportedEncodingException processing extraPeerDataType ("+extraPeerDataTypeString+") in file "+extraPeerDataFile.getPath(), e); throw new Error("Impossible: JVM doesn't support UTF-8: " + e, e); } try { synchronized(queuedToSendN2NMExtraPeerDataFileNumbers) { node.usm.send(this, n2nm, null); Logger.normal(this, "Sent queued ("+fileNumber+") N2NM to '"+getName()+"': "+n2nm); sendSuccess = true; queuedToSendN2NMExtraPeerDataFileNumbers.remove(fileNumber); } deleteExtraPeerDataFile(fileNumber); } catch (NotConnectedException e) { sendSuccess = false; // redundant, but clear } } if(!sendSuccess) { synchronized(queuedToSendN2NMExtraPeerDataFileNumbers) { fs.putOverwrite("extraPeerDataType", Integer.toString(extraPeerDataType)); fs.removeValue("sentTime"); queuedToSendN2NMExtraPeerDataFileNumbers.add(Integer.valueOf(fileNumber)); } } return true; } else if(extraPeerDataType == Node.EXTRA_PEER_DATA_TYPE_BOOKMARK) { Logger.normal(this, "Read friend bookmark" + fs.toString()); handleFproxyBookmarkFeed(fs, fileNumber); return true; } else if(extraPeerDataType == Node.EXTRA_PEER_DATA_TYPE_DOWNLOAD) { Logger.normal(this, "Read friend download" + fs.toString()); handleFproxyDownloadFeed(fs, fileNumber); return true; } Logger.error(this, "Read unknown extra peer data type '"+extraPeerDataType+"' from file "+extraPeerDataFile.getPath()); return false; } public int writeNewExtraPeerDataFile(SimpleFieldSet fs, int extraPeerDataType) { String extraPeerDataDirPath = node.getExtraPeerDataDir(); if(extraPeerDataType > 0) fs.putOverwrite("extraPeerDataType", Integer.toString(extraPeerDataType)); File extraPeerDataPeerDir = new File(extraPeerDataDirPath+File.separator+getIdentityString()); if(!extraPeerDataPeerDir.exists()) { if(!extraPeerDataPeerDir.mkdir()) { Logger.error(this, "Extra peer data directory for peer could not be created: "+extraPeerDataPeerDir.getPath()); return -1; } } if(!extraPeerDataPeerDir.isDirectory()) { Logger.error(this, "Extra peer data directory for peer not a directory: "+extraPeerDataPeerDir.getPath()); return -1; } Integer[] localFileNumbers; int nextFileNumber = 0; synchronized(extraPeerDataFileNumbers) { // Find the first free slot localFileNumbers = extraPeerDataFileNumbers.toArray(new Integer[extraPeerDataFileNumbers.size()]); Arrays.sort(localFileNumbers); for (int localFileNumber : localFileNumbers) { if(localFileNumber > nextFileNumber) { break; } nextFileNumber = localFileNumber + 1; } extraPeerDataFileNumbers.add(nextFileNumber); } FileOutputStream fos; File extraPeerDataFile = new File(extraPeerDataPeerDir.getPath()+File.separator+nextFileNumber); if(extraPeerDataFile.exists()) { Logger.error(this, "Extra peer data file already exists: "+extraPeerDataFile.getPath()); return -1; } String f = extraPeerDataFile.getPath(); try { fos = new FileOutputStream(f); } catch (FileNotFoundException e2) { Logger.error(this, "Cannot write extra peer data file to disk: Cannot create " + f + " - " + e2, e2); return -1; } OutputStreamWriter w; try { w = new OutputStreamWriter(fos, "UTF-8"); } catch (UnsupportedEncodingException e2) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e2, e2); } BufferedWriter bw = new BufferedWriter(w); try { fs.writeTo(bw); bw.close(); } catch (IOException e) { try { fos.close(); } catch (IOException e1) { Logger.error(this, "Cannot close extra peer data file: "+e, e); } Logger.error(this, "Cannot write file: " + e, e); return -1; } return nextFileNumber; } public void deleteExtraPeerDataFile(int fileNumber) { String extraPeerDataDirPath = node.getExtraPeerDataDir(); File extraPeerDataPeerDir = new File(extraPeerDataDirPath, getIdentityString()); if(!extraPeerDataPeerDir.exists()) { Logger.error(this, "Extra peer data directory for peer does not exist: "+extraPeerDataPeerDir.getPath()); return; } if(!extraPeerDataPeerDir.isDirectory()) { Logger.error(this, "Extra peer data directory for peer not a directory: "+extraPeerDataPeerDir.getPath()); return; } File extraPeerDataFile = new File(extraPeerDataPeerDir, Integer.toString(fileNumber)); if(!extraPeerDataFile.exists()) { Logger.error(this, "Extra peer data file for peer does not exist: "+extraPeerDataFile.getPath()); return; } synchronized(extraPeerDataFileNumbers) { extraPeerDataFileNumbers.remove(fileNumber); } if(!extraPeerDataFile.delete()) { if(extraPeerDataFile.exists()) { Logger.error(this, "Cannot delete file "+extraPeerDataFile+" after sending message to "+getPeer()+" - it may be resent on resting the node"); } else { Logger.normal(this, "File does not exist when deleting: "+extraPeerDataFile+" after sending message to "+getPeer()); } } } public void removeExtraPeerDataDir() { String extraPeerDataDirPath = node.getExtraPeerDataDir(); File extraPeerDataPeerDir = new File(extraPeerDataDirPath+File.separator+getIdentityString()); if(!extraPeerDataPeerDir.exists()) { Logger.error(this, "Extra peer data directory for peer does not exist: "+extraPeerDataPeerDir.getPath()); return; } if(!extraPeerDataPeerDir.isDirectory()) { Logger.error(this, "Extra peer data directory for peer not a directory: "+extraPeerDataPeerDir.getPath()); return; } Integer[] localFileNumbers; synchronized(extraPeerDataFileNumbers) { localFileNumbers = extraPeerDataFileNumbers.toArray(new Integer[extraPeerDataFileNumbers.size()]); } for (Integer localFileNumber : localFileNumbers) { deleteExtraPeerDataFile(localFileNumber.intValue()); } extraPeerDataPeerDir.delete(); } public boolean rewriteExtraPeerDataFile(SimpleFieldSet fs, int extraPeerDataType, int fileNumber) { String extraPeerDataDirPath = node.getExtraPeerDataDir(); if(extraPeerDataType > 0) fs.putOverwrite("extraPeerDataType", Integer.toString(extraPeerDataType)); File extraPeerDataPeerDir = new File(extraPeerDataDirPath+File.separator+getIdentityString()); if(!extraPeerDataPeerDir.exists()) { Logger.error(this, "Extra peer data directory for peer does not exist: "+extraPeerDataPeerDir.getPath()); return false; } if(!extraPeerDataPeerDir.isDirectory()) { Logger.error(this, "Extra peer data directory for peer not a directory: "+extraPeerDataPeerDir.getPath()); return false; } File extraPeerDataFile = new File(extraPeerDataDirPath+File.separator+getIdentityString()+File.separator+fileNumber); if(!extraPeerDataFile.exists()) { Logger.error(this, "Extra peer data file for peer does not exist: "+extraPeerDataFile.getPath()); return false; } String f = extraPeerDataFile.getPath(); FileOutputStream fos; try { fos = new FileOutputStream(f); } catch (FileNotFoundException e2) { Logger.error(this, "Cannot write extra peer data file to disk: Cannot open " + f + " - " + e2, e2); return false; } OutputStreamWriter w; try { w = new OutputStreamWriter(fos, "UTF-8"); } catch (UnsupportedEncodingException e2) { throw new Error("Impossible: JVM doesn't support UTF-8: " + e2, e2); } BufferedWriter bw = new BufferedWriter(w); try { fs.writeTo(bw); bw.close(); } catch (IOException e) { try { fos.close(); } catch (IOException e1) { Logger.error(this, "Cannot close extra peer data file: "+e, e); } Logger.error(this, "Cannot write file: " + e, e); return false; } return true; } public synchronized String getPrivateDarknetCommentNote() { return privateDarknetComment; } public synchronized void setPrivateDarknetCommentNote(String comment) { int localFileNumber; privateDarknetComment = comment; localFileNumber = privateDarknetCommentFileNumber; SimpleFieldSet fs = new SimpleFieldSet(true); fs.put("peerNoteType", Node.PEER_NOTE_TYPE_PRIVATE_DARKNET_COMMENT); fs.putSingle("privateDarknetComment", Base64.encodeUTF8(comment)); if(localFileNumber == -1) { localFileNumber = writeNewExtraPeerDataFile(fs, Node.EXTRA_PEER_DATA_TYPE_PEER_NOTE); privateDarknetCommentFileNumber = localFileNumber; } else { rewriteExtraPeerDataFile(fs, Node.EXTRA_PEER_DATA_TYPE_PEER_NOTE, localFileNumber); } } @Override public void queueN2NM(SimpleFieldSet fs) { int fileNumber = writeNewExtraPeerDataFile( fs, Node.EXTRA_PEER_DATA_TYPE_QUEUED_TO_SEND_N2NM); synchronized(queuedToSendN2NMExtraPeerDataFileNumbers) { queuedToSendN2NMExtraPeerDataFileNumbers.add(fileNumber); } } public void sendQueuedN2NMs() { if(logMINOR) Logger.minor(this, "Sending queued N2NMs for "+shortToString()); Integer[] localFileNumbers; synchronized(queuedToSendN2NMExtraPeerDataFileNumbers) { localFileNumbers = queuedToSendN2NMExtraPeerDataFileNumbers.toArray(new Integer[queuedToSendN2NMExtraPeerDataFileNumbers.size()]); } Arrays.sort(localFileNumbers); for (Integer localFileNumber : localFileNumbers) { rereadExtraPeerDataFile(localFileNumber.intValue()); } } @Override void startARKFetcher() { synchronized(this) { if(isListenOnly) { Logger.minor(this, "Not starting ark fetcher for "+this+" as it's in listen-only mode."); return; } } super.startARKFetcher(); } @Override public String getTMCIPeerInfo() { return getName()+'\t'+super.getTMCIPeerInfo(); } /** * A method to be called once at the beginning of every time isConnected() is true */ @Override protected void onConnect() { super.onConnect(); sendQueuedN2NMs(); } // File transfer offers // FIXME this should probably be somewhere else, along with the N2NM stuff... but where? // FIXME this should be persistent across node restarts /** Files I have offered to this peer */ private final HashMap<Long, FileOffer> myFileOffersByUID = new HashMap<Long, FileOffer>(); /** Files this peer has offered to me */ private final HashMap<Long, FileOffer> hisFileOffersByUID = new HashMap<Long, FileOffer>(); private void storeOffers() { // FIXME do something } // FIXME refactor this. We want to be able to send file transfers from code that isn't related to fproxy. // FIXME and it should be able to talk to plugins on other nodes etc etc. // FIXME there are already type fields etc, so this shouldn't be too difficult? But it's not really supported at the moment. // FIXME See also e.g. fcp/SendTextMessage. class FileOffer { final long uid; final String filename; final String mimeType; final String comment; /** Only valid if amIOffering == false. Set when start receiving. */ private File destination; private RandomAccessBuffer data; final long size; /** Who is offering it? True = I am offering it, False = I am being offered it */ final boolean amIOffering; private PartiallyReceivedBulk prb; private BulkTransmitter transmitter; private BulkReceiver receiver; /** True if the offer has either been accepted or rejected */ private boolean acceptedOrRejected; FileOffer(long uid, RandomAccessBuffer data, String filename, String mimeType, String comment) throws IOException { this.uid = uid; this.data = data; this.filename = filename; this.mimeType = mimeType; this.comment = comment; size = data.size(); amIOffering = true; } public FileOffer(SimpleFieldSet fs, boolean amIOffering) throws FSParseException { uid = fs.getLong("uid"); size = fs.getLong("size"); mimeType = fs.get("metadata.contentType"); filename = FileUtil.sanitize(fs.get("filename"), mimeType); destination = null; String s = fs.get("comment"); if(s != null) { try { s = Base64.decodeUTF8(s); } catch (IllegalBase64Exception e) { // Maybe it wasn't encoded? FIXME remove Logger.error(this, "Bad Base64 encoding when decoding a private darknet comment SimpleFieldSet", e); } } comment = s; this.amIOffering = amIOffering; } public void toFieldSet(SimpleFieldSet fs) { fs.put("uid", uid); fs.putSingle("filename", filename); fs.putSingle("metadata.contentType", mimeType); fs.putSingle("comment", Base64.encodeUTF8(comment)); fs.put("size", size); } public void accept() { acceptedOrRejected = true; final String baseFilename = "direct-"+FileUtil.sanitize(getName())+"-"+filename; final File dest = node.clientCore.downloadsDir().file(baseFilename+".part"); destination = node.clientCore.downloadsDir().file(baseFilename); try { data = new FileRandomAccessBuffer(dest, size, false); } catch (IOException e) { // Impossible throw new Error("Impossible: FileNotFoundException opening with RAF with rw! "+e, e); } prb = new PartiallyReceivedBulk(node.usm, size, Node.PACKET_SIZE, data, false); receiver = new BulkReceiver(prb, DarknetPeerNode.this, uid, null); // FIXME make this persistent node.executor.execute(new Runnable() { @Override public void run() { if(logMINOR) Logger.minor(this, "Received file"); try { if(!receiver.receive()) { String err = "Failed to receive "+this; Logger.error(this, err); System.err.println(err); onReceiveFailure(); } else { data.close(); if(!dest.renameTo(node.clientCore.downloadsDir().file(baseFilename))){ Logger.error(this, "Failed to rename "+dest.getName()+" to remove .part suffix."); } onReceiveSuccess(); } } catch (Throwable t) { Logger.error(this, "Caught "+t+" receiving file", t); onReceiveFailure(); } finally { remove(); } if(logMINOR) Logger.minor(this, "Received file"); } }, "Receiver for bulk transfer "+uid+":"+filename); sendFileOfferAccepted(uid); } protected void remove() { Long l = uid; synchronized(DarknetPeerNode.this) { myFileOffersByUID.remove(l); hisFileOffersByUID.remove(l); } data.close(); } public void send() throws DisconnectedException { prb = new PartiallyReceivedBulk(node.usm, size, Node.PACKET_SIZE, data, true); transmitter = new BulkTransmitter(prb, DarknetPeerNode.this, uid, false, node.nodeStats.nodeToNodeCounter, false); if(logMINOR) Logger.minor(this, "Sending "+uid); node.executor.execute(new Runnable() { @Override public void run() { if(logMINOR) Logger.minor(this, "Sending file"); try { if(!transmitter.send()) { String err = "Failed to send "+uid+" for "+FileOffer.this; Logger.error(this, err); System.err.println(err); } } catch (Throwable t) { Logger.error(this, "Caught "+t+" sending file", t); remove(); } if(logMINOR) Logger.minor(this, "Sent file"); } }, "Sender for bulk transfer "+uid+":"+filename); } public void reject() { acceptedOrRejected = true; sendFileOfferRejected(uid); } public void onRejected() { transmitter.cancel("FileOffer: Offer rejected"); // FIXME prb's can't be shared, right? Well they aren't here... prb.abort(RetrievalException.CANCELLED_BY_RECEIVER, "Cancelled by receiver"); } protected void onReceiveFailure() { UserAlert alert = new AbstractUserAlert() { @Override public String dismissButtonText() { return NodeL10n.getBase().getString("UserAlert.hide"); } @Override public HTMLNode getHTMLText() { HTMLNode div = new HTMLNode("div"); div.addChild("p", l10n("failedReceiveHeader", new String[] { "filename", "node" }, new String[] { filename, getName() })); // Descriptive table describeFile(div); return div; } @Override public short getPriorityClass() { return UserAlert.MINOR; } @Override public String getText() { StringBuilder sb = new StringBuilder(); sb.append(l10n("failedReceiveHeader", new String[] { "filename", "node" }, new String[] { filename, getName() })); sb.append('\n'); sb.append(l10n("fileLabel")); sb.append(' '); sb.append(filename); sb.append('\n'); sb.append(l10n("sizeLabel")); sb.append(' '); sb.append(SizeUtil.formatSize(size)); sb.append('\n'); sb.append(l10n("mimeLabel")); sb.append(' '); sb.append(mimeType); sb.append('\n'); sb.append(l10n("senderLabel")); sb.append(' '); sb.append(getName()); sb.append('\n'); if(comment != null && comment.length() > 0) { sb.append(l10n("commentLabel")); sb.append(' '); sb.append(comment); } return sb.toString(); } @Override public String getTitle() { return l10n("failedReceiveTitle"); } @Override public boolean isValid() { return true; } @Override public void isValid(boolean validity) { // Ignore } @Override public void onDismiss() { // Ignore } @Override public boolean shouldUnregisterOnDismiss() { return true; } @Override public boolean userCanDismiss() { return true; } @Override public String getShortText() { return l10n("failedReceiveShort", new String[] { "filename", "node" }, new String[] { filename, getName() }); } }; node.clientCore.alerts.register(alert); } private void onReceiveSuccess() { UserAlert alert = new AbstractUserAlert() { @Override public String dismissButtonText() { return NodeL10n.getBase().getString("UserAlert.hide"); } @Override public HTMLNode getHTMLText() { HTMLNode div = new HTMLNode("div"); // FIXME localise!!! div.addChild("p", l10n("succeededReceiveHeader", new String[] { "filename", "node" }, new String[] { filename, getName() })); // Descriptive table describeFile(div); return div; } @Override public short getPriorityClass() { return UserAlert.MINOR; } @Override public String getText() { String header = l10n("succeededReceiveHeader", new String[] { "filename", "node" }, new String[] { filename, getName() }); return describeFileText(header); } @Override public String getTitle() { return l10n("succeededReceiveTitle"); } @Override public boolean isValid() { return true; } @Override public void isValid(boolean validity) { // Ignore } @Override public void onDismiss() { // Ignore } @Override public boolean shouldUnregisterOnDismiss() { return true; } @Override public boolean userCanDismiss() { return true; } @Override public String getShortText() { return l10n("succeededReceiveShort", new String[] { "filename", "node" }, new String[] { filename, getName() }); } }; node.clientCore.alerts.register(alert); } /** Ask the user whether (s)he wants to download a file from a direct peer */ public UserAlert askUserUserAlert() { return new AbstractUserAlert() { @Override public String dismissButtonText() { return null; // Cannot hide, but can reject } @Override public HTMLNode getHTMLText() { HTMLNode div = new HTMLNode("div"); div.addChild("p", l10n("offeredFileHeader", "name", getName())); // Descriptive table describeFile(div); // Accept/reject form // Hopefully we will have a container when this function is called! HTMLNode form = node.clientCore.getToadletContainer().addFormChild(div, "/friends/", "f2fFileOfferAcceptForm"); // FIXME node_ is inefficient form.addChild("input", new String[] { "type", "name" }, new String[] { "hidden", "node_"+DarknetPeerNode.this.hashCode() }); form.addChild("input", new String[] { "type", "name", "value" }, new String[] { "hidden", "id", Long.toString(uid) }); form.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "acceptTransfer", l10n("acceptTransferButton") }); form.addChild("input", new String[] { "type", "name", "value" }, new String[] { "submit", "rejectTransfer", l10n("rejectTransferButton") }); return div; } @Override public short getPriorityClass() { return UserAlert.MINOR; } @Override public String getText() { String header = l10n("offeredFileHeader", "name", getName()); return describeFileText(header); } @Override public String getTitle() { return l10n("askUserTitle"); } @Override public boolean isValid() { if(acceptedOrRejected) { node.clientCore.alerts.unregister(this); return false; } return true; } @Override public void isValid(boolean validity) { // Ignore } @Override public void onDismiss() { // Ignore } @Override public boolean shouldUnregisterOnDismiss() { return false; } @Override public boolean userCanDismiss() { return false; // should accept or reject } @Override public String getShortText() { return l10n("offeredFileShort", new String[] { "filename", "node" }, new String[] { filename, getName() }); } }; } protected void addComment(HTMLNode node) { String[] lines = comment.split("\n"); for (int i = 0, c = lines.length; i < c; i++) { node.addChild("#", lines[i]); if(i != lines.length - 1) node.addChild("br"); } } private String l10n(String key) { return NodeL10n.getBase().getString("FileOffer."+key); } private String l10n(String key, String pattern, String value) { return NodeL10n.getBase().getString("FileOffer."+key, pattern, value); } private String l10n(String key, String[] pattern, String[] value) { return NodeL10n.getBase().getString("FileOffer."+key, pattern, value); } private String describeFileText(String header) { StringBuilder sb = new StringBuilder(); sb.append(header); sb.append('\n'); sb.append(l10n("fileLabel")); sb.append(' '); sb.append(filename); sb.append('\n'); sb.append(l10n("sizeLabel")); sb.append(' '); sb.append(SizeUtil.formatSize(size)); sb.append('\n'); sb.append(l10n("mimeLabel")); sb.append(' '); sb.append(mimeType); sb.append('\n'); sb.append(l10n("senderLabel")); sb.append(' '); sb.append(userToString()); sb.append('\n'); if(comment != null && comment.length() > 0) { sb.append(l10n("commentLabel")); sb.append(' '); sb.append(comment); } return sb.toString(); } private void describeFile(HTMLNode div) { HTMLNode table = div.addChild("table", "border", "0"); HTMLNode row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("fileLabel")); row.addChild("td").addChild("#", filename); if(destination != null) { row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("fileSavedToLabel")); row.addChild("td").addChild("#", destination.getPath()); } row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("sizeLabel")); row.addChild("td").addChild("#", SizeUtil.formatSize(size)); row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("mimeLabel")); row.addChild("td").addChild("#", mimeType); row = table.addChild("tr"); row.addChild("td").addChild("#", l10n("senderLabel")); row.addChild("td").addChild("#", getName()); row = table.addChild("tr"); if(comment != null && comment.length() > 0) { row.addChild("td").addChild("#", l10n("commentLabel")); addComment(row.addChild("td")); } } } public int sendBookmarkFeed(FreenetURI uri, String name, String description, boolean hasAnActiveLink) { long now = System.currentTimeMillis(); SimpleFieldSet fs = new SimpleFieldSet(true); fs.putSingle("URI", uri.toString()); fs.putSingle("Name", name); fs.put("composedTime", now); fs.put("hasAnActivelink", hasAnActiveLink); if(description != null) fs.putSingle("Description", Base64.encodeUTF8(description)); fs.put("type", Node.N2N_TEXT_MESSAGE_TYPE_BOOKMARK); sendNodeToNodeMessage(fs, Node.N2N_MESSAGE_TYPE_FPROXY, true, now, true); setPeerNodeStatus(System.currentTimeMillis()); return getPeerNodeStatus(); } public int sendDownloadFeed(FreenetURI URI, String description) { long now = System.currentTimeMillis(); SimpleFieldSet fs = new SimpleFieldSet(true); fs.putSingle("URI", URI.toString()); fs.put("composedTime", now); if(description != null) { fs.putSingle("Description", Base64.encodeUTF8(description)); } fs.put("type", Node.N2N_TEXT_MESSAGE_TYPE_DOWNLOAD); sendNodeToNodeMessage(fs, Node.N2N_MESSAGE_TYPE_FPROXY, true, now, true); setPeerNodeStatus(System.currentTimeMillis()); return getPeerNodeStatus(); } public int sendTextFeed(String message) { long now = System.currentTimeMillis(); SimpleFieldSet fs = new SimpleFieldSet(true); fs.put("type", Node.N2N_TEXT_MESSAGE_TYPE_USERALERT); fs.putSingle("text", Base64.encodeUTF8(message)); fs.put("composedTime", now); sendNodeToNodeMessage(fs, Node.N2N_MESSAGE_TYPE_FPROXY, true, now, true); this.setPeerNodeStatus(System.currentTimeMillis()); return getPeerNodeStatus(); } public int sendFileOfferAccepted(long uid) { long now = System.currentTimeMillis(); storeOffers(); SimpleFieldSet fs = new SimpleFieldSet(true); fs.put("type", Node.N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_ACCEPTED); fs.put("uid", uid); if(logMINOR) Logger.minor(this, "Sending node to node message (file offer accepted):\n"+fs); sendNodeToNodeMessage(fs, Node.N2N_MESSAGE_TYPE_FPROXY, true, now, true); setPeerNodeStatus(System.currentTimeMillis()); return getPeerNodeStatus(); } public int sendFileOfferRejected(long uid) { long now = System.currentTimeMillis(); storeOffers(); SimpleFieldSet fs = new SimpleFieldSet(true); fs.put("type", Node.N2N_TEXT_MESSAGE_TYPE_FILE_OFFER_REJECTED); fs.put("uid", uid); if(logMINOR) Logger.minor(this, "Sending node to node message (file offer rejected):\n"+fs); sendNodeToNodeMessage(fs, Node.N2N_MESSAGE_TYPE_FPROXY, true, now, true); setPeerNodeStatus(System.currentTimeMillis()); return getPeerNodeStatus(); } private int sendFileOffer(String fnam, String mime, String message, RandomAccessBuffer data) throws IOException { long uid = node.random.nextLong(); long now = System.currentTimeMillis(); FileOffer fo = new FileOffer(uid, data, fnam, mime, message); synchronized(this) { myFileOffersByUID.put(uid, fo); } storeOffers(); SimpleFieldSet fs = new SimpleFieldSet(true); fo.toFieldSet(fs); if(logMINOR) Logger.minor(this, "Sending node to node message (file offer):\n"+fs); fs.put("type", Node.N2N_TEXT_MESSAGE_TYPE_FILE_OFFER); sendNodeToNodeMessage(fs, Node.N2N_MESSAGE_TYPE_FPROXY, true, now, true); setPeerNodeStatus(System.currentTimeMillis()); return getPeerNodeStatus(); } public int sendFileOffer(File file, String message) throws IOException { String fnam = file.getName(); String mime = DefaultMIMETypes.guessMIMEType(fnam, false); RandomAccessBuffer data = new FileRandomAccessBuffer(file, true); return sendFileOffer(fnam, mime, message, data); } public int sendFileOffer(HTTPUploadedFile file, String message) throws IOException { String fnam = file.getFilename(); String mime = file.getContentType(); RandomAccessBuffer data = new ByteArrayRandomAccessBuffer(BucketTools.toByteArray(file.getData())); return sendFileOffer(fnam, mime, message, data); } public void handleFproxyN2NTM(SimpleFieldSet fs, int fileNumber) { String text = null; long composedTime = fs.getLong("composedTime", -1); long sentTime = fs.getLong("sentTime", -1); long receivedTime = fs.getLong("receivedTime", -1); try { text = Base64.decodeUTF8(fs.get("text")); } catch (IllegalBase64Exception e) { Logger.error(this, "Bad Base64 encoding when decoding a N2NTM SimpleFieldSet", e); return; } N2NTMUserAlert userAlert = new N2NTMUserAlert(this, text, fileNumber, composedTime, sentTime, receivedTime); node.clientCore.alerts.register(userAlert); } public void handleFproxyFileOffer(SimpleFieldSet fs, int fileNumber) { final FileOffer offer; try { offer = new FileOffer(fs, false); } catch (FSParseException e) { Logger.error(this, "Could not parse offer: "+e+" on "+this+" :\n"+fs, e); return; } Long u = offer.uid; synchronized (this) { if (hisFileOffersByUID.containsKey(u)) return; // Ignore re-advertisement hisFileOffersByUID.put(u, offer); } // Don't persist for now - FIXME this.deleteExtraPeerDataFile(fileNumber); UserAlert alert = offer.askUserUserAlert(); node.clientCore.alerts.register(alert); } public void acceptTransfer(long id) { if(logMINOR) Logger.minor(this, "Accepting transfer "+id+" on "+this); FileOffer fo; synchronized(this) { fo = hisFileOffersByUID.get(id); } if(fo == null) { Logger.error(this, "Cannot accept transfer "+id+" - does not exist"); return; } fo.accept(); } public void rejectTransfer(long id) { FileOffer fo; synchronized(this) { fo = hisFileOffersByUID.remove(id); } if(fo == null) { Logger.error(this, "Cannot accept transfer "+id+" - does not exist"); return; } fo.reject(); } public void handleFproxyFileOfferAccepted(SimpleFieldSet fs, int fileNumber) { // Don't persist for now - FIXME this.deleteExtraPeerDataFile(fileNumber); long uid; try { uid = fs.getLong("uid"); } catch (FSParseException e) { Logger.error(this, "Could not parse offer accepted: "+e+" on "+this+" :\n"+fs, e); return; } if(logMINOR) Logger.minor(this, "Offer accepted for "+uid); FileOffer fo; synchronized(this) { fo = (myFileOffersByUID.get(uid)); } if(fo == null) { Logger.error(this, "No such offer: "+uid); try { sendAsync(DMT.createFNPBulkSendAborted(uid), null, node.nodeStats.nodeToNodeCounter); } catch (NotConnectedException e) { // Fine by me! } return; } try { fo.send(); } catch (DisconnectedException e) { Logger.error(this, "Cannot send because node disconnected: "+e+" for "+uid+":"+fo.filename, e); } } public void handleFproxyFileOfferRejected(SimpleFieldSet fs, int fileNumber) { // Don't persist for now - FIXME this.deleteExtraPeerDataFile(fileNumber); long uid; try { uid = fs.getLong("uid"); } catch (FSParseException e) { Logger.error(this, "Could not parse offer rejected: "+e+" on "+this+" :\n"+fs, e); return; } FileOffer fo; synchronized(this) { fo = myFileOffersByUID.remove(uid); } fo.onRejected(); } public void handleFproxyBookmarkFeed(SimpleFieldSet fs, int fileNumber) { String name = fs.get("Name"); String description = null; FreenetURI uri = null; boolean hasAnActiveLink = fs.getBoolean("hasAnActivelink", false); long composedTime = fs.getLong("composedTime", -1); long sentTime = fs.getLong("sentTime", -1); long receivedTime = fs.getLong("receivedTime", -1); try { String s = fs.get("Description"); if(s != null) description = Base64.decodeUTF8(s); uri = new FreenetURI(fs.get("URI")); } catch (MalformedURLException e) { Logger.error(this, "Malformed URI in N2NTM Bookmark Feed message"); return; } catch (IllegalBase64Exception e) { Logger.error(this, "Bad Base64 encoding when decoding a N2NTM SimpleFieldSet", e); return; } BookmarkFeedUserAlert userAlert = new BookmarkFeedUserAlert(this, name, description, hasAnActiveLink, fileNumber, uri, composedTime, sentTime, receivedTime); node.clientCore.alerts.register(userAlert); } public void handleFproxyDownloadFeed(SimpleFieldSet fs, int fileNumber) { FreenetURI uri = null; String description = null; long composedTime = fs.getLong("composedTime", -1); long sentTime = fs.getLong("sentTime", -1); long receivedTime = fs.getLong("receivedTime", -1); try { String s = fs.get("Description"); if(s != null) description = Base64.decodeUTF8(s); uri = new FreenetURI(fs.get("URI")); } catch (MalformedURLException e) { Logger.error(this, "Malformed URI in N2NTM File Feed message"); return; } catch (IllegalBase64Exception e) { Logger.error(this, "Bad Base64 encoding when decoding a N2NTM SimpleFieldSet", e); return; } DownloadFeedUserAlert userAlert = new DownloadFeedUserAlert(this, description, fileNumber, uri, composedTime, sentTime, receivedTime); node.clientCore.alerts.register(userAlert); } @Override public String userToString() { return ""+getPeer()+" : "+getName(); } @Override public PeerNodeStatus getStatus(boolean noHeavy) { return new DarknetPeerNodeStatus(this, noHeavy); } @Override public boolean isDarknet() { return true; } @Override public boolean isOpennet() { return false; } @Override public boolean isSeed() { return false; } @Override public void onSuccess(boolean insert, boolean ssk) { // Ignore it } @Override public void onRemove() { // Do nothing // FIXME is there anything we should do? } @Override public boolean isRealConnection() { return true; } @Override public boolean recordStatus() { return true; } @Override protected boolean generateIdentityFromPubkey() { return false; } @Override public boolean equals(Object o) { if(o == this) return true; // Only equal to seednode of its own type. if(o instanceof DarknetPeerNode) { return super.equals(o); } else return false; } @Override public final boolean shouldDisconnectAndRemoveNow() { return false; } @Override /** Darknet peers clear peerAddedTime on connecting. */ protected void maybeClearPeerAddedTimeOnConnect() { peerAddedTime = 0; // don't store anymore } @Override /** Darknet nodes *do* export the peer added time. However it gets * cleared on connecting: It is only kept for never-connected peers * so we can see that we haven't had a connection in a long time and * offer to get rid of them. */ protected boolean shouldExportPeerAddedTime() { return true; } @Override protected void maybeClearPeerAddedTimeOnRestart(long now) { if((now - peerAddedTime) > DAYS.toMillis(30)) peerAddedTime = 0; if(!neverConnected) peerAddedTime = 0; } // FIXME find a better solution??? @Override public void fatalTimeout() { if(node.isStopping()) return; Logger.error(this, "Disconnecting from darknet node "+this+" because of fatal timeout", new Exception("error")); System.err.println("Your friend node \""+getName()+"\" ("+getPeer()+" version "+getVersion()+") is having severe problems. We have disconnected to try to limit the effect on us. It will reconnect soon."); // FIXME post a useralert // Disconnect. forceDisconnect(); } public synchronized FRIEND_TRUST getTrustLevel() { return trustLevel; } @Override public boolean shallWeRouteAccordingToOurPeersLocation() { if(!node.shallWeRouteAccordingToOurPeersLocation()) return false; // Globally disabled if(trustLevel == FRIEND_TRUST.LOW) return false; return true; } public void setTrustLevel(FRIEND_TRUST trust) { synchronized(this) { trustLevel = trust; } node.peers.writePeersDarknetUrgent(); } /** FIXME This should be the worse of our visibility for the peer and that which the peer has told us. * I.e. visibility is reciprocal. */ public synchronized FRIEND_VISIBILITY getVisibility() { // ourVisibility can't be null. if(ourVisibility.isStricterThan(theirVisibility)) return ourVisibility; return theirVisibility; } public synchronized FRIEND_VISIBILITY getOurVisibility() { return ourVisibility; } public void setVisibility(FRIEND_VISIBILITY visibility) { synchronized(this) { if(ourVisibility == visibility) return; ourVisibility = visibility; } node.peers.writePeersDarknetUrgent(); try { sendVisibility(); } catch (NotConnectedException e) { Logger.normal(this, "Disconnected while sending visibility update"); } } private void sendVisibility() throws NotConnectedException { sendAsync(DMT.createFNPVisibility(getOurVisibility().code), null, node.nodeStats.initialMessagesCtr); } public void handleVisibility(Message m) { FRIEND_VISIBILITY v = FRIEND_VISIBILITY.getByCode(m.getShort(DMT.FRIEND_VISIBILITY)); if(v == null) { Logger.error(this, "Bogus visibility setting from peer "+this+" : code "+m.getShort(DMT.FRIEND_VISIBILITY)); v = FRIEND_VISIBILITY.NO; } synchronized(this) { if(theirVisibility == v) return; theirVisibility = v; } node.peers.writePeersDarknet(); } public synchronized FRIEND_VISIBILITY getTheirVisibility() { if(theirVisibility == null) return FRIEND_VISIBILITY.NO; return theirVisibility; } @Override boolean dontKeepFullFieldSet() { return false; } private boolean sendingFullNoderef; public void sendFullNoderef() { synchronized(this) { if(sendingFullNoderef) return; // DoS???? sendingFullNoderef = true; } try { SimpleFieldSet myFullNoderef = node.exportDarknetPublicFieldSet(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); DeflaterOutputStream dos = new DeflaterOutputStream(baos); try { myFullNoderef.writeTo(dos); dos.close(); } catch (IOException e) { Logger.error(this, "Impossible: Caught error while writing compressed noderef: "+e, e); synchronized(this) { sendingFullNoderef = false; } return; } byte[] data = baos.toByteArray(); long uid = node.fastWeakRandom.nextLong(); RandomAccessBuffer raf = new ByteArrayRandomAccessBuffer(data); PartiallyReceivedBulk prb = new PartiallyReceivedBulk(node.usm, data.length, Node.PACKET_SIZE, raf, true); try { sendAsync(DMT.createFNPMyFullNoderef(uid, data.length), null, node.nodeStats.foafCounter); } catch (NotConnectedException e1) { // Ignore synchronized(this) { sendingFullNoderef = false; } return; } final BulkTransmitter bt; try { bt = new BulkTransmitter(prb, this, uid, false, node.nodeStats.foafCounter, false); } catch (DisconnectedException e) { synchronized(this) { sendingFullNoderef = false; } return; } node.executor.execute(new Runnable() { @Override public void run() { try { bt.send(); } catch (DisconnectedException e) { // :| } finally { synchronized(DarknetPeerNode.this) { sendingFullNoderef = false; } } } }); } catch (RuntimeException e) { synchronized(this) { sendingFullNoderef = false; } throw e; } catch (Error e) { synchronized(this) { sendingFullNoderef = false; } throw e; } } private boolean receivingFullNoderef; public void handleFullNoderef(Message m) { if(this.dontKeepFullFieldSet()) return; long uid = m.getLong(DMT.UID); int length = m.getInt(DMT.NODEREF_LENGTH); if(length > 8 * 1024) { // Way too long! return; } synchronized(this) { if(receivingFullNoderef) return; // DoS???? receivingFullNoderef = true; } try { final byte[] data = new byte[length]; RandomAccessBuffer raf = new ByteArrayRandomAccessBuffer(data); PartiallyReceivedBulk prb = new PartiallyReceivedBulk(node.usm, length, Node.PACKET_SIZE, raf, false); final BulkReceiver br = new BulkReceiver(prb, this, uid, node.nodeStats.foafCounter); node.executor.execute(new Runnable() { @Override public void run() { try { if(br.receive()) { ByteArrayInputStream bais = new ByteArrayInputStream(data); InflaterInputStream dis = new InflaterInputStream(bais); SimpleFieldSet fs; try { fs = new SimpleFieldSet(new BufferedReader(new InputStreamReader(dis, "UTF-8")), false, false); } catch (UnsupportedEncodingException e) { synchronized(DarknetPeerNode.this) { receivingFullNoderef = false; } Logger.error(this, "Impossible: "+e, e); e.printStackTrace(); return; } catch (IOException e) { synchronized(DarknetPeerNode.this) { receivingFullNoderef = false; } Logger.error(this, "Impossible: "+e, e); return; } try { processNewNoderef(fs, false, false, true); } catch (FSParseException e) { Logger.error(this, "Peer "+DarknetPeerNode.this+" sent bogus full noderef: "+e, e); synchronized(DarknetPeerNode.this) { receivingFullNoderef = false; } return; } synchronized(DarknetPeerNode.this) { fullFieldSet = fs; } node.peers.writePeersDarknet(); } else { Logger.error(this, "Failed to receive noderef from "+DarknetPeerNode.this); } } finally { synchronized(DarknetPeerNode.this) { receivingFullNoderef = false; } } } }); } catch (RuntimeException e) { synchronized(this) { receivingFullNoderef = false; } throw e; } catch (Error e) { synchronized(this) { receivingFullNoderef = false; } throw e; } } @Override protected void sendInitialMessages() { super.sendInitialMessages(); try { sendVisibility(); } catch(NotConnectedException e) { Logger.error(this, "Completed handshake with " + getPeer() + " but disconnected: "+e, e); } if(!dontKeepFullFieldSet()) { try { sendAsync(DMT.createFNPGetYourFullNoderef(), null, node.nodeStats.foafCounter); } catch (NotConnectedException e) { // Ignore } } } }
gpl-2.0
xubo245/CloudSW
src/main/java/htsjdk/samtools/cram/encoding/ExternalByteArrayEncoding.java
2292
/** * **************************************************************************** * Copyright 2013 EMBL-EBI * <p/> * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * <p/> * http://www.apache.org/licenses/LICENSE-2.0 * <p/> * 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 htsjdk.samtools.cram.encoding; import htsjdk.samtools.cram.io.ExposedByteArrayOutputStream; import htsjdk.samtools.cram.io.ITF8; import htsjdk.samtools.cram.structure.EncodingID; import htsjdk.samtools.cram.structure.EncodingParams; import java.io.InputStream; import java.util.Map; public class ExternalByteArrayEncoding implements Encoding<byte[]> { private static final EncodingID encodingId = EncodingID.EXTERNAL; private int contentId = -1; public ExternalByteArrayEncoding() { } public static EncodingParams toParam(final int contentId) { final ExternalByteArrayEncoding e = new ExternalByteArrayEncoding(); e.contentId = contentId; return new EncodingParams(encodingId, e.toByteArray()); } public byte[] toByteArray() { return ITF8.writeUnsignedITF8(contentId); } public void fromByteArray(final byte[] data) { contentId = ITF8.readUnsignedITF8(data); } @Override public BitCodec<byte[]> buildCodec(final Map<Integer, InputStream> inputMap, final Map<Integer, ExposedByteArrayOutputStream> outputMap) { final InputStream inputStream = inputMap == null ? null : inputMap.get(contentId); final ExposedByteArrayOutputStream outputStream = outputMap == null ? null : outputMap .get(contentId); return new ExternalByteArrayCodec(outputStream, inputStream); } @Override public EncodingID id() { return encodingId; } }
gpl-2.0
gernoteger/RemInD
remind-core/src/main/java/at/jit/remind/core/model/content/database/FixStatementFeedback.java
701
package at.jit.remind.core.model.content.database; import at.jit.remind.core.context.messaging.Feedback; public class FixStatementFeedback implements Feedback { private String sqlStatement; public FixStatementFeedback() { } public FixStatementFeedback(String sqlStatement) { this.sqlStatement = sqlStatement; } @Override public String name() { // TODO Auto-generated method stub return FixStatementFeedback.class.getName(); } public String getSqlStatement() { return sqlStatement; } public void setSqlStatement(String sqlStatement) { this.sqlStatement = sqlStatement; } public static String getName() { return FixStatementFeedback.class.getName(); } }
gpl-2.0
radut/UniversalMediaServer
src/main/java/net/pms/dlna/DLNAMediaInfo.java
71877
/* * PS3 Media Server, for streaming any medias to your PS3. * Copyright (C) 2008 A.Brochard * * 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; version 2 * of the License only. * * 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 net.pms.dlna; import java.awt.Color; import java.awt.Font; import java.awt.FontMetrics; import java.awt.Graphics2D; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.*; import java.util.*; import javax.imageio.ImageIO; import net.coobird.thumbnailator.Thumbnails; import net.pms.Messages; import net.pms.PMS; import net.pms.configuration.PmsConfiguration; import net.pms.configuration.RendererConfiguration; import net.pms.formats.AudioAsVideo; import net.pms.formats.Format; import net.pms.formats.v2.SubtitleType; import net.pms.io.OutputParams; import net.pms.io.ProcessWrapperImpl; import net.pms.network.HTTPResource; import net.pms.util.CoverUtil; import net.pms.util.FileUtil; import net.pms.util.MpegUtil; import net.pms.util.ProcessUtil; import static net.pms.util.StringUtil.*; import static org.apache.commons.lang3.StringUtils.isNotBlank; import static org.apache.commons.lang3.StringUtils.isBlank; import org.apache.sanselan.ImageInfo; import org.apache.sanselan.ImageReadException; import org.apache.sanselan.Sanselan; import org.apache.sanselan.common.IImageMetadata; import org.apache.sanselan.formats.jpeg.JpegImageMetadata; import org.apache.sanselan.formats.tiff.TiffField; import org.apache.sanselan.formats.tiff.constants.TiffConstants; import org.jaudiotagger.audio.AudioFile; import org.jaudiotagger.audio.AudioFileIO; import org.jaudiotagger.audio.AudioHeader; import org.jaudiotagger.audio.exceptions.CannotReadException; import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException; import org.jaudiotagger.audio.exceptions.ReadOnlyFileException; import org.jaudiotagger.tag.FieldKey; import org.jaudiotagger.tag.KeyNotFoundException; import org.jaudiotagger.tag.Tag; import org.jaudiotagger.tag.TagException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class keeps track of media file metadata scanned by the MediaInfo library. * * TODO: Change all instance variables to private. For backwards compatibility * with external plugin code the variables have all been marked as deprecated * instead of changed to private, but this will surely change in the future. * When everything has been changed to private, the deprecated note can be * removed. */ public class DLNAMediaInfo implements Cloneable { private static final Logger LOGGER = LoggerFactory.getLogger(DLNAMediaInfo.class); private static final PmsConfiguration configuration = PMS.getConfiguration(); public static final long ENDFILE_POS = 99999475712L; /** * Maximum size of a stream, taking into account that some renderers (like * the PS3) will convert this <code>long</code> to <code>int</code>. * Truncating this value will still return the maximum value that an * <code>int</code> can contain. */ public static final long TRANS_SIZE = Long.MAX_VALUE - Integer.MAX_VALUE - 1; private boolean h264_parsed; // Stored in database private Double durationSec; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public int bitrate; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public int width; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public int height; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public long size; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public String codecV; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public String frameRate; private String frameRateMode; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public String aspect; public String aspectRatioDvdIso; public String aspectRatioContainer; public String aspectRatioVideoTrack; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public byte thumb[]; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public String mimeType; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public int bitsPerPixel; private byte referenceFrameCount = -1; private String avcLevel = null; private String h264Profile = null; private List<DLNAMediaAudio> audioTracks = new ArrayList<>(); private List<DLNAMediaSubtitle> subtitleTracks = new ArrayList<>(); /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public String model; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public int exposure; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public int orientation; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public int iso; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public String muxingMode; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public String muxingModeAudio; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public String container; /** * @deprecated Use {@link #getH264AnnexB()} and {@link #setH264AnnexB(byte[])} to access this variable. */ @Deprecated public byte[] h264_annexB; /** * Not stored in database. * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public boolean mediaparsed; public boolean ffmpegparsed; /** * isMediaParserV2 related, used to manage thumbnail management separated * from the main parsing process. * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public boolean thumbready; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public int dvdtrack; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public boolean secondaryFormatValid = true; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public boolean parsing = false; private boolean ffmpeg_failure; private boolean ffmpeg_annexb_failure; private boolean muxable; private Map<String, String> extras; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public boolean encrypted; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public String matrixCoefficients; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public boolean embeddedFontExists = false; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public String stereoscopy; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public String fileTitleFromMetadata; /** * @deprecated Use standard getter and setter to access this variable. */ @Deprecated public String videoTrackTitleFromMetadata; private boolean gen_thumb; private int videoTrackCount = 0; private int imageCount = 0; public int getVideoTrackCount() { return videoTrackCount; } public void setVideoTrackCount(int value) { videoTrackCount = value; } public int getAudioTrackCount() { return audioTracks.size(); } public int getImageCount() { return imageCount; } public void setImageCount(int value) { imageCount = value; } public int getSubTrackCount() { return subtitleTracks.size(); } public boolean isVideo() { return videoTrackCount > 0; } public boolean isAudio() { return videoTrackCount == 0 && audioTracks.size() == 1; } public boolean hasAudio() { return audioTracks.size() > 0; } /** * @return the number of subtitle tracks embedded in the media file. */ public boolean hasSubtitles() { return subtitleTracks.size() > 0; } public boolean isImage() { return videoTrackCount == 0 && audioTracks.size() == 0 && imageCount > 0; } /** * Used to determine whether tsMuxeR can mux the file to the renderer * instead of transcoding. * Also used by DLNAResource to help determine the DLNA.ORG_PN (file type) * value to send to the renderer. * * Some of this code is repeated in isVideoWithinH264LevelLimits(), and since * both functions are sometimes (but not always) used together, this is * not an efficient use of code. * * TODO: Fix the above situation. * TODO: Now that FFmpeg is muxing without tsMuxeR, we should make a separate * function for that, or even better, re-think this whole approach. * * @param mediaRenderer The renderer we might mux to * * @return */ public boolean isMuxable(RendererConfiguration mediaRenderer) { // Make sure the file is H.264 video if (isH264()) { muxable = true; } // Check if the renderer supports the resolution of the video if ( ( mediaRenderer.isMaximumResolutionSpecified() && ( width > mediaRenderer.getMaxVideoWidth() || height > mediaRenderer.getMaxVideoHeight() ) ) || ( !mediaRenderer.isMuxNonMod4Resolution() && !isMod4() ) ) { muxable = false; } // Temporary fix: MediaInfo support will take care of this in the future // For now, http://ps3mediaserver.org/forum/viewtopic.php?f=11&t=6361&start=0 // Bravia does not support AVC video at less than 288px high if (mediaRenderer.isBRAVIA() && height < 288) { muxable = false; } return muxable; } /** * Whether a file is a WEB-DL release. * * It's important for some devices like PS3 because WEB-DL files often have * some difference (possibly not starting on a keyframe or something to do with * SEI output from MEncoder, possibly something else) that makes the PS3 not * accept them when output from tsMuxeR via MEncoder. * * The above statement may not be applicable when using tsMuxeR via FFmpeg * so we should reappraise the situation if we make that change. * * It is unlikely it will return false-positives but it will return * false-negatives. * * @param filename the filename * @param params the file properties * * @return whether a file is a WEB-DL release */ public boolean isWebDl(String filename, OutputParams params) { // Check the filename if (filename.toLowerCase().replaceAll("\\-", "").contains("webdl")) { return true; } // Check the metadata if ( ( getFileTitleFromMetadata() != null && getFileTitleFromMetadata().toLowerCase().replaceAll("\\-", "").contains("webdl") ) || ( getVideoTrackTitleFromMetadata() != null && getVideoTrackTitleFromMetadata().toLowerCase().replaceAll("\\-", "").contains("webdl") ) || ( params.aid != null && params.aid.getAudioTrackTitleFromMetadata() != null && params.aid.getAudioTrackTitleFromMetadata().toLowerCase().replaceAll("\\-", "").contains("webdl") ) || ( params.sid != null && params.sid.getSubtitlesTrackTitleFromMetadata() != null && params.sid.getSubtitlesTrackTitleFromMetadata().toLowerCase().replaceAll("\\-", "").contains("webdl") ) ) { return true; } return false; } public Map<String, String> getExtras() { return extras; } public void putExtra(String key, String value) { if (extras == null) { extras = new HashMap<>(); } extras.put(key, value); } public String getExtrasAsString() { if (extras == null) { return null; } StringBuilder sb = new StringBuilder(); for (Map.Entry<String, String> entry : extras.entrySet()) { sb.append(entry.getKey()); sb.append("|"); sb.append(entry.getValue()); sb.append("|"); } return sb.toString(); } public void setExtrasAsString(String value) { if (value != null) { StringTokenizer st = new StringTokenizer(value, "|"); while (st.hasMoreTokens()) { try { putExtra(st.nextToken(), st.nextToken()); } catch (NoSuchElementException nsee) { LOGGER.debug("Caught exception", nsee); } } } } public DLNAMediaInfo() { thumbready = true; // this class manages thumbnails by default with the parser_v1 method gen_thumb = false; } @Deprecated public void generateThumbnail(InputFile input, Format ext, int type, Double seekPosition, boolean resume) { generateThumbnail(input, ext, type, seekPosition, resume, null); } public void generateThumbnail(InputFile input, Format ext, int type, Double seekPosition, boolean resume, RendererConfiguration renderer) { DLNAMediaInfo forThumbnail = new DLNAMediaInfo(); forThumbnail.gen_thumb = true; forThumbnail.durationSec = getDurationInSeconds(); if (seekPosition <= forThumbnail.durationSec) { forThumbnail.durationSec = seekPosition; } else { forThumbnail.durationSec /= 2; } forThumbnail.parse(input, ext, type, true, resume, renderer); thumb = forThumbnail.thumb; } private ProcessWrapperImpl getFFmpegThumbnail(InputFile media, boolean resume, RendererConfiguration renderer) { /** * Note: The text output from FFmpeg is used by renderers that do * not use MediaInfo, so do not make any changes that remove or * minimize the amount of text given by FFmpeg here */ String args[] = new String[14]; args[0] = getFfmpegPath(); File file = media.getFile(); boolean dvrms = file != null && file.getAbsolutePath().toLowerCase().endsWith("dvr-ms"); if (dvrms && isNotBlank(configuration.getFfmpegAlternativePath())) { args[0] = configuration.getFfmpegAlternativePath(); } args[1] = "-ss"; if (resume) { args[2] = "" + (int) getDurationInSeconds(); } else { args[2] = "" + configuration.getThumbnailSeekPos(); } args[3] = "-i"; if (file != null) { args[4] = ProcessUtil.getShortFileNameIfWideChars(file.getAbsolutePath()); } else { args[4] = "-"; } args[5] = "-an"; args[6] = "-an"; // Thumbnail resolution int thumbnailWidth = 320; int thumbnailHeight = 180; double thumbnailRatio = 1.78; if (renderer != null) { thumbnailWidth = renderer.getThumbnailWidth(); thumbnailHeight = renderer.getThumbnailHeight(); thumbnailRatio = renderer.getThumbnailRatio(); } args[7] = "-vf"; args[8] = "scale='if(gt(a," + thumbnailRatio + ")," + thumbnailWidth + ",-1)':'if(gt(a," + thumbnailRatio + "),-1," + thumbnailHeight + ")', pad=" + thumbnailWidth + ":" + thumbnailHeight + ":(" + thumbnailWidth + "-iw)/2:(" + thumbnailHeight + "-ih)/2"; args[9] = "-vframes"; args[10] = "1"; args[11] = "-f"; args[12] = "image2"; args[13] = "pipe:"; // FIXME MPlayer should not be used if thumbnail generation is disabled if (!configuration.isThumbnailGenerationEnabled() || (configuration.isUseMplayerForVideoThumbs() && !dvrms)) { args[2] = "0"; for (int i = 5; i <= 13; i++) { args[i] = "-an"; } } OutputParams params = new OutputParams(configuration); params.maxBufferSize = 1; params.stdin = media.getPush(); params.noexitcheck = true; // not serious if anything happens during the thumbnailer // true: consume stderr on behalf of the caller i.e. parse() final ProcessWrapperImpl pw = new ProcessWrapperImpl(args, params, false, true); // FAILSAFE parsing = true; Runnable r = new Runnable() { @Override public void run() { try { Thread.sleep(10000); ffmpeg_failure = true; } catch (InterruptedException e) { } pw.stopProcess(); parsing = false; } }; Thread failsafe = new Thread(r, "FFmpeg Thumbnail Failsafe"); failsafe.start(); pw.runInSameThread(); parsing = false;; return pw; } private ProcessWrapperImpl getMplayerThumbnail(InputFile media, boolean resume) throws IOException { File file = media.getFile(); String args[] = new String[14]; args[0] = configuration.getMplayerPath(); args[1] = "-ss"; if (resume) { args[2] = "" + (int) getDurationInSeconds(); } else { args[2] = "" + configuration.getThumbnailSeekPos(); } args[3] = "-quiet"; if (file != null) { args[4] = ProcessUtil.getShortFileNameIfWideChars(file.getAbsolutePath()); } else { args[4] = "-"; } args[5] = "-msglevel"; args[6] = "all=4"; args[7] = "-vf"; args[8] = "scale=320:-2,expand=:180"; args[9] = "-frames"; args[10] = "1"; args[11] = "-vo"; String frameName = "" + media.hashCode(); frameName = "mplayer_thumbs:subdirs=\"" + frameName + "\""; frameName = frameName.replace(',', '_'); args[12] = "jpeg:outdir=" + frameName; args[13] = "-nosound"; OutputParams params = new OutputParams(configuration); params.workDir = configuration.getTempFolder(); params.maxBufferSize = 1; params.stdin = media.getPush(); params.log = true; params.noexitcheck = true; // not serious if anything happens during the thumbnailer final ProcessWrapperImpl pw = new ProcessWrapperImpl(args, params); // FAILSAFE parsing = true; Runnable r = new Runnable() { @Override public void run() { try { Thread.sleep(3000); } catch (InterruptedException e) { } pw.stopProcess(); parsing = false; } }; Thread failsafe = new Thread(r, "MPlayer Thumbnail Failsafe"); failsafe.start(); pw.runInSameThread(); parsing = false; return pw; } private String getFfmpegPath() { String value = configuration.getFfmpegPath(); if (value == null) { LOGGER.info("No FFmpeg - unable to thumbnail"); throw new RuntimeException("No FFmpeg - unable to thumbnail"); } else { return value; } } @Deprecated public void parse(InputFile inputFile, Format ext, int type, boolean thumbOnly, boolean resume) { parse(inputFile, ext, type, thumbOnly, resume, null); } /** * Parse media without using MediaInfo. */ public void parse(InputFile inputFile, Format ext, int type, boolean thumbOnly, boolean resume, RendererConfiguration renderer) { int i = 0; while (isParsing()) { if (i == 5) { mediaparsed = true; break; } try { Thread.sleep(1000); } catch (InterruptedException e) { } i++; } if (isMediaparsed()) { return; } if (inputFile != null) { File file = inputFile.getFile(); if (file != null) { size = file.length(); } else { size = inputFile.getSize(); } ProcessWrapperImpl pw = null; boolean ffmpeg_parsing = true; if (type == Format.AUDIO || ext instanceof AudioAsVideo) { ffmpeg_parsing = false; DLNAMediaAudio audio = new DLNAMediaAudio(); if (file != null) { try { AudioFile af = AudioFileIO.read(file); AudioHeader ah = af.getAudioHeader(); if (ah != null && !thumbOnly) { int length = ah.getTrackLength(); int rate = ah.getSampleRateAsNumber(); if (ah.getEncodingType().toLowerCase().contains("flac 24")) { audio.setBitsperSample(24); } audio.setSampleFrequency("" + rate); durationSec = (double) length; bitrate = (int) ah.getBitRateAsNumber(); audio.getAudioProperties().setNumberOfChannels(2); if (ah.getChannels() != null && ah.getChannels().toLowerCase().contains("mono")) { audio.getAudioProperties().setNumberOfChannels(1); } else if (ah.getChannels() != null && ah.getChannels().toLowerCase().contains("stereo")) { audio.getAudioProperties().setNumberOfChannels(2); } else if (ah.getChannels() != null) { audio.getAudioProperties().setNumberOfChannels(Integer.parseInt(ah.getChannels())); } audio.setCodecA(ah.getEncodingType().toLowerCase()); if (audio.getCodecA().contains("(windows media")) { audio.setCodecA(audio.getCodecA().substring(0, audio.getCodecA().indexOf("(windows media")).trim()); } } Tag t = af.getTag(); if (t != null) { if (t.getArtworkList().size() > 0) { thumb = t.getArtworkList().get(0).getBinaryData(); } else { if (configuration.getAudioThumbnailMethod() > 0) { thumb = CoverUtil.get().getThumbnailFromArtistAlbum( configuration.getAudioThumbnailMethod() == 1 ? CoverUtil.AUDIO_AMAZON : CoverUtil.AUDIO_DISCOGS, audio.getArtist(), audio.getAlbum() ); } } if (!thumbOnly) { audio.setAlbum(t.getFirst(FieldKey.ALBUM)); audio.setArtist(t.getFirst(FieldKey.ARTIST)); audio.setSongname(t.getFirst(FieldKey.TITLE)); String y = t.getFirst(FieldKey.YEAR); try { if (y.length() > 4) { y = y.substring(0, 4); } audio.setYear(Integer.parseInt(((y != null && y.length() > 0) ? y : "0"))); y = t.getFirst(FieldKey.TRACK); audio.setTrack(Integer.parseInt(((y != null && y.length() > 0) ? y : "1"))); audio.setGenre(t.getFirst(FieldKey.GENRE)); } catch (NumberFormatException | KeyNotFoundException e) { LOGGER.debug("Error parsing unimportant metadata: " + e.getMessage()); } } } } catch (CannotReadException | IOException | TagException | ReadOnlyFileException | InvalidAudioFrameException | NumberFormatException | KeyNotFoundException e) { LOGGER.debug("Error parsing audio file: {} - {}", e.getMessage(), e.getCause() != null ? e.getCause().getMessage() : ""); ffmpeg_parsing = false; } if (audio.getSongname() != null && audio.getSongname().length() > 0) { if (renderer != null && renderer.isPrependTrackNumbers() && audio.getTrack() > 0) { audio.setSongname(audio.getTrack() + ": " + audio.getSongname()); } } else { audio.setSongname(file.getName()); } if (!ffmpeg_parsing) { audioTracks.add(audio); } } } if (type == Format.IMAGE && file != null) { try { ffmpeg_parsing = false; ImageInfo info = Sanselan.getImageInfo(file); width = info.getWidth(); height = info.getHeight(); bitsPerPixel = info.getBitsPerPixel(); String formatName = info.getFormatName(); if (formatName.startsWith("JPEG")) { codecV = "jpg"; IImageMetadata meta = Sanselan.getMetadata(file); if (meta != null && meta instanceof JpegImageMetadata) { JpegImageMetadata jpegmeta = (JpegImageMetadata) meta; TiffField tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_MODEL); if (tf != null) { model = tf.getStringValue().trim(); } tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_EXPOSURE_TIME); if (tf != null) { exposure = (int) (1000 * tf.getDoubleValue()); } tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_ORIENTATION); if (tf != null) { orientation = tf.getIntValue(); } tf = jpegmeta.findEXIFValue(TiffConstants.EXIF_TAG_ISO); if (tf != null) { // Galaxy Nexus jpg pictures may contain multiple values, take the first int[] isoValues = tf.getIntArrayValue(); iso = isoValues[0]; } } } else if (formatName.startsWith("PNG")) { codecV = "png"; } else if (formatName.startsWith("GIF")) { codecV = "gif"; } else if (formatName.startsWith("TIF")) { codecV = "tiff"; } container = codecV; imageCount++; } catch (ImageReadException | IOException e) { LOGGER.info("Error parsing image ({}) with Sanselan, switching to FFmpeg.", file.getAbsolutePath()); } if (configuration.getImageThumbnailsEnabled() && gen_thumb) { LOGGER.trace("Creating (temporary) thumbnail: {}", file.getName()); // Create the thumbnail image using the Thumbnailator library try { ByteArrayOutputStream out = new ByteArrayOutputStream(); Thumbnails.of(file) .size(320, 180) .outputFormat("JPEG") .outputQuality(1.0f) .toOutputStream(out); thumb = out.toByteArray(); } catch (IOException | IllegalArgumentException | IllegalStateException e) { LOGGER.debug("Error generating thumbnail for: " + file.getName()); LOGGER.debug("The full error was: " + e); } } } if (ffmpeg_parsing) { if (!thumbOnly || !configuration.isUseMplayerForVideoThumbs()) { pw = getFFmpegThumbnail(inputFile, resume, renderer); } boolean dvrms = false; String input = "-"; if (file != null) { input = ProcessUtil.getShortFileNameIfWideChars(file.getAbsolutePath()); dvrms = file.getAbsolutePath().toLowerCase().endsWith("dvr-ms"); } if (pw != null && !ffmpeg_failure && !thumbOnly) { parseFFmpegInfo(pw.getResults(), input); } if ( !thumbOnly && container != null && file != null && container.equals("mpegts") && isH264() && getDurationInSeconds() == 0 ) { // Parse the duration try { int length = MpegUtil.getDurationFromMpeg(file); if (length > 0) { durationSec = (double) length; } } catch (IOException e) { LOGGER.trace("Error retrieving length: " + e.getMessage()); } } if (configuration.isUseMplayerForVideoThumbs() && type == Format.VIDEO && !dvrms) { try { getMplayerThumbnail(inputFile, resume); String frameName = "" + inputFile.hashCode(); frameName = configuration.getTempFolder() + "/mplayer_thumbs/" + frameName + "00000001/00000001.jpg"; frameName = frameName.replace(',', '_'); File jpg = new File(frameName); if (jpg.exists()) { try (InputStream is = new FileInputStream(jpg)) { int sz = is.available(); if (sz > 0) { thumb = new byte[sz]; is.read(thumb); } } if (!jpg.delete()) { jpg.deleteOnExit(); } // Try and retry if (!jpg.getParentFile().delete() && !jpg.getParentFile().delete()) { LOGGER.debug("Failed to delete \"" + jpg.getParentFile().getAbsolutePath() + "\""); } } } catch (IOException e) { LOGGER.debug("Caught exception", e); } } if (type == Format.VIDEO && pw != null && thumb == null) { InputStream is; try { int sz = 0; is = pw.getInputStream(0); if (is != null) { sz = is.available(); if (sz > 0) { thumb = new byte[sz]; is.read(thumb); } is.close(); } if (sz > 0 && !net.pms.PMS.isHeadless()) { BufferedImage image = ImageIO.read(new ByteArrayInputStream(thumb)); if (image != null) { if (MediaMonitor.isWatched(file.getAbsolutePath())) { /** * TODO: Cache the calculated values * TODO: Include and use a custom font */ String text = Messages.getString("DLNAResource.4"); int thumbnailWidth = renderer.getThumbnailWidth(); int fontSize = thumbnailWidth / 6; Graphics2D g = image.createGraphics(); g.setPaint(new Color(0.0f, 0.0f, 0.0f, 0.6f)); g.fillRect(0, 0, thumbnailWidth, renderer.getThumbnailHeight()); g.setColor(new Color(0.9f, 0.9f, 0.9f, 1.0f)); g.setFont(new Font("Arial", Font.PLAIN, fontSize)); FontMetrics fm = g.getFontMetrics(); Rectangle2D textsize = fm.getStringBounds(text, g); int textWidth = (int) textsize.getWidth(); int horizontalPosition = (thumbnailWidth - textWidth) / 2; // Use a smaller font size if there isn't enough room if (textWidth > thumbnailWidth) { for (int divider = 7; divider < 99; divider++) { fontSize = thumbnailWidth / divider; g.setFont(new Font("Arial", Font.PLAIN, fontSize)); fm = g.getFontMetrics(); textsize = fm.getStringBounds(text, g); textWidth = (int) textsize.getWidth(); if (textWidth <= (thumbnailWidth * 0.9)) { horizontalPosition = (thumbnailWidth - textWidth) / 2; break; } } } int verticalPosition = (int) (renderer.getThumbnailHeight() - textsize.getHeight()) / 2 + fm.getAscent(); g.drawString(text, horizontalPosition, verticalPosition); } ByteArrayOutputStream out = new ByteArrayOutputStream(); ImageIO.write(image, "jpeg", out); thumb = out.toByteArray(); } } } catch (IOException e) { LOGGER.debug("Error while decoding thumbnail: " + e.getMessage()); } } } finalize(type, inputFile); mediaparsed = true; } } /** * Parses media info from FFmpeg's stderr output * * @param lines The stderr output * @param input The FFmpeg input (-i) argument used */ public void parseFFmpegInfo(List<String> lines, String input) { if (lines != null) { if ("-".equals(input)) { input = "pipe:"; } boolean matchs = false; int langId = 0; int subId = 0; ListIterator<String> FFmpegMetaData = lines.listIterator(); for (String line : lines) { FFmpegMetaData.next(); line = line.trim(); if (line.startsWith("Output")) { matchs = false; } else if (line.startsWith("Input")) { if (line.contains(input)) { matchs = true; container = line.substring(10, line.indexOf(',', 11)).trim(); /** * This method is very inaccurate because the Input line in the FFmpeg output * returns "mov,mp4,m4a,3gp,3g2,mj2" for all 6 of those formats, meaning that * we think they are all "mov". * * Here we workaround it by using the file extension, but the best idea is to * prevent using this method by using MediaInfo=true in renderer configs. */ if ("mov".equals(container)) { container = line.substring(line.lastIndexOf('.') + 1, line.lastIndexOf("'")).trim(); LOGGER.trace("Setting container to " + container + " from the filename. To prevent false-positives, use MediaInfo=true in the renderer config."); } } else { matchs = false; } } else if (matchs) { if (line.contains("Duration")) { StringTokenizer st = new StringTokenizer(line, ","); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.startsWith("Duration: ")) { String durationStr = token.substring(10); int l = durationStr.substring(durationStr.indexOf('.') + 1).length(); if (l < 4) { durationStr += "00".substring(0, 3 - l); } if (durationStr.contains("N/A")) { durationSec = null; } else { durationSec = parseDurationString(durationStr); } } else if (token.startsWith("bitrate: ")) { String bitr = token.substring(9); int spacepos = bitr.indexOf(' '); if (spacepos > -1) { String value = bitr.substring(0, spacepos); String unit = bitr.substring(spacepos + 1); bitrate = Integer.parseInt(value); if (unit.equals("kb/s")) { bitrate = 1024 * bitrate; } if (unit.equals("mb/s")) { bitrate = 1048576 * bitrate; } } } } } else if (line.contains("Audio:")) { StringTokenizer st = new StringTokenizer(line, ","); int a = line.indexOf('('); int b = line.indexOf("):", a); DLNAMediaAudio audio = new DLNAMediaAudio(); audio.setId(langId++); if (a > -1 && b > a) { audio.setLang(line.substring(a + 1, b)); } else { audio.setLang(DLNAMediaLang.UND); } // Get TS IDs a = line.indexOf("[0x"); b = line.indexOf(']', a); if (a > -1 && b > a + 3) { String idString = line.substring(a + 3, b); try { audio.setId(Integer.parseInt(idString, 16)); } catch (NumberFormatException nfe) { LOGGER.debug("Error parsing Stream ID: " + idString); } } while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.startsWith("Stream")) { audio.setCodecA(token.substring(token.indexOf("Audio: ") + 7)); } else if (token.endsWith("Hz")) { audio.setSampleFrequency(token.substring(0, token.indexOf("Hz")).trim()); } else if (token.equals("mono")) { audio.getAudioProperties().setNumberOfChannels(1); } else if (token.equals("stereo")) { audio.getAudioProperties().setNumberOfChannels(2); } else if (token.equals("5:1") || token.equals("5.1") || token.equals("6 channels")) { audio.getAudioProperties().setNumberOfChannels(6); } else if (token.equals("5 channels")) { audio.getAudioProperties().setNumberOfChannels(5); } else if (token.equals("4 channels")) { audio.getAudioProperties().setNumberOfChannels(4); } else if (token.equals("2 channels")) { audio.getAudioProperties().setNumberOfChannels(2); } else if (token.equals("s32")) { audio.setBitsperSample(32); } else if (token.equals("s24")) { audio.setBitsperSample(24); } else if (token.equals("s16")) { audio.setBitsperSample(16); } } int FFmpegMetaDataNr = FFmpegMetaData.nextIndex(); if (FFmpegMetaDataNr > -1) { line = lines.get(FFmpegMetaDataNr); } if (line.contains("Metadata:")) { FFmpegMetaDataNr += 1; line = lines.get(FFmpegMetaDataNr); while (line.indexOf(" ") == 0) { if (line.toLowerCase().contains("title :")) { int aa = line.indexOf(": "); int bb = line.length(); if (aa > -1 && bb > aa) { audio.setAudioTrackTitleFromMetadata(line.substring(aa + 2, bb)); break; } } else { FFmpegMetaDataNr += 1; line = lines.get(FFmpegMetaDataNr); } } } audioTracks.add(audio); } else if (line.contains("Video:")) { StringTokenizer st = new StringTokenizer(line, ","); while (st.hasMoreTokens()) { String token = st.nextToken().trim(); if (token.startsWith("Stream")) { codecV = token.substring(token.indexOf("Video: ") + 7); videoTrackCount++; } else if ((token.contains("tbc") || token.contains("tb(c)"))) { // A/V sync issues with newest FFmpeg, due to the new tbr/tbn/tbc outputs // Priority to tb(c) String frameRateDoubleString = token.substring(0, token.indexOf("tb")).trim(); try { if (!frameRateDoubleString.equals(frameRate)) {// tbc taken into account only if different than tbr Double frameRateDouble = Double.parseDouble(frameRateDoubleString); frameRate = String.format(Locale.ENGLISH, "%.2f", frameRateDouble / 2); } } catch (NumberFormatException nfe) { // Could happen if tbc is "1k" or something like that, no big deal LOGGER.debug("Could not parse frame rate \"" + frameRateDoubleString + "\""); } } else if ((token.contains("tbr") || token.contains("tb(r)")) && frameRate == null) { frameRate = token.substring(0, token.indexOf("tb")).trim(); } else if ((token.contains("fps") || token.contains("fps(r)")) && frameRate == null) { // dvr-ms ? frameRate = token.substring(0, token.indexOf("fps")).trim(); } else if (token.indexOf('x') > -1 && !token.contains("max")) { String resolution = token.trim(); if (resolution.contains(" [")) { resolution = resolution.substring(0, resolution.indexOf(" [")); } try { width = Integer.parseInt(resolution.substring(0, resolution.indexOf('x'))); } catch (NumberFormatException nfe) { LOGGER.debug("Could not parse width from \"" + resolution.substring(0, resolution.indexOf('x')) + "\""); } try { height = Integer.parseInt(resolution.substring(resolution.indexOf('x') + 1)); } catch (NumberFormatException nfe) { LOGGER.debug("Could not parse height from \"" + resolution.substring(resolution.indexOf('x') + 1) + "\""); } } } } else if (line.contains("Subtitle:")) { DLNAMediaSubtitle lang = new DLNAMediaSubtitle(); // $ ffmpeg -codecs | grep "^...S" // ..S... = Subtitle codec // DES... ass ASS (Advanced SSA) subtitle // DES... dvb_subtitle DVB subtitles (decoders: dvbsub ) (encoders: dvbsub ) // ..S... dvb_teletext DVB teletext // DES... dvd_subtitle DVD subtitles (decoders: dvdsub ) (encoders: dvdsub ) // ..S... eia_608 EIA-608 closed captions // D.S... hdmv_pgs_subtitle HDMV Presentation Graphic Stream subtitles (decoders: pgssub ) // D.S... jacosub JACOsub subtitle // D.S... microdvd MicroDVD subtitle // DES... mov_text MOV text // D.S... mpl2 MPL2 subtitle // D.S... pjs PJS (Phoenix Japanimation Society) subtitle // D.S... realtext RealText subtitle // D.S... sami SAMI subtitle // DES... srt SubRip subtitle with embedded timing // DES... ssa SSA (SubStation Alpha) subtitle // DES... subrip SubRip subtitle // D.S... subviewer SubViewer subtitle // D.S... subviewer1 SubViewer v1 subtitle // D.S... text raw UTF-8 text // D.S... vplayer VPlayer subtitle // D.S... webvtt WebVTT subtitle // DES... xsub XSUB if (line.contains("srt") || line.contains("subrip")) { lang.setType(SubtitleType.SUBRIP); } else if (line.contains(" text")) { // excludes dvb_teletext, mov_text, realtext lang.setType(SubtitleType.TEXT); } else if (line.contains("microdvd")) { lang.setType(SubtitleType.MICRODVD); } else if (line.contains("sami")) { lang.setType(SubtitleType.SAMI); } else if (line.contains("ass") || line.contains("ssa")) { lang.setType(SubtitleType.ASS); } else if (line.contains("dvd_subtitle")) { lang.setType(SubtitleType.VOBSUB); } else if (line.contains("xsub")) { lang.setType(SubtitleType.DIVX); } else if (line.contains("mov_text")) { lang.setType(SubtitleType.TX3G); } else if (line.contains("webvtt")) { lang.setType(SubtitleType.WEBVTT); } else { lang.setType(SubtitleType.UNKNOWN); } int a = line.indexOf('('); int b = line.indexOf("):", a); if (a > -1 && b > a) { lang.setLang(line.substring(a + 1, b)); } else { lang.setLang(DLNAMediaLang.UND); } lang.setId(subId++); int FFmpegMetaDataNr = FFmpegMetaData.nextIndex(); if (FFmpegMetaDataNr > -1) { line = lines.get(FFmpegMetaDataNr); } if (line.contains("Metadata:")) { FFmpegMetaDataNr += 1; line = lines.get(FFmpegMetaDataNr); while (line.indexOf(" ") == 0) { if (line.toLowerCase().contains("title :")) { int aa = line.indexOf(": "); int bb = line.length(); if (aa > -1 && bb > aa) { lang.setSubtitlesTrackTitleFromMetadata(line.substring(aa + 2, bb)); break; } } else { FFmpegMetaDataNr += 1; line = lines.get(FFmpegMetaDataNr); } } } subtitleTracks.add(lang); } } } } ffmpegparsed = true; } public boolean isH264() { return codecV != null && codecV.startsWith("h264"); } /** * Disable LPCM transcoding for MP4 container with non-H264 video as workaround for MEncoder's A/V sync bug */ public boolean isValidForLPCMTranscoding() { if (container != null) { if (container.equals("mp4")) { return isH264(); } else { return true; } } return false; } public int getFrameNumbers() { double fr = Double.parseDouble(frameRate); return (int) (getDurationInSeconds() * fr); } public void setDuration(Double d) { this.durationSec = d; } public Double getDuration() { return durationSec; } /** * @return 0 if nothing is specified, otherwise the duration */ public double getDurationInSeconds() { return durationSec != null ? durationSec : 0; } public String getDurationString() { return durationSec != null ? convertTimeToString(durationSec, DURATION_TIME_FORMAT) : null; } /** * @deprecated Use {@link #StringUtil.convertTimeToString(durationSec, StringUtil.DURATION_TIME_FORMAT)} instead. */ public static String getDurationString(double d) { return convertTimeToString(d, DURATION_TIME_FORMAT); } public static Double parseDurationString(String duration) { return duration != null ? convertStringToTime(duration) : null; } public void finalize(int type, InputFile f) { String codecA = null; if (getFirstAudioTrack() != null) { codecA = getFirstAudioTrack().getCodecA(); } if (container != null) { switch (container) { case "avi": mimeType = HTTPResource.AVI_TYPEMIME; break; case "asf": case "wmv": mimeType = HTTPResource.WMV_TYPEMIME; break; case "matroska": case "mkv": mimeType = HTTPResource.MATROSKA_TYPEMIME; break; case "3gp": mimeType = HTTPResource.THREEGPP_TYPEMIME; break; case "3g2": mimeType = HTTPResource.THREEGPP2_TYPEMIME; break; case "mov": mimeType = HTTPResource.MOV_TYPEMIME; break; } } if (mimeType == null) { if (codecV != null) { if (codecV.equals("mjpeg") || "jpg".equals(container)) { mimeType = HTTPResource.JPEG_TYPEMIME; } else if ("png".equals(codecV) || "png".equals(container)) { mimeType = HTTPResource.PNG_TYPEMIME; } else if ("gif".equals(codecV) || "gif".equals(container)) { mimeType = HTTPResource.GIF_TYPEMIME; } else if (codecV.startsWith("h264") || codecV.equals("h263") || codecV.toLowerCase().equals("mpeg4") || codecV.toLowerCase().equals("mp4")) { mimeType = HTTPResource.MP4_TYPEMIME; } else if (codecV.contains("mpeg") || codecV.contains("mpg")) { mimeType = HTTPResource.MPEG_TYPEMIME; } } else if (codecV == null && codecA != null) { if (codecA.contains("mp3")) { mimeType = HTTPResource.AUDIO_MP3_TYPEMIME; } else if (codecA.contains("aac")) { mimeType = HTTPResource.AUDIO_MP4_TYPEMIME; } else if (codecA.contains("flac")) { mimeType = HTTPResource.AUDIO_FLAC_TYPEMIME; } else if (codecA.contains("vorbis")) { mimeType = HTTPResource.AUDIO_OGG_TYPEMIME; } else if (codecA.contains("asf") || codecA.startsWith("wm")) { mimeType = HTTPResource.AUDIO_WMA_TYPEMIME; } else if (codecA.startsWith("pcm") || codecA.contains("wav")) { mimeType = HTTPResource.AUDIO_WAV_TYPEMIME; } } if (mimeType == null) { mimeType = HTTPResource.getDefaultMimeType(type); } } if (getFirstAudioTrack() == null || !(type == Format.AUDIO && getFirstAudioTrack().getBitsperSample() == 24 && getFirstAudioTrack().getSampleRate() > 48000)) { secondaryFormatValid = false; } // Check for external subs here if (f.getFile() != null && type == Format.VIDEO && configuration.isAutoloadExternalSubtitles()) { FileUtil.isSubtitlesExists(f.getFile(), this); } } /** * Checks whether the video has too many reference frames per pixels for the renderer * TODO move to PlayerUtil */ public synchronized boolean isVideoWithinH264LevelLimits(InputFile f, RendererConfiguration mediaRenderer) { if (!h264_parsed) { if (isH264()) { if ( container != null && ( container.equals("matroska") || container.equals("mkv") || container.equals("mov") || container.equals("mp4") ) ) { // Containers without h264_annexB byte headers[][] = getAnnexBFrameHeader(f); if (ffmpeg_annexb_failure) { LOGGER.info("Error parsing information from the file: " + f.getFilename()); } if (headers != null) { h264_annexB = headers[1]; if (h264_annexB != null) { int skip = 5; if (h264_annexB[2] == 1) { skip = 4; } byte header[] = new byte[h264_annexB.length - skip]; System.arraycopy(h264_annexB, skip, header, 0, header.length); if ( referenceFrameCount > -1 && ( "4.1".equals(avcLevel) || "4.2".equals(avcLevel) || "5".equals(avcLevel) || "5.0".equals(avcLevel) || "5.1".equals(avcLevel) || "5.2".equals(avcLevel) ) && width > 0 && height > 0 ) { int maxref; if (mediaRenderer == null || mediaRenderer.isPS3()) { /** * 2013-01-25: Confirmed maximum reference frames on PS3: * - 4 for 1920x1080 * - 11 for 1280x720 * Meaning this math is correct */ maxref = (int) Math.floor(10252743 / (double) (width * height)); } else { /** * This is the math for level 4.1, which results in: * - 4 for 1920x1080 * - 9 for 1280x720 */ maxref = (int) Math.floor(8388608 / (double) (width * height)); } if (referenceFrameCount > maxref) { LOGGER.debug("The file " + f.getFilename() + " is not compatible with this renderer because it can only take " + maxref + " reference frames at this resolution while this file has " + referenceFrameCount + " reference frames"); return false; } else if (referenceFrameCount == -1) { LOGGER.debug("The file " + f.getFilename() + " may not be compatible with this renderer because we can't get its number of reference frames"); return false; } } } else { LOGGER.debug("The H.264 stream inside the following file is not compatible with this renderer: " + f.getFilename()); return false; } } else { return false; } } } h264_parsed = true; } return true; } public boolean isMuxable(String filename, String codecA) { return codecA != null && (codecA.startsWith("dts") || codecA.equals("dca")); } public boolean isLossless(String codecA) { return codecA != null && (codecA.contains("pcm") || codecA.startsWith("dts") || codecA.equals("dca") || codecA.contains("flac")) && !codecA.contains("pcm_u8") && !codecA.contains("pcm_s8"); } @Override public String toString() { StringBuilder result = new StringBuilder(); result.append("container: "); result.append(container); result.append(", bitrate: "); result.append(bitrate); result.append(", size: "); result.append(size); if (videoTrackCount > 0) { result.append(", video tracks: "); result.append(videoTrackCount); } if (getAudioTrackCount() > 0) { result.append(", audio tracks: "); result.append(getAudioTrackCount()); } if (imageCount > 0) { result.append(", images: "); result.append(imageCount); } if (getSubTrackCount() > 0) { result.append(", subtitle tracks: "); result.append(getSubTrackCount()); } result.append(", video codec: "); result.append(codecV); result.append(", duration: "); result.append(getDurationString()); result.append(", width: "); result.append(width); result.append(", height: "); result.append(height); result.append(", frame rate: "); result.append(frameRate); if (thumb != null) { result.append(", thumb size: "); result.append(thumb.length); } if (isNotBlank(muxingMode)) { result.append(", muxing mode: "); result.append(muxingMode); } result.append(", mime type: "); result.append(mimeType); if (isNotBlank(matrixCoefficients)) { result.append(", matrix coefficients: "); result.append(matrixCoefficients); } result.append(", attached fonts: "); result.append(embeddedFontExists); if (isNotBlank(fileTitleFromMetadata)) { result.append(", file title from metadata: "); result.append(fileTitleFromMetadata); } if (isNotBlank(videoTrackTitleFromMetadata)) { result.append(", video track title from metadata: "); result.append(videoTrackTitleFromMetadata); } for (DLNAMediaAudio audio : audioTracks) { result.append("\n\tAudio track "); result.append(audio.toString()); } for (DLNAMediaSubtitle sub : subtitleTracks) { result.append("\n\tSubtitle track "); result.append(sub.toString()); } return result.toString(); } public InputStream getThumbnailInputStream() { return new ByteArrayInputStream(thumb); } public String getValidFps(boolean ratios) { String validFrameRate = null; if (frameRate != null && frameRate.length() > 0) { try { double fr = Double.parseDouble(frameRate.replace(',', '.')); if (fr >= 14.99 && fr < 15.1) { validFrameRate = "15"; } else if (fr > 23.9 && fr < 23.99) { validFrameRate = ratios ? "24000/1001" : "23.976"; } else if (fr > 23.99 && fr < 24.1) { validFrameRate = "24"; } else if (fr >= 24.99 && fr < 25.1) { validFrameRate = "25"; } else if (fr > 29.9 && fr < 29.99) { validFrameRate = ratios ? "30000/1001" : "29.97"; } else if (fr >= 29.99 && fr < 30.1) { validFrameRate = "30"; } else if (fr > 47.9 && fr < 47.99) { validFrameRate = ratios ? "48000/1001" : "47.952"; } else if (fr > 49.9 && fr < 50.1) { validFrameRate = "50"; } else if (fr > 59.8 && fr < 59.99) { validFrameRate = ratios ? "60000/1001" : "59.94"; } else if (fr >= 59.99 && fr < 60.1) { validFrameRate = "60"; } } catch (NumberFormatException nfe) { LOGGER.error(null, nfe); } } return validFrameRate; } public DLNAMediaAudio getFirstAudioTrack() { if (audioTracks.size() > 0) { return audioTracks.get(0); } return null; } /** * @deprecated use getAspectRatioMencoderMpegopts() for the original * functionality of this method, or use getAspectRatioContainer() for a * better default method to get aspect ratios. */ @Deprecated public String getValidAspect(boolean ratios) { return getAspectRatioMencoderMpegopts(ratios); } /** * Converts the result of getAspectRatioDvdIso() to provide * MEncoderVideo with a valid value for the "vaspect" option in the * "-mpegopts" command. * * Note: Our code never uses a false value for "ratios", so unless any * plugins rely on it we can simplify things by removing that parameter. * * @param ratios * @return */ public String getAspectRatioMencoderMpegopts(boolean ratios) { String a = null; if (aspectRatioDvdIso != null) { double ar = Double.parseDouble(aspectRatioDvdIso); if (ar > 1.7 && ar < 1.8) { a = ratios ? "16/9" : "1.777777777777777"; } if (ar > 1.3 && ar < 1.4) { a = ratios ? "4/3" : "1.333333333333333"; } } return a; } public String getResolution() { if (width > 0 && height > 0) { return width + "x" + height; } return null; } public int getRealVideoBitrate() { if (bitrate > 0) { return (bitrate / 8); } int realBitrate = 10000000; if (getDurationInSeconds() != 0) { realBitrate = (int) (size / getDurationInSeconds()); } return realBitrate; } public boolean isHDVideo() { return (width > 864 || height > 540); } public boolean isMpegTS() { return container != null && container.equals("mpegts"); } public byte[][] getAnnexBFrameHeader(InputFile f) { String[] cmdArray = new String[14]; cmdArray[0] = configuration.getFfmpegPath(); cmdArray[1] = "-i"; if (f.getPush() == null && f.getFilename() != null) { cmdArray[2] = f.getFilename(); } else { cmdArray[2] = "-"; } cmdArray[3] = "-vframes"; cmdArray[4] = "1"; cmdArray[5] = "-c:v"; cmdArray[6] = "copy"; cmdArray[7] = "-f"; cmdArray[8] = "h264"; cmdArray[9] = "-bsf"; cmdArray[10] = "h264_mp4toannexb"; cmdArray[11] = "-an"; cmdArray[12] = "-y"; cmdArray[13] = "pipe:"; byte[][] returnData = new byte[2][]; OutputParams params = new OutputParams(configuration); params.maxBufferSize = 1; params.stdin = f.getPush(); final ProcessWrapperImpl pw = new ProcessWrapperImpl(cmdArray, params); Runnable r = new Runnable() { @Override public void run() { try { Thread.sleep(3000); ffmpeg_annexb_failure = true; } catch (InterruptedException e) { } pw.stopProcess(); } }; Thread failsafe = new Thread(r, "FFMpeg AnnexB Frame Header Failsafe"); failsafe.start(); pw.runInSameThread(); if (ffmpeg_annexb_failure) { return null; } InputStream is; ByteArrayOutputStream baot = new ByteArrayOutputStream(); try { is = pw.getInputStream(0); byte b[] = new byte[4096]; int n; while ((n = is.read(b)) > 0) { baot.write(b, 0, n); } byte data[] = baot.toByteArray(); baot.close(); returnData[0] = data; is.close(); int kf = 0; for (int i = 3; i < data.length; i++) { if (data[i - 3] == 1 && (data[i - 2] & 37) == 37 && (data[i - 1] & -120) == -120) { kf = i - 2; break; } } int st = 0; boolean found = false; if (kf > 0) { for (int i = kf; i >= 5; i--) { if (data[i - 5] == 0 && data[i - 4] == 0 && data[i - 3] == 0 && (data[i - 2] & 1) == 1 && (data[i - 1] & 39) == 39) { st = i - 5; found = true; break; } } } if (found) { byte header[] = new byte[kf - st]; System.arraycopy(data, st, header, 0, kf - st); returnData[1] = header; } } catch (IOException e) { LOGGER.debug("Caught exception", e); } return returnData; } @Override protected Object clone() throws CloneNotSupportedException { Object cloned = super.clone(); if (cloned instanceof DLNAMediaInfo) { DLNAMediaInfo mediaCloned = ((DLNAMediaInfo) cloned); mediaCloned.setAudioTracksList(new ArrayList<DLNAMediaAudio>()); for (DLNAMediaAudio audio : audioTracks) { mediaCloned.getAudioTracksList().add((DLNAMediaAudio) audio.clone()); } mediaCloned.setSubtitleTracksList(new ArrayList<DLNAMediaSubtitle>()); for (DLNAMediaSubtitle sub : subtitleTracks) { mediaCloned.getSubtitleTracksList().add((DLNAMediaSubtitle) sub.clone()); } } return cloned; } /** * @return the bitrate * @since 1.50.0 */ public int getBitrate() { return bitrate; } /** * @param bitrate the bitrate to set * @since 1.50.0 */ public void setBitrate(int bitrate) { this.bitrate = bitrate; } /** * @return the width * @since 1.50.0 */ public int getWidth() { return width; } /** * @param width the width to set * @since 1.50.0 */ public void setWidth(int width) { this.width = width; } /** * @return the height * @since 1.50.0 */ public int getHeight() { return height; } /** * @param height the height to set * @since 1.50.0 */ public void setHeight(int height) { this.height = height; } /** * @return the size * @since 1.50.0 */ public long getSize() { return size; } /** * @param size the size to set * @since 1.50.0 */ public void setSize(long size) { this.size = size; } /** * @return the codecV * @since 1.50.0 */ public String getCodecV() { return codecV; } /** * @param codecV the codecV to set * @since 1.50.0 */ public void setCodecV(String codecV) { this.codecV = codecV; } /** * @return the frameRate * @since 1.50.0 */ public String getFrameRate() { return frameRate; } /** * @param frameRate the frameRate to set * @since 1.50.0 */ public void setFrameRate(String frameRate) { this.frameRate = frameRate; } /** * @return the frameRateMode * @since 1.55.0 */ public String getFrameRateMode() { return frameRateMode; } /** * @param frameRateMode the frameRateMode to set * @since 1.55.0 */ public void setFrameRateMode(String frameRateMode) { this.frameRateMode = frameRateMode; } /** * @deprecated use getAspectRatioDvdIso() for the original * functionality of this method, or use getAspectRatioContainer() for a * better default method to get aspect ratios. */ @Deprecated public String getAspect() { return getAspectRatioDvdIso(); } /** * The aspect ratio for a DVD ISO video track * * @return the aspect * @since 1.50.0 */ public String getAspectRatioDvdIso() { return aspectRatioDvdIso; } /** * @deprecated use setAspectRatioDvdIso() for the original * functionality of this method, or use setAspectRatioContainer() for a * better default method to set aspect ratios. */ @Deprecated public void setAspect(String aspect) { setAspectRatioDvdIso(aspect); } /** * @param aspect the aspect to set * @since 1.50.0 */ public void setAspectRatioDvdIso(String aspect) { this.aspectRatioDvdIso = aspect; } /** * Get the aspect ratio reported by the file/container. * This is the aspect ratio that the renderer should display the video * at, and is usually the same as the video track aspect ratio. * * @return the aspect ratio reported by the file/container */ public String getAspectRatioContainer() { return aspectRatioContainer; } /** * Set the aspect ratio reported by the file/container. * * @see #getAspectRatioContainer() * @param aspect the aspect ratio to set */ public void setAspectRatioContainer(String aspect) { this.aspectRatioContainer = getFormattedAspectRatio(aspect); } /** * Get the aspect ratio of the video track. * This is the actual aspect ratio of the pixels, which is not * always the aspect ratio that the renderer should display or that we * should output; that is {@link #getAspectRatioContainer()} * * @return the aspect ratio of the video track */ public String getAspectRatioVideoTrack() { return aspectRatioVideoTrack; } /** * @param aspect the aspect ratio to set */ public void setAspectRatioVideoTrack(String aspect) { this.aspectRatioVideoTrack = getFormattedAspectRatio(aspect); } /** * Make sure the aspect ratio is formatted, e.g. 16:9 not 1.78 * * @param aspect the possibly-unformatted aspect ratio * * @return the formatted aspect ratio or null */ public String getFormattedAspectRatio(String aspect) { if (isBlank(aspect)) { return null; } else { if (aspect.contains(":")) { return aspect; } else { double exactAspectRatio = Double.parseDouble(aspect); if (exactAspectRatio > 1.7 && exactAspectRatio <= 1.8) { return "16:9"; } else if (exactAspectRatio > 1.3 && exactAspectRatio < 1.4) { return "4:3"; } else if (exactAspectRatio > 1.2 && exactAspectRatio < 1.3) { return "5:4"; } else { return null; } } } } /** * @return the thumb * @since 1.50.0 */ public byte[] getThumb() { return thumb; } /** * @param thumb the thumb to set * @since 1.50.0 */ public void setThumb(byte[] thumb) { this.thumb = thumb; } /** * @return the mimeType * @since 1.50.0 */ public String getMimeType() { return mimeType; } /** * @param mimeType the mimeType to set * @since 1.50.0 */ public void setMimeType(String mimeType) { this.mimeType = mimeType; } public String getMatrixCoefficients() { return matrixCoefficients; } public void setMatrixCoefficients(String matrixCoefficients) { this.matrixCoefficients = matrixCoefficients; } /** * @return whether the file container has custom fonts attached. */ public boolean isEmbeddedFontExists() { return embeddedFontExists; } /** * Sets whether the file container has custom fonts attached. * * @param exists true if at least one attached font exists */ public void setEmbeddedFontExists(boolean exists) { this.embeddedFontExists = exists; } public String getFileTitleFromMetadata() { return fileTitleFromMetadata; } public void setFileTitleFromMetadata(String value) { this.fileTitleFromMetadata = value; } public String getVideoTrackTitleFromMetadata() { return videoTrackTitleFromMetadata; } public void setVideoTrackTitleFromMetadata(String value) { this.videoTrackTitleFromMetadata = value; } /** * @return the bitsPerPixel * @since 1.50.0 */ public int getBitsPerPixel() { return bitsPerPixel; } /** * @param bitsPerPixel the bitsPerPixel to set * @since 1.50.0 */ public void setBitsPerPixel(int bitsPerPixel) { this.bitsPerPixel = bitsPerPixel; } /** * @return reference frame count for video stream or {@code -1} if not parsed. */ public synchronized byte getReferenceFrameCount() { return referenceFrameCount; } /** * Sets reference frame count for video stream or {@code -1} if not parsed. * * @param referenceFrameCount reference frame count. */ public synchronized void setReferenceFrameCount(byte referenceFrameCount) { if (referenceFrameCount < -1) { throw new IllegalArgumentException("referenceFrameCount should be >= -1."); } this.referenceFrameCount = referenceFrameCount; } /** * @return AVC level for video stream or {@code null} if not parsed. */ public synchronized String getAvcLevel() { return avcLevel; } /** * Sets AVC level for video stream or {@code null} if not parsed. * * @param avcLevel AVC level. */ public synchronized void setAvcLevel(String avcLevel) { this.avcLevel = avcLevel; } public synchronized int getAvcAsInt() { try { return Integer.parseInt(getAvcLevel().replaceAll("\\.", "")); } catch (Exception e) { return 0; } } public synchronized String getH264Profile() { return h264Profile; } public synchronized void setH264Profile(String s) { h264Profile = s; } /** * @return the audioTracks * @since 1.60.0 */ // TODO (breaking change): rename to getAudioTracks public List<DLNAMediaAudio> getAudioTracksList() { return audioTracks; } /** * @return the audioTracks * @deprecated use getAudioTracksList() instead */ @Deprecated public ArrayList<DLNAMediaAudio> getAudioCodes() { if (audioTracks instanceof ArrayList) { return (ArrayList<DLNAMediaAudio>) audioTracks; } else { return new ArrayList<>(); } } /** * @param audioTracks the audioTracks to set * @since 1.60.0 */ // TODO (breaking change): rename to setAudioTracks public void setAudioTracksList(List<DLNAMediaAudio> audioTracks) { this.audioTracks = audioTracks; } /** * @param audioTracks the audioTracks to set * @deprecated use setAudioTracksList(ArrayList<DLNAMediaAudio> audioTracks) instead */ @Deprecated public void setAudioCodes(List<DLNAMediaAudio> audioTracks) { setAudioTracksList(audioTracks); } /** * @return the subtitleTracks * @since 1.60.0 */ // TODO (breaking change): rename to getSubtitleTracks public List<DLNAMediaSubtitle> getSubtitleTracksList() { return subtitleTracks; } /** * @return the subtitleTracks * @deprecated use getSubtitleTracksList() instead */ @Deprecated public ArrayList<DLNAMediaSubtitle> getSubtitlesCodes() { if (subtitleTracks instanceof ArrayList) { return (ArrayList<DLNAMediaSubtitle>) subtitleTracks; } else { return new ArrayList<>(); } } /** * @param subtitleTracks the subtitleTracks to set * @since 1.60.0 */ // TODO (breaking change): rename to setSubtitleTracks public void setSubtitleTracksList(List<DLNAMediaSubtitle> subtitleTracks) { this.subtitleTracks = subtitleTracks; } /** * @param subtitleTracks the subtitleTracks to set * @deprecated use setSubtitleTracksList(ArrayList<DLNAMediaSubtitle> subtitleTracks) instead */ @Deprecated public void setSubtitlesCodes(List<DLNAMediaSubtitle> subtitleTracks) { setSubtitleTracksList(subtitleTracks); } /** * @return the model * @since 1.50.0 */ public String getModel() { return model; } /** * @param model the model to set * @since 1.50.0 */ public void setModel(String model) { this.model = model; } /** * @return the exposure * @since 1.50.0 */ public int getExposure() { return exposure; } /** * @param exposure the exposure to set * @since 1.50.0 */ public void setExposure(int exposure) { this.exposure = exposure; } /** * @return the orientation * @since 1.50.0 */ public int getOrientation() { return orientation; } /** * @param orientation the orientation to set * @since 1.50.0 */ public void setOrientation(int orientation) { this.orientation = orientation; } /** * @return the iso * @since 1.50.0 */ public int getIso() { return iso; } /** * @param iso the iso to set * @since 1.50.0 */ public void setIso(int iso) { this.iso = iso; } /** * @return the muxingMode * @since 1.50.0 */ public String getMuxingMode() { return muxingMode; } /** * @param muxingMode the muxingMode to set * @since 1.50.0 */ public void setMuxingMode(String muxingMode) { this.muxingMode = muxingMode; } /** * @return the muxingModeAudio * @since 1.50.0 */ public String getMuxingModeAudio() { return muxingModeAudio; } /** * @param muxingModeAudio the muxingModeAudio to set * @since 1.50.0 */ public void setMuxingModeAudio(String muxingModeAudio) { this.muxingModeAudio = muxingModeAudio; } /** * @return the container * @since 1.50.0 */ public String getContainer() { return container; } /** * @param container the container to set * @since 1.50.0 */ public void setContainer(String container) { this.container = container; } /** * @return the h264_annexB * @since 1.50.0 */ public byte[] getH264AnnexB() { return h264_annexB; } /** * @param h264AnnexB the h264_annexB to set * @since 1.50.0 */ public void setH264AnnexB(byte[] h264AnnexB) { this.h264_annexB = h264AnnexB; } /** * @return the mediaparsed * @since 1.50.0 */ public boolean isMediaparsed() { return mediaparsed; } /** * @param mediaparsed the mediaparsed to set * @since 1.50.0 */ public void setMediaparsed(boolean mediaparsed) { this.mediaparsed = mediaparsed; } public boolean isFFmpegparsed() { return ffmpegparsed; } /** * @return the thumbready * @since 1.50.0 */ public boolean isThumbready() { return thumbready; } /** * @param thumbready the thumbready to set * @since 1.50.0 */ public void setThumbready(boolean thumbready) { this.thumbready = thumbready; } /** * @return the dvdtrack * @since 1.50.0 */ public int getDvdtrack() { return dvdtrack; } /** * @param dvdtrack the dvdtrack to set * @since 1.50.0 */ public void setDvdtrack(int dvdtrack) { this.dvdtrack = dvdtrack; } /** * @return the secondaryFormatValid * @since 1.50.0 */ public boolean isSecondaryFormatValid() { return secondaryFormatValid; } /** * @param secondaryFormatValid the secondaryFormatValid to set * @since 1.50.0 */ public void setSecondaryFormatValid(boolean secondaryFormatValid) { this.secondaryFormatValid = secondaryFormatValid; } /** * @return the parsing * @since 1.50.0 */ public boolean isParsing() { return parsing; } /** * @param parsing the parsing to set * @since 1.50.0 */ public void setParsing(boolean parsing) { this.parsing = parsing; } /** * @return the encrypted * @since 1.50.0 */ public boolean isEncrypted() { return encrypted; } /** * @param encrypted the encrypted to set * @since 1.50.0 */ public void setEncrypted(boolean encrypted) { this.encrypted = encrypted; } public boolean isMod4() { if ( height % 4 != 0 || width % 4 != 0 ) { return false; } return true; } /** * Note: This is based on a flag in Matroska files, and as such it is * unreliable; it will be unlikely to find a false-positive but there * will be false-negatives, similar to language flags. * * @return whether the video track is 3D */ public boolean is3d() { return isNotBlank(stereoscopy); } /** * The significance of this is that the aspect ratio should not be kept * in this case when transcoding. * Example: 3840x1080 should be resized to 1920x1080, not 1920x540. * * @return whether the video track is full SBS or OU 3D */ public boolean is3dFullSbsOrOu() { if (!is3d()) { return false; } switch (stereoscopy) { case "overunderrt": case "OULF": case "OURF": case "SBSLF": case "SBSRF": case "top-bottom (left eye first)": case "top-bottom (right eye first)": case "side by side (left eye first)": case "side by side (right eye first)": return true; } return false; } /** * Note: This is based on a flag in Matroska files, and as such it is * unreliable; it will be unlikely to find a false-positive but there * will be false-negatives, similar to language flags. * * @return the type of stereoscopy (3D) of the video track */ public String getStereoscopy() { return stereoscopy; } /** * Sets the type of stereoscopy (3D) of the video track. * * Note: This is based on a flag in Matroska files, and as such it is * unreliable; it will be unlikely to find a false-positive but there * will be false-negatives, similar to language flags. * * @param stereoscopy the type of stereoscopy (3D) of the video track */ public void setStereoscopy(String stereoscopy) { this.stereoscopy = stereoscopy; } /** * Used by FFmpeg for 3D video format naming */ public enum Mode3D { SBSL, SBSR, HSBSL, OUL, OUR, HOUL, ARCG, ARCH, ARCC, ARCD, AGMG, AGMH, AGMC, AGMD, AYBG, AYBH, AYBC, AYBD }; public Mode3D get3DLayout() { if (!is3d()) { return null; } isAnaglyph = true; switch (stereoscopy) { case "overunderrt": case "OULF": case "top-bottom (left eye first)": isAnaglyph = false; return Mode3D.OUL; case "OURF": case "top-bottom (right eye first)": isAnaglyph = false; return Mode3D.OUR; case "SBSLF": case "side by side (left eye first)": isAnaglyph = false; return Mode3D.SBSL; case "SBSRF": case "side by side (right eye first)": isAnaglyph = false; return Mode3D.SBSR; case "half top-bottom (left eye first)": isAnaglyph = false; return Mode3D.HOUL; case "half side by side (left eye first)": isAnaglyph = false; return Mode3D.HSBSL; case "ARCG": return Mode3D.ARCG; case "ARCH": return Mode3D.ARCH; case "ARCC": return Mode3D.ARCC; case "ARCD": return Mode3D.ARCD; case "AGMG": return Mode3D.AGMG; case "AGMH": return Mode3D.AGMH; case "AGMC": return Mode3D.AGMC; case "AGMD": return Mode3D.AGMD; case "AYBG": return Mode3D.AYBG; case "AYBH": return Mode3D.AYBH; case "AYBC": return Mode3D.AYBC; case "AYBD": return Mode3D.AYBD; } return null; } private boolean isAnaglyph; public boolean stereoscopyIsAnaglyph() { get3DLayout(); return isAnaglyph; } public boolean isDVDResolution() { return (width == 720 && height == 576) || (width == 720 && height == 480); } }
gpl-2.0
malizadehq/MyTelegram
TMessagesProj/src/main/java/org/telegram/messenger/VideoEditedInfo.java
1968
/* * This is the source code of Telegram for Android v. 3.x.x. * It is licensed under GNU GPL v. 2 or later. * You should have received a copy of the license in this archive (see LICENSE). * * Copyright Nikolai Kudashov, 2013-2016. */ package org.telegram.messenger; import java.util.Locale; public class VideoEditedInfo { public long startTime; public long endTime; public int rotationValue; public int originalWidth; public int originalHeight; public int resultWidth; public int resultHeight; public int bitrate; public String originalPath; public String getString() { return String.format(Locale.US, "-1_%d_%d_%d_%d_%d_%d_%d_%d_%s", startTime, endTime, rotationValue, originalWidth, originalHeight, bitrate, resultWidth, resultHeight, originalPath); } public boolean parseString(String string) { if (string.length() < 6) { return false; } try { String args[] = string.split("_"); if (args.length >= 10) { startTime = Long.parseLong(args[1]); endTime = Long.parseLong(args[2]); rotationValue = Integer.parseInt(args[3]); originalWidth = Integer.parseInt(args[4]); originalHeight = Integer.parseInt(args[5]); bitrate = Integer.parseInt(args[6]); resultWidth = Integer.parseInt(args[7]); resultHeight = Integer.parseInt(args[8]); for (int a = 9; a < args.length; a++) { if (originalPath == null) { originalPath = args[a]; } else { originalPath += "_" + args[a]; } } } return true; } catch (Exception e) { FileLog.e("tmessages", e); } return false; } }
gpl-2.0
gnooth/j
src/org/armedbear/lisp/SpecialOperators.java
24723
/* * SpecialOperators.java * * Copyright (C) 2003-2007 Peter Graves * $Id: SpecialOperators.java,v 1.57 2007/09/17 18:15:15 piso Exp $ * * 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.armedbear.lisp; import java.util.ArrayList; public final class SpecialOperators extends Lisp { // ### quote private static final SpecialOperator QUOTE = new SpecialOperator(Symbol.QUOTE, "thing") { public LispObject execute(LispObject args, Environment env) throws ConditionThrowable { if (args.cdr() != NIL) return error(new WrongNumberOfArgumentsException(this)); return ((Cons)args).car; } }; // ### if private static final SpecialOperator IF = new SpecialOperator(Symbol.IF, "test then &optional else") { public LispObject execute(LispObject args, Environment env) throws ConditionThrowable { final LispThread thread = LispThread.currentThread(); switch (args.length()) { case 2: { if (eval(((Cons)args).car, env, thread) != NIL) return eval(args.cadr(), env, thread); thread.clearValues(); return NIL; } case 3: { if (eval(((Cons)args).car, env, thread) != NIL) return eval(args.cadr(), env, thread); return eval((((Cons)args).cdr).cadr(), env, thread); } default: return error(new WrongNumberOfArgumentsException(this)); } } }; // ### let private static final SpecialOperator LET = new SpecialOperator(Symbol.LET, "bindings &body body") { public LispObject execute(LispObject args, Environment env) throws ConditionThrowable { if (args == NIL) return error(new WrongNumberOfArgumentsException(this)); return _let(args, env, false); } }; // ### let* private static final SpecialOperator LET_STAR = new SpecialOperator(Symbol.LET_STAR, "bindings &body body") { public LispObject execute(LispObject args, Environment env) throws ConditionThrowable { if (args == NIL) return error(new WrongNumberOfArgumentsException(this)); return _let(args, env, true); } }; private static final LispObject _let(LispObject args, Environment env, boolean sequential) throws ConditionThrowable { LispObject result = NIL; final LispThread thread = LispThread.currentThread(); final SpecialBinding lastSpecialBinding = thread.lastSpecialBinding; try { LispObject varList = checkList(args.car()); LispObject body = args.cdr(); // Process declarations. LispObject specials = NIL; while (body != NIL) { LispObject obj = body.car(); if (obj instanceof Cons && ((Cons)obj).car == Symbol.DECLARE) { LispObject decls = ((Cons)obj).cdr; while (decls != NIL) { LispObject decl = decls.car(); if (decl instanceof Cons && ((Cons)decl).car == Symbol.SPECIAL) { LispObject vars = ((Cons)decl).cdr; while (vars != NIL) { specials = new Cons(vars.car(), specials); vars = ((Cons)vars).cdr; } } decls = ((Cons)decls).cdr; } body = ((Cons)body).cdr; } else break; } Environment ext = new Environment(env); if (sequential) { // LET* while (varList != NIL) { final Symbol symbol; LispObject value; LispObject obj = varList.car(); if (obj instanceof Cons) { if (obj.length() > 2) return error(new LispError("The LET* binding specification " + obj.writeToString() + " is invalid.")); try { symbol = (Symbol) ((Cons)obj).car; } catch (ClassCastException e) { return type_error(((Cons)obj).car, Symbol.SYMBOL); } value = eval(obj.cadr(), ext, thread); } else { try { symbol = (Symbol) obj; } catch (ClassCastException e) { return type_error(obj, Symbol.SYMBOL); } value = NIL; } if (specials != NIL && memq(symbol, specials)) { thread.bindSpecial(symbol, value); ext.declareSpecial(symbol); } else if (symbol.isSpecialVariable()) { thread.bindSpecial(symbol, value); } else ext.bind(symbol, value); varList = ((Cons)varList).cdr; } } else { // LET final int length = varList.length(); LispObject[] vals = new LispObject[length]; for (int i = 0; i < length; i++) { LispObject obj = ((Cons)varList).car; if (obj instanceof Cons) { if (obj.length() > 2) return error(new LispError("The LET binding specification " + obj.writeToString() + " is invalid.")); vals[i] = eval(obj.cadr(), env, thread); } else vals[i] = NIL; varList = ((Cons)varList).cdr; } varList = args.car(); int i = 0; while (varList != NIL) { final Symbol symbol; LispObject obj = varList.car(); if (obj instanceof Cons) { try { symbol = (Symbol) ((Cons)obj).car; } catch (ClassCastException e) { return type_error(((Cons)obj).car, Symbol.SYMBOL); } } else { try { symbol = (Symbol) obj; } catch (ClassCastException e) { return type_error(obj, Symbol.SYMBOL); } } LispObject value = vals[i]; if (specials != NIL && memq(symbol, specials)) { thread.bindSpecial(symbol, value); ext.declareSpecial(symbol); } else if (symbol.isSpecialVariable()) { thread.bindSpecial(symbol, value); } else ext.bind(symbol, value); varList = ((Cons)varList).cdr; ++i; } } // Make sure free special declarations are visible in the body. // "The scope of free declarations specifically does not include // initialization forms for bindings established by the form // containing the declarations." (3.3.4) while (specials != NIL) { Symbol symbol = (Symbol) specials.car(); ext.declareSpecial(symbol); specials = ((Cons)specials).cdr; } while (body != NIL) { result = eval(body.car(), ext, thread); body = ((Cons)body).cdr; } } finally { thread.lastSpecialBinding = lastSpecialBinding; } return result; } // ### symbol-macrolet private static final SpecialOperator SYMBOL_MACROLET = new SpecialOperator(Symbol.SYMBOL_MACROLET, "macrobindings &body body") { public LispObject execute(LispObject args, Environment env) throws ConditionThrowable { LispObject varList = checkList(args.car()); final LispThread thread = LispThread.currentThread(); LispObject result = NIL; if (varList != NIL) { SpecialBinding lastSpecialBinding = thread.lastSpecialBinding; try { Environment ext = new Environment(env); for (int i = varList.length(); i-- > 0;) { LispObject obj = varList.car(); varList = varList.cdr(); if (obj instanceof Cons && obj.length() == 2) { Symbol symbol = checkSymbol(obj.car()); if (symbol.isSpecialVariable()) { return error(new ProgramError( "Attempt to bind the special variable " + symbol.writeToString() + " with SYMBOL-MACROLET.")); } bind(symbol, new SymbolMacro(obj.cadr()), ext); } else { return error(new ProgramError( "Malformed symbol-expansion pair in SYMBOL-MACROLET: " + obj.writeToString())); } } LispObject body = args.cdr(); while (body != NIL) { result = eval(body.car(), ext, thread); body = body.cdr(); } } finally { thread.lastSpecialBinding = lastSpecialBinding; } } else { LispObject body = args.cdr(); while (body != NIL) { result = eval(body.car(), env, thread); body = body.cdr(); } } return result; } }; // ### load-time-value form &optional read-only-p => object private static final SpecialOperator LOAD_TIME_VALUE = new SpecialOperator(Symbol.LOAD_TIME_VALUE, "form &optional read-only-p") { public LispObject execute(LispObject args, Environment env) throws ConditionThrowable { switch (args.length()) { case 1: case 2: return eval(args.car(), new Environment(), LispThread.currentThread()); default: return error(new WrongNumberOfArgumentsException(this)); } } }; // ### locally private static final SpecialOperator LOCALLY = new SpecialOperator(Symbol.LOCALLY, "&body body") { public LispObject execute(LispObject args, Environment env) throws ConditionThrowable { final LispThread thread = LispThread.currentThread(); final Environment ext = new Environment(env); args = ext.processDeclarations(args); LispObject result = NIL; while (args != NIL) { result = eval(args.car(), ext, thread); args = args.cdr(); } return result; } }; // ### progn private static final SpecialOperator PROGN = new SpecialOperator(Symbol.PROGN, "&rest forms") { public LispObject execute(LispObject args, Environment env) throws ConditionThrowable { LispThread thread = LispThread.currentThread(); LispObject result = NIL; while (args != NIL) { result = eval(args.car(), env, thread); args = ((Cons)args).cdr; } return result; } }; // ### flet private static final SpecialOperator FLET = new SpecialOperator(Symbol.FLET, "definitions &body body") { public LispObject execute(LispObject args, Environment env) throws ConditionThrowable { return _flet(args, env, false); } }; // ### labels private static final SpecialOperator LABELS = new SpecialOperator(Symbol.LABELS, "definitions &body body") { public LispObject execute(LispObject args, Environment env) throws ConditionThrowable { return _flet(args, env, true); } }; private static final LispObject _flet(LispObject args, Environment env, boolean recursive) throws ConditionThrowable { // First argument is a list of local function definitions. LispObject defs = checkList(args.car()); final LispThread thread = LispThread.currentThread(); LispObject result; if (defs != NIL) { SpecialBinding lastSpecialBinding = thread.lastSpecialBinding; Environment ext = new Environment(env); while (defs != NIL) { final LispObject def = checkList(defs.car()); final LispObject name = def.car(); final Symbol symbol; if (name instanceof Symbol) { symbol = checkSymbol(name); if (symbol.getSymbolFunction() instanceof SpecialOperator) { String message = symbol.getName() + " is a special operator and may not be redefined"; return error(new ProgramError(message)); } } else if (isValidSetfFunctionName(name)) symbol = checkSymbol(name.cadr()); else return type_error(name, FUNCTION_NAME); LispObject rest = def.cdr(); LispObject parameters = rest.car(); LispObject body = rest.cdr(); LispObject decls = NIL; while (body.car() instanceof Cons && body.car().car() == Symbol.DECLARE) { decls = new Cons(body.car(), decls); body = body.cdr(); } body = new Cons(symbol, body); body = new Cons(Symbol.BLOCK, body); body = new Cons(body, NIL); while (decls != NIL) { body = new Cons(decls.car(), body); decls = decls.cdr(); } LispObject lambda_expression = new Cons(Symbol.LAMBDA, new Cons(parameters, body)); LispObject lambda_name = list2(recursive ? Symbol.LABELS : Symbol.FLET, name); Closure closure = new Closure(lambda_name, lambda_expression, recursive ? ext : env); ext.addFunctionBinding(name, closure); defs = defs.cdr(); } try { result = progn(args.cdr(), ext, thread); } finally { thread.lastSpecialBinding = lastSpecialBinding; } } else result = progn(args.cdr(), env, thread); return result; } // ### the value-type form => result* private static final SpecialOperator THE = new SpecialOperator(Symbol.THE, "type value") { public LispObject execute(LispObject args, Environment env) throws ConditionThrowable { if (args.length() != 2) return error(new WrongNumberOfArgumentsException(this)); return eval(args.cadr(), env, LispThread.currentThread()); } }; // ### progv private static final SpecialOperator PROGV = new SpecialOperator(Symbol.PROGV, "symbols values &body body") { public LispObject execute(LispObject args, Environment env) throws ConditionThrowable { if (args.length() < 2) return error(new WrongNumberOfArgumentsException(this)); final LispThread thread = LispThread.currentThread(); final LispObject symbols = checkList(eval(args.car(), env, thread)); LispObject values = checkList(eval(args.cadr(), env, thread)); SpecialBinding lastSpecialBinding = thread.lastSpecialBinding; try { // Set up the new bindings. progvBindVars(symbols, values, thread); // Implicit PROGN. LispObject result = NIL; LispObject body = args.cdr().cdr(); while (body != NIL) { result = eval(body.car(), env, thread); body = body.cdr(); } return result; } finally { thread.lastSpecialBinding = lastSpecialBinding; } } }; // ### declare private static final SpecialOperator DECLARE = new SpecialOperator(Symbol.DECLARE, "&rest declaration-specifiers") { public LispObject execute(LispObject args, Environment env) throws ConditionThrowable { while (args != NIL) { LispObject decl = args.car(); args = args.cdr(); if (decl instanceof Cons && decl.car() == Symbol.SPECIAL) { LispObject vars = decl.cdr(); while (vars != NIL) { Symbol var = checkSymbol(vars.car()); env.declareSpecial(var); vars = vars.cdr(); } } } return NIL; } }; // ### function private static final SpecialOperator FUNCTION = new SpecialOperator(Symbol.FUNCTION, "thing") { public LispObject execute(LispObject args, Environment env) throws ConditionThrowable { final LispObject arg = args.car(); if (arg instanceof Symbol) { LispObject operator = env.lookupFunction(arg); if (operator instanceof Autoload) { Autoload autoload = (Autoload) operator; autoload.load(); operator = autoload.getSymbol().getSymbolFunction(); } if (operator instanceof Function) return operator; if (operator instanceof StandardGenericFunction) return operator; return error(new UndefinedFunction(arg)); } if (arg instanceof Cons) { LispObject car = ((Cons)arg).car; if (car == Symbol.SETF) { LispObject f = env.lookupFunction(arg); if (f != null) return f; Symbol symbol = checkSymbol(arg.cadr()); f = get(symbol, Symbol.SETF_FUNCTION, null); if (f != null) return f; f = get(symbol, Symbol.SETF_INVERSE, null); if (f != null) return f; } if (car == Symbol.LAMBDA) return new Closure(arg, env); if (car == Symbol.NAMED_LAMBDA) { LispObject name = arg.cadr(); if (name instanceof Symbol || isValidSetfFunctionName(name)) { return new Closure(name, new Cons(Symbol.LAMBDA, arg.cddr()), env); } return type_error(name, FUNCTION_NAME); } } return error(new UndefinedFunction(list2(Keyword.NAME, arg))); } }; // ### setq private static final SpecialOperator SETQ = new SpecialOperator(Symbol.SETQ, "&rest vars-and-values") { public LispObject execute(LispObject args, Environment env) throws ConditionThrowable { LispObject value = Symbol.NIL; final LispThread thread = LispThread.currentThread(); while (args != NIL) { Symbol symbol = checkSymbol(args.car()); if (symbol.isConstant()) { return error(new ProgramError(symbol.writeToString() + " is a constant and thus cannot be set.")); } args = args.cdr(); if (symbol.isSpecialVariable() || env.isDeclaredSpecial(symbol)) { SpecialBinding binding = thread.getSpecialBinding(symbol); if (binding != null) { if (binding.value instanceof SymbolMacro) { LispObject expansion = ((SymbolMacro)binding.value).getExpansion(); LispObject form = list3(Symbol.SETF, expansion, args.car()); value = eval(form, env, thread); } else { value = eval(args.car(), env, thread); binding.value = value; } } else { if (symbol.getSymbolValue() instanceof SymbolMacro) { LispObject expansion = ((SymbolMacro)symbol.getSymbolValue()).getExpansion(); LispObject form = list3(Symbol.SETF, expansion, args.car()); value = eval(form, env, thread); } else { value = eval(args.car(), env, thread); symbol.setSymbolValue(value); } } } else { // Not special. Binding binding = env.getBinding(symbol); if (binding != null) { if (binding.value instanceof SymbolMacro) { LispObject expansion = ((SymbolMacro)binding.value).getExpansion(); LispObject form = list3(Symbol.SETF, expansion, args.car()); value = eval(form, env, thread); } else { value = eval(args.car(), env, thread); binding.value = value; } } else { if (symbol.getSymbolValue() instanceof SymbolMacro) { LispObject expansion = ((SymbolMacro)symbol.getSymbolValue()).getExpansion(); LispObject form = list3(Symbol.SETF, expansion, args.car()); value = eval(form, env, thread); } else { value = eval(args.car(), env, thread); symbol.setSymbolValue(value); } } } args = args.cdr(); } // Return primary value only! thread._values = null; return value; } }; }
gpl-2.0
samskivert/ikvm-openjdk
build/linux-amd64/impsrc/com/sun/xml/internal/xsom/impl/parser/state/ersSet.java
5728
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ /* this file is generated by RelaxNGCC */ package com.sun.xml.internal.xsom.impl.parser.state; import org.xml.sax.SAXException; import org.xml.sax.XMLReader; import org.xml.sax.Attributes; import com.sun.xml.internal.xsom.impl.parser.NGCCRuntimeEx; import com.sun.xml.internal.xsom.*; import com.sun.xml.internal.xsom.parser.*; import com.sun.xml.internal.xsom.impl.*; import com.sun.xml.internal.xsom.impl.parser.*; import org.xml.sax.Locator; import org.xml.sax.ContentHandler; import org.xml.sax.helpers.*; import java.util.*; class ersSet extends NGCCHandler { private String v; protected final NGCCRuntimeEx $runtime; private int $_ngcc_current_state; protected String $uri; protected String $localName; protected String $qname; public final NGCCRuntime getRuntime() { return($runtime); } public ersSet(NGCCHandler parent, NGCCEventSource source, NGCCRuntimeEx runtime, int cookie) { super(source, parent, cookie); $runtime = runtime; $_ngcc_current_state = 1; } public ersSet(NGCCRuntimeEx runtime) { this(null, runtime, runtime, -1); } public void enterElement(String $__uri, String $__local, String $__qname, Attributes $attrs) throws SAXException { int $ai; $uri = $__uri; $localName = $__local; $qname = $__qname; switch($_ngcc_current_state) { case 0: { revertToParentFromEnterElement(makeResult(), super._cookie, $__uri, $__local, $__qname, $attrs); } break; default: { unexpectedEnterElement($__qname); } break; } } public void leaveElement(String $__uri, String $__local, String $__qname) throws SAXException { int $ai; $uri = $__uri; $localName = $__local; $qname = $__qname; switch($_ngcc_current_state) { case 0: { revertToParentFromLeaveElement(makeResult(), super._cookie, $__uri, $__local, $__qname); } break; default: { unexpectedLeaveElement($__qname); } break; } } public void enterAttribute(String $__uri, String $__local, String $__qname) throws SAXException { int $ai; $uri = $__uri; $localName = $__local; $qname = $__qname; switch($_ngcc_current_state) { case 0: { revertToParentFromEnterAttribute(makeResult(), super._cookie, $__uri, $__local, $__qname); } break; default: { unexpectedEnterAttribute($__qname); } break; } } public void leaveAttribute(String $__uri, String $__local, String $__qname) throws SAXException { int $ai; $uri = $__uri; $localName = $__local; $qname = $__qname; switch($_ngcc_current_state) { case 0: { revertToParentFromLeaveAttribute(makeResult(), super._cookie, $__uri, $__local, $__qname); } break; default: { unexpectedLeaveAttribute($__qname); } break; } } public void text(String $value) throws SAXException { int $ai; switch($_ngcc_current_state) { case 1: { v = $value; $_ngcc_current_state = 0; } break; case 0: { revertToParentFromText(makeResult(), super._cookie, $value); } break; } } public void onChildCompleted(Object $__result__, int $__cookie__, boolean $__needAttCheck__)throws SAXException { switch($__cookie__) { } } public boolean accepted() { return(($_ngcc_current_state == 0)); } private Integer makeResult() { if(v==null) return new Integer($runtime.blockDefault); if(v.indexOf("#all")!=-1) return new Integer( XSType.EXTENSION|XSType.RESTRICTION|XSType.SUBSTITUTION); int r = 0; if(v.indexOf("extension")!=-1) r|=XSType.EXTENSION; if(v.indexOf("restriction")!=-1) r|=XSType.RESTRICTION; if(v.indexOf("substitution")!=-1) r|=XSType.SUBSTITUTION; return new Integer(r); } }
gpl-2.0
RangerRick/opennms
opennms-config/src/main/java/org/opennms/netmgt/config/UserFactory.java
6182
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2012 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2012 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published * by the Free Software Foundation, either version 3 of the License, * or (at your option) any later version. * * OpenNMS(R) is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.config; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStreamWriter; import java.io.Writer; import org.exolab.castor.xml.MarshalException; import org.exolab.castor.xml.ValidationException; import org.opennms.core.utils.ConfigFileConstants; /** * <p>UserFactory class.</p> * * @author ranger * @version $Id: $ */ public class UserFactory extends UserManager { /** * The static singleton instance of the UserFactory */ private static UserManager instance; /** * File path of users.xml */ protected File usersFile; /** * Boolean indicating if the init() method has been called */ private static boolean initialized = false; /** * */ private File m_usersConfFile; /** * */ private long m_lastModified; /** * */ private long m_fileSize; /** * Initializes the factory * * @throws java.io.IOException if any. * @throws java.io.FileNotFoundException if any. * @throws org.exolab.castor.xml.ValidationException if any. * @throws org.exolab.castor.xml.MarshalException if any. */ public UserFactory() throws MarshalException, ValidationException, FileNotFoundException, IOException { super(GroupFactory.getInstance()); reload(); } /** * <p>init</p> * * @throws java.io.IOException if any. * @throws java.io.FileNotFoundException if any. * @throws org.exolab.castor.xml.MarshalException if any. * @throws org.exolab.castor.xml.ValidationException if any. */ public static synchronized void init() throws IOException, FileNotFoundException, MarshalException, ValidationException { if (instance == null || !initialized) { GroupFactory.init(); instance = new UserFactory(); initialized = true; } } /** * Singleton static call to get the only instance that should exist for the * UserFactory * * @return the single user factory instance */ static synchronized public UserManager getInstance() { return instance; } /** * <p>Setter for the field <code>instance</code>.</p> * * @param mgr a {@link org.opennms.netmgt.config.UserManager} object. */ static synchronized public void setInstance(UserManager mgr) { initialized = true; instance = mgr; } /** * <p>reload</p> * * @throws java.io.IOException if any. * @throws java.io.FileNotFoundException if any. * @throws org.exolab.castor.xml.MarshalException if any. * @throws org.exolab.castor.xml.ValidationException if any. */ public void reload() throws IOException, FileNotFoundException, MarshalException, ValidationException { // Form the complete filename for the config file // m_usersConfFile = ConfigFileConstants.getFile(ConfigFileConstants.USERS_CONF_FILE_NAME); InputStream configIn = new FileInputStream(m_usersConfFile); m_lastModified = m_usersConfFile.lastModified(); m_fileSize = m_usersConfFile.length(); parseXML(configIn); initialized = true; } /** {@inheritDoc} */ @Override protected void saveXML(String writerString) throws IOException { if (writerString != null) { Writer fileWriter = new OutputStreamWriter(new FileOutputStream(m_usersConfFile), "UTF-8"); fileWriter.write(writerString); fileWriter.flush(); fileWriter.close(); } } /** * <p>isUpdateNeeded</p> * * @return a boolean. */ @Override public boolean isUpdateNeeded() { if (m_usersConfFile == null) { return true; } else { // Check to see if the file size has changed if (m_fileSize != m_usersConfFile.length()) { return true; // Check to see if the timestamp has changed } else if (m_lastModified != m_usersConfFile.lastModified()) { return true; } else { return false; } } } /** * <p>update</p> * * @throws java.io.IOException if any. * @throws java.io.FileNotFoundException if any. * @throws org.exolab.castor.xml.MarshalException if any. * @throws org.exolab.castor.xml.ValidationException if any. */ @Override public void doUpdate() throws IOException, FileNotFoundException, MarshalException, ValidationException { if (isUpdateNeeded()) { reload(); } } @Override public long getLastModified() { return m_lastModified; } @Override public long getFileSize() { return m_fileSize; } }
gpl-2.0
skyHALud/codenameone
Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/jdktools/modules/jpda/src/test/java/org/apache/harmony/jpda/tests/jdwp/Method/VariableTableTest.java
3905
/* * 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. */ /** * @author Anton V. Karnachuk */ /** * Created on 14.02.2005 */ package org.apache.harmony.jpda.tests.jdwp.Method; import java.io.UnsupportedEncodingException; import org.apache.harmony.jpda.tests.framework.jdwp.CommandPacket; import org.apache.harmony.jpda.tests.framework.jdwp.JDWPCommands; import org.apache.harmony.jpda.tests.framework.jdwp.ReplyPacket; import org.apache.harmony.jpda.tests.share.JPDADebuggeeSynchronizer; /** * JDWP Unit test for Method.VariableTable command. */ public class VariableTableTest extends JDWPMethodTestCase { public static void main(String[] args) { junit.textui.TestRunner.run(VariableTableTest.class); } /** * This testcase exercises Method.VariableTable command. * <BR>It runs MethodDebuggee, receives methods of debuggee. * For each received method sends Method.VariableTable command * and prints returned VariableTable. */ public void testVariableTableTest001() throws UnsupportedEncodingException { logWriter.println("testVariableTableTest001 started"); synchronizer.receiveMessage(JPDADebuggeeSynchronizer.SGNL_READY); long classID = getClassIDBySignature("L"+getDebuggeeClassName().replace('.', '/')+";"); MethodInfo[] methodsInfo = jdwpGetMethodsInfo(classID); assertFalse("Invalid number of methods: 0", methodsInfo.length == 0); for (int i = 0; i < methodsInfo.length; i++) { logWriter.println(methodsInfo[i].toString()); // get variable table for this class CommandPacket packet = new CommandPacket( JDWPCommands.MethodCommandSet.CommandSetID, JDWPCommands.MethodCommandSet.VariableTableCommand); packet.setNextValueAsClassID(classID); packet.setNextValueAsMethodID(methodsInfo[i].getMethodID()); ReplyPacket reply = debuggeeWrapper.vmMirror.performCommand(packet); checkReplyPacket(reply, "Method::VariableTable command"); int argCnt = reply.getNextValueAsInt(); logWriter.println("argCnt = "+argCnt); int slots = reply.getNextValueAsInt(); logWriter.println("slots = "+slots); for (int j = 0; j < slots; j++) { long codeIndex = reply.getNextValueAsLong(); logWriter.println("codeIndex = "+codeIndex); String name = reply.getNextValueAsString(); logWriter.println("name = "+name); String signature = reply.getNextValueAsString(); logWriter.println("signature = "+signature); int length = reply.getNextValueAsInt(); logWriter.println("length = "+length); int slot = reply.getNextValueAsInt(); logWriter.println("slot = "+slot); } } synchronizer.sendMessage(JPDADebuggeeSynchronizer.SGNL_CONTINUE); } }
gpl-2.0
scoophealth/oscar
src/main/java/oscar/oscarEncounter/oscarMeasurements/util/RuleBaseCreator.java
5095
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * 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. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package oscar.oscarEncounter.oscarMeasurements.util; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.List; import org.apache.log4j.Logger; import org.drools.RuleBase; import org.drools.io.RuleBaseLoader; import org.jdom.Element; import org.jdom.Namespace; import org.jdom.output.Format; import org.jdom.output.XMLOutputter; import org.oscarehr.drools.RuleBaseFactory; import org.oscarehr.util.MiscUtils; /** * Class used to create Drools XML files * @author jaygallagher */ public class RuleBaseCreator { private static final Logger log = MiscUtils.getLogger(); Namespace namespace = Namespace.getNamespace("http://drools.org/rules"); Namespace javaNamespace = Namespace.getNamespace("java", "http://drools.org/semantics/java"); Namespace xsNs = Namespace.getNamespace("xs", "http://www.w3.org/2001/XMLSchema-instance"); public RuleBase getRuleBase(String rulesetName, List<Element> elementRules) throws Exception { long timer = System.currentTimeMillis(); try { Element va = new Element("rule-set"); addAttributeifValueNotNull(va, "name", rulesetName); va.setNamespace(namespace); va.addNamespaceDeclaration(javaNamespace); va.addNamespaceDeclaration(xsNs); va.setAttribute("schemaLocation", "http://drools.org/rules rules.xsd http://drools.org/semantics/java java.xsd", xsNs); for (Element ele : elementRules) { va.addContent(ele); } XMLOutputter outp = new XMLOutputter(); outp.setFormat(Format.getPrettyFormat()); String ooo = outp.outputString(va); log.debug(ooo); RuleBase ruleBase=RuleBaseFactory.getRuleBase("RuleBaseCreator:"+ooo); if (ruleBase!=null) return(ruleBase); ruleBase = RuleBaseLoader.loadFromInputStream(new ByteArrayInputStream(ooo.getBytes())); RuleBaseFactory.putRuleBase("RuleBaseCreator:"+ooo, ruleBase); return ruleBase; } finally { log.debug("generateRuleBase TimeMs : " + (System.currentTimeMillis() - timer)); } } public void test() { ArrayList elementList = new ArrayList(); ArrayList list = new ArrayList(); list.add(new DSCondition("getLastDateRecordedInMonths", "REBG", ">=", "3")); list.add(new DSCondition("getLastDateRecordedInMonths", "REBG", "<", "6")); Element ruleElement = getRule("REBG1", "oscar.oscarEncounter.oscarMeasurements.MeasurementInfo", list, "MiscUtils.getLogger().debug(\"REBG 1 getting called\");"); elementList.add(ruleElement); list = new ArrayList(); list.add(new DSCondition("getLastDateRecordedInMonths", "REBG", ">", "6")); ruleElement = getRule("REBG2", "oscar.oscarEncounter.oscarMeasurements.MeasurementInfo", list, "MiscUtils.getLogger().debug(\"REBG 1 getting called\");"); elementList.add(ruleElement); list = new ArrayList(); list.add(new DSCondition("getLastDateRecordedInMonths", "REBG", "==", "-1")); ruleElement = getRule("REBG3", "oscar.oscarEncounter.oscarMeasurements.MeasurementInfo", list, "MiscUtils.getLogger().debug(\"REBG 1 getting called\");"); elementList.add(ruleElement); } void addAttributeifValueNotNull(Element element, String attr, String value) { if (value != null) { element.setAttribute(attr, value); } } public Element getRule(String ruleName, String incomingClass, List<DSCondition> conditions, String consequence) { Element rule = new Element("rule", namespace); addAttributeifValueNotNull(rule, "name", ruleName); Element param = new Element("parameter", namespace); addAttributeifValueNotNull(param, "identifier", "m"); Element classEle = new Element("class", namespace); classEle.setText(incomingClass); rule.addContent(param); param.addContent(classEle); for (DSCondition cond : conditions) { Element condElement = new Element("condition", javaNamespace); condElement.setText("m." + cond.getType() + " " + cond.getComparision() + " " + cond.getValue()); rule.addContent(condElement); } Element conseq = new Element("consequence", javaNamespace); conseq.addContent(consequence); rule.addContent(conseq); log.debug("Return Rule" + rule); return rule; } }
gpl-2.0
sfreihofer/fractals
src/main/java/ch/sfdr/fractals/fractals/ComplexOrbitCycleFinder.java
9602
package ch.sfdr.fractals.fractals; import java.util.ArrayList; import java.util.List; import ch.sfdr.fractals.math.ComplexNumber; /** * Finds cycles in orbits of escape time fractal functions. * Uses a Newton iterator with a Jacobi matrix to find the root for a given * start point. The basic iteration: * z = z - jacobian(z)^{-1} * f(z) * @author D.Ritz */ public strictfp class ComplexOrbitCycleFinder { // the tolerance in the newton finding private static final double TOL = 1e-13; // the tolerance comparing cycle start points private static final double POINT_TOL = 1e-6; // the "h" used in diff. Smaller values would cause NaN problems private static final double DIFF_H = 1e-8; private StepFractalFunction function; private int cycleLength; private long delay; // the maximum number of iterations private int maxIter = 400; private ComplexOrbitCycleListener listener; private Thread thread; private List<ComplexNumber> cycleStartPoints; private StatisticsObserver statObserver; /** * constructs a cycle finder for the given fractal function * @param listener the listener */ public ComplexOrbitCycleFinder(ComplexOrbitCycleListener listener) { this.listener = listener; cycleStartPoints = new ArrayList<ComplexNumber>(); } /** * returns the maximum number of iterations allowed * @return the max number of iterations */ public int getMaxIter() { return maxIter; } /** * sets the maximum number of iterations allowed * @param maxIter max number of iterations */ public void setMaxIter(int maxIter) { this.maxIter = maxIter; } /** * Gets the number of cycles found * @return the number of cycles */ public int getCyclesFound() { return cycleStartPoints.size(); } /** * Gets the length of a cycle * @return the cycleLength the length of a cycle */ public int getCycleLength() { return cycleLength; } /** * Sets the StatisticsObserver * @param statObserver the statObserver to set */ public void setStatObserver(StatisticsObserver statObserver) { this.statObserver = statObserver; } /** * Gets the StatisticsObserver * @return the statObserver */ public StatisticsObserver getStatObserver() { return statObserver; } /** * finds a cycle of given length, starting the Newton iteration with the * given start value * @param cycleLenght length of the cycle to find * @param start the start value for the Newton iteration * @return One possible point as ComplexNumber where a cycle occurs */ private ComplexNumber findCycle(int cycleLenght, ComplexNumber start) { this.cycleLength = cycleLenght; // the value that should converge to the solution ComplexNumber z = start.clone(); // the function value, i.e. the difference to 0 ComplexNumber f = new ComplexNumber(1, 1); // the delta from the jacobian multiplied by the function value ComplexNumber delta = new ComplexNumber(0, 0); // the jacobian (and it's inverse) Jacobian2x2 jac = new Jacobian2x2(); int i = 0; while ((Math.abs(f.getReal()) + Math.abs(f.getImaginary()) > TOL) && i++ < maxIter) { // get the inverse of the jacobian jac.jacobian(z).invert(); // get the function value callFunction(z, f); // multiply inverse of the jacobian with the current function value delta.set( jac.get(0, 0) * f.getReal() + jac.get(0, 1) * f.getImaginary(), jac.get(1, 0) * f.getReal() + jac.get(1, 1) * f.getImaginary()); // subtract the delta form the current value z.subtract(delta); } if (i >= maxIter || z.isNaN()) return null; return z; } /** * Tries to find all cycles of a given length. The Listener will be called * with the results * @param function the fractal step function * @param length the length of the cycles * @param delay the delay in milliseconds between each cycle found */ public synchronized void findAllCycles(StepFractalFunction function, int length, long delay) { stop(); this.function = function; this.cycleLength = length; this.delay = delay; cycleStartPoints.clear(); thread = new Thread() { @Override public void run() { boolean completed = doFindAllCycles(); if (completed && statObserver != null) { statObserver.statisticsDataAvailable( ComplexOrbitCycleFinder.this); } }; }; thread.start(); } /** * stop any running calculation */ public synchronized void stop() { if (thread != null) { thread.interrupt(); try { thread.join(); } catch (InterruptedException e) { } thread = null; } } /** * waits for completion * @throws InterruptedException */ public void waitForCompletion() throws InterruptedException { Thread t; synchronized (this) { t = thread; } if (t != null) t.join(); } /** * Scans over the whole boundary area. The area is divided into * (5 * cycleLength) pieces in both directions. * @return true if completed, false if interrupted */ private boolean doFindAllCycles() { double xmin = function.getLowerBounds().getReal(); double ymin = function.getLowerBounds().getImaginary(); double xmax = function.getUpperBounds().getReal(); double ymax = function.getUpperBounds().getImaginary(); double boundary = function.getBoundarySqr(); int divide = 3 * cycleLength * cycleLength; double stepSizeX = Math.abs(xmax - xmin) / divide; double stepSizeY = Math.abs(ymax - ymin) / divide; ComplexNumber start = new ComplexNumber(0, 0); long lastCycleTs = System.currentTimeMillis(); long stepsToTry = divide * divide; long stepsDone = 0; int lastPercentage = 0; for (double x = xmin; x < xmax; x += stepSizeX) { for (double y = ymin; y < ymax; y += stepSizeY) { // progress update stepsDone++; int p = (int) (100D * stepsDone / stepsToTry); if (p != lastPercentage) { lastPercentage = p; if (statObserver != null) statObserver.updateProgess(ComplexOrbitCycleFinder.this, p); } // skip points outside the boundary circle if (x * x + y * y > boundary) continue; start.set(x, y); ComplexNumber z = findCycle(cycleLength, start); if (Thread.interrupted()) return false; // check list if this (very similar) point has already been found boolean newCycle = addNewCycle(z); if (newCycle) { boolean cont = listener.cycleFound(z, cycleLength); if (!cont) return true; // delay the next cycle long dur = System.currentTimeMillis() - lastCycleTs; long sleepDelay = delay - dur; if (sleepDelay > 0) { try { Thread.sleep(sleepDelay); } catch (InterruptedException e) { return false; } } lastCycleTs = System.currentTimeMillis(); } } } return true; } /** * checks if a cycle is new by looking it up in the list * @param z the start point of the cycle * @return true if the cycle is new, false if already found before */ private boolean addNewCycle(ComplexNumber z) { // max iterations count reached or NaN if (z == null) return false; // compare against points found previously for (ComplexNumber c : cycleStartPoints) { if (Math.abs(c.getReal() - z.getReal()) < POINT_TOL && Math.abs(c.getImaginary() - z.getImaginary()) < POINT_TOL) { return false; } } // new...add it to the list cycleStartPoints.add(z); return true; } /** * calls the fractal function cycleLength times * @param start the start value * @param res the result * @return the value after cycleCount iterations */ private ComplexNumber callFunction(ComplexNumber start, ComplexNumber res) { res.set(start); for (int i = 0; i < cycleLength; i++) function.step(start, res); // bring it to the f(z) = 0 form res = res.subtract(start); return res; } /** * A 2x2 matrix jacobian, with the ability to invert itself. * All objects are pre-allocated. */ private class Jacobian2x2 { private double[][] elem = new double[2][2]; private double[][] inv = new double[2][2]; private ComplexNumber start = new ComplexNumber(0, 0); private ComplexNumber zd = new ComplexNumber(0, 0); private ComplexNumber zd2 = new ComplexNumber(0, 0); public double get(int x, int y) { return elem[x][y]; } public void set(int x, int y, double val) { elem[x][y] = val; } /** * inverts this jacobian * @return this */ public Jacobian2x2 invert() { double det = elem[0][0] * elem[1][1] - elem[0][1] * elem[1][0]; inv[0][0] = elem[1][1] / det; inv[0][1] = -elem[0][1] / det; inv[1][0] = -elem[1][0] / det; inv[1][1] = elem[0][0] / det; // just swap the two buffers - no instantiations double[][] tmp = elem; elem = inv; inv = tmp; return this; } /** * builds the jacobian matrix with numerical differentiation (central diff') * @param z the complex number * @return this */ public Jacobian2x2 jacobian(ComplexNumber z) { // x part start.set(z.getReal() + DIFF_H, z.getImaginary()); callFunction(start, zd); start.set(z.getReal() - DIFF_H, z.getImaginary()); callFunction(start, zd2); zd.subtract(zd2); set(0, 0, zd.getReal() / (2 * DIFF_H)); set(1, 0, zd.getImaginary() / (2 * DIFF_H)); // y part: start.set(z.getReal(), z.getImaginary() + DIFF_H); callFunction(start, zd); start.set(z.getReal(), z.getImaginary() - DIFF_H); callFunction(start, zd2); zd.subtract(zd2); set(0, 1, zd.getReal() / (2 * DIFF_H)); set(1, 1, zd.getImaginary() / (2 * DIFF_H)); return this; } } }
gpl-2.0
jimixing/CU
sp_uiconfig/core/java/com/ebao/gs/pol/config/datamodel/PageDataModelField.java
905
package com.ebao.gs.pol.config.datamodel; public class PageDataModelField { private int nodeId; private String fieldDisplayName; private int fieldId; private String tableName; private String whereClause; public int getNodeId() { return nodeId; } public void setNodeId(int nodeId) { this.nodeId = nodeId; } public String getFieldDisplayName() { return fieldDisplayName; } public void setFieldDisplayName(String fieldDisplayName) { this.fieldDisplayName = fieldDisplayName; } public int getFieldId() { return fieldId; } public void setFieldId(int fieldId) { this.fieldId = fieldId; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public String getWhereClause() { return whereClause; } public void setWhereClause(String whereClause) { this.whereClause = whereClause; } }
gpl-2.0
AlexGavruskin/tauGeodesic
tauSpace/Mean.java
3834
/* * Copyright (C) 2014 Alex Gavryushkin <alex@gavruskin.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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ import beast.evolution.tree.Tree; import java.util.Date; import java.util.Random; /** * Computing Frechet mean. * * Created on 24/11/14. * @author Alex Gavryushkin <alex@gavruskin.com> */ public class Mean { public static TauTree mean(TauTree[] trees, int numIter, int matchLength, double epsilon) { int CauchyMax = 0; // This is for testing. Can be removed. int convergenceCounter = 0; // Counts number of iterations the two means are no further apart than epsilon. // Find the first mean candidate randomly: Random random = new Random(); int r = random.nextInt(trees.length); TauTree meanOld = new TauTree(); for (TauPartition m : trees[r].tauPartitions) { meanOld.addPartition(m); } int i = 1; while (i < numIter) { int j = random.nextInt(trees.length); TauTree meanNew = Geodesic.geodesic(meanOld, trees[j], (double) 1 / (i + 1)).tree; double tmpDistance = Geodesic.geodesic(meanOld, meanNew, 0.5).geoLength; // 0.5 here is a random choice. We only need the geo.geoLength. if (i % 10000 == 0 || convergenceCounter >= 50) { System.out.println("The test distance is " + tmpDistance + "."); Date date = new Date(); System.out.println("The convergence counter is " + convergenceCounter + " on " + date + "."); meanNew.labelMap = trees[0].labelMap; Tree meanNewBeast = TauTree.constructFromTauTree(meanNew); System.out.println("The running mean tree is"); System.out.println(meanNewBeast.getRoot().toNewick()); System.out.print("\n"); } // Check for convergence: if (tmpDistance < epsilon) { convergenceCounter++; if (convergenceCounter > CauchyMax) { CauchyMax = convergenceCounter; } if (convergenceCounter == matchLength) { System.out.println("\nThe total number of Sturm iterations is " + i + ".\n"); double firstTau = 0.0; for (int k = 0; k < trees.length; k++) { firstTau += trees[k].firstTau; } meanOld.firstTau = firstTau / trees.length; return meanOld; } } else { convergenceCounter = 0; } meanOld.tauPartitions.clear(); for (TauPartition m: meanNew.tauPartitions) { meanOld.addPartition(m); } i++; } System.out.println("\nAfter " + i +" iterations, the Sturm sequence has not converged! Try a longer sequence.\n"); System.out.println("The maximal length of Cauchy sequence is " + CauchyMax + ".\n"); double firstTau = 0.0; for (int k = 0; k < trees.length; k++) { firstTau += trees[k].firstTau; } meanOld.firstTau = firstTau / trees.length; return meanOld; } }
gpl-2.0
samskivert/ikvm-openjdk
build/linux-amd64/impsrc/com/sun/xml/internal/messaging/saaj/util/JaxmURI.java
44453
/* * Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.xml.internal.messaging.saaj.util; // Imported from: org.apache.xerces.util // Needed to work around differences in JDK1.2 and 1.3 and deal with userInfo import java.io.IOException; import java.io.Serializable; /********************************************************************** * A class to represent a Uniform Resource Identifier (URI). This class * is designed to handle the parsing of URIs and provide access to * the various components (scheme, host, port, userinfo, path, query * string and fragment) that may constitute a URI. * <p> * Parsing of a URI specification is done according to the URI * syntax described in RFC 2396 * <http://www.ietf.org/rfc/rfc2396.txt?number=2396>. Every URI consists * of a scheme, followed by a colon (':'), followed by a scheme-specific * part. For URIs that follow the "generic URI" syntax, the scheme- * specific part begins with two slashes ("//") and may be followed * by an authority segment (comprised of user information, host, and * port), path segment, query segment and fragment. Note that RFC 2396 * no longer specifies the use of the parameters segment and excludes * the "user:password" syntax as part of the authority segment. If * "user:password" appears in a URI, the entire user/password string * is stored as userinfo. * <p> * For URIs that do not follow the "generic URI" syntax (e.g. mailto), * the entire scheme-specific part is treated as the "path" portion * of the URI. * <p> * Note that, unlike the java.net.URL class, this class does not provide * any built-in network access functionality nor does it provide any * scheme-specific functionality (for example, it does not know a * default port for a specific scheme). Rather, it only knows the * grammar and basic set of operations that can be applied to a URI. * * @version * **********************************************************************/ public class JaxmURI implements Serializable { /******************************************************************* * MalformedURIExceptions are thrown in the process of building a URI * or setting fields on a URI when an operation would result in an * invalid URI specification. * ********************************************************************/ public static class MalformedURIException extends IOException { /****************************************************************** * Constructs a <code>MalformedURIException</code> with no specified * detail message. ******************************************************************/ public MalformedURIException() { super(); } /***************************************************************** * Constructs a <code>MalformedURIException</code> with the * specified detail message. * * @param p_msg the detail message. ******************************************************************/ public MalformedURIException(String p_msg) { super(p_msg); } } /** reserved characters */ private static final String RESERVED_CHARACTERS = ";/?:@&=+$,"; /** URI punctuation mark characters - these, combined with alphanumerics, constitute the "unreserved" characters */ private static final String MARK_CHARACTERS = "-_.!~*'() "; /** scheme can be composed of alphanumerics and these characters */ private static final String SCHEME_CHARACTERS = "+-."; /** userinfo can be composed of unreserved, escaped and these characters */ private static final String USERINFO_CHARACTERS = ";:&=+$,"; /** Stores the scheme (usually the protocol) for this URI. */ private String m_scheme = null; /** If specified, stores the userinfo for this URI; otherwise null */ private String m_userinfo = null; /** If specified, stores the host for this URI; otherwise null */ private String m_host = null; /** If specified, stores the port for this URI; otherwise -1 */ private int m_port = -1; /** If specified, stores the path for this URI; otherwise null */ private String m_path = null; /** If specified, stores the query string for this URI; otherwise null. */ private String m_queryString = null; /** If specified, stores the fragment for this URI; otherwise null */ private String m_fragment = null; private static boolean DEBUG = false; /** * Construct a new and uninitialized URI. */ public JaxmURI() { } /** * Construct a new URI from another URI. All fields for this URI are * set equal to the fields of the URI passed in. * * @param p_other the URI to copy (cannot be null) */ public JaxmURI(JaxmURI p_other) { initialize(p_other); } /** * Construct a new URI from a URI specification string. If the * specification follows the "generic URI" syntax, (two slashes * following the first colon), the specification will be parsed * accordingly - setting the scheme, userinfo, host,port, path, query * string and fragment fields as necessary. If the specification does * not follow the "generic URI" syntax, the specification is parsed * into a scheme and scheme-specific part (stored as the path) only. * * @param p_uriSpec the URI specification string (cannot be null or * empty) * * @exception MalformedURIException if p_uriSpec violates any syntax * rules */ public JaxmURI(String p_uriSpec) throws MalformedURIException { this((JaxmURI)null, p_uriSpec); } /** * Construct a new URI from a base URI and a URI specification string. * The URI specification string may be a relative URI. * * @param p_base the base URI (cannot be null if p_uriSpec is null or * empty) * @param p_uriSpec the URI specification string (cannot be null or * empty if p_base is null) * * @exception MalformedURIException if p_uriSpec violates any syntax * rules */ public JaxmURI(JaxmURI p_base, String p_uriSpec) throws MalformedURIException { initialize(p_base, p_uriSpec); } /** * Construct a new URI that does not follow the generic URI syntax. * Only the scheme and scheme-specific part (stored as the path) are * initialized. * * @param p_scheme the URI scheme (cannot be null or empty) * @param p_schemeSpecificPart the scheme-specific part (cannot be * null or empty) * * @exception MalformedURIException if p_scheme violates any * syntax rules */ public JaxmURI(String p_scheme, String p_schemeSpecificPart) throws MalformedURIException { if (p_scheme == null || p_scheme.trim().length() == 0) { throw new MalformedURIException( "Cannot construct URI with null/empty scheme!"); } if (p_schemeSpecificPart == null || p_schemeSpecificPart.trim().length() == 0) { throw new MalformedURIException( "Cannot construct URI with null/empty scheme-specific part!"); } setScheme(p_scheme); setPath(p_schemeSpecificPart); } /** * Construct a new URI that follows the generic URI syntax from its * component parts. Each component is validated for syntax and some * basic semantic checks are performed as well. See the individual * setter methods for specifics. * * @param p_scheme the URI scheme (cannot be null or empty) * @param p_host the hostname or IPv4 address for the URI * @param p_path the URI path - if the path contains '?' or '#', * then the query string and/or fragment will be * set from the path; however, if the query and * fragment are specified both in the path and as * separate parameters, an exception is thrown * @param p_queryString the URI query string (cannot be specified * if path is null) * @param p_fragment the URI fragment (cannot be specified if path * is null) * * @exception MalformedURIException if any of the parameters violates * syntax rules or semantic rules */ public JaxmURI(String p_scheme, String p_host, String p_path, String p_queryString, String p_fragment) throws MalformedURIException { this(p_scheme, null, p_host, -1, p_path, p_queryString, p_fragment); } /** * Construct a new URI that follows the generic URI syntax from its * component parts. Each component is validated for syntax and some * basic semantic checks are performed as well. See the individual * setter methods for specifics. * * @param p_scheme the URI scheme (cannot be null or empty) * @param p_userinfo the URI userinfo (cannot be specified if host * is null) * @param p_host the hostname or IPv4 address for the URI * @param p_port the URI port (may be -1 for "unspecified"; cannot * be specified if host is null) * @param p_path the URI path - if the path contains '?' or '#', * then the query string and/or fragment will be * set from the path; however, if the query and * fragment are specified both in the path and as * separate parameters, an exception is thrown * @param p_queryString the URI query string (cannot be specified * if path is null) * @param p_fragment the URI fragment (cannot be specified if path * is null) * * @exception MalformedURIException if any of the parameters violates * syntax rules or semantic rules */ public JaxmURI(String p_scheme, String p_userinfo, String p_host, int p_port, String p_path, String p_queryString, String p_fragment) throws MalformedURIException { if (p_scheme == null || p_scheme.trim().length() == 0) { throw new MalformedURIException("Scheme is required!"); } if (p_host == null) { if (p_userinfo != null) { throw new MalformedURIException( "Userinfo may not be specified if host is not specified!"); } if (p_port != -1) { throw new MalformedURIException( "Port may not be specified if host is not specified!"); } } if (p_path != null) { if (p_path.indexOf('?') != -1 && p_queryString != null) { throw new MalformedURIException( "Query string cannot be specified in path and query string!"); } if (p_path.indexOf('#') != -1 && p_fragment != null) { throw new MalformedURIException( "Fragment cannot be specified in both the path and fragment!"); } } setScheme(p_scheme); setHost(p_host); setPort(p_port); setUserinfo(p_userinfo); setPath(p_path); setQueryString(p_queryString); setFragment(p_fragment); } /** * Initialize all fields of this URI from another URI. * * @param p_other the URI to copy (cannot be null) */ private void initialize(JaxmURI p_other) { m_scheme = p_other.getScheme(); m_userinfo = p_other.getUserinfo(); m_host = p_other.getHost(); m_port = p_other.getPort(); m_path = p_other.getPath(); m_queryString = p_other.getQueryString(); m_fragment = p_other.getFragment(); } /** * Initializes this URI from a base URI and a URI specification string. * See RFC 2396 Section 4 and Appendix B for specifications on parsing * the URI and Section 5 for specifications on resolving relative URIs * and relative paths. * * @param p_base the base URI (may be null if p_uriSpec is an absolute * URI) * @param p_uriSpec the URI spec string which may be an absolute or * relative URI (can only be null/empty if p_base * is not null) * * @exception MalformedURIException if p_base is null and p_uriSpec * is not an absolute URI or if * p_uriSpec violates syntax rules */ private void initialize(JaxmURI p_base, String p_uriSpec) throws MalformedURIException { if (p_base == null && (p_uriSpec == null || p_uriSpec.trim().length() == 0)) { throw new MalformedURIException( "Cannot initialize URI with empty parameters."); } // just make a copy of the base if spec is empty if (p_uriSpec == null || p_uriSpec.trim().length() == 0) { initialize(p_base); return; } String uriSpec = p_uriSpec.trim(); int uriSpecLen = uriSpec.length(); int index = 0; // Check for scheme, which must be before `/'. Also handle names with // DOS drive letters ('D:'), so 1-character schemes are not allowed. int colonIdx = uriSpec.indexOf(':'); int slashIdx = uriSpec.indexOf('/'); if ((colonIdx < 2) || (colonIdx > slashIdx && slashIdx != -1)) { int fragmentIdx = uriSpec.indexOf('#'); // A standalone base is a valid URI according to spec if (p_base == null && fragmentIdx != 0 ) { throw new MalformedURIException("No scheme found in URI."); } } else { initializeScheme(uriSpec); index = m_scheme.length()+1; } // two slashes means generic URI syntax, so we get the authority if (((index+1) < uriSpecLen) && (uriSpec.substring(index).startsWith("//"))) { index += 2; int startPos = index; // get authority - everything up to path, query or fragment char testChar = '\0'; while (index < uriSpecLen) { testChar = uriSpec.charAt(index); if (testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } // if we found authority, parse it out, otherwise we set the // host to empty string if (index > startPos) { initializeAuthority(uriSpec.substring(startPos, index)); } else { m_host = ""; } } initializePath(uriSpec.substring(index)); // Resolve relative URI to base URI - see RFC 2396 Section 5.2 // In some cases, it might make more sense to throw an exception // (when scheme is specified is the string spec and the base URI // is also specified, for example), but we're just following the // RFC specifications if (p_base != null) { // check to see if this is the current doc - RFC 2396 5.2 #2 // note that this is slightly different from the RFC spec in that // we don't include the check for query string being null // - this handles cases where the urispec is just a query // string or a fragment (e.g. "?y" or "#s") - // see <http://www.ics.uci.edu/~fielding/url/test1.html> which // identified this as a bug in the RFC if (m_path.length() == 0 && m_scheme == null && m_host == null) { m_scheme = p_base.getScheme(); m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); m_path = p_base.getPath(); if (m_queryString == null) { m_queryString = p_base.getQueryString(); } return; } // check for scheme - RFC 2396 5.2 #3 // if we found a scheme, it means absolute URI, so we're done if (m_scheme == null) { m_scheme = p_base.getScheme(); } else { return; } // check for authority - RFC 2396 5.2 #4 // if we found a host, then we've got a network path, so we're done if (m_host == null) { m_userinfo = p_base.getUserinfo(); m_host = p_base.getHost(); m_port = p_base.getPort(); } else { return; } // check for absolute path - RFC 2396 5.2 #5 if (m_path.length() > 0 && m_path.startsWith("/")) { return; } // if we get to this point, we need to resolve relative path // RFC 2396 5.2 #6 String path = new String(); String basePath = p_base.getPath(); // 6a - get all but the last segment of the base URI path if (basePath != null) { int lastSlash = basePath.lastIndexOf('/'); if (lastSlash != -1) { path = basePath.substring(0, lastSlash+1); } } // 6b - append the relative URI path path = path.concat(m_path); // 6c - remove all "./" where "." is a complete path segment index = -1; while ((index = path.indexOf("/./")) != -1) { path = path.substring(0, index+1).concat(path.substring(index+3)); } // 6d - remove "." if path ends with "." as a complete path segment if (path.endsWith("/.")) { path = path.substring(0, path.length()-1); } // 6e - remove all "<segment>/../" where "<segment>" is a complete // path segment not equal to ".." index = 1; int segIndex = -1; String tempString = null; while ((index = path.indexOf("/../", index)) > 0) { tempString = path.substring(0, path.indexOf("/../")); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { if (!tempString.substring(segIndex++).equals("..")) { path = path.substring(0, segIndex).concat(path.substring(index+4)); } else index += 4; } else index += 4; } // 6f - remove ending "<segment>/.." where "<segment>" is a // complete path segment if (path.endsWith("/..")) { tempString = path.substring(0, path.length()-3); segIndex = tempString.lastIndexOf('/'); if (segIndex != -1) { path = path.substring(0, segIndex+1); } } m_path = path; } } /** * Initialize the scheme for this URI from a URI string spec. * * @param p_uriSpec the URI specification (cannot be null) * * @exception MalformedURIException if URI does not have a conformant * scheme */ private void initializeScheme(String p_uriSpec) throws MalformedURIException { int uriSpecLen = p_uriSpec.length(); int index = 0; String scheme = null; char testChar = '\0'; while (index < uriSpecLen) { testChar = p_uriSpec.charAt(index); if (testChar == ':' || testChar == '/' || testChar == '?' || testChar == '#') { break; } index++; } scheme = p_uriSpec.substring(0, index); if (scheme.length() == 0) { throw new MalformedURIException("No scheme found in URI."); } else { setScheme(scheme); } } /** * Initialize the authority (userinfo, host and port) for this * URI from a URI string spec. * * @param p_uriSpec the URI specification (cannot be null) * * @exception MalformedURIException if p_uriSpec violates syntax rules */ private void initializeAuthority(String p_uriSpec) throws MalformedURIException { int index = 0; int start = 0; int end = p_uriSpec.length(); char testChar = '\0'; String userinfo = null; // userinfo is everything up @ if (p_uriSpec.indexOf('@', start) != -1) { while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '@') { break; } index++; } userinfo = p_uriSpec.substring(start, index); index++; } // host is everything up to ':' String host = null; start = index; while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == ':') { break; } index++; } host = p_uriSpec.substring(start, index); int port = -1; if (host.length() > 0) { // port if (testChar == ':') { index++; start = index; while (index < end) { index++; } String portStr = p_uriSpec.substring(start, index); if (portStr.length() > 0) { for (int i = 0; i < portStr.length(); i++) { if (!isDigit(portStr.charAt(i))) { throw new MalformedURIException( portStr + " is invalid. Port should only contain digits!"); } } try { port = Integer.parseInt(portStr); } catch (NumberFormatException nfe) { // can't happen } } } } setHost(host); setPort(port); setUserinfo(userinfo); } /** * Initialize the path for this URI from a URI string spec. * * @param p_uriSpec the URI specification (cannot be null) * * @exception MalformedURIException if p_uriSpec violates syntax rules */ private void initializePath(String p_uriSpec) throws MalformedURIException { if (p_uriSpec == null) { throw new MalformedURIException( "Cannot initialize path from null string!"); } int index = 0; int start = 0; int end = p_uriSpec.length(); char testChar = '\0'; // path - everything up to query string or fragment while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '?' || testChar == '#') { break; } // check for valid escape sequence if (testChar == '%') { if (index+2 >= end || !isHex(p_uriSpec.charAt(index+1)) || !isHex(p_uriSpec.charAt(index+2))) { throw new MalformedURIException( "Path contains invalid escape sequence!"); } } else if (!isReservedCharacter(testChar) && !isUnreservedCharacter(testChar)) { throw new MalformedURIException( "Path contains invalid character: " + testChar); } index++; } m_path = p_uriSpec.substring(start, index); // query - starts with ? and up to fragment or end if (testChar == '?') { index++; start = index; while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '#') { break; } if (testChar == '%') { if (index+2 >= end || !isHex(p_uriSpec.charAt(index+1)) || !isHex(p_uriSpec.charAt(index+2))) { throw new MalformedURIException( "Query string contains invalid escape sequence!"); } } else if (!isReservedCharacter(testChar) && !isUnreservedCharacter(testChar)) { throw new MalformedURIException( "Query string contains invalid character:" + testChar); } index++; } m_queryString = p_uriSpec.substring(start, index); } // fragment - starts with # if (testChar == '#') { index++; start = index; while (index < end) { testChar = p_uriSpec.charAt(index); if (testChar == '%') { if (index+2 >= end || !isHex(p_uriSpec.charAt(index+1)) || !isHex(p_uriSpec.charAt(index+2))) { throw new MalformedURIException( "Fragment contains invalid escape sequence!"); } } else if (!isReservedCharacter(testChar) && !isUnreservedCharacter(testChar)) { throw new MalformedURIException( "Fragment contains invalid character:"+testChar); } index++; } m_fragment = p_uriSpec.substring(start, index); } } /** * Get the scheme for this URI. * * @return the scheme for this URI */ public String getScheme() { return m_scheme; } /** * Get the scheme-specific part for this URI (everything following the * scheme and the first colon). See RFC 2396 Section 5.2 for spec. * * @return the scheme-specific part for this URI */ public String getSchemeSpecificPart() { StringBuffer schemespec = new StringBuffer(); if (m_userinfo != null || m_host != null || m_port != -1) { schemespec.append("//"); } if (m_userinfo != null) { schemespec.append(m_userinfo); schemespec.append('@'); } if (m_host != null) { schemespec.append(m_host); } if (m_port != -1) { schemespec.append(':'); schemespec.append(m_port); } if (m_path != null) { schemespec.append((m_path)); } if (m_queryString != null) { schemespec.append('?'); schemespec.append(m_queryString); } if (m_fragment != null) { schemespec.append('#'); schemespec.append(m_fragment); } return schemespec.toString(); } /** * Get the userinfo for this URI. * * @return the userinfo for this URI (null if not specified). */ public String getUserinfo() { return m_userinfo; } /** * Get the host for this URI. * * @return the host for this URI (null if not specified). */ public String getHost() { return m_host; } /** * Get the port for this URI. * * @return the port for this URI (-1 if not specified). */ public int getPort() { return m_port; } /** * Get the path for this URI (optionally with the query string and * fragment). * * @param p_includeQueryString if true (and query string is not null), * then a "?" followed by the query string * will be appended * @param p_includeFragment if true (and fragment is not null), * then a "#" followed by the fragment * will be appended * * @return the path for this URI possibly including the query string * and fragment */ public String getPath(boolean p_includeQueryString, boolean p_includeFragment) { StringBuffer pathString = new StringBuffer(m_path); if (p_includeQueryString && m_queryString != null) { pathString.append('?'); pathString.append(m_queryString); } if (p_includeFragment && m_fragment != null) { pathString.append('#'); pathString.append(m_fragment); } return pathString.toString(); } /** * Get the path for this URI. Note that the value returned is the path * only and does not include the query string or fragment. * * @return the path for this URI. */ public String getPath() { return m_path; } /** * Get the query string for this URI. * * @return the query string for this URI. Null is returned if there * was no "?" in the URI spec, empty string if there was a * "?" but no query string following it. */ public String getQueryString() { return m_queryString; } /** * Get the fragment for this URI. * * @return the fragment for this URI. Null is returned if there * was no "#" in the URI spec, empty string if there was a * "#" but no fragment following it. */ public String getFragment() { return m_fragment; } /** * Set the scheme for this URI. The scheme is converted to lowercase * before it is set. * * @param p_scheme the scheme for this URI (cannot be null) * * @exception MalformedURIException if p_scheme is not a conformant * scheme name */ public void setScheme(String p_scheme) throws MalformedURIException { if (p_scheme == null) { throw new MalformedURIException( "Cannot set scheme from null string!"); } if (!isConformantSchemeName(p_scheme)) { throw new MalformedURIException("The scheme is not conformant."); } m_scheme = p_scheme.toLowerCase(); } /** * Set the userinfo for this URI. If a non-null value is passed in and * the host value is null, then an exception is thrown. * * @param p_userinfo the userinfo for this URI * * @exception MalformedURIException if p_userinfo contains invalid * characters */ public void setUserinfo(String p_userinfo) throws MalformedURIException { if (p_userinfo == null) { m_userinfo = null; } else { if (m_host == null) { throw new MalformedURIException( "Userinfo cannot be set when host is null!"); } // userinfo can contain alphanumerics, mark characters, escaped // and ';',':','&','=','+','$',',' int index = 0; int end = p_userinfo.length(); char testChar = '\0'; while (index < end) { testChar = p_userinfo.charAt(index); if (testChar == '%') { if (index+2 >= end || !isHex(p_userinfo.charAt(index+1)) || !isHex(p_userinfo.charAt(index+2))) { throw new MalformedURIException( "Userinfo contains invalid escape sequence!"); } } else if (!isUnreservedCharacter(testChar) && USERINFO_CHARACTERS.indexOf(testChar) == -1) { throw new MalformedURIException( "Userinfo contains invalid character:"+testChar); } index++; } } m_userinfo = p_userinfo; } /** * Set the host for this URI. If null is passed in, the userinfo * field is also set to null and the port is set to -1. * * @param p_host the host for this URI * * @exception MalformedURIException if p_host is not a valid IP * address or DNS hostname. */ public void setHost(String p_host) throws MalformedURIException { if (p_host == null || p_host.trim().length() == 0) { m_host = p_host; m_userinfo = null; m_port = -1; } else if (!isWellFormedAddress(p_host)) { throw new MalformedURIException("Host is not a well formed address!"); } m_host = p_host; } /** * Set the port for this URI. -1 is used to indicate that the port is * not specified, otherwise valid port numbers are between 0 and 65535. * If a valid port number is passed in and the host field is null, * an exception is thrown. * * @param p_port the port number for this URI * * @exception MalformedURIException if p_port is not -1 and not a * valid port number */ public void setPort(int p_port) throws MalformedURIException { if (p_port >= 0 && p_port <= 65535) { if (m_host == null) { throw new MalformedURIException( "Port cannot be set when host is null!"); } } else if (p_port != -1) { throw new MalformedURIException("Invalid port number!"); } m_port = p_port; } /** * Set the path for this URI. If the supplied path is null, then the * query string and fragment are set to null as well. If the supplied * path includes a query string and/or fragment, these fields will be * parsed and set as well. Note that, for URIs following the "generic * URI" syntax, the path specified should start with a slash. * For URIs that do not follow the generic URI syntax, this method * sets the scheme-specific part. * * @param p_path the path for this URI (may be null) * * @exception MalformedURIException if p_path contains invalid * characters */ public void setPath(String p_path) throws MalformedURIException { if (p_path == null) { m_path = null; m_queryString = null; m_fragment = null; } else { initializePath(p_path); } } /** * Append to the end of the path of this URI. If the current path does * not end in a slash and the path to be appended does not begin with * a slash, a slash will be appended to the current path before the * new segment is added. Also, if the current path ends in a slash * and the new segment begins with a slash, the extra slash will be * removed before the new segment is appended. * * @param p_addToPath the new segment to be added to the current path * * @exception MalformedURIException if p_addToPath contains syntax * errors */ public void appendPath(String p_addToPath) throws MalformedURIException { if (p_addToPath == null || p_addToPath.trim().length() == 0) { return; } if (!isURIString(p_addToPath)) { throw new MalformedURIException( "Path contains invalid character!"); } if (m_path == null || m_path.trim().length() == 0) { if (p_addToPath.startsWith("/")) { m_path = p_addToPath; } else { m_path = "/" + p_addToPath; } } else if (m_path.endsWith("/")) { if (p_addToPath.startsWith("/")) { m_path = m_path.concat(p_addToPath.substring(1)); } else { m_path = m_path.concat(p_addToPath); } } else { if (p_addToPath.startsWith("/")) { m_path = m_path.concat(p_addToPath); } else { m_path = m_path.concat("/" + p_addToPath); } } } /** * Set the query string for this URI. A non-null value is valid only * if this is an URI conforming to the generic URI syntax and * the path value is not null. * * @param p_queryString the query string for this URI * * @exception MalformedURIException if p_queryString is not null and this * URI does not conform to the generic * URI syntax or if the path is null */ public void setQueryString(String p_queryString) throws MalformedURIException { if (p_queryString == null) { m_queryString = null; } else if (!isGenericURI()) { throw new MalformedURIException( "Query string can only be set for a generic URI!"); } else if (getPath() == null) { throw new MalformedURIException( "Query string cannot be set when path is null!"); } else if (!isURIString(p_queryString)) { throw new MalformedURIException( "Query string contains invalid character!"); } else { m_queryString = p_queryString; } } /** * Set the fragment for this URI. A non-null value is valid only * if this is a URI conforming to the generic URI syntax and * the path value is not null. * * @param p_fragment the fragment for this URI * * @exception MalformedURIException if p_fragment is not null and this * URI does not conform to the generic * URI syntax or if the path is null */ public void setFragment(String p_fragment) throws MalformedURIException { if (p_fragment == null) { m_fragment = null; } else if (!isGenericURI()) { throw new MalformedURIException( "Fragment can only be set for a generic URI!"); } else if (getPath() == null) { throw new MalformedURIException( "Fragment cannot be set when path is null!"); } else if (!isURIString(p_fragment)) { throw new MalformedURIException( "Fragment contains invalid character!"); } else { m_fragment = p_fragment; } } /** * Determines if the passed-in Object is equivalent to this URI. * * @param p_test the Object to test for equality. * * @return true if p_test is a URI with all values equal to this * URI, false otherwise */ public boolean equals(Object p_test) { if (p_test instanceof JaxmURI) { JaxmURI testURI = (JaxmURI) p_test; if (((m_scheme == null && testURI.m_scheme == null) || (m_scheme != null && testURI.m_scheme != null && m_scheme.equals(testURI.m_scheme))) && ((m_userinfo == null && testURI.m_userinfo == null) || (m_userinfo != null && testURI.m_userinfo != null && m_userinfo.equals(testURI.m_userinfo))) && ((m_host == null && testURI.m_host == null) || (m_host != null && testURI.m_host != null && m_host.equals(testURI.m_host))) && m_port == testURI.m_port && ((m_path == null && testURI.m_path == null) || (m_path != null && testURI.m_path != null && m_path.equals(testURI.m_path))) && ((m_queryString == null && testURI.m_queryString == null) || (m_queryString != null && testURI.m_queryString != null && m_queryString.equals(testURI.m_queryString))) && ((m_fragment == null && testURI.m_fragment == null) || (m_fragment != null && testURI.m_fragment != null && m_fragment.equals(testURI.m_fragment)))) { return true; } } return false; } /** * Get the URI as a string specification. See RFC 2396 Section 5.2. * * @return the URI string specification */ public String toString() { StringBuffer uriSpecString = new StringBuffer(); if (m_scheme != null) { uriSpecString.append(m_scheme); uriSpecString.append(':'); } uriSpecString.append(getSchemeSpecificPart()); return uriSpecString.toString(); } /** * Get the indicator as to whether this URI uses the "generic URI" * syntax. * * @return true if this URI uses the "generic URI" syntax, false * otherwise */ public boolean isGenericURI() { // presence of the host (whether valid or empty) means // double-slashes which means generic uri return (m_host != null); } /** * Determine whether a scheme conforms to the rules for a scheme name. * A scheme is conformant if it starts with an alphanumeric, and * contains only alphanumerics, '+','-' and '.'. * * @return true if the scheme is conformant, false otherwise */ public static boolean isConformantSchemeName(String p_scheme) { if (p_scheme == null || p_scheme.trim().length() == 0) { return false; } if (!isAlpha(p_scheme.charAt(0))) { return false; } char testChar; for (int i = 1; i < p_scheme.length(); i++) { testChar = p_scheme.charAt(i); if (!isAlphanum(testChar) && SCHEME_CHARACTERS.indexOf(testChar) == -1) { return false; } } return true; } /** * Determine whether a string is syntactically capable of representing * a valid IPv4 address or the domain name of a network host. A valid * IPv4 address consists of four decimal digit groups separated by a * '.'. A hostname consists of domain labels (each of which must * begin and end with an alphanumeric but may contain '-') separated & by a '.'. See RFC 2396 Section 3.2.2. * * @return true if the string is a syntactically valid IPv4 address * or hostname */ public static boolean isWellFormedAddress(String p_address) { if (p_address == null) { return false; } String address = p_address.trim(); int addrLength = address.length(); if (addrLength == 0 || addrLength > 255) { return false; } if (address.startsWith(".") || address.startsWith("-")) { return false; } // rightmost domain label starting with digit indicates IP address // since top level domain label can only start with an alpha // see RFC 2396 Section 3.2.2 int index = address.lastIndexOf('.'); if (address.endsWith(".")) { index = address.substring(0, index).lastIndexOf('.'); } if (index+1 < addrLength && isDigit(p_address.charAt(index+1))) { char testChar; int numDots = 0; // make sure that 1) we see only digits and dot separators, 2) that // any dot separator is preceded and followed by a digit and // 3) that we find 3 dots for (int i = 0; i < addrLength; i++) { testChar = address.charAt(i); if (testChar == '.') { if (!isDigit(address.charAt(i-1)) || (i+1 < addrLength && !isDigit(address.charAt(i+1)))) { return false; } numDots++; } else if (!isDigit(testChar)) { return false; } } if (numDots != 3) { return false; } } else { // domain labels can contain alphanumerics and '-" // but must start and end with an alphanumeric char testChar; for (int i = 0; i < addrLength; i++) { testChar = address.charAt(i); if (testChar == '.') { if (!isAlphanum(address.charAt(i-1))) { return false; } if (i+1 < addrLength && !isAlphanum(address.charAt(i+1))) { return false; } } else if (!isAlphanum(testChar) && testChar != '-') { return false; } } } return true; } /** * Determine whether a char is a digit. * * @return true if the char is betweeen '0' and '9', false otherwise */ private static boolean isDigit(char p_char) { return p_char >= '0' && p_char <= '9'; } /** * Determine whether a character is a hexadecimal character. * * @return true if the char is betweeen '0' and '9', 'a' and 'f' * or 'A' and 'F', false otherwise */ private static boolean isHex(char p_char) { return (isDigit(p_char) || (p_char >= 'a' && p_char <= 'f') || (p_char >= 'A' && p_char <= 'F')); } /** * Determine whether a char is an alphabetic character: a-z or A-Z * * @return true if the char is alphabetic, false otherwise */ private static boolean isAlpha(char p_char) { return ((p_char >= 'a' && p_char <= 'z') || (p_char >= 'A' && p_char <= 'Z' )); } /** * Determine whether a char is an alphanumeric: 0-9, a-z or A-Z * * @return true if the char is alphanumeric, false otherwise */ private static boolean isAlphanum(char p_char) { return (isAlpha(p_char) || isDigit(p_char)); } /** * Determine whether a character is a reserved character: * ';', '/', '?', ':', '@', '&', '=', '+', '$' or ',' * * @return true if the string contains any reserved characters */ private static boolean isReservedCharacter(char p_char) { return RESERVED_CHARACTERS.indexOf(p_char) != -1; } /** * Determine whether a char is an unreserved character. * * @return true if the char is unreserved, false otherwise */ private static boolean isUnreservedCharacter(char p_char) { return (isAlphanum(p_char) || MARK_CHARACTERS.indexOf(p_char) != -1); } /** * Determine whether a given string contains only URI characters (also * called "uric" in RFC 2396). uric consist of all reserved * characters, unreserved characters and escaped characters. * * @return true if the string is comprised of uric, false otherwise */ private static boolean isURIString(String p_uric) { if (p_uric == null) { return false; } int end = p_uric.length(); char testChar = '\0'; for (int i = 0; i < end; i++) { testChar = p_uric.charAt(i); if (testChar == '%') { if (i+2 >= end || !isHex(p_uric.charAt(i+1)) || !isHex(p_uric.charAt(i+2))) { return false; } else { i += 2; continue; } } if (isReservedCharacter(testChar) || isUnreservedCharacter(testChar)) { continue; } else { return false; } } return true; } }
gpl-2.0
csytang/vreHadoop
src/Patch/Hadoop/Statistic/JobDataCollector.java
3617
package Patch.Hadoop.Statistic; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.Map; import java.util.Set; import soot.SootClass; import soot.jimple.Stmt; import vreAnalyzer.Blocks.CodeBlock; import vreAnalyzer.Elements.CFGNode; import vreAnalyzer.Tag.SourceLocationTag; import vreAnalyzer.Tag.SourceLocationTag.LocationType; import Patch.Hadoop.Job.JobHub; import Patch.Hadoop.Job.JobVariable; import Patch.Hadoop.ReuseAssets.ReuseAsset; import Patch.Hadoop.Tag.BlockJobTag; public class JobDataCollector { public static JobDataCollector instance; protected Map<JobVariable,JobStatistic>jobToStatistic; private boolean startFromSource = false; public JobDataCollector(){ jobToStatistic = new HashMap<JobVariable,JobStatistic>(); } public static JobDataCollector inst(){ if(instance==null) instance = new JobDataCollector(); return instance; } public Map<JobVariable,JobStatistic>getJobToStatistic(){ return jobToStatistic; } public void parse(Map<JobVariable,JobHub>jobtoHub){ for(Map.Entry<JobVariable, JobHub>entry:jobtoHub.entrySet()){ JobVariable job = entry.getKey(); JobHub hub = entry.getValue(); Map<SootClass,LinkedList<CodeBlock>>jobUsesSequence = hub.getjobUse(); JobStatistic jobstat = null; if(!jobToStatistic.containsKey(job)){ jobstat = new JobStatistic(job); jobToStatistic.put(job, jobstat); } else jobstat = jobToStatistic.get(job); /////////////////////////////////////////////////////////////////////////// for(Map.Entry<SootClass, LinkedList<CodeBlock>>blockentry:jobUsesSequence.entrySet()){ LinkedList<CodeBlock>blocks = blockentry.getValue(); for(CodeBlock block:blocks){ BlockJobTag bmTag = block.getTag(BlockJobTag.TAG_NAME); if(bmTag==null) continue; Set<JobVariable> bindingjobs = bmTag.getJobs(); Set<Integer>lines = new HashSet<Integer>(); int line = 0; for(CFGNode cfgNode:block.getCFGNodes()){ if(cfgNode.isSpecial()) continue; Stmt stmt = cfgNode.getStmt(); SourceLocationTag slcTag = (SourceLocationTag) stmt.getTag(SourceLocationTag.TAG_NAME); if(slcTag.getTagType()==LocationType.SOURCE_TAG){// start from java source code startFromSource = true; for(int i = slcTag.getStartLineNumber();i <= slcTag.getEndLineNumber();i++){ lines.add(i); } jobstat.addUseStmts(blockentry.getKey(), lines); } else{// start from bytecode startFromSource = false; line = slcTag.getStartLineNumber(); lines.add(line); jobstat.addUseStmts(blockentry.getKey(), line); } } ///// if(bindingjobs.size()>1){ ReuseAsset comasst = null; boolean firstTime = true; for(JobVariable jb:bindingjobs){ jobtoHub.get(jb).addSharedUse(block); if(firstTime){ comasst = ReuseAsset.tryToCreate(block,lines.size(), bindingjobs); firstTime = false; } if(jobToStatistic.containsKey(jb)){ jobToStatistic.get(jb).addReuseAsset(blockentry.getKey(),comasst,lines); }else{ JobStatistic dependstatis = new JobStatistic(jb); dependstatis.addReuseAsset(blockentry.getKey(),comasst,lines); jobToStatistic.put(jb, dependstatis); } } } ///// } } /////////////////////////////////////////////////////////////////////////// } } public Map<CodeBlock,ReuseAsset> getCommonAssets(){ return ReuseAsset.getBlockToAsset(); } }
gpl-2.0
gburca/VirtMus
ICEpdf/icepdf/viewer/src/org/icepdf/ri/common/views/annotations/TextAnnotationComponent.java
2214
/* * Copyright 2006-2014 ICEsoft Technologies Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the * License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS * IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language * governing permissions and limitations under the License. */ package org.icepdf.ri.common.views.annotations; import org.icepdf.core.pobjects.annotations.Annotation; import org.icepdf.ri.common.views.AbstractPageViewComponent; import org.icepdf.ri.common.views.DocumentViewController; import org.icepdf.ri.common.views.DocumentViewModel; import java.awt.*; import java.util.logging.Logger; /** * The TextAnnotationComponent encapsulates a TextAnnotation objects. It * also provides basic editing functionality such as resizing, moving and change * the border color and style as well as the fill color. * <p/> * The Viewer RI implementation contains a TextAnnotationPanel class which * can edit the various properties of this component. * * @see org.icepdf.ri.common.utility.annotation.TextAnnotationPanel * @since 5.0 */ public class TextAnnotationComponent extends MarkupAnnotationComponent { private static final Logger logger = Logger.getLogger(TextAnnotationComponent.class.toString()); public TextAnnotationComponent(Annotation annotation, DocumentViewController documentViewController, AbstractPageViewComponent pageViewComponent, DocumentViewModel documentViewModel) { super(annotation, documentViewController, pageViewComponent, documentViewModel); isRollover = false; isMovable = true; isResizable = false; isShowInvisibleBorder = false; } @Override public void resetAppearanceShapes() { annotation.resetAppearanceStream(getPageTransform()); } @Override public void paintComponent(Graphics g) { } }
gpl-2.0
mviitanen/marsmod
mcp/src/minecraft_server/net/minecraft/command/server/CommandBanIp.java
4172
package net.minecraft.command.server; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import net.minecraft.command.CommandBase; import net.minecraft.command.ICommandSender; import net.minecraft.command.PlayerNotFoundException; import net.minecraft.command.WrongUsageException; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.server.MinecraftServer; import net.minecraft.server.management.IPBanEntry; import net.minecraft.util.IChatComponent; public class CommandBanIp extends CommandBase { public static final Pattern field_147211_a = Pattern.compile("^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$"); private static final String __OBFID = "CL_00000139"; public String getCommandName() { return "ban-ip"; } /** * Return the required permission level for this command. */ public int getRequiredPermissionLevel() { return 3; } /** * Returns true if the given command sender is allowed to use this command. */ public boolean canCommandSenderUseCommand(ICommandSender p_71519_1_) { return MinecraftServer.getServer().getConfigurationManager().getBannedIPs().func_152689_b() && super.canCommandSenderUseCommand(p_71519_1_); } public String getCommandUsage(ICommandSender p_71518_1_) { return "commands.banip.usage"; } public void processCommand(ICommandSender p_71515_1_, String[] p_71515_2_) { if (p_71515_2_.length >= 1 && p_71515_2_[0].length() > 1) { Matcher var3 = field_147211_a.matcher(p_71515_2_[0]); IChatComponent var4 = null; if (p_71515_2_.length >= 2) { var4 = func_147178_a(p_71515_1_, p_71515_2_, 1); } if (var3.matches()) { this.func_147210_a(p_71515_1_, p_71515_2_[0], var4 == null ? null : var4.getUnformattedText()); } else { EntityPlayerMP var5 = MinecraftServer.getServer().getConfigurationManager().func_152612_a(p_71515_2_[0]); if (var5 == null) { throw new PlayerNotFoundException("commands.banip.invalid", new Object[0]); } this.func_147210_a(p_71515_1_, var5.getPlayerIP(), var4 == null ? null : var4.getUnformattedText()); } } else { throw new WrongUsageException("commands.banip.usage", new Object[0]); } } /** * Adds the strings available in this command to the given list of tab completion options. */ public List addTabCompletionOptions(ICommandSender p_71516_1_, String[] p_71516_2_) { return p_71516_2_.length == 1 ? getListOfStringsMatchingLastWord(p_71516_2_, MinecraftServer.getServer().getAllUsernames()) : null; } protected void func_147210_a(ICommandSender p_147210_1_, String p_147210_2_, String p_147210_3_) { IPBanEntry var4 = new IPBanEntry(p_147210_2_, (Date)null, p_147210_1_.getCommandSenderName(), (Date)null, p_147210_3_); MinecraftServer.getServer().getConfigurationManager().getBannedIPs().func_152687_a(var4); List var5 = MinecraftServer.getServer().getConfigurationManager().getPlayerList(p_147210_2_); String[] var6 = new String[var5.size()]; int var7 = 0; EntityPlayerMP var9; for (Iterator var8 = var5.iterator(); var8.hasNext(); var6[var7++] = var9.getCommandSenderName()) { var9 = (EntityPlayerMP)var8.next(); var9.playerNetServerHandler.kickPlayerFromServer("You have been IP banned."); } if (var5.isEmpty()) { func_152373_a(p_147210_1_, this, "commands.banip.success", new Object[] {p_147210_2_}); } else { func_152373_a(p_147210_1_, this, "commands.banip.success.players", new Object[] {p_147210_2_, joinNiceString(var6)}); } } }
gpl-2.0
msafin/wmc
src/com/android/volley/VolleyLog.java
6196
/* * Copyright (C) 2011 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.volley; import java.util.ArrayList; import java.util.List; import java.util.Locale; import android.os.SystemClock; import android.util.Log; /** Logging helper class. */ public class VolleyLog { public static String TAG = "Volley"; public static boolean DEBUG = Log.isLoggable(TAG, Log.VERBOSE); /** * Customize the log tag for your application, so that other apps * using Volley don't mix their logs with yours. * <br /> * Enable the log property for your tag before starting your app: * <br /> * {@code adb shell setprop log.tag.&lt;tag&gt;} */ public static void setTag(String tag) { d("Changing log tag to %s", tag); TAG = tag; // Reinitialize the DEBUG "constant" DEBUG = Log.isLoggable(TAG, Log.VERBOSE); } public static void v(String format, Object... args) { if (DEBUG) { Log.v(TAG, buildMessage(format, args)); } } public static void d(String format, Object... args) { Log.d(TAG, buildMessage(format, args)); } public static void e(String format, Object... args) { Log.e(TAG, buildMessage(format, args)); } public static void e(Throwable tr, String format, Object... args) { Log.e(TAG, buildMessage(format, args), tr); } public static void wtf(String format, Object... args) { Log.wtf(TAG, buildMessage(format, args)); } public static void wtf(Throwable tr, String format, Object... args) { Log.wtf(TAG, buildMessage(format, args), tr); } /** * Formats the caller's provided message and prepends useful info like * calling thread ID and method name. */ private static String buildMessage(String format, Object... args) { String msg = (args == null) ? format : String.format(Locale.US, format, args); StackTraceElement[] trace = new Throwable().fillInStackTrace().getStackTrace(); String caller = "<unknown>"; // Walk up the stack looking for the first caller outside of VolleyLog. // It will be at least two frames up, so start there. for (int i = 2; i < trace.length; i++) { Class<?> clazz = trace[i].getClass(); if (!clazz.equals(VolleyLog.class)) { String callingClass = trace[i].getClassName(); callingClass = callingClass.substring(callingClass.lastIndexOf('.') + 1); callingClass = callingClass.substring(callingClass.lastIndexOf('$') + 1); caller = callingClass + "." + trace[i].getMethodName(); break; } } return String.format(Locale.US, "[%d] %s: %s", Thread.currentThread().getId(), caller, msg); } /** * A simple event log with records containing a name, thread ID, and timestamp. */ static class MarkerLog { public static final boolean ENABLED = VolleyLog.DEBUG; /** Minimum duration from first marker to last in an marker log to warrant logging. */ private static final long MIN_DURATION_FOR_LOGGING_MS = 0; private static class Marker { public final String name; public final long thread; public final long time; public Marker(String name, long thread, long time) { this.name = name; this.thread = thread; this.time = time; } } private final List<Marker> mMarkers = new ArrayList<Marker>(); private boolean mFinished = false; /** Adds a marker to this log with the specified name. */ public synchronized void add(String name, long threadId) { if (mFinished) { throw new IllegalStateException("Marker added to finished log"); } mMarkers.add(new Marker(name, threadId, SystemClock.elapsedRealtime())); } /** * Closes the log, dumping it to logcat if the time difference between * the first and last markers is greater than {@link #MIN_DURATION_FOR_LOGGING_MS}. * @param header Header string to print above the marker log. */ public synchronized void finish(String header) { mFinished = true; long duration = getTotalDuration(); if (duration <= MIN_DURATION_FOR_LOGGING_MS) { return; } long prevTime = mMarkers.get(0).time; d("(%-4d ms) %s", duration, header); for (Marker marker : mMarkers) { long thisTime = marker.time; d("(+%-4d) [%2d] %s", (thisTime - prevTime), marker.thread, marker.name); prevTime = thisTime; } } @Override protected void finalize() throws Throwable { // Catch requests that have been collected (and hence end-of-lifed) // but had no debugging output printed for them. if (!mFinished) { finish("Request on the loose"); e("Marker log finalized without finish() - uncaught exit point for request"); } } /** Returns the time difference between the first and last events in this log. */ private long getTotalDuration() { if (mMarkers.size() == 0) { return 0; } long first = mMarkers.get(0).time; long last = mMarkers.get(mMarkers.size() - 1).time; return last - first; } } }
gpl-2.0
qeef/orte
orte/java/src/org/ocera/orte/rtpseye/PubSubInfoTableModel.java
2364
/* * PubSubInfoTableModel.java * * Created on 10. květen 2005, 15:15 */ package org.ocera.orte.rtpseye; import javax.swing.table.AbstractTableModel; import javax.swing.table.*; import org.ocera.orte.types.AppInfo; import java.util.Vector; import org.ocera.orte.types.CommonPubSubInfo; /** * * @author luky */ public class PubSubInfoTableModel extends AbstractTableModel { /** Creates a new instance of PubSubInfoTableModel */ public PubSubInfoTableModel() { } public void setValueAtCurrentColumn(Object value, int row) { tableData[row][Constant.CURRENT_VALUE] = value; fireTableDataChanged(); return; } public void fillTableByPSInfo(CommonPubSubInfo info) { int row = 0; tableData = tableWithFirstColumn; // type setValueAtCurrentColumn(type,row++); // type name setValueAtCurrentColumn(info.getTypeName(),row++); // topic setValueAtCurrentColumn(info.getTopic(),row++); return; } public void clearTable() { tableData = emptyTable; fireTableDataChanged(); return; } public void setType(String type) { this.type = type; return; } public void setColumnIdentifiers(Vector setColumnIdentifiers) { /* TODO */ } public int getRowCount() { return tableData.length; } public int getColumnCount() { return tableData[0].length; } public Object getValueAt(int row, int column) { return tableData[row][column]; } public void setValueAt(Object value,int row, int column) { tableData[row][column] = value; fireTableDataChanged(); return; } // variables private String type; Object[][] tableData; Object[][] tableWithFirstColumn = new Object [][] { {"type", null}, {"type name", null}, {"topic", null}, {null, null} }; Object[][] emptyTable = new Object [][] { {null, null}, {null, null}, {null, null}, {null, null} }; }
gpl-2.0
bramalingam/bioformats
components/forks/poi/src/loci/poi/hpsf/TypeWriter.java
7809
/* * #%L * Fork of Apache Jakarta POI. * %% * Copyright (C) 2008 - 2016 Open Microscopy Environment: * - Board of Regents of the University of Wisconsin-Madison * - Glencoe Software, Inc. * - University of Dundee * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ /* ==================================================================== 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 loci.poi.hpsf; import java.io.IOException; import java.io.OutputStream; import loci.poi.util.LittleEndian; /** * <p>Class for writing little-endian data and more.</p> * * @author Rainer Klute <a * href="mailto:klute@rainer-klute.de">&lt;klute@rainer-klute.de&gt;</a> * @version $Id: TypeWriter.java 489730 2006-12-22 19:18:16Z bayard $ * @since 2003-02-20 */ public class TypeWriter { /** * <p>Writes a two-byte value (short) to an output stream.</p> * * @param out The stream to write to. * @param n The value to write. * @return The number of bytes that have been written. * @exception IOException if an I/O error occurs */ public static int writeToStream(final OutputStream out, final short n) throws IOException { final int length = LittleEndian.SHORT_SIZE; byte[] buffer = new byte[length]; LittleEndian.putShort(buffer, 0, n); // FIXME: unsigned out.write(buffer, 0, length); return length; } /** * <p>Writes a four-byte value to an output stream.</p> * * @param out The stream to write to. * @param n The value to write. * @exception IOException if an I/O error occurs * @return The number of bytes written to the output stream. */ public static int writeToStream(final OutputStream out, final int n) throws IOException { final int l = LittleEndian.INT_SIZE; final byte[] buffer = new byte[l]; LittleEndian.putInt(buffer, 0, n); out.write(buffer, 0, l); return l; } /** * <p>Writes a eight-byte value to an output stream.</p> * * @param out The stream to write to. * @param n The value to write. * @exception IOException if an I/O error occurs * @return The number of bytes written to the output stream. */ public static int writeToStream(final OutputStream out, final long n) throws IOException { final int l = LittleEndian.LONG_SIZE; final byte[] buffer = new byte[l]; LittleEndian.putLong(buffer, 0, n); out.write(buffer, 0, l); return l; } /** * <p>Writes an unsigned two-byte value to an output stream.</p> * * @param out The stream to write to * @param n The value to write * @exception IOException if an I/O error occurs */ public static void writeUShortToStream(final OutputStream out, final int n) throws IOException { int high = n & 0xFFFF0000; if (high != 0) throw new IllegalPropertySetDataException ("Value " + n + " cannot be represented by 2 bytes."); writeToStream(out, (short) n); } /** * <p>Writes an unsigned four-byte value to an output stream.</p> * * @param out The stream to write to. * @param n The value to write. * @return The number of bytes that have been written to the output stream. * @exception IOException if an I/O error occurs */ public static int writeUIntToStream(final OutputStream out, final long n) throws IOException { long high = n & 0xFFFFFFFF00000000L; if (high != 0 && high != 0xFFFFFFFF00000000L) throw new IllegalPropertySetDataException ("Value " + n + " cannot be represented by 4 bytes."); return writeToStream(out, (int) n); } /** * <p>Writes a 16-byte {@link ClassID} to an output stream.</p> * * @param out The stream to write to * @param n The value to write * @return The number of bytes written * @exception IOException if an I/O error occurs */ public static int writeToStream(final OutputStream out, final ClassID n) throws IOException { byte[] b = new byte[16]; n.write(b, 0); out.write(b, 0, b.length); return b.length; } /** * <p>Writes an array of {@link Property} instances to an output stream * according to the Horrible Property Stream Format.</p> * * @param out The stream to write to * @param properties The array to write to the stream * @param codepage The codepage number to use for writing strings * @exception IOException if an I/O error occurs * @throws UnsupportedVariantTypeException if HPSF does not support some * variant type. */ public static void writeToStream(final OutputStream out, final Property[] properties, final int codepage) throws IOException, UnsupportedVariantTypeException { /* If there are no properties don't write anything. */ if (properties == null) return; /* Write the property list. This is a list containing pairs of property * ID and offset into the stream. */ for (int i = 0; i < properties.length; i++) { final Property p = properties[i]; writeUIntToStream(out, p.getID()); writeUIntToStream(out, p.getSize()); } /* Write the properties themselves. */ for (int i = 0; i < properties.length; i++) { final Property p = properties[i]; long type = p.getType(); writeUIntToStream(out, type); VariantSupport.write(out, (int) type, p.getValue(), codepage); } } /** * <p>Writes a double value value to an output stream.</p> * * @param out The stream to write to. * @param n The value to write. * @exception IOException if an I/O error occurs * @return The number of bytes written to the output stream. */ public static int writeToStream(final OutputStream out, final double n) throws IOException { final int l = LittleEndian.DOUBLE_SIZE; final byte[] buffer = new byte[l]; LittleEndian.putDouble(buffer, 0, n); out.write(buffer, 0, l); return l; } }
gpl-2.0
veithen/rhq-websphere-plugin
websphere-apis/src/main/java/com/ibm/websphere/management/configservice/ConfigServiceHelper.java
1302
/* * RHQ WebSphere Plug-in * Copyright (C) 2012 Crossroads Bank for Social Security * All rights reserved. * * 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, and/or the GNU Lesser * General Public License, version 2.1, also 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 and the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU General Public License * and the GNU Lesser 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.ibm.websphere.management.configservice; import javax.management.AttributeList; import javax.management.AttributeNotFoundException; public class ConfigServiceHelper { public static Object getAttributeValue(AttributeList attrList, String name) throws AttributeNotFoundException { return null; } }
gpl-2.0
bugcy013/opennms-tmp-tools
features/system-report/src/main/java/org/opennms/systemreport/AbstractSystemReportPlugin.java
18200
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2010-2011 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2011 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.systemreport; import java.io.BufferedReader; import java.io.DataInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.PipedInputStream; import java.io.PipedOutputStream; import java.io.StringReader; import java.lang.management.ManagementFactory; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.charset.Charset; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import javax.management.MBeanServerConnection; import javax.management.ObjectName; import javax.management.remote.JMXConnector; import javax.management.remote.JMXConnectorFactory; import javax.management.remote.JMXServiceURL; import org.apache.commons.exec.CommandLine; import org.apache.commons.exec.DefaultExecutor; import org.apache.commons.exec.ExecuteWatchdog; import org.apache.commons.exec.PumpStreamHandler; import org.apache.commons.io.IOUtils; import org.apache.commons.lang.builder.CompareToBuilder; import org.opennms.core.utils.LogUtils; import org.opennms.systemreport.system.PsParser; import org.springframework.core.io.ByteArrayResource; import org.springframework.core.io.Resource; public abstract class AbstractSystemReportPlugin implements SystemReportPlugin { protected static final long MAX_PROCESS_WAIT = 10000; // milliseconds private MBeanServerConnection m_connection = null; public int getPriority() { return 99; } public TreeMap<String, Resource> getEntries() { throw new UnsupportedOperationException("You must override getEntries()!"); } public String toString() { return String.format("%s[%d]", getName(), getPriority()); } public int compareTo(final SystemReportPlugin o) { return new CompareToBuilder() .append(this.getPriority(), (o == null? Integer.MIN_VALUE:o.getPriority())) .append(this.getName(), (o == null? null:o.getName())) .toComparison(); } protected String slurp(final File lsb) { if (lsb != null && lsb.exists()) { FileInputStream stream = null; try { stream = new FileInputStream(lsb); FileChannel fc = stream.getChannel(); MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size()); return Charset.defaultCharset().decode(bb).toString().replace("[\\r\\n]*$", ""); } catch (final Exception e) { LogUtils.debugf(this, e, "Unable to read from file '%s'", lsb.getPath()); } finally { IOUtils.closeQuietly(stream); } } return null; } protected String slurpCommand(final String[] command) { Process p = null; InputStream is = null; InputStreamReader isr = null; BufferedReader br = null; StringBuffer sb = new StringBuffer(); try { p = Runtime.getRuntime().exec(command); is = p.getInputStream(); isr = new InputStreamReader(is); br = new BufferedReader(isr); while (br.ready()) { final String line = br.readLine(); if (line == null) break; sb.append(line); if (br.ready()) sb.append("\n"); } } catch (final Throwable e) { LogUtils.debugf(this, e, "Failure attempting to run command '%s'", Arrays.asList(command).toString()); } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(isr); IOUtils.closeQuietly(is); } return sb.toString(); } protected Map<String,String> splitMultilineString(final String regex, final String text) { final Map<String,String> map = new HashMap<String,String>(); if (text != null) { final StringReader sr = new StringReader(text); final BufferedReader br = new BufferedReader(sr); try { while (br.ready()) { final String line = br.readLine(); if (line == null) break; final String[] entry = line.split(regex, 2); if (entry.length == 2) { map.put(entry[0], entry[1]); } } } catch (final IOException e) { LogUtils.debugf(this, e, "an error occurred parsing the text"); } finally { IOUtils.closeQuietly(br); IOUtils.closeQuietly(sr); } } return map; } protected Resource getResourceFromProperty(final String propertyName) { return getResource(System.getProperty(propertyName)); } protected Resource getResource(final String text) { if (text == null) return new ByteArrayResource(new byte[0]); return new ByteArrayResource(text.getBytes()); } protected String findBinary(final String name) { List<String> pathEntries = new ArrayList<String>(); final String path = System.getenv().get("PATH"); if (path != null) { for (final String p : path.split(File.pathSeparator)) { pathEntries.add(p); } // make sure sbin is in the path, too, just in case pathEntries.add("/sbin"); pathEntries.add("/usr/sbin"); pathEntries.add("/usr/local/sbin"); } for (final String dir : pathEntries) { File file = new File(dir, name); if (file.exists()) { return file.getPath(); } file = new File(dir, name + ".exe"); if (file.exists()) { return file.getPath(); } } return null; } protected String slurpOutput(CommandLine command, boolean ignoreExitCode) { LogUtils.debugf(this, "running: %s", command.toString()); final Map<String,String> environment = new HashMap<String,String>(System.getenv()); environment.put("COLUMNS", "2000"); DataInputStream input = null; PipedInputStream pis = null; OutputSuckingParser parser = null; String topOutput = null; final DefaultExecutor executor = new DefaultExecutor(); final PipedOutputStream output = new PipedOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(output, output); executor.setWatchdog(new ExecuteWatchdog(MAX_PROCESS_WAIT)); executor.setStreamHandler(streamHandler); try { LogUtils.tracef(this, "executing '%s'", command.toString()); pis = new PipedInputStream(output); input = new DataInputStream(pis); parser = new OutputSuckingParser(input); parser.start(); int exitValue = executor.execute(command, environment); IOUtils.closeQuietly(output); parser.join(MAX_PROCESS_WAIT); if (!ignoreExitCode && exitValue != 0) { LogUtils.debugf(this, "error running '%s': exit value was %d", command.toString(), exitValue); } else { topOutput = parser.getOutput(); } LogUtils.tracef(this, "finished '%s'", command.toString()); } catch (final Exception e) { LogUtils.debugf(this, e, "Failed to run '%s'", command.toString()); } finally { IOUtils.closeQuietly(output); IOUtils.closeQuietly(input); IOUtils.closeQuietly(pis); } return topOutput; } protected File createTemporaryFileFromString(final String text) { File tempFile = null; FileWriter fw = null; try { tempFile = File.createTempFile("topReportPlugin", null); tempFile.deleteOnExit(); fw = new FileWriter(tempFile); fw.write(text); fw.close(); } catch (final Exception e) { LogUtils.debugf(this, e, "Unable to write to temporary file."); } finally { IOUtils.closeQuietly(fw); } return tempFile; } protected Set<Integer> getOpenNMSProcesses() { LogUtils.debugf(this, "getOpenNMSProcesses()"); final Set<Integer> processes = new HashSet<Integer>(); final String jps = findBinary("jps"); LogUtils.debugf(this, "jps = %s", jps); DataInputStream input = null; PsParser parser = null; PipedInputStream pis = null; PipedOutputStream output = new PipedOutputStream(); DefaultExecutor executor = new DefaultExecutor(); executor.setWatchdog(new ExecuteWatchdog(5000)); if (jps != null) { CommandLine command = CommandLine.parse(jps + " -v"); PumpStreamHandler streamHandler = new PumpStreamHandler(output, System.err); try { LogUtils.tracef(this, "executing '%s'", command.toString()); pis = new PipedInputStream(output); input = new DataInputStream(pis); parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0); parser.start(); executor.setStreamHandler(streamHandler); int exitValue = executor.execute(command); IOUtils.closeQuietly(output); parser.join(); processes.addAll(parser.getProcesses()); LogUtils.tracef(this, "finished '%s'", command.toString()); if (exitValue != 0) { LogUtils.debugf(this, "error running '%s': exit value was %d", command.toString(), exitValue); } } catch (final Exception e) { LogUtils.debugf(this, e, "Failed to run '%s'", command.toString()); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(pis); IOUtils.closeQuietly(output); } } LogUtils.tracef(this, "looking for ps"); final String ps = findBinary("ps"); if (ps != null) { // try Linux/Mac style CommandLine command = CommandLine.parse(ps + " aww -o pid -o args"); output = new PipedOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(output, System.err); try { LogUtils.debugf(this, "executing '%s'", command.toString()); pis = new PipedInputStream(output); input = new DataInputStream(pis); parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0); parser.start(); executor.setStreamHandler(streamHandler); int exitValue = executor.execute(command); IOUtils.closeQuietly(output); parser.join(MAX_PROCESS_WAIT); processes.addAll(parser.getProcesses()); LogUtils.tracef(this, "finished '%s'", command.toString()); if (exitValue != 0) { LogUtils.debugf(this, "error running '%s': exit value was %d", command.toString(), exitValue); } } catch (final Exception e) { LogUtils.debugf(this, e, "error running '%s'", command.toString()); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(pis); IOUtils.closeQuietly(output); } if (processes.size() == 0) { // try Solaris style command = CommandLine.parse(ps + " -ea -o pid -o args"); output = new PipedOutputStream(); streamHandler = new PumpStreamHandler(output, System.err); try { LogUtils.debugf(this, "executing '%s'", command.toString()); pis = new PipedInputStream(output); input = new DataInputStream(pis); parser = new PsParser(input, "opennms_bootstrap.jar", "status", 0); parser.start(); executor.setStreamHandler(streamHandler); int exitValue = executor.execute(command); IOUtils.closeQuietly(output); parser.join(MAX_PROCESS_WAIT); processes.addAll(parser.getProcesses()); LogUtils.tracef(this, "finished '%s'", command.toString()); if (exitValue != 0) { LogUtils.debugf(this, "error running '%s': exit value was %d", command.toString(), exitValue); } } catch (final Exception e) { LogUtils.debugf(this, e, "error running '%s'", command.toString()); } finally { IOUtils.closeQuietly(input); IOUtils.closeQuietly(pis); IOUtils.closeQuietly(output); } } } if (processes.size() == 0) { LogUtils.warnf(this, "Unable to find any OpenNMS processes."); } return processes; } private MBeanServerConnection getConnection() { final List<Integer> ports = new ArrayList<Integer>(); Integer p = Integer.getInteger("com.sun.management.jmxremote.port"); if (p != null) ports.add(p); ports.add(18980); ports.add(1099); for (final Integer port : ports) { LogUtils.tracef(this, "Trying JMX at localhost:%d/jmxrmi", port); try { JMXServiceURL url = new JMXServiceURL(String.format("service:jmx:rmi:///jndi/rmi://localhost:%d/jmxrmi", port)); JMXConnector jmxc = JMXConnectorFactory.connect(url, null); return jmxc.getMBeanServerConnection(); } catch (final Exception e) { LogUtils.debugf(this, e, "Unable to get JMX connection to OpenNMS on port %d.", port); } } return null; } protected void addGetters(final Object o, final Map<String,Resource> map) { if (o != null) { for (Method method : o.getClass().getDeclaredMethods()) { method.setAccessible(true); if (method.getName().startsWith("get") && Modifier.isPublic(method.getModifiers())) { Object value; try { value = method.invoke(o); } catch (Throwable e) { value = e; } final String key = method.getName().replaceFirst("^get", "").replaceAll("([A-Z])", " $1").replaceFirst("^ ", "").replaceAll("\\bVm\\b", "VM"); map.put(key, getResource(value.toString())); } } } } protected <T> List<T> getBeans(final String mxBeanName, final Class<T> clazz) { initializeConnection(); List<T> beans = new ArrayList<T>(); if (m_connection == null) return beans; try { ObjectName o = new ObjectName(mxBeanName + ",*"); for (final ObjectName name : (Set<ObjectName>)m_connection.queryNames(o, null)) { beans.add(getBean(name.getCanonicalName(), clazz)); } } catch (final Exception e) { LogUtils.warnf(this, e, "Unable to get beans of type '%s'", mxBeanName); } return beans; } protected <T> T getBean(final String mxBeanName, final Class<T> clazz) { final List<Class<T>> classes = new ArrayList<Class<T>>(); classes.add(clazz); return getBean(mxBeanName, classes); } protected <T> T getBean(final String mxBeanName, final List<? extends Class<T>> classes) { initializeConnection(); if (m_connection == null || mxBeanName == null || classes == null || classes.size() == 0) { return null; } T bean = null; for (final Class<T> c : classes) { try { bean = ManagementFactory.newPlatformMXBeanProxy(m_connection, mxBeanName, c); break; } catch (final Exception e) { LogUtils.infof(this, e, "Unable to get management bean %s for class %s", mxBeanName, c.getName()); } } return bean; } private void initializeConnection() { if (m_connection == null) { m_connection = getConnection(); } } }
gpl-2.0
IDMNYU/Creative-Coding-UG-Fall-2014
Class25/dronestuff/odc-master/platforms/ardrone/src/main/java/com/codeminders/ardrone/data/decoder/ardrone20/ARDrone20VideoDataDecoder.java
9820
package com.codeminders.ardrone.data.decoder.ardrone20; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.Socket; import com.codeminders.ardrone.ARDrone; import com.codeminders.ardrone.VideoDataDecoder; import com.codeminders.ardrone.data.ARDroneDataReader; import com.xuggle.xuggler.Global; import com.xuggle.xuggler.ICodec; import com.xuggle.xuggler.IContainer; import com.xuggle.xuggler.IPacket; import com.xuggle.xuggler.IPixelFormat; import com.xuggle.xuggler.IStream; import com.xuggle.xuggler.IStreamCoder; import com.xuggle.xuggler.IVideoPicture; import com.xuggle.xuggler.IVideoResampler; import com.xuggle.xuggler.Utils; import com.xuggle.xuggler.video.IConverter; import com.xuggle.xuggler.video.ConverterFactory; /* Modified 2013, Tim Wood retrofit to JavaDrone based on: ARDroneForP5 https://github.com/shigeodayo/ARDroneForP5 Copyright (C) 2013, Shigeo YOSHIDA. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ public class ARDrone20VideoDataDecoder extends VideoDataDecoder { private Logger log = Logger.getLogger(this.getClass().getName()); private boolean done = false; public ARDrone20VideoDataDecoder(ARDrone drone) { super(drone); setName("ARDrone 2.0 Video decoding thread"); } @Override public void run() { // Create a Xuggler container object IContainer container = IContainer.make(); IConverter converter = null; // Open up the container try { if (container.open(getDataReader().getDataStream(), null) < 0) throw new IllegalArgumentException("could not open inpustream"); } catch (Exception e1) { e1.printStackTrace(); } // query how many streams the call to open found int numStreams = container.getNumStreams(); // and iterate through the streams to find the first video stream int videoStreamId = -1; IStreamCoder videoCoder = null; for (int i = 0; i < numStreams; i++) { // Find the stream object IStream stream = container.getStream(i); // Get the pre-configured decoder that can decode this stream; IStreamCoder coder = stream.getStreamCoder(); if (coder.getCodecType() == ICodec.Type.CODEC_TYPE_VIDEO) { videoStreamId = i; videoCoder = coder; break; } } if (videoStreamId == -1) throw new RuntimeException("could not find video stream"); /* * Now we have found the video stream in this file. Let's open up our * decoder so it can do work. */ if (videoCoder.open() < 0) throw new RuntimeException( "could not open video decoder for container"); // causes additional latency!!!??? // videoCoder.setProperty("vprofile", "baseline"); // videoCoder.setProperty("tune", "zerolatency"); IVideoResampler resampler = null; if (videoCoder.getPixelType() != IPixelFormat.Type.BGR24) { // if this stream is not in BGR24, we're going to need to // convert it. The VideoResampler does that for us. resampler = IVideoResampler.make(videoCoder.getWidth(), videoCoder.getHeight(), IPixelFormat.Type.BGR24, videoCoder.getWidth(), videoCoder.getHeight(), videoCoder.getPixelType()); if (resampler == null) throw new RuntimeException( "could not create color space resampler."); } /* * Now, we start walking through the container looking at each packet. */ IPacket packet = IPacket.make(); long firstTimestampInStream = Global.NO_PTS; long systemClockStartTime = 0; try{ while (container.readNextPacket(packet) >= 0) { /* * Now we have a packet, let's see if it belongs to our video stream */ if (packet.getStreamIndex() == videoStreamId) { /* * We allocate a new picture to get the data out of Xuggler */ IVideoPicture picture = IVideoPicture.make( videoCoder.getPixelType(), videoCoder.getWidth(), videoCoder.getHeight()); try { int offset = 0; while (offset < packet.getSize()) { // System.out.println("VideoManager.decode(): decode one image"); /* * Now, we decode the video, checking for any errors. */ int bytesDecoded = videoCoder.decodeVideo(picture, packet, offset); if (bytesDecoded < 0) throw new RuntimeException( "got error decoding video"); offset += bytesDecoded; /* * Some decoders will consume data in a packet, but will * not be able to construct a full video picture yet. * Therefore you should always check if you got a * complete picture from the decoder */ if (picture.isComplete()) { // System.out.println("VideoManager.decode(): image complete"); IVideoPicture newPic = picture; /* * If the resampler is not null, that means we * didn't get the video in BGR24 format and need to * convert it into BGR24 format. */ if (resampler != null) { // we must resample newPic = IVideoPicture .make(resampler.getOutputPixelFormat(), picture.getWidth(), picture.getHeight()); if (resampler.resample(newPic, picture) < 0) throw new RuntimeException( "could not resample video"); } if (newPic.getPixelType() != IPixelFormat.Type.BGR24) throw new RuntimeException( "could not decode video as BGR 24 bit data"); /** * We could just display the images as quickly as we * decode them, but it turns out we can decode a lot * faster than you think. * * So instead, the following code does a poor-man's * version of trying to match up the frame-rate * requested for each IVideoPicture with the system * clock time on your computer. * * Remember that all Xuggler IAudioSamples and * IVideoPicture objects always give timestamps in * Microseconds, relative to the first decoded item. * If instead you used the packet timestamps, they * can be in different units depending on your * IContainer, and IStream and things can get hairy * quickly. */ if (firstTimestampInStream == Global.NO_PTS) { // This is our first time through firstTimestampInStream = picture.getTimeStamp(); // get the starting clock time so we can hold up // frames until the right time. systemClockStartTime = System .currentTimeMillis(); } else { long systemClockCurrentTime = System .currentTimeMillis(); long millisecondsClockTimeSinceStartofVideo = systemClockCurrentTime - systemClockStartTime; // compute how long for this frame since the // first frame in the stream. // remember that IVideoPicture and IAudioSamples // timestamps are always in MICROSECONDS, // so we divide by 1000 to get milliseconds. long millisecondsStreamTimeSinceStartOfVideo = (picture .getTimeStamp() - firstTimestampInStream) / 1000; final long millisecondsTolerance = 50; // and we // give // ourselfs // 50 ms // of // tolerance final long millisecondsToSleep = (millisecondsStreamTimeSinceStartOfVideo - (millisecondsClockTimeSinceStartofVideo + millisecondsTolerance)); if (millisecondsToSleep > 0) { try { Thread.sleep(millisecondsToSleep); } catch (InterruptedException e) { // we might get this when the user // closes the dialog box, so just return // from the method. return; } } } // And finally, convert the BGR24 to an Java // buffered image if(converter == null) converter = ConverterFactory.createConverter(ConverterFactory.XUGGLER_BGR_24, newPic); BufferedImage bi = converter.toImage(newPic); int[] buf = bi.getRGB(0, 0, bi.getWidth() ,bi.getHeight(), null, 0, bi.getWidth()); notifyDroneWithDecodedFrame(0, 0, bi.getWidth() ,bi.getHeight(), buf, 0, bi.getWidth()); } } // end of while } catch (Exception exc) { System.out.println(exc); // exc.printStackTrace(); } } else { /* * This packet isn't part of our video stream, so we just * silently drop it. */ do { } while (false); } }} catch( Exception e){ try { getDataReader().reconnect(); } catch (IOException e1) { log.log(Level.SEVERE, " Error reconnecting video data reader", e); } } /* * Technically since we're exiting anyway, these will be cleaned up by * the garbage collector... but because we're nice people and want to be * invited places for Christmas, we're going to show how to clean up. */ if (videoCoder != null) { videoCoder.close(); videoCoder = null; } if (container != null) { container.close(); container = null; } } @Override public void finish() { done = true; } }
gpl-2.0
khmMinecraftProjects/HoloAPI
src/main/java/com/dsh105/holoapi/command/sub/MoveCommand.java
2450
/* * This file is part of HoloAPI. * * HoloAPI 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. * * HoloAPI 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 HoloAPI. If not, see <http://www.gnu.org/licenses/>. */ package com.dsh105.holoapi.command.sub; import com.dsh105.command.Command; import com.dsh105.command.CommandEvent; import com.dsh105.command.CommandListener; import com.dsh105.holoapi.HoloAPI; import com.dsh105.holoapi.api.Hologram; import com.dsh105.holoapi.config.Lang; import com.dsh105.holoapi.util.MiscUtil; import org.bukkit.Location; import org.bukkit.entity.Player; public class MoveCommand implements CommandListener { @Command( command = "move <id>", description = "Move a hologram to your current position", permission = "holoapi.holo.move" ) public boolean command(CommandEvent<Player> event) { final Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } hologram.move(event.sender().getLocation()); event.respond(Lang.HOLOGRAM_MOVED.getValue()); return true; } @Command( command = "move <id> <world> <x> <y> <z>", description = "Move a hologram to your current position", permission = "holoapi.holo.move" ) public boolean moveLocation(CommandEvent<Player> event) { Hologram hologram = HoloAPI.getManager().getHologram(event.variable("id")); if (hologram == null) { event.respond(Lang.HOLOGRAM_NOT_FOUND.getValue("id", event.variable("id"))); return true; } Location location = MiscUtil.getLocation(event); if (location == null) { return true; } hologram.move(location); event.respond(Lang.HOLOGRAM_MOVED.getValue()); return true; } }
gpl-3.0
jukiewiczm/renjin
core/src/main/java/org/renjin/invoke/codegen/scalars/LogicalType.java
685
package org.renjin.invoke.codegen.scalars; import org.renjin.sexp.Logical; import org.renjin.sexp.LogicalArrayVector; import org.renjin.sexp.LogicalVector; public class LogicalType extends ScalarType { @Override public Class getScalarType() { return Logical.class; } @Override public String getConversionMethod() { throw new UnsupportedOperationException(); } @Override public String getAccessorMethod() { return "getElementAsLogical"; } @Override public Class getVectorType() { return LogicalVector.class; } @Override public Class<LogicalArrayVector.Builder> getBuilderClass() { return LogicalArrayVector.Builder.class; } }
gpl-3.0
jtux270/translate
ovirt/backend/manager/modules/restapi/interface/definition/src/main/java/org/ovirt/engine/api/resource/aaa/GroupsResource.java
1853
/* * Copyright (c) 2010 Red Hat, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ovirt.engine.api.resource.aaa; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.POST; import javax.ws.rs.Produces; import javax.ws.rs.core.Response; import org.jboss.resteasy.annotations.providers.jaxb.Formatted; import org.ovirt.engine.api.model.Group; import org.ovirt.engine.api.model.Groups; import org.ovirt.engine.api.resource.ApiMediaType; @Path("/groups") @Produces({ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML}) public interface GroupsResource { @GET @Formatted public Groups list(); @POST @Formatted @Consumes({ApiMediaType.APPLICATION_XML, ApiMediaType.APPLICATION_JSON, ApiMediaType.APPLICATION_X_YAML}) public Response add(Group Group); @DELETE @Path("{id}") public Response remove(@PathParam("id") String id); /** * Sub-resource locator method, returns individual GroupResource on which * the remainder of the URI is dispatched. * * @param id the Group ID * @return matching subresource if found */ @Path("{id}") public GroupResource getGroupSubResource(@PathParam("id") String id); }
gpl-3.0
mbshopM/openconcerto
Modules/Module EBICS/src/org/apache/xml/security/utils/CachedXPathAPIHolder.java
2135
/** * 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.xml.security.utils; import org.apache.xpath.CachedXPathAPI; import org.w3c.dom.Document; /** * @author Raul Benito */ public class CachedXPathAPIHolder { static ThreadLocal<CachedXPathAPI> local = new ThreadLocal<CachedXPathAPI>(); static ThreadLocal<Document> localDoc = new ThreadLocal<Document>(); /** * Sets the doc for the xpath transformation. Resets the cache if needed * @param doc */ public static void setDoc(Document doc) { if (localDoc.get() != doc) { CachedXPathAPI cx = local.get(); if (cx == null) { cx = new CachedXPathAPI(); local.set(cx); localDoc.set(doc); return; } //Different docs reset. cx.getXPathContext().reset(); localDoc.set(doc); } } /** * @return the cachexpathapi for this thread */ public static CachedXPathAPI getCachedXPathAPI() { CachedXPathAPI cx = local.get(); if (cx == null) { cx = new CachedXPathAPI(); local.set(cx); localDoc.set(null); } return cx; } }
gpl-3.0
dhootha/osmtracker-android
app/src/main/java/me/guillaumin/android/osmtracker/activity/TrackDetail.java
10368
package me.guillaumin.android.osmtracker.activity; import java.sql.Date; import java.text.DateFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import me.guillaumin.android.osmtracker.OSMTracker; import me.guillaumin.android.osmtracker.R; import me.guillaumin.android.osmtracker.db.TrackContentProvider; import me.guillaumin.android.osmtracker.db.TrackContentProvider.Schema; import me.guillaumin.android.osmtracker.db.model.Track; import me.guillaumin.android.osmtracker.gpx.ExportToStorageTask; import me.guillaumin.android.osmtracker.util.MercatorProjection; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Intent; import android.database.Cursor; import android.graphics.Paint; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.widget.SimpleAdapter; import android.widget.TextView; import android.widget.Toast; /** * Display details about one track. Allow naming the track. * The track ID is passed into the Bundle via {@link Schema#COL_TRACK_ID}. * * @author Jeremy D Monin <jdmonin@nand.net> * */ public class TrackDetail extends TrackDetailEditor implements AdapterView.OnItemClickListener { @SuppressWarnings("unused") private static final String TAG = TrackDetail.class.getSimpleName(); /** * Key to bind the "key" of each item using SimpleListAdapter */ private static final String ITEM_KEY = "key"; /** * Key to bind the "value" of each item using SimpleListAdapter */ private static final String ITEM_VALUE = "value"; /** * Position of the waypoints counts in the list */ private static final int WP_COUNT_INDEX = 0; /** Does this track have any waypoints? If true, underline Waypoint count in the list. */ private boolean trackHasWaypoints = false; /** * List with track info */ private ListView lv; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState, R.layout.trackdetail, getIntent().getExtras().getLong(Schema.COL_TRACK_ID)); lv = (ListView) findViewById(R.id.trackdetail_list); final Button btnOk = (Button) findViewById(R.id.trackdetail_btn_ok); btnOk.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { save(); finish(); } }); final Button btnCancel = (Button) findViewById(R.id.trackdetail_btn_cancel); btnCancel.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // Just close the dialog finish(); } }); // Do not show soft keyboard by default getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN); // further work is done in onResume. } @Override protected void onResume() { super.onResume(); // Query the track values ContentResolver cr = getContentResolver(); Cursor cursor = cr.query( ContentUris.withAppendedId(TrackContentProvider.CONTENT_URI_TRACK, trackId), null, null, null, null); if (! cursor.moveToFirst()) { // This shouldn't occur, it's here just in case. // So, don't make each language translate/localize it. Toast.makeText(this, "Track ID not found.", Toast.LENGTH_SHORT).show(); cursor.close(); finish(); return; // <--- Early return --- } // Bind WP count, TP count, start date, etc. // Fill name-field only if empty (in case changed by user/restored by onRestoreInstanceState) Track t = Track.build(trackId, cursor, cr, true); bindTrack(t); String from[] = new String[]{ITEM_KEY, ITEM_VALUE}; int[] to = new int[] {R.id.trackdetail_item_key, R.id.trackdetail_item_value}; // Waypoint count final int wpCount = t.getWpCount(); trackHasWaypoints = (wpCount > 0); List<HashMap<String, String>> data = new ArrayList<HashMap<String, String>>(); HashMap<String, String> map = new HashMap<String, String>(); map.put(ITEM_KEY, getResources().getString(R.string.trackmgr_waypoints_count)); map.put(ITEM_VALUE, Integer.toString(wpCount)); data.add(WP_COUNT_INDEX, map); // Trackpoint count map = new HashMap<String, String>(); map.put(ITEM_KEY, getResources().getString(R.string.trackmgr_trackpoints_count)); map.put(ITEM_VALUE, Integer.toString(t.getTpCount())); data.add(map); // Start date map = new HashMap<String, String>(); map.put(ITEM_KEY, getResources().getString(R.string.trackdetail_startdate)); map.put(ITEM_VALUE, t.getStartDateAsString()); data.add(map); // End date map = new HashMap<String, String>(); map.put(ITEM_KEY, getResources().getString(R.string.trackdetail_enddate)); map.put(ITEM_VALUE, t.getEndDateAsString()); data.add(map); // Start point map = new HashMap<String, String>(); map.put(ITEM_KEY, getResources().getString(R.string.trackdetail_startloc)); map.put(ITEM_VALUE, MercatorProjection.formatDegreesAsDMS(t.getStartLat(), true) + " " + MercatorProjection.formatDegreesAsDMS(t.getStartLong(), false)); data.add(map); // End point map = new HashMap<String, String>(); map.put(ITEM_KEY, getResources().getString(R.string.trackdetail_endloc)); map.put(ITEM_VALUE, MercatorProjection.formatDegreesAsDMS(t.getEndLat(), true) + " " + MercatorProjection.formatDegreesAsDMS(t.getEndLong(), false)); data.add(map); // OSM Upload date map = new HashMap<String, String>(); map.put(ITEM_KEY, getResources().getString(R.string.trackdetail_osm_upload_date)); if (cursor.isNull(cursor.getColumnIndex(Schema.COL_OSM_UPLOAD_DATE))) { map.put(ITEM_VALUE, getResources().getString(R.string.trackdetail_osm_upload_notyet)); } else { map.put(ITEM_VALUE, DateFormat.getDateTimeInstance().format(new Date(cursor.getLong(cursor.getColumnIndex(Schema.COL_EXPORT_DATE))))); } data.add(map); // Exported date. Should be the last item in order to be refreshed // if the user exports the track map = new HashMap<String, String>(); map.put(ITEM_KEY, getResources().getString(R.string.trackdetail_exportdate)); if (cursor.isNull(cursor.getColumnIndex(Schema.COL_EXPORT_DATE))) { map.put(ITEM_VALUE, getResources().getString(R.string.trackdetail_export_notyet)); } else { map.put(ITEM_VALUE, (DateFormat.getDateTimeInstance().format(new Date(cursor.getLong(cursor.getColumnIndex(Schema.COL_EXPORT_DATE)))))); } data.add(map); cursor.close(); TrackDetailSimpleAdapter adapter = new TrackDetailSimpleAdapter(data, from, to); lv.setAdapter(adapter); // Click on Waypoint count to see the track's WaypointList lv.setOnItemClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.trackdetail_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { Intent i; switch(item.getItemId()) { case R.id.trackdetail_menu_save: save(); finish(); break; case R.id.trackdetail_menu_cancel: finish(); break; case R.id.trackdetail_menu_display: boolean useOpenStreetMapBackground = PreferenceManager.getDefaultSharedPreferences(this).getBoolean( OSMTracker.Preferences.KEY_UI_DISPLAYTRACK_OSM, OSMTracker.Preferences.VAL_UI_DISPLAYTRACK_OSM); if (useOpenStreetMapBackground) { i = new Intent(this, DisplayTrackMap.class); } else { i = new Intent(this, DisplayTrack.class); } i.putExtra(Schema.COL_TRACK_ID, trackId); startActivity(i); break; case R.id.trackdetail_menu_export: new ExportToStorageTask(this, trackId).execute(); // Pick last list item (Exported date) and update it SimpleAdapter adapter = ((SimpleAdapter) lv.getAdapter()); @SuppressWarnings("unchecked") Map<String, String> data = (Map<String, String>) adapter.getItem(adapter.getCount()-1); data.put(ITEM_VALUE, DateFormat.getDateTimeInstance().format(new Date(System.currentTimeMillis()))); adapter.notifyDataSetChanged(); break; case R.id.trackdetail_menu_osm_upload: i = new Intent(this, OpenStreetMapUpload.class); i.putExtra(Schema.COL_TRACK_ID, trackId); startActivity(i); break; } return super.onOptionsItemSelected(item); } /** * Handle clicks on list items; for Waypoint count, show this track's list of waypoints ({@link WaypointList}). * Ignore all other clicks. * @param position Item number in the list; this method assumes Waypoint count is position 0 (first item). */ public void onItemClick(AdapterView<?> parent, View view, final int position, final long rowid) { if (position != WP_COUNT_INDEX) { return; } Intent i = new Intent(this, WaypointList.class); i.putExtra(Schema.COL_TRACK_ID, trackId); startActivity(i); } /** * Extend SimpleAdapter so we can underline the clickable Waypoint count. * Always uses <tt>R.layout.trackdetail_item</tt> as its list item resource. */ private class TrackDetailSimpleAdapter extends SimpleAdapter { public TrackDetailSimpleAdapter (List<? extends Map<String, ?>> data, String[] from, int[] to) { super(TrackDetail.this, data, R.layout.trackdetail_item, from, to); } /** * Get the layout for this list item. (<tt>trackdetail_item.xml</tt>) * @param position Item number in the list */ public View getView(final int position, View convertView, ViewGroup parent) { View v = super.getView(position, convertView, parent); if (! (v instanceof ViewGroup)) return v; // should not happen; v is trackdetail_item, a LinearLayout final boolean wantsUnderline = ((position == WP_COUNT_INDEX) && trackHasWaypoints); View vi = ((ViewGroup) v).findViewById(R.id.trackdetail_item_key); if ((vi != null) && (vi instanceof TextView)) { final int flags = ((TextView) vi).getPaintFlags(); if (wantsUnderline) ((TextView) vi).setPaintFlags(flags | Paint.UNDERLINE_TEXT_FLAG); else ((TextView) vi).setPaintFlags(flags & ~Paint.UNDERLINE_TEXT_FLAG); } return v; } } // inner class TrackDetailSimpleAdapter } // public class TrackDetail
gpl-3.0
hassanNS/oStoryBook-410-Project
src/shef/ui/text/actions/SelectAllAction.java
981
package shef.ui.text.actions; import java.awt.event.ActionEvent; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import javax.swing.Action; import javax.swing.JEditorPane; import javax.swing.KeyStroke; import storybook.toolkit.I18N; /** * @author Bob Select all action */ public class SelectAllAction extends BasicEditAction { /** * */ private static final long serialVersionUID = 1L; public SelectAllAction() { super(I18N.getMsg("shef.select_all")); putValue(MNEMONIC_KEY, (int) I18N.getMnemonic("shef.select_all")); putValue(ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_MASK)); putValue(Action.SHORT_DESCRIPTION, getValue(Action.NAME)); } /* (non-Javadoc) * @see shef.ui.text.actions.BasicEditAction#doEdit(java.awt.event.ActionEvent, javax.swing.JEditorPane) */ @Override protected void doEdit(ActionEvent e, JEditorPane editor) { editor.selectAll(); } }
gpl-3.0
marcuseng/simcity
src/mainCity/market/test/DeliveryManTest.java
29636
package mainCity.market.test; import java.util.Map; import java.util.TreeMap; import role.market.MarketDeliveryManRole; import role.market.MarketDeliveryManRole.AgentState; import role.market.MarketDeliveryManRole.DeliveryEvent; import role.market.MarketDeliveryManRole.DeliveryState; import mainCity.PersonAgent; import mainCity.PersonAgent.ActionType; import mainCity.market.test.mock.*; import mainCity.restaurants.EllenRestaurant.test.mock.MockCashier; import mainCity.restaurants.EllenRestaurant.test.mock.MockCook; import junit.framework.TestCase; public class DeliveryManTest extends TestCase { MarketDeliveryManRole deliveryMan; MockDeliveryManGui gui; MockEmployee employee; MockCashier ellenCashier; //from ellen's restaurant MockCook ellenCook; //from ellen's restaurant MockOtherCashier otherCashier; //to simulate cashier from marcus' restaurant MockOtherCook otherCook; //to simulate cook from marcus' restaurant public void setUp() throws Exception{ super.setUp(); PersonAgent d = new PersonAgent("Delivery man"); deliveryMan = new MarketDeliveryManRole(d, d.getName()); d.addRole(ActionType.work, deliveryMan); gui = new MockDeliveryManGui("MockDeliveryGui"); deliveryMan.setGui(gui); employee = new MockEmployee("MockEmployee"); ellenCashier = new MockCashier("MockCashier"); ellenCook = new MockCook("MockCook"); otherCashier = new MockOtherCashier("MarcusCashier"); otherCook = new MockOtherCook("MarcusCook"); } //=============================== NEXT TEST ========================================================================= public void testOneNormalBusinessScenario(){ gui.deliveryMan = deliveryMan; //preconditions assertEquals("Delivery man should have 0 bills in it. It doesn't.", deliveryMan.getBills().size(), 0); assertEquals("Delivery man should have 0 available money but does not.", deliveryMan.getCash(), 0.0); assertTrue("Delivery man should be in state == doingNothing. He isn't.", deliveryMan.getState() == AgentState.doingNothing); Map<String, Integer>inventory = new TreeMap<String, Integer>(); inventory.put("steak", 1); //cost of steak = 15.99 inventory.put("soup", 2); //cost of soup = 5.00 //step 1 deliveryMan.msgHereIsOrderForDelivery("mockEllenRestaurant", inventory, 25.99); //postconditions 1/preconditions 2 assertEquals("MockCashier should have an empty event log before the Cashier's scheduler is called. Instead, the MockEmployee's event log reads: " + ellenCashier.log.toString(), 0, ellenCashier.log.size()); assertEquals("MockCook should have an empty event log before the Cashier's scheduler is called. Instead, the MockCook's event log reads: " + ellenCook.log.toString(), 0, ellenCook.log.size()); assertEquals("Cashier should have 1 bill but does not.", deliveryMan.getBills().size(), 1); assertTrue("Delivery man should contain a check with state == newBill. It doesn't.", deliveryMan.bills.get(0).getState() == DeliveryState.newBill); assertTrue("Delivery man should contain a check with event == deliveryRequested. It doesn't.", deliveryMan.bills.get(0).getEvent() == DeliveryEvent.deliveryRequested); assertTrue("Delivery man should contain a check with a null cook. It doesn't.", deliveryMan.bills.get(0).getCook() == null); assertTrue("Delivery man should contain a check with a null cashier. It doesn't.", deliveryMan.bills.get(0).getCashier() == null); assertTrue("Delivery man should contain a check with the right restaurant in it. It doesn't.", deliveryMan.bills.get(0).getRestaurant().equalsIgnoreCase("mockEllenRestaurant")); assertTrue("Delivery man should contain a check with the correct amountCharged. It doesn't.", deliveryMan.bills.get(0).getAmountCharged() == 25.99); //step 2 - we have to manually set the cashier and cook beforehand // (the ContactList as is won't accept interfaces, so we can't run through the action normally // - see hack in Market1DeliveryManRole) deliveryMan.bills.get(0).setCashier(ellenCashier); deliveryMan.bills.get(0).setCook(ellenCook); deliveryMan.msgAtDestination(); assertTrue("Delivery man's scheduler should have returned true (needs to react), but didn't.", deliveryMan.pickAndExecuteAnAction()); //postconditions 2/preconditions 3 assertTrue("MockCook should have logged \"Received msgHereIsYourOrder\" but didn't. His log reads instead: " + ellenCook.log.getLastLoggedEvent().toString(), ellenCook.log.containsString("Received msgHereIsYourOrder from delivery man.")); assertTrue("MockCashier should have logged \"Received msgHereIsMarketBill\" but didn't. His log reads instead: " + ellenCashier.log.getLastLoggedEvent().toString(), ellenCashier.log.containsString("Received msgHereIsMarketBill from Delivery man for $25.99.")); assertTrue("Delivery man should contain a check with state == waitingForPayment. It doesn't.", deliveryMan.bills.get(0).getState() == DeliveryState.waitingForPayment); assertTrue("Delivery man should be in state == makingDelivery. He isn't.", deliveryMan.getState() == AgentState.makingDelivery); assertFalse("Delivery man's scheduler should have returned false (waiting), but didn't.", deliveryMan.pickAndExecuteAnAction()); //step 3 deliveryMan.msgHereIsPayment(50, "mockEllenRestaurant"); //postconditions 3/preconditions 4 assertTrue("Delivery man should contain a check with the correct amountPaid. It doesn't.", deliveryMan.bills.get(0).getAmountPaid() == 50); assertTrue("Delivery man should contain a check with state == waitingForPayment. It doesn't.", deliveryMan.bills.get(0).getState() == DeliveryState.waitingForPayment); assertTrue("Delivery man should contain a check with event == receivedPayment. It doesn't.", deliveryMan.bills.get(0).getEvent() == DeliveryEvent.receivedPayment); //step 4 assertTrue("Delivery man's scheduler should have returned true (needs to react), but didn't.", deliveryMan.pickAndExecuteAnAction()); //postconditions 4/preconditions 5 assertTrue("MockCashier should have logged \"Received msgHereIsChange\" but didn't. His log reads instead: " + ellenCashier.log.getLastLoggedEvent().toString(), ellenCashier.log.containsString("Received msgHereIsChange from Delivery man for $24.01.")); assertTrue("Delivery man should contain a check with the correct amountMarketGets. It doesn't.", deliveryMan.bills.get(0).getAmountMarketGets() == 25.99); assertTrue("Delivery man should contain a check with state == waitingForVerification. It doesn't.", deliveryMan.bills.get(0).getState() == DeliveryState.waitingForVerification); //step 5 deliveryMan.msgChangeVerified("mockEllenRestaurant"); //postconditions 5/preconditions 6 assertEquals("Delivery man should have $25.99 available money but does not.", deliveryMan.getCash(), 25.99); assertTrue("Delivery man should contain a check with event == changeVerified. It doesn't.", deliveryMan.bills.get(0).getEvent() == DeliveryEvent.changeVerified); //step 6 - message semaphore before it's acquired to avoid locking deliveryMan.msgAtHome(); assertTrue("Delivery man's scheduler should have returned true (needs to react), but didn't.", deliveryMan.pickAndExecuteAnAction()); //postconditions 6 assertEquals("Delivery man should have 0 bills in it. It doesn't.", deliveryMan.getBills().size(), 0); assertTrue("MockDeliveryManGui should have logged \"Told to DoGoToHomePosition\" but didn't.", gui.log.containsString("Gui is told to DoGoToHomePosition by agent.")); assertTrue("Delivery man should be in state == doingNothing. He isn't.", deliveryMan.getState() == AgentState.doingNothing); assertFalse("Delivery man's scheduler should have returned false (nothing left to do), but didn't.", deliveryMan.pickAndExecuteAnAction()); } //=============================== NEXT TEST ========================================================================= public void testTwoNormalBusinessScenario(){ gui.deliveryMan = deliveryMan; //preconditions assertEquals("Delivery man should have 0 bills in it. It doesn't.", deliveryMan.getBills().size(), 0); assertEquals("Delivery man should have 0 available money but does not.", deliveryMan.getCash(), 0.0); assertTrue("Delivery man should be in state == doingNothing. He isn't.", deliveryMan.getState() == AgentState.doingNothing); Map<String, Integer>inventory = new TreeMap<String, Integer>(); inventory.put("steak", 1); //cost of steak = 15.99 inventory.put("soup", 2); //cost of soup = 5.00 Map<String, Integer>inventory2 = new TreeMap<String, Integer>(); inventory2.put("pizza", 1); //cost of pizza = 8.99 inventory2.put("pasta", 2); //cost of pasta = 20.00 //step 1 deliveryMan.msgHereIsOrderForDelivery("mockEllenRestaurant", inventory, 25.99); deliveryMan.msgHereIsOrderForDelivery("mockMarcusRestaurant", inventory2, 48.99); //postconditions 1/preconditions 2 assertEquals("MockCashier should have an empty event log before the Cashier's scheduler is called. Instead, the MockEmployee's event log reads: " + ellenCashier.log.toString(), 0, ellenCashier.log.size()); assertEquals("MockCook should have an empty event log before the Cashier's scheduler is called. Instead, the MockCook's event log reads: " + ellenCook.log.toString(), 0, ellenCook.log.size()); assertEquals("Cashier should have 2 bills but does not.", deliveryMan.getBills().size(), 2); assertTrue("Delivery man should contain a check with state == newBill. It doesn't.", deliveryMan.bills.get(0).getState() == DeliveryState.newBill); assertTrue("Delivery man should contain a check with event == deliveryRequested. It doesn't.", deliveryMan.bills.get(0).getEvent() == DeliveryEvent.deliveryRequested); assertTrue("Delivery man should contain a check with a null cook. It doesn't.", deliveryMan.bills.get(0).getCook() == null); assertTrue("Delivery man should contain a check with a null cashier. It doesn't.", deliveryMan.bills.get(0).getCashier() == null); assertTrue("Delivery man should contain a check with the right restaurant in it. It doesn't.", deliveryMan.bills.get(0).getRestaurant().equalsIgnoreCase("mockEllenRestaurant")); assertTrue("Delivery man should contain a check with the correct amountCharged. It doesn't.", deliveryMan.bills.get(0).getAmountCharged() == 25.99); assertTrue("Delivery man should contain a check with state == newBill. It doesn't.", deliveryMan.bills.get(1).getState() == DeliveryState.newBill); assertTrue("Delivery man should contain a check with event == deliveryRequested. It doesn't.", deliveryMan.bills.get(1).getEvent() == DeliveryEvent.deliveryRequested); assertTrue("Delivery man should contain a check with a null cook. It doesn't.", deliveryMan.bills.get(1).getCook() == null); assertTrue("Delivery man should contain a check with a null cashier. It doesn't.", deliveryMan.bills.get(1).getCashier() == null); assertTrue("Delivery man should contain a check with the right restaurant in it. It doesn't.", deliveryMan.bills.get(1).getRestaurant().equalsIgnoreCase("mockMarcusRestaurant")); assertTrue("Delivery man should contain a check with the correct amountCharged. It doesn't.", deliveryMan.bills.get(1).getAmountCharged() == 48.99); //step 2 deliveryMan.bills.get(0).setCashier(ellenCashier); deliveryMan.bills.get(0).setCook(ellenCook); deliveryMan.msgAtDestination(); assertTrue("Delivery man's scheduler should have returned true (needs to react to new bill), but didn't.", deliveryMan.pickAndExecuteAnAction()); //postconditions 2/preconditions 3 assertTrue("MockCook should have logged \"Received msgHereIsYourOrder\" but didn't. His log reads instead: " + ellenCook.log.getLastLoggedEvent().toString(), ellenCook.log.containsString("Received msgHereIsYourOrder from delivery man.")); assertTrue("MockCashier should have logged \"Received msgHereIsMarketBill\" but didn't. His log reads instead: " + ellenCashier.log.getLastLoggedEvent().toString(), ellenCashier.log.containsString("Received msgHereIsMarketBill from Delivery man for $25.99.")); assertTrue("Delivery man should contain a check with state == waitingForPayment. It doesn't.", deliveryMan.bills.get(0).getState() == DeliveryState.waitingForPayment); assertTrue("Delivery man should be in state == makingDelivery. He isn't.", deliveryMan.getState() == AgentState.makingDelivery); assertFalse("Delivery man's scheduler should have returned false (waiting), but didn't.", deliveryMan.pickAndExecuteAnAction()); //step 3 deliveryMan.msgHereIsPayment(50, "mockEllenRestaurant"); //postconditions 3/preconditions 4 assertTrue("Delivery man should contain a check with the correct amountPaid. It doesn't.", deliveryMan.bills.get(0).getAmountPaid() == 50); assertTrue("Delivery man should contain a check with state == waitingForPayment. It doesn't.", deliveryMan.bills.get(0).getState() == DeliveryState.waitingForPayment); assertTrue("Delivery man should contain a check with event == receivedPayment. It doesn't.", deliveryMan.bills.get(0).getEvent() == DeliveryEvent.receivedPayment); assertTrue("Delivery man should be in state == makingDelivery. He isn't.", deliveryMan.getState() == AgentState.makingDelivery); //step 4 deliveryMan.msgAtDestination(); assertTrue("Delivery man's scheduler should have returned true (needs to react to newest bill), but didn't.", deliveryMan.pickAndExecuteAnAction()); //postconditions 4/preconditions 5 assertTrue("MockCashier should have logged \"Received msgHereIsChange\" but didn't. His log reads instead: " + ellenCashier.log.getLastLoggedEvent().toString(), ellenCashier.log.containsString("Received msgHereIsChange from Delivery man for $24.01.")); assertTrue("Delivery man should contain a check with the correct amountMarketGets. It doesn't.", deliveryMan.bills.get(0).getAmountMarketGets() == 25.99); assertTrue("Delivery man should contain a check with state == waitingForVerification. It doesn't.", deliveryMan.bills.get(0).getState() == DeliveryState.waitingForVerification); //step 5 deliveryMan.msgChangeVerified("mockEllenRestaurant"); //postconditions 5/preconditions 6 assertEquals("Delivery man should have $25.99 available money but does not.", deliveryMan.getCash(), 25.99); assertTrue("Delivery man should contain a check with event == changeVerified. It doesn't.", deliveryMan.bills.get(0).getEvent() == DeliveryEvent.changeVerified); //step 6 - message semaphore before it's acquired to avoid locking deliveryMan.msgAtHome(); assertTrue("Delivery man's scheduler should have returned true (needs to react and remove business), but didn't.", deliveryMan.pickAndExecuteAnAction()); //postconditions 6/preconditions 7 assertEquals("Delivery man should have 1 bill in it. It doesn't.", deliveryMan.getBills().size(), 1); assertTrue("MockDeliveryManGui should have logged \"Told to DoGoToHomePosition\" but didn't.", gui.log.containsString("Gui is told to DoGoToHomePosition by agent.")); assertTrue("Delivery man should be in state == doingNothing. He isn't.", deliveryMan.getState() == AgentState.doingNothing); //step 7 - message semaphore before it's acquired to avoid locking deliveryMan.bills.get(0).setCashier(otherCashier); deliveryMan.bills.get(0).setCook(otherCook); deliveryMan.msgAtDestination(); assertTrue("Delivery man's scheduler should have returned true (needs to react to newest bill), but didn't.", deliveryMan.pickAndExecuteAnAction()); //postconditions 7/preconditions 8 assertTrue("MockCook should have logged \"Received msgHereIsYourOrder\" but didn't. His log reads instead: " + otherCook.log.getLastLoggedEvent().toString(), otherCook.log.containsString("Received msgHereIsYourOrder from delivery man.")); assertTrue("MockCashier should have logged \"Received msgHereIsMarketBill\" but didn't. His log reads instead: " + otherCashier.log.getLastLoggedEvent().toString(), otherCashier.log.containsString("Received msgHereIsMarketBill from Delivery man for $48.99.")); assertTrue("Delivery man should contain a check with state == waitingForPayment. It doesn't.", deliveryMan.bills.get(0).getState() == DeliveryState.waitingForPayment); assertTrue("Delivery man should be in state == makingDelivery. He isn't.", deliveryMan.getState() == AgentState.makingDelivery); assertFalse("Delivery man's scheduler should have returned false (waiting), but didn't.", deliveryMan.pickAndExecuteAnAction()); //step 8 deliveryMan.msgHereIsPayment(50, "mockMarcusRestaurant"); //postconditions 8/preconditions 9 assertTrue("Delivery man should contain a check with the correct amountPaid. It doesn't.", deliveryMan.bills.get(0).getAmountPaid() == 50); assertTrue("Delivery man should contain a check with state == waitingForPayment. It doesn't.", deliveryMan.bills.get(0).getState() == DeliveryState.waitingForPayment); assertTrue("Delivery man should contain a check with event == receivedPayment. It doesn't.", deliveryMan.bills.get(0).getEvent() == DeliveryEvent.receivedPayment); //step 9 assertTrue("Delivery man's scheduler should have returned true (needs to react), but didn't.", deliveryMan.pickAndExecuteAnAction()); //postconditions 9/preconditions 10 assertTrue("MockCashier should have logged \"Received msgHereIsChange\" but didn't. His log reads instead: " + otherCashier.log.getLastLoggedEvent().toString(), otherCashier.log.containsString("Received msgHereIsChange from Delivery man for $1.01.")); assertTrue("Delivery man should contain a check with the correct amountMarketGets. It doesn't.", deliveryMan.bills.get(0).getAmountMarketGets() == 48.99); assertTrue("Delivery man should contain a check with state == waitingForVerification. It doesn't.", deliveryMan.bills.get(0).getState() == DeliveryState.waitingForVerification); //step 10 deliveryMan.msgChangeVerified("mockMarcusRestaurant"); //postconditions 10/preconditions 11 assertEquals("Delivery man should have $74.98 available money but does not.", deliveryMan.getCash(), 74.98); assertTrue("Delivery man should contain a check with event == changeVerified. It doesn't.", deliveryMan.bills.get(0).getEvent() == DeliveryEvent.changeVerified); //step 11 - message semaphore before it's acquired to avoid locking deliveryMan.msgAtHome(); assertTrue("Delivery man's scheduler should have returned true (needs to react), but didn't.", deliveryMan.pickAndExecuteAnAction()); //postconditions 11 assertEquals("Delivery man should have 0 bills in it. It doesn't.", deliveryMan.getBills().size(), 0); assertTrue("MockDeliveryManGui should have logged \"Told to DoGoToHomePosition\" but didn't.", gui.log.containsString("Gui is told to DoGoToHomePosition by agent.")); assertTrue("Delivery man should be in state == doingNothing. He isn't.", deliveryMan.getState() == AgentState.doingNothing); } //=============================== NEXT TEST ========================================================================= public void testOneFlakeBusinessScenario(){ gui.deliveryMan = deliveryMan; deliveryMan.deliveryGui = gui; //preconditions assertEquals("Delivery man should have 0 bills in it. It doesn't.", deliveryMan.getBills().size(), 0); assertEquals("Delivery man should have 0 available money but does not.", deliveryMan.getCash(), 0.0); assertTrue("Delivery man should be in state == doingNothing. He isn't.", deliveryMan.getState() == AgentState.doingNothing); Map<String, Integer>inventory = new TreeMap<String, Integer>(); inventory.put("steak", 1); //cost of steak = 15.99 inventory.put("soup", 2); //cost of soup = 5.00 //step 1 deliveryMan.msgHereIsOrderForDelivery("mockEllenRestaurant", inventory, 25.99); //postconditions 1/preconditions 2 assertEquals("MockCashier should have an empty event log before the Cashier's scheduler is called. Instead, the MockEmployee's event log reads: " + ellenCashier.log.toString(), 0, ellenCashier.log.size()); assertEquals("MockCook should have an empty event log before the Cashier's scheduler is called. Instead, the MockCook's event log reads: " + ellenCook.log.toString(), 0, ellenCook.log.size()); assertEquals("Delivery man should have 1 bill but does not.", deliveryMan.getBills().size(), 1); assertTrue("Delivery man should contain a check with state == newBill. It doesn't.", deliveryMan.bills.get(0).getState() == DeliveryState.newBill); assertTrue("Delivery man should contain a check with event == deliveryRequested. It doesn't.", deliveryMan.bills.get(0).getEvent() == DeliveryEvent.deliveryRequested); assertTrue("Delivery man should contain a check with a null cook. It doesn't.", deliveryMan.bills.get(0).getCook() == null); assertTrue("Delivery man should contain a check with a null cashier. It doesn't.", deliveryMan.bills.get(0).getCashier() == null); assertTrue("Delivery man should contain a check with the right restaurant in it. It doesn't.", deliveryMan.bills.get(0).getRestaurant().equalsIgnoreCase("mockEllenRestaurant")); assertTrue("Delivery man should contain a check with the correct amountCharged. It doesn't.", deliveryMan.bills.get(0).getAmountCharged() == 25.99); //step 2 deliveryMan.bills.get(0).setCashier(ellenCashier); deliveryMan.bills.get(0).setCook(ellenCook); deliveryMan.msgAtDestination(); assertTrue("Delivery man's scheduler should have returned true (needs to react), but didn't.", deliveryMan.pickAndExecuteAnAction()); //postconditions 2/preconditions 3 assertTrue("MockCook should have logged \"Received msgHereIsYourOrder\" but didn't. His log reads instead: " + ellenCook.log.getLastLoggedEvent().toString(), ellenCook.log.containsString("Received msgHereIsYourOrder from delivery man.")); assertTrue("MockCashier should have logged \"Received msgHereIsMarketBill\" but didn't. His log reads instead: " + ellenCashier.log.getLastLoggedEvent().toString(), ellenCashier.log.containsString("Received msgHereIsMarketBill from Delivery man for $25.99.")); assertTrue("Delivery man should contain a check with state == waitingForPayment. It doesn't.", deliveryMan.bills.get(0).getState() == DeliveryState.waitingForPayment); assertTrue("Delivery man should be in state == makingDelivery. He isn't.", deliveryMan.getState() == AgentState.makingDelivery); assertFalse("Delivery man's scheduler should have returned false (waiting), but didn't.", deliveryMan.pickAndExecuteAnAction()); //step 3 deliveryMan.msgHereIsPayment(10, "mockEllenRestaurant"); //less than bill charge //postconditions 3/preconditions 4 assertTrue("Delivery man should contain a check with the correct amountPaid. It doesn't.", deliveryMan.bills.get(0).getAmountPaid() == 10); assertTrue("Delivery man should contain a check with state == waitingForPayment. It doesn't.", deliveryMan.bills.get(0).getState() == DeliveryState.waitingForPayment); assertTrue("Delivery man should contain a check with event == receivedPayment. It doesn't.", deliveryMan.bills.get(0).getEvent() == DeliveryEvent.receivedPayment); //step 4 assertTrue("Delivery man's scheduler should have returned true (needs to react), but didn't.", deliveryMan.pickAndExecuteAnAction()); //postconditions 4/preconditions 5 assertTrue("MockCashier should have logged \"Received msgNotEnoughMoney\" but didn't. His log reads instead: " + ellenCashier.log.getLastLoggedEvent().toString(), ellenCashier.log.containsString("Received msgNotEnoughMoney, amount owed = $15.99")); assertTrue("Delivery man should contain a check with the correct amountMarketGets. It doesn't.", deliveryMan.bills.get(0).getAmountMarketGets() == 10); assertTrue("Delivery man should contain a check with the correct amountOwed. It doesn't. Its amountOwed = " + deliveryMan.bills.get(0).getAmountMarketGets(), deliveryMan.bills.get(0).getAmountOwed() == 15.99); assertTrue("Delivery man should contain a check with state == oweMoney. It doesn't.", deliveryMan.bills.get(0).getState() == DeliveryState.oweMoney); //step 5 deliveryMan.msgIOweYou(15.99, "mockEllenRestaurant"); //postconditions 5/preconditions 6 assertEquals("Delivery man should have $10 available money but does not.", deliveryMan.getCash(), 10.0); assertTrue("Delivery man should contain a check with event == acknowledgedDebt. It doesn't.", deliveryMan.bills.get(0).getEvent() == DeliveryEvent.acknowledgedDebt); //step 6 - call semaphore release before it's acquired to avoid locking deliveryMan.msgAtHome(); assertTrue("Delivery man's scheduler should have returned true (needs to react), but didn't.", deliveryMan.pickAndExecuteAnAction()); //postconditions 6 assertEquals("Delivery man should have 0 bills in it. It doesn't.", deliveryMan.getBills().size(), 0); assertTrue("MockDeliveryManGui should have logged \"Told to DoGoToHomePosition\" but didn't.", gui.log.containsString("Gui is told to DoGoToHomePosition by agent.")); assertTrue("Delivery man should be in state == doingNothing. He isn't.", deliveryMan.getState() == AgentState.doingNothing); assertFalse("Delivery man's scheduler should have returned false (nothing left to do), but didn't.", deliveryMan.pickAndExecuteAnAction()); } }
gpl-3.0
pritam176/UAQ
WebServiceFrontDesk/src/com/uaq/ws/webservice/interfac/IScannerService.java
302
package com.uaq.ws.webservice.interfac; import javax.ws.rs.GET; import javax.ws.rs.Path; import javax.ws.rs.Produces; import com.uaq.ws.pojo.Response; @Path("/scanner/") public interface IScannerService { @GET @Produces("application/json;charset=utf-8") @Path("/scan") Response scan(); }
gpl-3.0
boyentenbi/BloodLink
BloodLink/backend/build/tmp/appengineEndpointsExpandClientLibs/messaging-v1-java.zip-unzipped/messaging/src/main/java/com/example/peter/myapplication/backend/messaging/MessagingRequest.java
6513
/* * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ /* * This code was generated by https://code.google.com/p/google-apis-client-generator/ * (build: 2015-08-03 17:34:38 UTC) * on 2015-08-16 at 16:14:12 UTC * Modify at your own risk. */ package com.example.peter.myapplication.backend.messaging; /** * Messaging request. * * @since 1.3 */ @SuppressWarnings("javadoc") public abstract class MessagingRequest<T> extends com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest<T> { /** * @param client Google client * @param method HTTP Method * @param uriTemplate URI template for the path relative to the base URL. If it starts with a "/" * the base path from the base URL will be stripped out. The URI template can also be a * full URL. URI template expansion is done using * {@link com.google.api.client.http.UriTemplate#expand(String, String, Object, boolean)} * @param content A POJO that can be serialized into JSON or {@code null} for none * @param responseClass response class to parse into */ public MessagingRequest( Messaging client, String method, String uriTemplate, Object content, Class<T> responseClass) { super( client, method, uriTemplate, content, responseClass); } /** Data format for the response. */ @com.google.api.client.util.Key private java.lang.String alt; /** * Data format for the response. [default: json] */ public java.lang.String getAlt() { return alt; } /** Data format for the response. */ public MessagingRequest<T> setAlt(java.lang.String alt) { this.alt = alt; return this; } /** Selector specifying which fields to include in a partial response. */ @com.google.api.client.util.Key private java.lang.String fields; /** * Selector specifying which fields to include in a partial response. */ public java.lang.String getFields() { return fields; } /** Selector specifying which fields to include in a partial response. */ public MessagingRequest<T> setFields(java.lang.String fields) { this.fields = fields; return this; } /** * API key. Your API key identifies your project and provides you with API access, quota, and * reports. Required unless you provide an OAuth 2.0 token. */ @com.google.api.client.util.Key private java.lang.String key; /** * API key. Your API key identifies your project and provides you with API access, quota, and * reports. Required unless you provide an OAuth 2.0 token. */ public java.lang.String getKey() { return key; } /** * API key. Your API key identifies your project and provides you with API access, quota, and * reports. Required unless you provide an OAuth 2.0 token. */ public MessagingRequest<T> setKey(java.lang.String key) { this.key = key; return this; } /** OAuth 2.0 token for the current user. */ @com.google.api.client.util.Key("oauth_token") private java.lang.String oauthToken; /** * OAuth 2.0 token for the current user. */ public java.lang.String getOauthToken() { return oauthToken; } /** OAuth 2.0 token for the current user. */ public MessagingRequest<T> setOauthToken(java.lang.String oauthToken) { this.oauthToken = oauthToken; return this; } /** Returns response with indentations and line breaks. */ @com.google.api.client.util.Key private java.lang.Boolean prettyPrint; /** * Returns response with indentations and line breaks. [default: true] */ public java.lang.Boolean getPrettyPrint() { return prettyPrint; } /** Returns response with indentations and line breaks. */ public MessagingRequest<T> setPrettyPrint(java.lang.Boolean prettyPrint) { this.prettyPrint = prettyPrint; return this; } /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string * assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. */ @com.google.api.client.util.Key private java.lang.String quotaUser; /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string * assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. */ public java.lang.String getQuotaUser() { return quotaUser; } /** * Available to use for quota purposes for server-side applications. Can be any arbitrary string * assigned to a user, but should not exceed 40 characters. Overrides userIp if both are provided. */ public MessagingRequest<T> setQuotaUser(java.lang.String quotaUser) { this.quotaUser = quotaUser; return this; } /** * IP address of the site where the request originates. Use this if you want to enforce per-user * limits. */ @com.google.api.client.util.Key private java.lang.String userIp; /** * IP address of the site where the request originates. Use this if you want to enforce per-user * limits. */ public java.lang.String getUserIp() { return userIp; } /** * IP address of the site where the request originates. Use this if you want to enforce per-user * limits. */ public MessagingRequest<T> setUserIp(java.lang.String userIp) { this.userIp = userIp; return this; } @Override public final Messaging getAbstractGoogleClient() { return (Messaging) super.getAbstractGoogleClient(); } @Override public MessagingRequest<T> setDisableGZipContent(boolean disableGZipContent) { return (MessagingRequest<T>) super.setDisableGZipContent(disableGZipContent); } @Override public MessagingRequest<T> setRequestHeaders(com.google.api.client.http.HttpHeaders headers) { return (MessagingRequest<T>) super.setRequestHeaders(headers); } @Override public MessagingRequest<T> set(String parameterName, Object value) { return (MessagingRequest<T>) super.set(parameterName, value); } }
gpl-3.0
gameminers/Ethereal-Installer
src/main/java/com/gameminers/ethereal/installer/ImageURL.java
2423
package com.gameminers.ethereal.installer; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import javax.imageio.ImageIO; import javax.xml.bind.DatatypeConverter; import com.gameminers.ethereal.lib.Resources; public class ImageURL { public static String create(BufferedImage image) { ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { ImageIO.write(image, "PNG", stream); stream.close(); return "data:image/png;base64,"+DatatypeConverter.printBase64Binary(stream.toByteArray()); } catch (IOException ex) { return "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAs"+ "TAAALEwEAmpwYAAAAB3RJTUUH1QIKEjQLqADJWQAAAlhJREFUOMt9k9FLU2EYxn/nbGvbwW0HOtLCxWJOGAihCF6IRLuovNEKkd30F3jr"+ "MPwf7HpSN0ESrhvrMgqFKAUNhKiIOXfjkR3b1mLipnLO93VxTF2NPnjgex++93kf3o9HocNZB0PAqANJAdhQFPDhDlT/fqtcLDbAkDDvg"+ "0woHg8E4nEkcGhZ/CgUjhqQF5C910GITUh9gt29oSFpLy9LaZptcFZWZGlsTL6G3ZeQanOwAYYKW73j4zE9mwW/H2y7fYLXC7ZNbXGR1Y"+ "UF8xgGH0JVBZAwfzWRiOmTkxAKwcAA1OtQKrmo111O07g8MsKN4eGYgHkAdR0MH2SujI5CuQzJpOsgnYbDQxfptMslk8hCgeuGQRAyT8F"+ "QPsL9br9/uS+Tca1GozA3B7oOjYbLhcNIy+JoYgJ7cxOAz8AXeKA6kAwGAud219ZgehpqNQiHz5qb6fRZM0AX4EDS6wCy1YKdnfOFeTwg"+ "BP/7c+kKoDpQbJ6cIPf3Xeg6LC1BdzfSspCWhRKNoq2ucimVwgf4gIYrUOQNGO+hJbxeKSIRKctlKaWU0rKk7O93YVkuVy5LEYlI4fXKZ"+ "9B6DIZ6F6q/IG9qGkowCLkcVCowNeXuoVZz75UK5HIowSDfNI0K5GegqgC8AkNR1a2biURM1zTQNGg22xdwylWaTV6USuaJEIOzfwQA8p"+ "BSPZ63g319sd5YrFPG+GqavNveNo8d5/Yj+P5PmJ6D4cB8VyiUudbTE4iEwwjgZ6NBcW/vqHJwkJeQnb0QJqXTpCegC7hln8bZOY3zTIc"+ "U/gbWdhZxsMASegAAAABJRU5ErkJggg=="; } } public static BufferedImage decode(String dataURL) { if (dataURL.startsWith("data:image/png;base64,")) { String b64data = dataURL.substring(22); byte[] decoded = DatatypeConverter.parseBase64Binary(b64data); ByteArrayInputStream stream = new ByteArrayInputStream(decoded); try { return ImageIO.read(stream); } catch (Exception ex) {} } return Resources.getPNGAsset("iface/error-32"); } }
gpl-3.0
14mRh4X0r/Bukkit
src/main/java/org/bukkit/event/player/PlayerInventoryEvent.java
595
package org.bukkit.event.player; import org.bukkit.entity.Player; import org.bukkit.inventory.Inventory; /** * Represents a player related inventory event */ public class PlayerInventoryEvent extends PlayerEvent { protected Inventory inventory; public PlayerInventoryEvent(final Type type, final Player player, final Inventory inventory) { super(type, player); this.inventory = inventory; } /** * Gets the Inventory involved in this event * * @return Inventory */ public Inventory getInventory() { return inventory; } }
gpl-3.0
joangui/DataSynth
src/main/java/org/dama/datasynth/matching/graphs/LinearWeightedGreedyPartitioner.java
2567
package org.dama.datasynth.matching.graphs; import org.dama.datasynth.matching.graphs.types.Graph; import org.dama.datasynth.matching.graphs.types.GraphPartitioner; import org.dama.datasynth.matching.graphs.types.Partition; import org.dama.datasynth.matching.graphs.types.Traversal; import java.util.Arrays; import java.util.Set; /** * Created by aprat on 27/02/17. */ public class LinearWeightedGreedyPartitioner extends GraphPartitioner { private int partitionCapacities []= null; private Partition partition = new Partition(); private int numPartitions = 0; private double score(int partitionNeighbors, long partitionCount, int partitionCapacity) { return partitionNeighbors * (1 - (double) partitionCount / (double) partitionCapacity); } public LinearWeightedGreedyPartitioner(Graph graph, Class<? extends Traversal> traversalType, double [] partitionCapacities) { super(graph, traversalType); this.numPartitions = partitionCapacities.length; this.partitionCapacities = new int[numPartitions]; Arrays.setAll(this.partitionCapacities, (int i ) -> (int)(partitionCapacities[i]*graph.getNumNodes())); while(traversal.hasNext()) { long node = traversal.next(); int partitionId = findBestPartition(node); partition.addToPartition(node,partitionId); } } private int findBestPartition(long node) { int partitionNeighbors[] = new int[numPartitions]; Arrays.fill(partitionNeighbors,0); Set<Long> neighbors = graph.getNeighbors(node); for (Long neighbor : neighbors) { Integer i = partition.getNodePartition(neighbor); if (i != null) { partitionNeighbors[i]++; } } int bestPartition = 0; double bestScore = score(partitionNeighbors[0], partition.getPartitionSize(0),partitionCapacities[0]); for (int i = 1; i < numPartitions; ++i) { double newScore = score(partitionNeighbors[i], partition.getPartitionSize(0), partitionCapacities[i]); if (newScore > bestScore) { bestPartition = i; bestScore = newScore; } } if (bestScore == 0) { int leastPopulatedPartition = 0; long minPopulation = partitionCapacities[0] - partition.getPartitionSize(0); for (int i = 1; i < numPartitions; i++) { long population = partitionCapacities[i] - partition.getPartitionSize(i); if (population > minPopulation) { minPopulation = population; leastPopulatedPartition = i; } } return leastPopulatedPartition; } return bestPartition; } @Override public Partition getPartition() { return partition; } }
gpl-3.0
jackwish/apkdemo
src/com/young/apkdemo/SdkActivity.java
2867
/* * Copyright (C) 2015 Mu Weiyang <young.mu@aliyun.com> * * This program is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License version 3, 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 warranties of * MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR * PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. * */ package com.young.apkdemo; import com.young.apkdemo.sdk.IpcActivity; import com.young.apkdemo.sdk.WidgetActivity; import com.young.apkdemo.sdk.DataStorageActivity; import com.young.apkdemo.sdk.sdkMiscActivity; import android.app.Activity; import android.os.Bundle; import android.util.Log; import android.content.Intent; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class SdkActivity extends Activity implements OnClickListener { private static final String TAG = "apkdemo"; private Button ipcBtn; private Button widgetBtn; private Button dataStorageBtn; private Button miscBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.sdk); Log.i(TAG, "enter SDK Activity"); // get buttons and set listeners ipcBtn = (Button)findViewById(R.id.ipc_button); widgetBtn = (Button)findViewById(R.id.widget_button); dataStorageBtn = (Button)findViewById(R.id.datastorage_button); miscBtn = (Button)findViewById(R.id.sdkmisc_button); ipcBtn.setOnClickListener(this); widgetBtn.setOnClickListener(this); dataStorageBtn.setOnClickListener(this); miscBtn.setOnClickListener(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.ipc_button: Intent ipcIntent = new Intent(SdkActivity.this, IpcActivity.class); startActivity(ipcIntent); break; case R.id.widget_button: Intent widgetIntent = new Intent(SdkActivity.this, WidgetActivity.class); startActivity(widgetIntent); break; case R.id.datastorage_button: Intent datastorageIntent = new Intent(SdkActivity.this, DataStorageActivity.class); startActivity(datastorageIntent); break; case R.id.sdkmisc_button: Intent miscIntent = new Intent(SdkActivity.this, sdkMiscActivity.class); startActivity(miscIntent); break; default: break; } } }
gpl-3.0
c0c0n3/ome-smuggler
components/server/src/test/java/integration/serialization/ProcessedImportTest.java
998
package integration.serialization; import com.google.gson.reflect.TypeToken; import ome.smuggler.core.types.ImportBatchId; import ome.smuggler.core.types.ImportId; import ome.smuggler.core.types.ProcessedImport; import ome.smuggler.core.types.QueuedImport; import org.junit.Test; public class ProcessedImportTest extends JsonWriteReadTest { @Test @SuppressWarnings("unchecked") public void serializeAndDeserialize() { QueuedImport task = new QueuedImport(new ImportId(new ImportBatchId()), ImportInputTest.makeNew()); ProcessedImport initialValue = ProcessedImport.succeeded(task); Class<ProcessedImport> valueType = (Class<ProcessedImport>) initialValue.getClass(); TypeToken<ProcessedImport> typeToken = new TypeToken<ProcessedImport>(){}; assertWriteThenReadGivesInitialValue(initialValue, valueType); assertWriteThenReadGivesInitialValue(initialValue, typeToken); } }
gpl-3.0
xawksow/FoxBot-DGC
src/main/java/co/foxdev/foxbot/utils/database/Database.java
7438
package co.foxdev.foxbot.utils.database; import org.apache.commons.lang3.time.DateUtils; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Random; /** * Created by xawksow on 30.07.14. */ public class Database { private static Connection connection = null; public Database (){ try { Class.forName("org.sqlite.JDBC"); connection = DriverManager.getConnection("jdbc:sqlite:bot.db"); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } System.out.println("Opened database successfully"); } public static void initialize(){ try { Class.forName("org.sqlite.JDBC"); connection = DriverManager.getConnection("jdbc:sqlite:bot.db"); } catch ( Exception e ) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); System.exit(0); } System.out.println("Opened database successfully"); } public static int addQuote(String user, String text){ int id = 0; if(connection == null) initialize(); try { Statement stmt = connection.createStatement(); String sql = "INSERT INTO quotes (user,text,date) " + "VALUES ('"+user+"', '"+text+"', '"+System.currentTimeMillis()+"' );"; stmt.executeUpdate(sql); stmt.close(); stmt = connection.createStatement(); sql = "SELECT MAX(id) from quotes;"; ResultSet rs = stmt.executeQuery(sql); while(rs.next()) id = rs.getInt(1); stmt.close(); connection.commit(); } catch (Exception e) { } return id; } public static ArrayList<String> findQuote(String searchText){ if(connection == null) initialize(); ArrayList<String> quoteList = new ArrayList<String>(); try { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT * FROM quotes where user LIKE '%"+searchText+"%' OR text LIKE '%"+searchText+"%' ORDER BY id DESC LIMIT 0,5;"); while ( rs.next() ) { int id = rs.getInt("id"); String user = rs.getString("user"); String date = rs.getString("date"); String text = rs.getString("text"); Long unixTime = Long.parseLong(date); Date realDate = new Date(unixTime); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm"); quoteList.add("["+id+"] ["+text+"] by "+user+" at "+sdf.format(realDate)); } rs.close(); stmt.close(); } catch (Exception e) { } return quoteList; } public static String getQuote(int id){ if(connection == null) initialize(); String quote = "Nothing found."; try { Statement stmt = connection.createStatement(); String sql = "SELECT * FROM quotes where id="+id+" ;"; if(id == -1) sql = "SELECT * from quotes ORDER BY id DESC LIMIT 0,1;"; ResultSet rs = stmt.executeQuery(sql); while ( rs.next() ) { int qid = rs.getInt("id"); String user = rs.getString("user"); String date = rs.getString("date"); String text = rs.getString("text"); Long unixTime = Long.parseLong(date); Date realDate = new Date(unixTime); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm"); quote = "["+qid+"] ["+text+"] by "+user+" at "+sdf.format(realDate); } rs.close(); stmt.close(); } catch (Exception e) { System.out.println("Get Quote failed with: "+e.getMessage()); } return quote; } public static void addLastSeen(String user){ int id = -1; if(connection == null) initialize(); try { Statement stmt = connection.createStatement(); String sql = "SELECT id from seen where user='"+user+"';"; ResultSet rs = stmt.executeQuery(sql); while(rs.next()) id = rs.getInt(1); stmt.close(); stmt = connection.createStatement(); if(id == -1) sql = "INSERT INTO seen (user,date) " + "VALUES ('"+user+"', '"+System.currentTimeMillis()+"' );"; else sql = "UPDATE seen SET date ='"+System.currentTimeMillis()+"' where id="+id+";"; stmt.executeUpdate(sql); stmt.close(); connection.commit(); } catch (Exception e) { } } public static String getLastSeen(String user) { String result = "I have never seen "+user+"!"; if(connection == null) initialize(); try { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT * FROM seen where user='"+user+"' collate nocase;;"); while ( rs.next() ) { int id = rs.getInt("id"); String usr = rs.getString("user"); String date = rs.getString("date"); Long unixTime = Long.parseLong(date); Date realDate = new Date(unixTime); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm"); result = "I last saw "+usr+" at "+sdf.format(realDate); } rs.close(); stmt.close(); } catch (Exception e) { System.out.println("Last seen user failed: "+e.getMessage()); } return result; } public static String getRandomQuote(){ if(connection == null) initialize(); ArrayList<String> quoteList = new ArrayList<String>(); String quote = "Nothing found."; try { Statement stmt = connection.createStatement(); ResultSet rs = stmt.executeQuery( "SELECT * FROM quotes;"); while ( rs.next() ) { int id = rs.getInt("id"); String user = rs.getString("user"); String date = rs.getString("date"); String text = rs.getString("text"); Long unixTime = Long.parseLong(date); Date realDate = new Date(unixTime); SimpleDateFormat sdf = new SimpleDateFormat("dd.MM.yyyy HH:mm"); quoteList.add("["+id+"] ["+text+"] by "+user+" at "+sdf.format(realDate)); } rs.close(); stmt.close(); } catch (Exception e) { System.out.println("Get Quote failed with: "+e.getMessage()); } Random rand = new Random(); if(quoteList.size() > 0) quote = quoteList.get(rand.nextInt(quoteList.size())); return quote; } }
gpl-3.0
TheMurderer/keel
src/keel/Algorithms/UnsupervisedLearning/AssociationRules/FuzzyRuleLearning/GeneticFuzzyApriori/MembershipFunction.java
4376
/*********************************************************************** This file is part of KEEL-software, the Data Mining tool for regression, classification, clustering, pattern mining and so on. Copyright (C) 2004-2010 F. Herrera (herrera@decsai.ugr.es) L. Sánchez (luciano@uniovi.es) J. Alcalá-Fdez (jalcala@decsai.ugr.es) S. García (sglopez@ujaen.es) A. Fernández (alberto.fernandez@ujaen.es) J. Luengo (julianlm@decsai.ugr.es) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ **********************************************************************/ package keel.Algorithms.UnsupervisedLearning.AssociationRules.FuzzyRuleLearning.GeneticFuzzyApriori; /** * <p> * @author Written by Alvaro Lopez * @version 1.0 * @since JDK1.6 * </p> */ public class MembershipFunction implements Comparable { /** * <p> * It depicts a Membership Function represented by a 2-tuple and indicating the center and the spread of an isosceles-triangle * </p> */ private double c; private double w; /** * <p> * Default constructor * </p> */ public MembershipFunction() { } /** * <p> * It returns the center of an isosceles-triangle * </p> * @return A value representing the center of the isosceles-triangle */ public double getC() { return this.c; } /** * <p> * It sets the center of an isosceles-triangle * </p> * @param c A value representing the center of the isosceles-triangle */ public void setC(double c) { this.c = c; } /** * <p> * It returns the spread of an isosceles-triangle * </p> * @return A value representing the spread of the isosceles-triangle */ public double getW() { return this.w; } /** * <p> * It sets the spread of an isosceles-triangle * </p> * @param w A value representing the spread of the isosceles-triangle */ public void setW(double w) { this.w = w; } /** * It computes the overlap length of a membership functions with respect to another one * @param membership_function The membership function with which to compute the overlap length * @return A value indicating the overlap length */ public double calculateOverlapLength(MembershipFunction membership_function) { double x3_mf1, x0_mf2; x3_mf1 = this.c + this.w; x0_mf2 = membership_function.c - membership_function.w; return (x3_mf1 - x0_mf2); } /** * <p> * It allows to clone correctly a membership function * </p> * @return A copy of the membership function */ public MembershipFunction clone() { MembershipFunction mf = new MembershipFunction(); mf.c = this.c; mf.w = this.w; return mf; } /** * <p> * It compares a membership function with another one in order to accomplish ordering (ascending) later. * The comparison is achieved by considering the values of the centers. * For this reason, note that this method provides a natural ordering that is inconsistent with equals * </p> * @param obj The object to be compared * @return A negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object */ public int compareTo(Object obj) { double aux; MembershipFunction mf = (MembershipFunction)obj; if (this.c > mf.c) { aux = this.w; this.w = mf.w; mf.w = aux; return 1; } else if (this.c < mf.c) return -1; return 0; } /** * <p> * It returns a raw string representation of a membership function * </p> * @return A raw string representation of the membership function */ public String toString() { return ( "(c: " + this.c + ", w: " + this.w + ")" ); } }
gpl-3.0
TonyClark/ESL
src_before_threads/ast/query/instrs/control/Goto.java
484
package ast.query.instrs.control; import ast.query.instrs.Instr; import ast.query.machine.Machine; public class Goto extends Instr { int offset; public Goto(int offset) { super(); this.offset = offset; } public void perform(Machine machine) { machine.go(offset); } public String toString() { return "Goto(" + offset + ")"; } public int getOffset() { return offset; } public void setOffset(int offset) { this.offset = offset; } }
gpl-3.0
vdt/Deskera-Accounting
Maven_Accounting_Libs/mavenAccSalesOrder/src/main/java/com/krawler/hql/accounting/BillingSalesOrderDetail.java
2539
/* * Copyright (C) 2012 Krawler Information Systems Pvt Ltd * All rights reserved. * * 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.krawler.hql.accounting; import com.krawler.common.admin.Company; /** * * @author krawler-user */ public class BillingSalesOrderDetail { private String ID; private int srno; private BillingSalesOrder salesOrder; private String productDetail; private double quantity; private double rate; private String remark; private Company company; private Tax tax; public String getID() { return ID; } public void setID(String ID) { this.ID = ID; } public int getSrno() { return srno; } public void setSrno(int srno) { this.srno = srno; } public Company getCompany() { return company; } public void setCompany(Company company) { this.company = company; } public BillingSalesOrder getSalesOrder() { return salesOrder; } public void setSalesOrder(BillingSalesOrder salesOrder) { this.salesOrder = salesOrder; } public double getRate() { return rate; } public void setRate(double rate) { this.rate = rate; } public String getProductDetail() { return productDetail; } public void setProductDetail(String productDetail) { this.productDetail = productDetail; } public double getQuantity() { return quantity; } public void setQuantity(double quantity) { this.quantity = quantity; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public Tax getTax() { return tax; } public void setTax(Tax tax) { this.tax = tax; } }
gpl-3.0
iotaledger/iri
src/main/java/com/iota/iri/model/StateDiff.java
2598
package com.iota.iri.model; import com.iota.iri.storage.Persistable; import com.iota.iri.utils.Serializer; import org.apache.commons.lang3.ArrayUtils; import javax.naming.OperationNotSupportedException; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * Creates a persistable State object, used to map addresses with values in the DB and snapshots. */ public class StateDiff implements Persistable { /** The map storing the address and balance of the current object */ public Map<Hash, Long> state; /** * Returns a byte array of the state map contained in the object. If no data is present in the state, * a new empty byte array is returned instead. */ @Override public byte[] bytes(){ int size = state.size(); if (size == 0) { return new byte[0]; } byte[] temp = new byte[size * (Hash.SIZE_IN_BYTES + Long.BYTES)]; int index = 0; for (Entry<Hash,Long> entry : state.entrySet()){ byte[] key = entry.getKey().bytes(); System.arraycopy(key, 0, temp, index, key.length); index += key.length; byte[] value = Serializer.serialize(entry.getValue()); System.arraycopy(value, 0, temp, index, value.length); index += value.length; } return temp; } /** * Iterates through the given byte array and populates the state map with the contained address * hashes and the associated balance. * * @param bytes The source data to be placed in the State */ public void read(byte[] bytes) { int i; state = new HashMap<>(); if(bytes != null) { for (i = 0; i < bytes.length; i += Hash.SIZE_IN_BYTES + Long.BYTES) { state.put(HashFactory.ADDRESS.create(bytes, i, Hash.SIZE_IN_BYTES), Serializer.getLong(Arrays.copyOfRange(bytes, i + Hash.SIZE_IN_BYTES, i + Hash.SIZE_IN_BYTES + Long.BYTES))); } } } @Override public byte[] metadata() { return new byte[0]; } @Override public void readMetadata(byte[] bytes) { } @Override public boolean canMerge() { return false; } @Override public Persistable mergeInto(Persistable source) throws OperationNotSupportedException { throw new OperationNotSupportedException("This object is not mergeable"); } @Override public boolean exists() { return !(this.state == null || this.state.isEmpty()); } }
gpl-3.0
BGI-flexlab/SOAPgaeaDevelopment4.0
src/main/java/org/bgi/flexlab/gaea/tools/annotator/interval/IntervalComparatorByStart.java
3055
/******************************************************************************* * Copyright (c) 2017, BGI-Shenzhen * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> * * This file incorporates work covered by the following copyright and * Permission notices: * * Copyright (C) 2016 Pablo Cingolani(pcingola@users.sourceforge.net) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *******************************************************************************/ package org.bgi.flexlab.gaea.tools.annotator.interval; import java.util.Comparator; /** * Compare intervals by start position * @author pcingola * */ public class IntervalComparatorByStart implements Comparator<Marker> { int order = 1; public IntervalComparatorByStart() { super(); } public IntervalComparatorByStart(boolean reverse) { super(); if (reverse) order = -1; } @Override public int compare(Marker i1, Marker i2) { // Compare chromosome if ((i1.getChromosomeNum() == 0) || (i2.getChromosomeNum() == 0)) { // Use string version? // Chromosome by string int c = i1.getChromosomeName().compareTo(i2.getChromosomeName()); if (c != 0) return order * c; } else { // Use numeric version if (i1.getChromosomeNum() > i2.getChromosomeNum()) return order; if (i1.getChromosomeNum() < i2.getChromosomeNum()) return -order; } // Start if (i1.getStart() > i2.getStart()) return order; if (i1.getStart() < i2.getStart()) return -order; // End if (i1.getEnd() > i2.getEnd()) return order; if (i1.getEnd() < i2.getEnd()) return -order; // Compare by ID if ((i1.getId() == null) && (i2.getId() == null)) return 0; if ((i1.getId() != null) && (i2.getId() == null)) return -1; if ((i1.getId() == null) && (i2.getId() != null)) return 1; return i1.getId().compareTo(i2.getId()); } }
gpl-3.0
mitukiii/TumblifeForAndroid
src/jp/mitukiii/tumblife/KeyCodeMap.java
3392
package jp.mitukiii.tumblife; public enum KeyCodeMap { KEYCODE_UNKNOWN ("UNKNOWN", 0), KEYCODE_SOFT_LEFT ("SOFT_LEFT", 1), KEYCODE_SOFT_RIGHT ("SOFT_RIGHT", 2), KEYCODE_HOME ("HOME", 3), KEYCODE_BACK ("BACK", 4), KEYCODE_CALL ("CALL", 5), KEYCODE_ENDCALL ("ENDCALL", 6), KEYCODE_0 ("0", 7), KEYCODE_1 ("1", 8), KEYCODE_2 ("2", 9), KEYCODE_3 ("3", 10), KEYCODE_4 ("4", 11), KEYCODE_5 ("5", 12), KEYCODE_6 ("6", 13), KEYCODE_7 ("7", 14), KEYCODE_8 ("8", 15), KEYCODE_9 ("9", 16), KEYCODE_STAR ("STAR", 17), KEYCODE_POUND ("POUND", 18), KEYCODE_DPAD_UP ("DPAD_UP", 19), KEYCODE_DPAD_DOWN ("DPAD_DOWN", 20), KEYCODE_DPAD_LEFT ("DPAD_LEFT", 21), KEYCODE_DPAD_RIGHT ("DPAD_RIGHT", 22), KEYCODE_DPAD_CENTER ("DPAD_CENTER", 23), KEYCODE_VOLUME_UP ("VOLUME_UP", 24), KEYCODE_VOLUME_DOWN ("VOLUME_DOWN", 25), KEYCODE_POWER ("POWER", 26), KEYCODE_CAMERA ("CAMERA", 27), KEYCODE_CLEAR ("CLEAR", 28), KEYCODE_A ("A", 29), KEYCODE_B ("B", 30), KEYCODE_C ("C", 31), KEYCODE_D ("D", 32), KEYCODE_E ("E", 33), KEYCODE_F ("F", 34), KEYCODE_G ("G", 35), KEYCODE_H ("H", 36), KEYCODE_I ("I", 37), KEYCODE_J ("J", 38), KEYCODE_K ("K", 39), KEYCODE_L ("L", 40), KEYCODE_M ("M", 41), KEYCODE_N ("N", 42), KEYCODE_O ("O", 43), KEYCODE_P ("P", 44), KEYCODE_Q ("Q", 45), KEYCODE_R ("R", 46), KEYCODE_S ("S", 47), KEYCODE_T ("T", 48), KEYCODE_U ("U", 49), KEYCODE_V ("V", 50), KEYCODE_W ("W", 51), KEYCODE_X ("X", 52), KEYCODE_Y ("Y", 53), KEYCODE_Z ("Z", 54), KEYCODE_COMMA ("COMMA", 55), KEYCODE_PERIOD ("PERIOD", 56), KEYCODE_ALT_LEFT ("ALT_LEFT", 57), KEYCODE_ALT_RIGHT ("ALT_RIGHT", 58), KEYCODE_SHIFT_LEFT ("SHIFT_LEFT", 59), KEYCODE_SHIFT_RIGHT ("SHIFT_RIGHT", 60), KEYCODE_TAB ("TAB", 61), KEYCODE_SPACE ("SPACE", 62), KEYCODE_SYM ("SYM", 63), KEYCODE_EXPLORER ("EXPLORER", 64), KEYCODE_ENVELOPE ("ENVELOPE", 65), KEYCODE_ENTER ("ENTER", 66), KEYCODE_DEL ("DEL", 67), KEYCODE_GRAVE ("GRAVE", 68), KEYCODE_MINUS ("MINUS", 69), KEYCODE_EQUALS ("EQUALS", 70), KEYCODE_LEFT_BRACKET ("LEFT_BRACKET", 71), KEYCODE_RIGHT_BRACKET ("RIGHT_BRACKET", 72), KEYCODE_BACKSLASH ("BACKSLASH", 73), KEYCODE_SEMICOLON ("SEMICOLON", 74), KEYCODE_APOSTROPHE ("APOSTROPHE", 75), KEYCODE_SLASH ("SLASH", 76), KEYCODE_AT ("AT", 77), KEYCODE_NUM ("NUM", 78), KEYCODE_HEADSETHOOK ("HEADSETHOOK", 79), KEYCODE_FOCUS ("FOCUS", 80), KEYCODE_PLUS ("PLUS", 81), KEYCODE_MENU ("MENU", 82), KEYCODE_NOTIFICATION ("NOTIFICATION", 83), KEYCODE_SEARCH ("SEARCH", 84), KEYCODE_MEDIA_PLAY_PAUSE ("MEDIA_PLAY_PAUSE", 85), KEYCODE_MEDIA_STOP ("MEDIA_STOP", 86), KEYCODE_MEDIA_NEXT ("MEDIA_NEXT", 87), KEYCODE_MEDIA_PREVIOUS ("MEDIA_PREVIOUS", 88), KEYCODE_MEDIA_REWIND ("MEDIA_REWIND", 89), KEYCODE_MEDIA_FAST_FORWARD ("MEDIA_FAST_FORWARD", 90), KEYCODE_MUTE ("MUTE", 91); private String name; private int keyCode; private KeyCodeMap(String name, int keyCode) { this.name = name; this.keyCode = keyCode; } public String getName() { return name; } public int getKeyCode() { return keyCode; } public static KeyCodeMap valueOf(int keyCode) { for (KeyCodeMap keyCodeMap : values()) { if (keyCodeMap.getKeyCode() == keyCode) { return keyCodeMap; } } return KeyCodeMap.KEYCODE_UNKNOWN; } }
gpl-3.0
uw-ictd/dfs-phishing-sms-client
QKSMS/src/main/java/com/moez/QKSMS/ui/dialog/mms/MMSDialogFragment.java
17084
package com.moez.QKSMS.ui.dialog.mms; import android.app.Dialog; import android.app.DialogFragment; import android.app.Fragment; import android.content.Context; import android.content.DialogInterface; import android.content.res.Resources; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.Window; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.ScrollView; import com.moez.QKSMS.R; import com.moez.QKSMS.common.utils.Units; import com.moez.QKSMS.ui.ThemeManager; import com.moez.QKSMS.ui.view.QKTextView; /** * @author Moez Bhatti * @author Shane Creighton-Young * @since 2015-02-08 * * BaseDialogFragment is a backwards-compatible, Material-styled Dialog fragment. * * To listen on results from BaseDialogFragment, launch it from a Fragment that implements * DialogFragmentListener. Then, the "onDialogFragmentResult" methods will get called much like * "onActivityResult". */ public class MMSDialogFragment extends DialogFragment { private final String TAG = "QKDialogFragment"; private Context mContext; private Resources mResources; protected DialogFragmentListener mListener; // Result codes for this public static final int POSITIVE_BUTTON_RESULT = 0; public static final int NEUTRAL_BUTTON_RESULT = 1; public static final int NEGATIVE_BUTTON_RESULT = 2; public static final int LIST_ITEM_CLICK_RESULT = 3; public static final int DISMISS_RESULT = 4; // Views private boolean mTitleEnabled; private String mTitleText; private QKTextView mTitleView; private LinearLayout mContentPanel; private boolean mMessageEnabled; private String mMessageText; private QKTextView mMessageView; private LinearLayout mCustomPanel; private boolean mCustomViewEnabled; private View mCustomView; private LinearLayout mButtonBar; private int mButtonBarOrientation = LinearLayout.HORIZONTAL; private boolean mPositiveButtonEnabled; private String mPositiveButtonText; private QKTextView mPositiveButtonView; private boolean mNeutralButtonEnabled; private String mNeutralButtonText; private QKTextView mNeutralButtonView; private boolean mNegativeButtonEnabled; private String mNegativeButtonText; private QKTextView mNegativeButtonView; public interface DialogFragmentListener { // Called when the DialogFragment button is pressed, the DialogFragment is dismissed, etc. public void onDialogFragmentResult(int resultCode, DialogFragment fragment); // Called when a list item within the dialog is pressed. public void onDialogFragmentListResult(int resultCode, DialogFragment fragment, int index); } public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Restore the target fragment; this is our listener. mListener = (DialogFragmentListener)getTargetFragment(); } /** * Sets the listener of the the DialogFragment. * * The generic stuff is just to ensure that the listener is both a Fragment and a * DialogFragmentListener. */ public <T extends Fragment & DialogFragmentListener> MMSDialogFragment setListener(T l) { mListener = l; setTargetFragment(l, 0); return this; } /** * Notify the listener of a result. */ protected void onResult(int resultCode) { if (mListener != null) { mListener.onDialogFragmentResult(resultCode, this); } } /** * Notify the listener of a result relating to a list item. */ protected void onListResult(int resultCode, int index) { if (mListener != null) { mListener.onDialogFragmentListResult(resultCode, this, index); } } // Make setTargetFragment final so that nobody subclasses BaseDialogFragment and breaks it. @Override final public void setTargetFragment(Fragment fragment, int requestCode) { super.setTargetFragment(fragment, requestCode); } /** * Builds the dialog using all the View parameters. */ @Override public Dialog onCreateDialog(Bundle savedInstanceState) { Dialog dialog = new Dialog(mContext); Window window = dialog.getWindow(); window.requestFeature(Window.FEATURE_NO_TITLE); window.setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT)); LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(R.layout.dialog_material, null); if (mTitleEnabled || mMessageEnabled) { mContentPanel = (LinearLayout) view.findViewById(R.id.contentPanel); mContentPanel.setVisibility(View.VISIBLE); } if (mTitleEnabled) { mTitleView = (QKTextView) view.findViewById(R.id.alertTitle); mTitleView.setVisibility(View.VISIBLE); mTitleView.setText(mTitleText); } if (mMessageEnabled) { mMessageView = (QKTextView) view.findViewById(R.id.message); mMessageView.setVisibility(View.VISIBLE); mMessageView.setText(mMessageText); } if (mCustomViewEnabled) { mCustomPanel = (LinearLayout) view.findViewById(R.id.customPanel); mCustomPanel.setVisibility(View.VISIBLE); if (mCustomView instanceof ListView) { mCustomPanel.addView(mCustomView); } else { ScrollView scrollView = new ScrollView(mContext); scrollView.addView(mCustomView); mCustomPanel.addView(scrollView); } } if (mPositiveButtonEnabled || mNeutralButtonEnabled || mNegativeButtonEnabled) { mButtonBar = (LinearLayout) view.findViewById(R.id.buttonPanel); mButtonBar.setVisibility(View.VISIBLE); mButtonBar.setOrientation(mButtonBarOrientation); } if (mPositiveButtonEnabled) { mPositiveButtonView = (QKTextView) view.findViewById(R.id.buttonPositive); mPositiveButtonView.setVisibility(View.VISIBLE); mPositiveButtonView.setText(mPositiveButtonText); mPositiveButtonView.setTextColor(ThemeManager.getColor()); mPositiveButtonView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onResult(POSITIVE_BUTTON_RESULT); } }); } if (mNeutralButtonEnabled) { mNeutralButtonView = (QKTextView) view.findViewById(R.id.buttonNeutral); mNeutralButtonView.setVisibility(View.VISIBLE); mNeutralButtonView.setText(mNeutralButtonText); mNeutralButtonView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onResult(NEUTRAL_BUTTON_RESULT); } }); } if (mNegativeButtonEnabled) { mNegativeButtonView = (QKTextView) view.findViewById(R.id.buttonNegative); mNegativeButtonView.setVisibility(View.VISIBLE); mNegativeButtonView.setText(mNegativeButtonText); mNegativeButtonView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onResult(NEGATIVE_BUTTON_RESULT); } }); } dialog.setContentView(view); return dialog; } @Override public void onStart() { super.onStart(); Window window = getDialog().getWindow(); WindowManager.LayoutParams windowParams = window.getAttributes(); windowParams.dimAmount = 0.33f; windowParams.flags |= WindowManager.LayoutParams.FLAG_DIM_BEHIND; window.setAttributes(windowParams); DisplayMetrics metrics = new DisplayMetrics(); getActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics); int width = (int) (metrics.widthPixels * 0.9); window.setLayout(width, ViewGroup.LayoutParams.WRAP_CONTENT); } /** * Called when the dialog is cancelled by the user (i.e. the user clicks outside of it) */ @Override public void onCancel(DialogInterface dialog) { onResult(DISMISS_RESULT); } public MMSDialogFragment setContext(Context context) { mContext = context; mResources = context.getResources(); return this; } public MMSDialogFragment setTitle(int resource) { return setTitle(mResources.getString(resource)); } public MMSDialogFragment setTitle(String title) { mTitleEnabled = true; mTitleText = title; return this; } public MMSDialogFragment setMessage(int resource) { return setMessage(mResources.getString(resource)); } public MMSDialogFragment setMessage(String message) { mMessageEnabled = true; mMessageText = message; return this; } public MMSDialogFragment setCancelOnTouchOutside(boolean cancelable) { setCancelable(cancelable); return this; } // TODO fix stack from bottom issue public MMSDialogFragment setButtonBarOrientation(int orientation) { mButtonBarOrientation = orientation; return this; } public MMSDialogFragment setCustomView(View view) { mCustomViewEnabled = true; mCustomView = view; return this; } public MMSDialogFragment setItems(int resource, final int resultCode) { return setItems(mResources.getStringArray(resource)); } public MMSDialogFragment setItems(String[] items) { ArrayAdapter adapter = new ArrayAdapter<>(mContext, R.layout.list_item_simple, items); ListView listView = new ListView(mContext); listView.setAdapter(adapter); listView.setDivider(null); listView.setPadding(0, Units.dpToPx(mContext, 8), 0, Units.dpToPx(mContext, 8)); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { onListResult(LIST_ITEM_CLICK_RESULT, position); dismiss(); } }); return setCustomView(listView); } public MMSDialogFragment setDoubleLineItems(int titles, int bodies) { return setDoubleLineItems( mResources.getStringArray(titles), mResources.getStringArray(bodies) ); } public MMSDialogFragment setDoubleLineItems(String[] titles, String[] bodies) { int size = Math.min(titles.length, bodies.length); DoubleLineListItem[] doubleLineListItems = new DoubleLineListItem[size]; for (int i = 0; i < size; i++) { doubleLineListItems[i] = new DoubleLineListItem(); doubleLineListItems[i].title = titles[i]; doubleLineListItems[i].body = bodies[i]; } ArrayAdapter adapter = new DoubleLineArrayAdapter(mContext, doubleLineListItems); ListView listView = new ListView(mContext); listView.setAdapter(adapter); listView.setDivider(null); listView.setPadding(0, Units.dpToPx(mContext, 8), 0, Units.dpToPx(mContext, 8)); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { onListResult(LIST_ITEM_CLICK_RESULT, position); dismiss(); } }); return setCustomView(listView); } public MMSDialogFragment setTripleLineItems(int titles, int subtitles, int bodies) { return setTripleLineItems( mResources.getStringArray(titles), mResources.getStringArray(subtitles), mResources.getStringArray(bodies) ); } public MMSDialogFragment setTripleLineItems(String[] titles, String[] subtitles, String[] bodies) { int size = Math.min(titles.length, Math.min(subtitles.length, bodies.length)); TripleLineListItem[] tripleLineListItems = new TripleLineListItem[size]; for (int i = 0; i < size; i++) { tripleLineListItems[i] = new TripleLineListItem(); tripleLineListItems[i].title = titles[i]; tripleLineListItems[i].subtitle = subtitles[i]; tripleLineListItems[i].body = bodies[i]; } ArrayAdapter adapter = new TripleLineArrayAdapter(mContext, tripleLineListItems); ListView listView = new ListView(mContext); listView.setAdapter(adapter); listView.setDivider(null); listView.setPadding(0, Units.dpToPx(mContext, 8), 0, Units.dpToPx(mContext, 8)); listView.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { onListResult(LIST_ITEM_CLICK_RESULT, position); dismiss(); } }); return setCustomView(listView); } public MMSDialogFragment setPositiveButton(int resource) { return setPositiveButton(mResources.getString(resource)); } public MMSDialogFragment setPositiveButton(String text) { mPositiveButtonEnabled = true; mPositiveButtonText = text; return this; } public MMSDialogFragment setNeutralButton(int resource) { return setNeutralButton(mResources.getString(resource)); } public MMSDialogFragment setNeutralButton(String text) { mNeutralButtonEnabled = true; mNeutralButtonText = text; return this; } public MMSDialogFragment setNegativeButton(int resource) { return setNegativeButton(mResources.getString(resource)); } public MMSDialogFragment setNegativeButton(String text) { mNegativeButtonEnabled = true; mNegativeButtonText = text; return this; } @Override public void onPause() { super.onPause(); dismiss(); } private class DoubleLineListItem { String title; String body; } private class DoubleLineArrayAdapter extends ArrayAdapter<DoubleLineListItem> { public DoubleLineArrayAdapter(Context context, DoubleLineListItem[] items) { super(context, R.layout.list_item_dual, items); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.list_item_dual, parent, false); } ((QKTextView) convertView.findViewById(R.id.list_item_title)) .setText(getItem(position).title); ((QKTextView) convertView.findViewById(R.id.list_item_body)) .setText(getItem(position).body); return convertView; } } private class TripleLineListItem { String title; String subtitle; String body; } private class TripleLineArrayAdapter extends ArrayAdapter<TripleLineListItem> { public TripleLineArrayAdapter(Context context, TripleLineListItem[] items) { super(context, R.layout.list_item_triple, items); } @Override public View getView(int position, View convertView, ViewGroup parent) { if (convertView == null) { LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = inflater.inflate(R.layout.list_item_triple, parent, false); } QKTextView title = (QKTextView) convertView.findViewById(R.id.list_item_title); title.setTextColor(ThemeManager.getColor()); title.setText(getItem(position).title); QKTextView subtitle = (QKTextView) convertView.findViewById(R.id.list_item_subtitle); subtitle.setTextColor(ThemeManager.getTextOnBackgroundPrimary()); subtitle.setText(getItem(position).subtitle); ((QKTextView) convertView.findViewById(R.id.list_item_body)) .setText(getItem(position).body); return convertView; } } }
gpl-3.0
OpenWIS/openwis
openwis-metadataportal/openwis-portal/src/main/java/org/openwis/metadataportal/kernel/search/query/solr/SolrQueryFactory.java
15030
package org.openwis.metadataportal.kernel.search.query.solr; import java.text.MessageFormat; import java.text.ParseException; import java.util.Date; import jeeves.utils.Log; import jeeves.utils.Xml; import org.apache.commons.lang.StringUtils; import org.apache.solr.client.solrj.SolrQuery; import org.apache.solr.client.solrj.util.ClientUtils; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.TermsParams; import org.apache.solr.common.util.DateUtil; import org.fao.geonet.constants.Geonet; import org.fao.geonet.kernel.search.IndexField; import org.jdom.Element; import org.openwis.metadataportal.kernel.search.query.AbstractSearchQueryFactory; import org.openwis.metadataportal.kernel.search.query.SearchQueryFactory; /** * A factory for creating SolrQuery objects. */ public class SolrQueryFactory extends AbstractSearchQueryFactory<SolrSearchQuery> implements SearchQueryFactory<SolrSearchQuery> { /** * Instantiates a new solr query factory. * * @param context the context */ public SolrQueryFactory() { super(); } /** * Builds the solr query. * * @param q the q * @return the solr query */ private SolrQuery buildSolrQuery(String q) { SolrQuery query = new SolrQuery(); query.setQuery(q); query.setIncludeScore(true); return query; } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory# * buildTermQuery(org.fao.geonet.kernel.search.IndexField) */ @Override public SolrSearchQuery buildTermQuery(IndexField field) { SolrQuery query = new SolrQuery(); query.set(TermsParams.TERMS, true); query.setQueryType("/" + CommonParams.TERMS); query.add(TermsParams.TERMS_FIELD, field.getField()); SolrSearchQuery result = new SolrSearchQuery(query); result.setTermQuery(true); return result; } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory# * buildTermQuery(org.fao.geonet.kernel.search.IndexField, java.lang.String, int, int) */ @Override public SolrSearchQuery buildTermQuery(IndexField field, String start, int maxResult, int countThreshold) { SolrSearchQuery result = this.buildTermQuery(field); SolrQuery query = result.getSolrQuery(); if (StringUtils.isNotBlank(start)) { query.set(TermsParams.TERMS_PREFIX_STR, start); } if (maxResult > 0) { query.set(TermsParams.TERMS_LIMIT, maxResult); } if (countThreshold > 0) { query.set(TermsParams.TERMS_MINCOUNT, countThreshold); } return result; } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#buildTermRangeQuery(org.fao.geonet.kernel.search.IndexField) */ @Override public SolrSearchQuery buildTermRangeQuery(IndexField field) { SolrQuery query = new SolrQuery(); query.set(TermsParams.TERMS, true); query.setQueryType("/range"); query.add(TermsParams.TERMS_FIELD, field.getField()); SolrSearchQuery result = new SolrSearchQuery(query); result.setTermQuery(true); return result; } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#escapeQueryChars(java.lang.String) */ @Override public String escapeQueryChars(String value) { return ClientUtils.escapeQueryChars(value); } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#escapeQueryCharsOmitWildCards(java.lang.String) */ @Override public String escapeQueryCharsOmitWildCards(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); // These characters are part of the query syntax and must be escaped if (c == '\\' || c == '+' || c == '-' || c == '!' || c == '(' || c == ')' || c == ':' || c == '^' || c == '[' || c == ']' || c == '\"' || c == '{' || c == '}' || c == '~' || c == '|' || c == '&' || c == ';' || Character.isWhitespace(c)) { sb.append('\\'); } sb.append(c); } return sb.toString(); } /** * Builds the any query. * * @param value the value * @return the search query * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#buildAnyQuery(java.lang.String) */ @Override public SolrSearchQuery buildAnyQuery(String value) { SolrQuery solrQuery = buildSolrQuery(value); // default search on any field return new SolrSearchQuery(solrQuery); } /** * Builds the query. * * @param field the field * @param value the value * @return the search query * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#buildQuery(java.lang.String, java.lang.Object) */ @Override public SolrSearchQuery buildQuery(IndexField field, Object value) { String q = MessageFormat.format("{0}:{1}", field.getField(), String.valueOf(value)); SolrQuery solrQuery = buildSolrQuery(q); return new SolrSearchQuery(solrQuery); } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#buildFieldPresentQuery(org.fao.geonet.kernel.search.IndexField) */ @Override public SolrSearchQuery buildFieldPresentQuery(IndexField field) { String q = MessageFormat.format("{0}:*", field.getField()); SolrQuery solrQuery = buildSolrQuery(q); return new SolrSearchQuery(solrQuery); } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#buildFieldNotPresentQuery(org.fao.geonet.kernel.search.IndexField) */ @Override public SolrSearchQuery buildFieldNotPresentQuery(IndexField field) { String q = MessageFormat.format("(*:* NOT {0}:*)", field.getField()); SolrQuery solrQuery = buildSolrQuery(q); return new SolrSearchQuery(solrQuery); } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#buildBetweenQuery(java.lang.String, java.lang.String, java.lang.String) */ @Override public SolrSearchQuery buildBetweenQuery(IndexField field, String from, String to) { SolrSearchQuery result = null; try { Date fromDate = DateUtil.parseDate(from); String sFromDate = DateUtil.getThreadLocalDateFormat().format(fromDate); Date toDate = DateUtil.parseDate(to); String sToDate = DateUtil.getThreadLocalDateFormat().format(toDate); String q = MessageFormat.format("{0}:[{1} TO {2}]", field.getField(), sFromDate, sToDate); SolrQuery solrQuery = buildSolrQuery(q); result = new SolrSearchQuery(solrQuery); } catch (ParseException e) { Log.warning( Geonet.SEARCH_ENGINE, MessageFormat.format("Could not create query ''{0} between {1} & {2}''", field.getField(), from, to), e); } return result; } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#buildAfterQuery(org.fao.geonet.kernel.search.IndexField, java.lang.String) */ @Override public SolrSearchQuery buildAfterQuery(IndexField dateField, String date) { return buildAfterQuery(dateField, date, true); } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#buildAfterQuery(org.fao.geonet.kernel.search.IndexField, java.lang.String, boolean) */ @Override public SolrSearchQuery buildAfterQuery(IndexField dateField, String date, boolean inclusive) { // FIXME Igor: handle inclusive flag SolrSearchQuery result = null; try { Date theDate = DateUtil.parseDate(date); String sDate = DateUtil.getThreadLocalDateFormat().format(theDate); String q = MessageFormat.format("{0}:[{1} TO *]", dateField.getField(), sDate); SolrQuery solrQuery = buildSolrQuery(q); result = new SolrSearchQuery(solrQuery); } catch (ParseException e) { Log.warning( Geonet.SEARCH_ENGINE, MessageFormat.format("Could not create query ''{0} after {1}''", dateField.getField(), date), e); } return result; } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#buildBeforeQuery(org.fao.geonet.kernel.search.IndexField, java.lang.String) */ @Override public SolrSearchQuery buildBeforeQuery(IndexField dateField, String date) { return buildBeforeQuery(dateField, date, true); } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#buildBeforeQuery(org.fao.geonet.kernel.search.IndexField, java.lang.String, boolean) */ @Override public SolrSearchQuery buildBeforeQuery(IndexField dateField, String date, boolean inclusive) { // FIXME Igor: handle inclusive flag SolrSearchQuery result = null; try { Date theDate = DateUtil.parseDate(date); String sDate = DateUtil.getThreadLocalDateFormat().format(theDate); String q = MessageFormat.format("{0}:[* TO {1}]", dateField.getField(), sDate); SolrQuery solrQuery = buildSolrQuery(q); result = new SolrSearchQuery(solrQuery); } catch (ParseException e) { Log.warning( Geonet.SEARCH_ENGINE, MessageFormat.format("Could not create query ''{0} after {1}''", dateField.getField(), date), e); } return result; } /** * Builds the all. * * @return the search query * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#buildAll() */ @Override public SolrSearchQuery buildAll() { SolrQuery solrQuery = buildSolrQuery("*"); return new SolrSearchQuery(solrQuery); } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#or(org.openwis.metadataportal.kernel.search.query.SearchQuery, org.openwis.metadataportal.kernel.search.query.SearchQuery) */ @Override public SolrSearchQuery or(SolrSearchQuery leftQuery, SolrSearchQuery rightQuery) { SolrSearchQuery result = null; if (leftQuery == null) { result = rightQuery; } else if (rightQuery == null) { result = leftQuery; } else { String q = MessageFormat.format("({0} OR {1})", leftQuery.getSolrQuery().getQuery(), rightQuery.getSolrQuery().getQuery()); // String q = MessageFormat.format("{0} {1}", leftQuery.getSolrQuery().getQuery(), rightQuery // .getSolrQuery().getQuery()); SolrQuery solrQuery = buildSolrQuery(q); result = new SolrSearchQuery(solrQuery); result.setSpatialQuery(leftQuery.isSpatial() || rightQuery.isSpatial()); result.setTermQuery(leftQuery.isTermQuery() || rightQuery.isTermQuery()); } return result; } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#and(org.openwis.metadataportal.kernel.search.query.SearchQuery, org.openwis.metadataportal.kernel.search.query.SearchQuery) */ @Override public SolrSearchQuery and(SolrSearchQuery leftQuery, SolrSearchQuery rightQuery) { SolrSearchQuery result = null; if (leftQuery == null) { result = rightQuery; } else if (rightQuery == null) { result = leftQuery; } else { String leftQ = leftQuery.getSolrQuery().getQuery(); String rightQ = rightQuery.getSolrQuery().getQuery(); String q = MessageFormat.format("({0} AND {1})", leftQ, rightQ); SolrQuery solrQuery = buildSolrQuery(q); result = new SolrSearchQuery(solrQuery); result.setSpatialQuery(leftQuery.isSpatial() || rightQuery.isSpatial()); result.setTermQuery(leftQuery.isTermQuery() || rightQuery.isTermQuery()); } return result; } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#not(org.openwis.metadataportal.kernel.search.query.SearchQuery) */ @Override public SolrSearchQuery not(SolrSearchQuery query) { SolrSearchQuery result = null; if (query != null) { String q = MessageFormat.format("NOT({0})", query.getSolrQuery().getQuery()); SolrQuery solrQuery = buildSolrQuery(q); result = new SolrSearchQuery(solrQuery); result.setSpatialQuery(query.isSpatial()); result.setTermQuery(query.isTermQuery()); } return result; } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#fuzzy(org.openwis.metadataportal.kernel.search.query.SearchQuery, float) */ @Override public SolrSearchQuery fuzzy(SolrSearchQuery query, float fuzzyFactor) { SolrSearchQuery result = null; if (query != null) { String q = MessageFormat.format("{0}~{1}", query.getSolrQuery().getQuery(), String.valueOf(fuzzyFactor)); SolrQuery solrQuery = buildSolrQuery(q); result = new SolrSearchQuery(solrQuery); } result.setSpatialQuery(query.isSpatial()); result.setTermQuery(query.isTermQuery()); return result; } // Implémentation de la methode boost @Override public SolrSearchQuery boost(SolrSearchQuery query, int boostFactor) { SolrSearchQuery result = null; if (query != null) { String q = MessageFormat.format("{0}^{1}", query.getSolrQuery().getQuery(), String.valueOf(boostFactor)); SolrQuery solrQuery = buildSolrQuery(q); result = new SolrSearchQuery(solrQuery); } result.setSpatialQuery(query.isSpatial()); result.setTermQuery(query.isTermQuery()); return result; } /** * {@inheritDoc} * @see org.openwis.metadataportal.kernel.search.query.SearchQueryFactory#addSpatialQuery(org.openwis.metadataportal.kernel.search.query.SearchQuery, org.jdom.Element) */ @Override public SolrSearchQuery addSpatialQuery(SolrSearchQuery query, Element xml, String filterVersion) { SolrSearchQuery result = null; if (query != null) { result = query; // use special Openwis searcher result.getSolrQuery().set("openwisRequest", Xml.getString(xml)); result.getSolrQuery().set("defType", "OpenwisSearch"); if (filterVersion != null) { result.getSolrQuery().set("filterVersion", filterVersion); } result.setSpatialQuery(true); } return result; } }
gpl-3.0
borboton13/sisk13
src/main/com/encens/khipus/dashboard/component/totalizer/Totalizer.java
278
package com.encens.khipus.dashboard.component.totalizer; import com.encens.khipus.dashboard.component.factory.DashboardObject; /** * @author * @version 2.7 */ public interface Totalizer<T extends DashboardObject> { void calculate(T instance); void initialize(); }
gpl-3.0
marvec/engine
war/src/test/java/io/lumeer/core/facade/UserFacadeIT.java
16237
/* * Lumeer: Modern Data Definition and Processing Platform * * Copyright (C) since 2017 Lumeer.io, s.r.o. and/or its affiliates. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package io.lumeer.core.facade; import static org.assertj.core.api.Assertions.*; import io.lumeer.api.model.DefaultWorkspace; import io.lumeer.api.model.Feedback; import io.lumeer.api.model.InvitationType; import io.lumeer.api.model.Organization; import io.lumeer.api.model.Permission; import io.lumeer.api.model.Permissions; import io.lumeer.api.model.Project; import io.lumeer.api.model.Role; import io.lumeer.api.model.RoleType; import io.lumeer.api.model.User; import io.lumeer.api.model.UserInvitation; import io.lumeer.core.auth.AuthenticatedUser; import io.lumeer.core.auth.PermissionsChecker; import io.lumeer.core.exception.BadFormatException; import io.lumeer.core.exception.NoResourcePermissionException; import io.lumeer.core.exception.ServiceLimitsExceededException; import io.lumeer.engine.IntegrationTestBase; import io.lumeer.storage.api.dao.FeedbackDao; import io.lumeer.storage.api.dao.OrganizationDao; import io.lumeer.storage.api.dao.ProjectDao; import io.lumeer.storage.api.dao.UserDao; import io.lumeer.storage.api.exception.ResourceNotFoundException; import org.jboss.arquillian.junit.Arquillian; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import java.time.ZonedDateTime; import java.time.temporal.ChronoUnit; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Optional; import java.util.Set; import javax.inject.Inject; @RunWith(Arquillian.class) public class UserFacadeIT extends IntegrationTestBase { private static final String USER = AuthenticatedUser.DEFAULT_EMAIL; private static final String USER1 = "user1@gmail.com"; private static final String USER2 = "user2@gmail.com"; private static final String USER3 = "user3@gmail.com"; private static final String USER4 = "user4@gmail.com"; private static final String USER1_NAME = "User 1"; private Organization organization; private String organizationId1; private String organizationId2; private String organizationIdNotPermission; private Project project; @Inject private UserFacade userFacade; @Inject private UserDao userDao; @Inject private OrganizationDao organizationDao; @Inject private ProjectDao projectDao; @Inject private FeedbackDao feedbackDao; @Inject private PermissionsChecker permissionsChecker; @Before public void configure() { User user = new User(USER); final User createdUser = userDao.createUser(user); Organization organization1 = new Organization(); organization1.setCode("LMR"); organization1.setPermissions(new Permissions()); organization1.getPermissions().updateUserPermissions(new Permission(createdUser.getId(), Set.of(new Role(RoleType.Read), new Role(RoleType.UserConfig)))); organization = organizationDao.createOrganization(organization1); organizationId1 = organization.getId(); Organization organization2 = new Organization(); organization2.setCode("MRL"); organization2.setPermissions(new Permissions()); organization2.getPermissions().updateUserPermissions(new Permission(createdUser.getId(), Set.of(new Role(RoleType.Read), new Role(RoleType.UserConfig)))); organizationId2 = organizationDao.createOrganization(organization2).getId(); Organization organization3 = new Organization(); organization3.setCode("RML"); organization3.setPermissions(new Permissions()); organizationIdNotPermission = organizationDao.createOrganization(organization3).getId(); projectDao.setOrganization(organization); Project project = new Project(); project.setCode("Lalala"); project.setPermissions(new Permissions()); project.getPermissions().updateUserPermissions(new Permission(createdUser.getId(), Project.ROLES)); this.project = projectDao.createProject(project); permissionsChecker.getPermissionAdapter().invalidateUserCache(); } @Test public void testCreateUser() { userFacade.createUser(organizationId1, prepareUser(organizationId1, USER1)); User stored = getUser(organizationId1, USER1); assertThat(stored).isNotNull(); assertThat(stored.getName()).isEqualTo(USER1); assertThat(stored.getEmail()).isEqualTo(USER1); assertThat(stored.getOrganizations()).containsOnly(organizationId1); } @Test public void testCreateUsersToWorkspace() { List<UserInvitation> users = Arrays.asList(new UserInvitation(USER1, InvitationType.JOIN_ONLY), new UserInvitation(USER2, InvitationType.JOIN_ONLY)); userFacade.createUsersInWorkspace(organizationId1, project.getId(), users); Arrays.asList(USER1, USER2).forEach(user -> { User stored = getUser(organizationId1, user); assertThat(stored).isNotNull(); assertThat(stored.getEmail()).isEqualTo(user); assertThat(stored.getOrganizations()).containsOnly(organizationId1); }); var organization = organizationDao.getOrganizationById(organizationId1); assertThat(organization.getPermissions().getUserPermissions().size()).isEqualTo(3); var project = projectDao.getProjectById(this.project.getId()); assertThat(project.getPermissions().getUserPermissions().size()).isEqualTo(3); } @Test public void testCreateUserMultipleOrganizations() { User user11 = userFacade.createUser(organizationId1, prepareUser(organizationId1, USER1)); User user21 = userFacade.createUser(organizationId1, prepareUser(organizationId1, USER2)); User user12 = userFacade.createUser(organizationId2, prepareUser(organizationId2, USER1)); User user32 = userFacade.createUser(organizationId2, prepareUser(organizationId2, USER3)); assertThat(user11.getId()).isEqualTo(user12.getId()); assertThat(user21.getId()).isNotEqualTo(user32.getId()); assertThat(user21.getId()).isNotEqualTo(user11.getId()); } @Test public void testCreateUserExistingOrganization() { User user1 = userFacade.createUser(organizationId1, prepareUser(organizationId1, USER1)); User user2 = userFacade.createUser(organizationId1, prepareUser(organizationId1, USER1)); User user3 = userFacade.createUser(organizationId1, prepareUser(organizationId1, USER1)); assertThat(user1.getId()).isEqualTo(user2.getId()).isEqualTo(user3.getId()); } @Test public void testCreateExistingUserInNewOrganization() { final var user = new User(null, USER1_NAME, USER1, Collections.singleton(organizationId1)); final var createdUser = userFacade.createUser(organizationId1, user); assertThat(createdUser).isNotNull(); assertThat(createdUser.getId()).isNotNull(); final var updatedUser = new User(null, null, USER1, Collections.singleton(organizationId2)); final var returnedUser = userFacade.createUser(organizationId2, updatedUser); assertThat(returnedUser).isNotNull(); assertThat(returnedUser.getId()).isEqualTo(createdUser.getId()); assertThat(returnedUser.getName()).isEqualTo(USER1_NAME); assertThat(returnedUser.getEmail()).isEqualTo(USER1); assertThat(returnedUser.getOrganizations()).containsOnly(organizationId2); assertThat(returnedUser.getOrganizations()).doesNotContain(organizationId1); final var storedUser = userDao.getUserById(createdUser.getId()); assertThat(storedUser).isNotNull(); assertThat(storedUser.getId()).isEqualTo(createdUser.getId()); assertThat(storedUser.getName()).isEqualTo(USER1_NAME); assertThat(storedUser.getEmail()).isEqualTo(USER1); assertThat(storedUser.getOrganizations()).contains(organizationId1); assertThat(storedUser.getOrganizations()).contains(organizationId2); } @Test public void testCreateUserNotPermission() { assertThatThrownBy(() -> userFacade.createUser(organizationIdNotPermission, prepareUser(organizationIdNotPermission, USER1))) .isInstanceOf(NoResourcePermissionException.class); } @Test public void testUpdateNameAndEmail() { String userId = createUser(organizationId1, USER1).getId(); User toUpdate = prepareUser(organizationId1, USER1); toUpdate.setEmail(USER3); toUpdate.setName("newName"); userFacade.updateUser(organizationId1, userId, toUpdate); User storedNotExisting = getUser(organizationId1, USER1); assertThat(storedNotExisting).isNull(); User storedExisting = getUser(organizationId1, USER3); assertThat(storedExisting).isNotNull(); assertThat(storedExisting.getName()).isEqualTo("newName"); } @Test public void testUpdateUserNotPermission() { String userId = createUser(organizationId1, USER1).getId(); assertThatThrownBy(() -> userFacade.updateUser(organizationIdNotPermission, userId, prepareUser(organizationIdNotPermission, USER3))) .isInstanceOf(NoResourcePermissionException.class); } @Test public void testUpdateUserBadFormat() { String userId = createUser(organizationId1, USER1).getId(); assertThatThrownBy(() -> userFacade.updateUser(organizationId2, userId, prepareUser(organizationId1, USER3))) .isInstanceOf(BadFormatException.class); } @Test public void testDeleteUserNoPermission() { String id = userFacade.createUser(organizationId1, prepareUser(organizationId1, USER1)).getId(); assertThatThrownBy(() -> userFacade.deleteUser(organizationIdNotPermission, id)) .isInstanceOf(NoResourcePermissionException.class); } @Test public void testGetAllUsers() { String id = userFacade.createUser(organizationId1, prepareUser(organizationId1, USER1)).getId(); String id2 = userFacade.createUser(organizationId1, prepareUser(organizationId1, USER2)).getId(); userFacade.createUser(organizationId2, prepareUser(organizationId2, USER1)); String id3 = userFacade.createUser(organizationId2, prepareUser(organizationId2, USER3)).getId(); List<User> users = userFacade.getUsers(organizationId1); assertThat(users).extracting(User::getId).containsOnly(id, id2); users = userFacade.getUsers(organizationId2); assertThat(users).extracting(User::getId).containsOnly(id, id3); } @Test public void testGetAllUsersNoPermission() { assertThatThrownBy(() -> userFacade.getUsers(organizationIdNotPermission)) .isInstanceOf(NoResourcePermissionException.class); } @Test public void testTooManyUsers() { userFacade.createUser(organizationId1, prepareUser(organizationId1, USER1)); userFacade.createUser(organizationId1, prepareUser(organizationId1, USER2)); userFacade.createUser(organizationId1, prepareUser(organizationId1, USER3)); assertThatExceptionOfType(ServiceLimitsExceededException.class).isThrownBy(() -> { userFacade.createUser(organizationId1, prepareUser(organizationId1, USER4)); }).as("On Trial plan, only 3 users should be allowed but it was possible to create 4th one."); } @Test public void testSetWorkspace() { DefaultWorkspace defaultWorkspace = new DefaultWorkspace(organization.getId(), project.getId()); userFacade.setDefaultWorkspace(defaultWorkspace); User currentUser = userFacade.getCurrentUser(); assertThat(currentUser.getDefaultWorkspace()).isNotNull(); assertThat(currentUser.getDefaultWorkspace().getOrganizationId()).isEqualTo(organization.getId()); assertThat(currentUser.getDefaultWorkspace().getOrganizationCode()).isEqualTo(organization.getCode()); assertThat(currentUser.getDefaultWorkspace().getProjectId()).isEqualTo(project.getId()); assertThat(currentUser.getDefaultWorkspace().getProjectCode()).isEqualTo(project.getCode()); } @Test public void testSetWorkspaceNotExisting() { DefaultWorkspace defaultWorkspace = new DefaultWorkspace("5aedf1030b4e0ec3f46502d8", "5aedf1030b4e0ec3f46502d8"); assertThatExceptionOfType(ResourceNotFoundException.class).isThrownBy(() -> userFacade.setDefaultWorkspace(defaultWorkspace)); } @Test public void testSetWorkspaceAndChange() { DefaultWorkspace defaultWorkspace = new DefaultWorkspace(organization.getId(), project.getId()); userFacade.setDefaultWorkspace(defaultWorkspace); User currentUser = userFacade.getCurrentUser(); assertThat(currentUser.getDefaultWorkspace().getOrganizationCode()).isNotEqualTo("newCode"); assertThat(currentUser.getDefaultWorkspace().getProjectCode()).isNotEqualTo("someNewCode"); project.setCode("someNewCode"); projectDao.updateProject(project.getId(), project); organization.setCode("newCode"); organizationDao.updateOrganization(organization.getId(), organization); currentUser = userFacade.getCurrentUser(); assertThat(currentUser.getDefaultWorkspace().getOrganizationCode()).isEqualTo("newCode"); assertThat(currentUser.getDefaultWorkspace().getProjectCode()).isEqualTo("someNewCode"); } @Test public void testSetWorkspaceAndRemove() { DefaultWorkspace defaultWorkspace = new DefaultWorkspace(organization.getId(), project.getId()); userFacade.setDefaultWorkspace(defaultWorkspace); User currentUser = userFacade.getCurrentUser(); assertThat(currentUser.getDefaultWorkspace()).isNotNull(); projectDao.deleteProject(project.getId()); currentUser = userFacade.getCurrentUser(); assertThat(currentUser.getDefaultWorkspace()).isNull(); } @Test public void testCreateFeedback() { ZonedDateTime before = ZonedDateTime.now(); String message = "This application is great!"; Feedback feedback = new Feedback(message); Feedback returnedFeedback = userFacade.createFeedback(feedback); ZonedDateTime after = ZonedDateTime.now(); assertThat(returnedFeedback).isNotNull(); assertThat(returnedFeedback.getId()).isNotNull(); assertThat(returnedFeedback.getUserId()).isEqualTo(userFacade.getCurrentUser().getId()); assertThat(returnedFeedback.getCreationTime()).isAfterOrEqualTo(before.truncatedTo(ChronoUnit.MILLIS)); assertThat(returnedFeedback.getCreationTime()).isBeforeOrEqualTo(after.truncatedTo(ChronoUnit.MILLIS)); assertThat(returnedFeedback.getMessage()).isEqualTo(message); Feedback storedFeedback = feedbackDao.getFeedbackById(returnedFeedback.getId()); assertThat(storedFeedback).isNotNull(); assertThat(storedFeedback.getId()).isEqualTo(returnedFeedback.getId()); assertThat(storedFeedback.getUserId()).isEqualTo(returnedFeedback.getUserId()); assertThat(storedFeedback.getCreationTime()).isEqualTo(returnedFeedback.getCreationTime().truncatedTo(ChronoUnit.MILLIS)); assertThat(storedFeedback.getMessage()).isEqualTo(returnedFeedback.getMessage()); } private User createUser(String organizationId, String user) { return userDao.createUser(prepareUser(organizationId, user)); } private User getUser(String organizationId, String user) { Optional<User> userOptional = userDao.getAllUsers(organizationId).stream().filter(u -> u.getEmail().equals(user)).findFirst(); return userOptional.orElse(null); } private User prepareUser(String organizationId, String user) { User u = new User(user); u.setName(user); u.setOrganizations(Collections.singleton(organizationId)); return u; } }
gpl-3.0
iti-luebeck/RTeasy2
Core/src/org/desert/core/Modes.java
286
/* * 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 org.desert.core; /** * * @author Christian */ public enum Modes { edit, simulate; }
gpl-3.0
hqnghi88/gamaClone
msi.gama.core/src/msi/gaml/extensions/multi_criteria/Candidate.java
1889
/********************************************************************************************* * * 'Candidate.java, in plugin msi.gama.core, is part of the source code of the * GAMA modeling and simulation platform. * (c) 2007-2016 UMI 209 UMMISCO IRD/UPMC & Partners * * Visit https://github.com/gama-platform/gama for license information and developers contact. * * **********************************************************************************************/ package msi.gaml.extensions.multi_criteria; import java.util.Map; public class Candidate { private int index; private Map<String, Double> valCriteria; protected Candidate(final int index, final Map<String, Double> valCriteria) { super(); this.index = index; this.valCriteria = valCriteria; } @Override public String toString() { return index + " -> " + valCriteria; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + index; result = prime * result + (valCriteria == null ? 0 : valCriteria.hashCode()); return result; } @Override public boolean equals(final Object obj) { if ( this == obj ) { return true; } if ( obj == null ) { return false; } if ( getClass() != obj.getClass() ) { return false; } Candidate other = (Candidate) obj; if ( index != other.index ) { return false; } if ( valCriteria == null ) { if ( other.valCriteria != null ) { return false; } } else if ( !valCriteria.equals(other.valCriteria) ) { return false; } return true; } public int getIndex() { return index; } public void setIndex(final int index) { this.index = index; } public Map<String, Double> getValCriteria() { return valCriteria; } public void setValCriteria(final Map<String, Double> valCriteria) { this.valCriteria = valCriteria; } }
gpl-3.0
JunkyBulgaria/Spig
src/main/java/net/minecraft/server/WorldGenVillage.java
4450
package net.minecraft.server; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Map.Entry; public class WorldGenVillage extends StructureGenerator { public static final List<BiomeBase> d = Arrays.asList(new BiomeBase[] { BiomeBase.PLAINS, BiomeBase.DESERT, BiomeBase.SAVANNA}); private int f; private int g; private int h; public WorldGenVillage() { this.g = 32; this.h = 8; } public WorldGenVillage(Map<String, String> map) { this(); Iterator iterator = map.entrySet().iterator(); while (iterator.hasNext()) { Entry entry = (Entry) iterator.next(); if (((String) entry.getKey()).equals("size")) { this.f = MathHelper.a((String) entry.getValue(), this.f, 0); } else if (((String) entry.getKey()).equals("distance")) { this.g = MathHelper.a((String) entry.getValue(), this.g, this.h + 1); } } } public String a() { return "Village"; } protected boolean a(int i, int j) { int k = i; int l = j; if (i < 0) { i -= this.g - 1; } if (j < 0) { j -= this.g - 1; } int i1 = i / this.g; int j1 = j / this.g; Random random = this.c.a(i1, j1, this.c.spigotConfig.villageSeed); // Spigot i1 *= this.g; j1 *= this.g; i1 += random.nextInt(this.g - this.h); j1 += random.nextInt(this.g - this.h); if (k == i1 && l == j1) { boolean flag = this.c.getWorldChunkManager().a(k * 16 + 8, l * 16 + 8, 0, WorldGenVillage.d); if (flag) { return true; } } return false; } protected StructureStart b(int i, int j) { return new WorldGenVillage.WorldGenVillageStart(this.c, this.b, i, j, this.f); } public static class WorldGenVillageStart extends StructureStart { private boolean c; public WorldGenVillageStart() {} public WorldGenVillageStart(World world, Random random, int i, int j, int k) { super(i, j); List list = WorldGenVillagePieces.a(random, k); WorldGenVillagePieces.WorldGenVillageStartPiece worldgenvillagepieces_worldgenvillagestartpiece = new WorldGenVillagePieces.WorldGenVillageStartPiece(world.getWorldChunkManager(), 0, random, (i << 4) + 2, (j << 4) + 2, list, k); this.a.add(worldgenvillagepieces_worldgenvillagestartpiece); worldgenvillagepieces_worldgenvillagestartpiece.a((StructurePiece) worldgenvillagepieces_worldgenvillagestartpiece, (List) this.a, random); List list1 = worldgenvillagepieces_worldgenvillagestartpiece.g; List list2 = worldgenvillagepieces_worldgenvillagestartpiece.f; int l; while (!list1.isEmpty() || !list2.isEmpty()) { StructurePiece structurepiece; if (list1.isEmpty()) { l = random.nextInt(list2.size()); structurepiece = (StructurePiece) list2.remove(l); structurepiece.a((StructurePiece) worldgenvillagepieces_worldgenvillagestartpiece, (List) this.a, random); } else { l = random.nextInt(list1.size()); structurepiece = (StructurePiece) list1.remove(l); structurepiece.a((StructurePiece) worldgenvillagepieces_worldgenvillagestartpiece, (List) this.a, random); } } this.c(); l = 0; Iterator iterator = this.a.iterator(); while (iterator.hasNext()) { StructurePiece structurepiece1 = (StructurePiece) iterator.next(); if (!(structurepiece1 instanceof WorldGenVillagePieces.WorldGenVillageRoadPiece)) { ++l; } } this.c = l > 2; } public boolean d() { return this.c; } public void a(NBTTagCompound nbttagcompound) { super.a(nbttagcompound); nbttagcompound.setBoolean("Valid", this.c); } public void b(NBTTagCompound nbttagcompound) { super.b(nbttagcompound); this.c = nbttagcompound.getBoolean("Valid"); } } }
gpl-3.0
JerryI00/Software-Adaptive-System
src/jmetal/util/comparators/ViolatedConstraintComparator.java
1968
// ViolatedConstraintComparator.java // // Author: // Antonio J. Nebro <antonio@lcc.uma.es> // Juan J. Durillo <durillo@lcc.uma.es> // // Copyright (c) 2011 Antonio J. Nebro, Juan J. Durillo // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. package jmetal.util.comparators; import jmetal.core.Solution; import java.util.Comparator; /** * This class implements a <code>Comparator</code> (a method for comparing * <code>Solution</code> objects) based on the number of violated constraints. */ public class ViolatedConstraintComparator implements Comparator{ /** * Compares two solutions. * @param o1 Object representing the first <code>Solution</code>. * @param o2 Object representing the second <code>Solution</code>. * @return -1, or 0, or 1 if o1 is less than, equal, or greater than o2, * respectively. */ public int compare(Object o1, Object o2) { Solution solution1 = (Solution) o1; Solution solution2 = (Solution) o2; if (solution1.getNumberOfViolatedConstraint() < solution2.getNumberOfViolatedConstraint()) { return -1; } else if (solution2.getNumberOfViolatedConstraint() < solution1.getNumberOfViolatedConstraint()) { return 1; } return 0; } // compare } // ViolatedConstraintComparator
gpl-3.0
k0smik0/FaCI
Analyzer/faci/src/grapher/net/iubris/faci/grapher/holder/_di/annotations/graphviewer/InteractionsGraphViewer.java
430
package net.iubris.faci.grapher.holder._di.annotations.graphviewer; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import javax.inject.Qualifier; @Qualifier @Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.METHOD }) @Retention(RetentionPolicy.RUNTIME) public @interface InteractionsGraphViewer {}
gpl-3.0
aviau/syncany-gbp
syncany-lib/src/test/java/org/syncany/tests/scenarios/longrunning/LongRunningLotsOfSmallFilesScenarioTest.java
1739
/* * Syncany, www.syncany.org * Copyright (C) 2011-2014 Philipp C. Heckel <philipp.heckel@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 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.syncany.tests.scenarios.longrunning; import static org.syncany.tests.util.TestAssertUtil.assertFileListEquals; import org.junit.Test; import org.syncany.plugins.transfer.TransferSettings; import org.syncany.tests.util.TestClient; import org.syncany.tests.util.TestConfigUtil; public class LongRunningLotsOfSmallFilesScenarioTest { @Test public void testLotsOfSmallFiles() throws Exception { // Setup TransferSettings testConnection = TestConfigUtil.createTestLocalConnection(); TestClient clientA = new TestClient("A", testConnection); TestClient clientB = new TestClient("B", testConnection); for (int i=0; i<10000; i++) { clientA.createNewFile("file"+i, 100+i); } clientA.up(); // This has caused a heap space exception clientB.down(); assertFileListEquals(clientA.getLocalFilesExcludeLockedAndNoRead(), clientB.getLocalFilesExcludeLockedAndNoRead()); // Tear down clientA.deleteTestData(); clientB.deleteTestData(); } }
gpl-3.0
metasfresh/metasfresh-webui
src/main/java/de/metas/ui/web/payment_allocation/process/PaymentsViewAllocateCommand.java
6840
package de.metas.ui.web.payment_allocation.process; import java.time.LocalDate; import java.util.List; import java.util.Optional; import javax.annotation.Nullable; import org.adempiere.exceptions.AdempiereException; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import de.metas.banking.payment.paymentallocation.service.AllocationAmounts; import de.metas.banking.payment.paymentallocation.service.PayableDocument; import de.metas.banking.payment.paymentallocation.service.PaymentAllocationBuilder; import de.metas.banking.payment.paymentallocation.service.PaymentAllocationBuilder.PayableRemainingOpenAmtPolicy; import de.metas.banking.payment.paymentallocation.service.PaymentAllocationResult; import de.metas.banking.payment.paymentallocation.service.PaymentDocument; import de.metas.currency.CurrencyCode; import de.metas.money.CurrencyId; import de.metas.money.Money; import de.metas.money.MoneyService; import de.metas.organization.OrgId; import de.metas.ui.web.payment_allocation.InvoiceRow; import de.metas.ui.web.payment_allocation.PaymentRow; import de.metas.util.lang.CoalesceUtil; import de.metas.util.time.SystemTime; import lombok.Builder; import lombok.NonNull; import lombok.Singular; /* * #%L * metasfresh-webui-api * %% * Copyright (C) 2020 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ public class PaymentsViewAllocateCommand { private final MoneyService moneyService; private final PaymentRow paymentRow; private final List<InvoiceRow> invoiceRows; private final PayableRemainingOpenAmtPolicy payableRemainingOpenAmtPolicy; private final LocalDate dateTrx; @Builder private PaymentsViewAllocateCommand( @NonNull final MoneyService moneyService, @Nullable final PaymentRow paymentRow, @NonNull @Singular final ImmutableList<InvoiceRow> invoiceRows, @Nullable final PayableRemainingOpenAmtPolicy payableRemainingOpenAmtPolicy, @Nullable final LocalDate dateTrx) { this.moneyService = moneyService; this.paymentRow = paymentRow; this.invoiceRows = invoiceRows; this.payableRemainingOpenAmtPolicy = CoalesceUtil.coalesce(payableRemainingOpenAmtPolicy, PayableRemainingOpenAmtPolicy.DO_NOTHING); this.dateTrx = dateTrx != null ? dateTrx : SystemTime.asLocalDate(); } public Optional<PaymentAllocationResult> dryRun() { final PaymentAllocationBuilder builder = preparePaymentAllocationBuilder(); if (builder == null) { return Optional.empty(); } final PaymentAllocationResult result = builder.dryRun().build(); return Optional.of(result); } public PaymentAllocationResult run() { final PaymentAllocationBuilder builder = preparePaymentAllocationBuilder(); if (builder == null) { throw new AdempiereException("Invalid allocation") .appendParametersToMessage() .setParameter("paymentRow", paymentRow) .setParameter("invoiceRows", invoiceRows) .setParameter("payableRemainingOpenAmtPolicy", payableRemainingOpenAmtPolicy); } return builder.build(); } private PaymentAllocationBuilder preparePaymentAllocationBuilder() { if (paymentRow == null && invoiceRows.isEmpty()) { return null; } final List<PaymentDocument> paymentDocuments = paymentRow != null ? ImmutableList.of(toPaymentDocument(paymentRow)) : ImmutableList.of(); final ImmutableList<PayableDocument> invoiceDocuments = invoiceRows.stream() .map(this::toPayableDocument) .collect(ImmutableList.toImmutableList()); return PaymentAllocationBuilder.newBuilder() .orgId(getOrgId()) .currencyId(getCurrencyId()) .dateTrx(dateTrx) .dateAcct(dateTrx) .paymentDocuments(paymentDocuments) .payableDocuments(invoiceDocuments) .allowPartialAllocations(true) .payableRemainingOpenAmtPolicy(payableRemainingOpenAmtPolicy); } private OrgId getOrgId() { if (paymentRow != null) { return paymentRow.getOrgId(); } if (!invoiceRows.isEmpty()) { final ImmutableSet<OrgId> invoiceOrgIds = invoiceRows.stream() .map(invoiceRow -> invoiceRow.getOrgId()) .collect(ImmutableSet.toImmutableSet()); if (invoiceOrgIds.size() != 1) { throw new AdempiereException("More than one organization found"); } else { return invoiceOrgIds.iterator().next(); } } throw new AdempiereException("Cannot detect organization if no payments and no invoices were specified"); } private CurrencyId getCurrencyId() { final CurrencyCode currencyCode = getCurrencyCode(); return moneyService.getCurrencyIdByCurrencyCode(currencyCode); } private CurrencyCode getCurrencyCode() { if (paymentRow != null) { return paymentRow.getOpenAmt().getCurrencyCode(); } if (!invoiceRows.isEmpty()) { final ImmutableSet<CurrencyCode> invoiceCurrencyCodes = invoiceRows.stream() .map(invoiceRow -> invoiceRow.getOpenAmt().getCurrencyCode()) .collect(ImmutableSet.toImmutableSet()); if (invoiceCurrencyCodes.size() != 1) { throw new AdempiereException("More than one currency found"); } else { return invoiceCurrencyCodes.iterator().next(); } } throw new AdempiereException("Cannot detect currency if no payments and no invoices were specified"); } private PayableDocument toPayableDocument(final InvoiceRow row) { final Money openAmt = moneyService.toMoney(row.getOpenAmt()); final Money discountAmt = moneyService.toMoney(row.getDiscountAmt()); return PayableDocument.builder() .invoiceId(row.getInvoiceId()) .bpartnerId(row.getBPartnerId()) .documentNo(row.getDocumentNo()) .isSOTrx(row.getSoTrx().toBoolean()) .creditMemo(row.isCreditMemo()) .openAmt(openAmt) .amountsToAllocate(AllocationAmounts.builder() .payAmt(openAmt) .discountAmt(discountAmt) .build()) .build(); } private PaymentDocument toPaymentDocument(final PaymentRow row) { final Money openAmt = moneyService.toMoney(row.getOpenAmt()); return PaymentDocument.builder() .paymentId(row.getPaymentId()) .bpartnerId(row.getBPartnerId()) .documentNo(row.getDocumentNo()) .paymentDirection(row.getPaymentDirection()) .openAmt(openAmt) .amountToAllocate(openAmt) .build(); } }
gpl-3.0