repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
rohitmohan96/ceylon-ide-eclipse | plugins/com.redhat.ceylon.eclipse.ui/src/com/redhat/ceylon/eclipse/core/model/CeylonBinaryUnit.java | 4602 | package com.redhat.ceylon.eclipse.core.model;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jdt.core.IClassFile;
import org.eclipse.jdt.core.IJavaElement;
import com.redhat.ceylon.model.typechecker.model.Declaration;
import com.redhat.ceylon.model.typechecker.model.Package;
import com.redhat.ceylon.eclipse.core.typechecker.ExternalPhasedUnit;
/*
* Created inside the JDTModelLoader.getCompiledUnit() function if the unit is a ceylon one
*/
public class CeylonBinaryUnit extends CeylonUnit implements IJavaModelAware {
IClassFile classFileElement;
CeylonToJavaMatcher ceylonToJavaMatcher;
public CeylonBinaryUnit(IClassFile typeRoot, String fileName, String relativePath, String fullPath, Package pkg) {
super();
this.classFileElement = typeRoot;
ceylonToJavaMatcher = new CeylonToJavaMatcher(typeRoot);
setFilename(fileName);
setRelativePath(relativePath);
setFullPath(fullPath);
setPackage(pkg);
}
/*
* Might be null if no source is linked to this ModelLoader-originating unit
*
* (non-Javadoc)
* @see com.redhat.ceylon.eclipse.core.model.CeylonUnit#getPhasedUnit()
*/
@Override
public ExternalPhasedUnit getPhasedUnit() {
return (ExternalPhasedUnit) super.getPhasedUnit();
}
public IClassFile getTypeRoot() {
return classFileElement;
}
public IProject getProject() {
if (getTypeRoot() != null) {
return (IProject) getTypeRoot().getJavaProject().getProject();
}
return null;
}
@Override
protected ExternalPhasedUnit setPhasedUnitIfNecessary() {
ExternalPhasedUnit phasedUnit = null;
if (phasedUnitRef != null) {
phasedUnit = (ExternalPhasedUnit) phasedUnitRef.get();
}
if (phasedUnit == null) {
try {
JDTModule module = getModule();
if (module.getArtifact() != null) {
String binaryUnitRelativePath = getFullPath().replace(module.getArtifact().getPath() + "!/", "");
String sourceUnitRelativePath = module.toSourceUnitRelativePath(binaryUnitRelativePath);
if (sourceUnitRelativePath != null) {
phasedUnit = (ExternalPhasedUnit) module.getPhasedUnitFromRelativePath(sourceUnitRelativePath);
}
}
} catch(Exception e) {
e.printStackTrace();
}
}
return phasedUnit != null ? createPhasedUnitRef(phasedUnit) : null;
}
@Override
public String getSourceFileName() {
String sourceRelativePath = getSourceRelativePath();
if (sourceRelativePath == null) {
return null;
}
String[] pathElements = sourceRelativePath.split("/");
return pathElements[pathElements.length-1];
}
@Override
public String getSourceRelativePath() {
return getModule().toSourceUnitRelativePath(getRelativePath());
}
@Override
public String getSourceFullPath() {
String sourceArchivePath = getModule().getSourceArchivePath();
if (sourceArchivePath == null) {
return null;
}
return sourceArchivePath + "!/" + getSourceRelativePath();
}
@Override
public String getCeylonSourceRelativePath() {
return getModule().getCeylonDeclarationFile(getSourceRelativePath());
}
@Override
public String getCeylonSourceFullPath() {
String sourceArchivePath = getModule().getSourceArchivePath();
if (sourceArchivePath == null) {
return null;
}
return sourceArchivePath + "!/" + getCeylonSourceRelativePath();
}
@Override
public IJavaElement toJavaElement(Declaration ceylonDeclaration, IProgressMonitor monitor) {
return ceylonToJavaMatcher.searchInClass(ceylonDeclaration, monitor);
}
@Override
public IJavaElement toJavaElement(Declaration ceylonDeclaration) {
return ceylonToJavaMatcher.searchInClass(ceylonDeclaration, null);
}
@Override
public String getCeylonFileName() {
String ceylonSourceRelativePath = getCeylonSourceRelativePath();
if (ceylonSourceRelativePath == null || ceylonSourceRelativePath.isEmpty()) {
return null;
}
String[] splitedPath = ceylonSourceRelativePath.split("/");
return splitedPath[splitedPath.length-1];
}
}
| epl-1.0 |
spenap/pennybank | src/main/java/com/googlecode/pennybank/swing/view/category/CategoriesComboBox.java | 1220 | /**
*
*/
package com.googlecode.pennybank.swing.view.category;
import javax.swing.JComboBox;
import com.googlecode.pennybank.App;
import com.googlecode.pennybank.model.category.entity.Category;
import com.googlecode.pennybank.swing.controller.category.CategoryComboBoxListener;
import com.googlecode.pennybank.swing.view.util.MessageManager;
/**
* Combo box extension which allow an user to pick up between the existing
* categories, choose a non-categorized option, or create a new one
*
* @author spenap
*/
@SuppressWarnings("serial")
public class CategoriesComboBox extends JComboBox {
/**
* Creates a combo box populated with the existing categories, following the
* conventions of a pop up menu.
*/
public CategoriesComboBox() {
this.putClientProperty("JComboBox.isPopDown", Boolean.FALSE);
updateModel();
addActionListener(new CategoryComboBoxListener(this));
}
/**
* Updates the combo box contents
*/
public void updateModel() {
this.removeAllItems();
this.addItem(MessageManager.getMessage("Category.Uncategorized"));
for (Category category : App.getCategories()) {
this.addItem(category.getName());
}
this.addItem(MessageManager.getMessage("Category.New"));
}
}
| epl-1.0 |
eveCSS/eveCSS | bundles/de.ptb.epics.eve.editor/src/de/ptb/epics/eve/editor/SelectionTracker.java | 633 | package de.ptb.epics.eve.editor;
import org.apache.log4j.Logger;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.ISelectionListener;
import org.eclipse.ui.IWorkbenchPart;
/**
*
*
* @author Marcus Michalsky
* @since 1.1
*/
public class SelectionTracker implements ISelectionListener {
private static Logger logger =
Logger.getLogger(SelectionTracker.class.getName());
/**
* {@inheritDoc}
*/
@Override
public void selectionChanged(IWorkbenchPart part, ISelection selection) {
logger.debug("selection changed. Part: " + part.getTitle() +
" Selected Item: " + selection.toString());
}
} | epl-1.0 |
OneXY/pss | src/main/java/com/onexy/pss/service/impl/EmployeeServiceImpl.java | 1588 | package com.onexy.pss.service.impl;
import java.util.List;
import com.onexy.pss.domain.Employee;
import com.onexy.pss.service.IEmployeeService;
public class EmployeeServiceImpl extends BaseServiceImpl<Employee> implements
IEmployeeService {
@Override
public boolean findByName(String name) {
String hql = "select count(o) from Employee o where o.name = ?";
List<Long> result = baseDao.findByHql(hql, name);
if (result.get(0).intValue() > 0) {
logger.info("用户名已存在");
return false;
}
logger.info("用户名不存在");
return true;
}
@Override
public Employee findForLogin(String username, String password) {
String hql = "select o from Employee o where o.name=? and o.password=?";
List<Employee> list = baseDao.findByHql(hql, username, password);
if (list.size()>0) {
return list.get(0);
}
return null;
}
@Override
public List<String> getAllResourceMethods() {
return baseDao.findByHql("select o.method from Resource o");
}
@Override
public List<String> findMethodsByLoginUser(Long id) {
String hql = "select distinct res.method from Employee o join o.roles r join r.resources res where o.id = ?";
return baseDao.findByHql(hql, id);
}
@Override
public List<Employee> findBuerysByDeptName(String deptName) {
String hql = "select e from Employee e where e.department.name=?";
return baseDao.findByHql(hql, deptName);
}
@Override
public List<Employee> findKeepersByDeptName(String deptName) {
String hql = "select e from Employee e where e.department.name=?";
return baseDao.findByHql(hql, deptName);
}
}
| epl-1.0 |
maieralex/smarthome | extensions/binding/org.eclipse.smarthome.binding.digitalstrom/src/main/java/org/eclipse/smarthome/binding/digitalstrom/internal/digitalSTROMLibary/digitalSTROMStructure/DetailedGroupInfo.java | 910 | /**
* 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.binding.digitalstrom.internal.digitalSTROMLibary.digitalSTROMStructure;
/**
* Copyright (c) 2010-2014, openHAB.org 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
*/
import java.util.List;
/**
* @author Alexander Betker
* @since 1.3.0
*/
public interface DetailedGroupInfo extends Group {
public List<String> getDeviceList();
}
| epl-1.0 |
gwt-plugins/gwt-eclipse-plugin | plugins/com.gwtplugins.gdt.eclipse.suite.update/src/com/google/gdt/eclipse/suite/update/FeatureUpdateCheckersMap.java | 2420 | /*******************************************************************************
* Copyright 2012 Google Inc. All Rights Reserved.
*
* 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
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*******************************************************************************/
package com.google.gdt.eclipse.suite.update;
import com.google.gdt.eclipse.core.update.internal.core.FeatureUpdateChecker;
import com.google.gdt.eclipse.suite.update.FeatureUpdateCheckersMap.UpdateSiteToken;
import java.util.EnumMap;
import java.util.Map;
/**
* A map from {@link UpdateSiteToken} to {@link FeatureUpdateChecker}. This is
* used to determine which FeatureUpdateChecker is to be used if the update site
* URL has the token given by UpdateSiteToken. FeatureUpdateChecker is used to
* scan the downloaded contents from the update site to determine if an update
* is available. The class is created so that we don't have to write
* EnumMap<UpdateSiteToken, FeatureUpdateChecker> again and again.
*/
public class FeatureUpdateCheckersMap
extends EnumMap<UpdateSiteToken, FeatureUpdateChecker> {
/**
* The token is a unique substring in the update site URL which will decide if
* the update site is for the GWT SDK.
*/
public enum UpdateSiteToken {
// TODO(deepanshu): Add a build time flag that will choose tokens based on the build being from
// trunk or release branch.
GWT_SDK("gwt");
private final String token;
private UpdateSiteToken(String token) {
this.token = token;
}
public String getToken() {
return token;
}
}
public FeatureUpdateCheckersMap(Class<UpdateSiteToken> keyType) {
super(keyType);
}
public FeatureUpdateCheckersMap(EnumMap<UpdateSiteToken, ? extends FeatureUpdateChecker> m) {
super(m);
}
public FeatureUpdateCheckersMap(Map<UpdateSiteToken, ? extends FeatureUpdateChecker> m) {
super(m);
}
}
| epl-1.0 |
michele-loreti/jResp | core/org.cmg.jresp.pastry/pastry-2.1/src/rice/persistence/Catalog.java | 6949 | /*******************************************************************************
"FreePastry" Peer-to-Peer Application Development Substrate
Copyright 2002-2007, Rice University. Copyright 2006-2007, Max Planck Institute
for Software Systems. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of Rice University (RICE), Max Planck Institute for Software
Systems (MPI-SWS) nor the names of its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
This software is provided by RICE, MPI-SWS and the contributors on an "as is"
basis, without any representations or warranties of any kind, express or implied
including, but not limited to, representations or warranties of
non-infringement, merchantability or fitness for a particular purpose. In no
event shall RICE, MPI-SWS or contributors be liable for any direct, indirect,
incidental, special, exemplary, or consequential damages (including, but not
limited to, procurement of substitute goods or services; loss of use, data, or
profits; or business interruption) however caused and on any theory of
liability, whether in contract, strict liability, or tort (including negligence
or otherwise) arising in any way out of the use of this software, even if
advised of the possibility of such damage.
*******************************************************************************/
package rice.persistence;
import java.util.*;
/*
* @(#) Catalog.java
*
* @author Ansley Post
* @author Alan Mislove
*
* @version $Id: Catalog.java 4654 2009-01-08 16:33:07Z jeffh $
*/
import java.io.*;
import rice.*;
import rice.p2p.commonapi.*;
/**
* This interface is the abstraction of something which holds objects
* which are available for lookup. This interface does not, however,
* specify how the objects are inserted, and makes NO guarantees as to
* whether objects available at a given point in time will be available
* at a later time.
*
* Implementations of the Catalog interface are designed to be interfaces
* which specify how objects are inserted and stored, and are designed to
* include a cache and persistent storage interface.
*/
@SuppressWarnings("unchecked")
public interface Catalog {
/**
* Returns whether or not an object is present in the location <code>id</code>.
*
* @param id The id of the object in question.
* @return Whether or not an object is present at id.
*/
public boolean exists(Id id);
/**
* Returns the object identified by the given id, or <code>null</code> if
* there is no corresponding object (through receiveResult on c).
*
* @param id The id of the object in question.
* @param c The command to run once the operation is complete
*/
public void getObject(Id id, Continuation c);
/**
* Returns the metadata associated with the provided object, or null if
* no metadata exists. The metadata must be stored in memory, so this
* operation is guaranteed to be fast and non-blocking.
*
* The metadata returned from this method must *NOT* be mutated in any way,
* as the actual reference to the internal object is returned. Mutating
* this metadata may make the internal indices incorrect, resulting
* in undefined behavior. Changing the metadata should be done by creating
* a new metadata object and calling setMetadata().
*
* @param id The id for which the metadata is needed
* @return The metadata, or null if none exists
*/
public Serializable getMetadata(Id id);
/**
* Updates the metadata stored under the given key to be the provided
* value. As this may require a disk access, the requestor must
* also provide a continuation to return the result to.
*
* @param id The id for the metadata
* @param metadata The metadata to store
* @param c The command to run once the operation is complete
*/
public void setMetadata(Id id, Serializable metadata, Continuation command);
/**
* Renames the given object to the new id. This method is potentially faster
* than store/cache and unstore/uncache.
*
* @param oldId The id of the object in question.
* @param newId The new id of the object in question.
* @param c The command to run once the operation is complete
*/
public void rename(Id oldId, Id newId, Continuation c);
/**
* Return the objects identified by the given range of ids. The IdSet
* returned contains the Ids of the stored objects. The range is
* partially inclusive, the lower range is inclusive, and the upper
* exclusive.
*
* NOTE: This method blocks so if the behavior of this method changes and
* no longer stored in memory, this method may be deprecated.
*
* @param range The range to query
* @return The idset containing the keys
*/
public IdSet scan(IdRange range);
/**
* Return all objects currently stored by this catalog
*
* NOTE: This method blocks so if the behavior of this method changes and
* no longer stored in memory, this method may be deprecated.
*
* @return The idset containing the keys
*/
public IdSet scan();
/**
* Returns a map which contains keys mapping ids to the associated
* metadata.
*
* @param range The range to query
* @return The map containing the keys
*/
public SortedMap scanMetadata(IdRange range);
/**
* Returns a map which contains keys mapping ids to the associated
* metadata.
*
* @return The treemap mapping ids to metadata
*/
public SortedMap scanMetadata();
/**
* Returns the submapping of ids which have metadata less than the provided
* value.
*
* @param value The maximal metadata value
* @return The submapping
*/
public SortedMap scanMetadataValuesHead(Object value);
/**
* Returns the submapping of ids which have metadata null
*
* @return The submapping
*/
public SortedMap scanMetadataValuesNull();
/**
* Returns the number of Ids currently stored in the catalog
*
* @return The number of ids in the catalog
*/
public int getSize();
/**
* Returns the total size of the stored data in bytes.
*
* @return The total storage size
*/
public long getTotalSize();
/**
* Method which is used to erase all data stored in the Catalog.
* Use this method with care!
*
* @param c The command to run once done
*/
public void flush(Continuation c);
}
| epl-1.0 |
whizzosoftware/hobson-hub-api | src/main/java/com/whizzosoftware/hobson/api/plugin/PluginManager.java | 7080 | /*
*******************************************************************************
* Copyright (c) 2014 Whizzo Software, LLC.
* 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 com.whizzosoftware.hobson.api.plugin;
import com.whizzosoftware.hobson.api.device.proxy.HobsonDeviceProxy;
import com.whizzosoftware.hobson.api.hub.HubContext;
import com.whizzosoftware.hobson.api.image.ImageInputStream;
import com.whizzosoftware.hobson.api.property.PropertyContainer;
import com.whizzosoftware.hobson.api.variable.DeviceVariableContext;
import com.whizzosoftware.hobson.api.variable.DeviceVariableState;
import com.whizzosoftware.hobson.api.variable.GlobalVariable;
import com.whizzosoftware.hobson.api.variable.GlobalVariableContext;
import io.netty.util.concurrent.Future;
import java.io.File;
import java.util.Collection;
import java.util.Map;
/**
* An interface for managing Hobson plugin functions.
*
* Note that this interface differentiates between local plugins (i.e. plugins installed on the hub) and remote
* plugins (i.e. plugins available from a remote repository).
*
* @author Dan Noguerol
* @since hobson-hub-api 0.1.6
*/
public interface PluginManager {
/**
* Add a remote repository.
*
* @param uri the URI of the repository
*/
void addRemoteRepository(String uri);
/**
* Returns a File for a plugin's data directory.
*
* @param ctx the context of the plugin
*
* @return a File instance
*/
File getDataDirectory(PluginContext ctx);
/**
* Returns a File for a named file located in a plugin's data directory.
*
* @param ctx the context of the plugin requesting the file
* @param filename the name of the data file
*
* @return a File instance (or null if not found)
*/
File getDataFile(PluginContext ctx, String filename);
/**
* Returns a global variable.
*
* @param gvctx the variable context
*
* @return a GlobalVariable instance
*/
GlobalVariable getGlobalVariable(GlobalVariableContext gvctx);
/**
* Returns all global variables published by a plugin.
*
* @param pctx the plugin context
*
* @return a Collection of GlobalVariable instances
*/
Collection<GlobalVariable> getGlobalVariables(PluginContext pctx);
/**
* Retrieves a specific plugin.
*
* @param ctx the context of the target plugin
*
* @return a HobsonPlugin instance (or null if not found)
*/
HobsonLocalPluginDescriptor getLocalPlugin(PluginContext ctx);
/**
* Returns the plugin level configuration.
*
* @param ctx the context of the target plugin
*
* @return a Dictionary (or null if there is no configuration)
*/
PropertyContainer getLocalPluginConfiguration(PluginContext ctx);
/**
* Returns the last check in time of a plugin's device.
*
* @param ctx the plugin context
* @param deviceId the device ID
*
* @return the last check in time (or null if the device has never checked in)
*/
Long getLocalPluginDeviceLastCheckin(PluginContext ctx, String deviceId);
/**
* Returns information about a plugin device variable.
*
* @param ctx the variable context
*
* @return a DeviceVariableState instance
*/
DeviceVariableState getLocalPluginDeviceVariable(DeviceVariableContext ctx);
/**
* Returns a plugin's icon.
*
* @param ctx the context of the target plugin
*
* @return an ImageInputStream (or null if the plugin has no icon and no default was found)
*/
ImageInputStream getLocalPluginIcon(PluginContext ctx);
/**
* Returns information about all local plugins installed on the hub.
*
* @param ctx the hub context
*
* @return a Collection of HobsonLocalPluginDescriptor instances
*/
Collection<HobsonLocalPluginDescriptor> getLocalPlugins(HubContext ctx);
/**
* Retrieves descriptor for a remotely available plugin.
*
* @param ctx the context of the plugin
* @param version the plugin version
* @return a PluginDescriptor instance
*/
HobsonPluginDescriptor getRemotePlugin(PluginContext ctx, String version);
/**
* Retrieve descriptors for all remotely available plugins.
*
* @param ctx the context of the target hub
*
* @return a PluginList
*/
Collection<HobsonPluginDescriptor> getRemotePlugins(HubContext ctx);
/**
* Retrieve the latest version of available remote plugins.
*
* @param ctx the hub context
*
* @return a Map of plugin ID to version string
*/
Map<String,String> getRemotePluginVersions(HubContext ctx);
/**
* Returns the remote repositories that have been enabled.
*
* @return a Collection of String URIs
*/
Collection<String> getRemoteRepositories();
/**
* Indicates whether a plugin has published a device variable.
*
* @param ctx the device variable context
*
* @return a boolean
*/
boolean hasLocalPluginDeviceVariable(DeviceVariableContext ctx);
/**
* Installs a specific version of a remote plugin.
*
* @param ctx the context of the target plugin
* @param pluginVersion the plugin version to install
*/
void installRemotePlugin(PluginContext ctx, String pluginVersion);
/**
* Reloads the specified plugin.
*
* @param ctx the context of the target plugin
*/
void reloadLocalPlugin(PluginContext ctx);
/**
* Removes a remote repository.
*
* @param uri the URI of the repository to remove
*/
void removeRemoteRepository(String uri);
/**
* Sets the plugin level configuration.
* @param ctx the context of the target plugin
* @param config the plugin configuration
*/
void setLocalPluginConfiguration(PluginContext ctx, Map<String,Object> config);
/**
* Sets an individual plugin level configuration property.
*
* @param ctx the context of the target hub
* @param name the configuration property name
* @param value the configuration property value
*/
void setLocalPluginConfigurationProperty(PluginContext ctx, String name, Object value);
/**
* Starts a plugin device.
*
* @param device the device proxy
* @param name the device's name
* @param config the device's configuration
* @param runnable a Runnable to execute after the device has started.
*
* @return a Future that indicates when the device has finished starting
*/
Future startPluginDevice(final HobsonDeviceProxy device, String name, final Map<String,Object> config, final Runnable runnable);
}
| epl-1.0 |
mattnl/openhab | bundles/binding/org.openhab.binding.maxcube/src/main/java/org/openhab/binding/maxcube/internal/message/S_Command.java | 3160 | /**
* Copyright (c) 2010-2015, openHAB.org 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.openhab.binding.maxcube.internal.message;
import org.apache.commons.codec.binary.Base64;
import org.openhab.binding.maxcube.internal.Utils;
import org.slf4j.Logger;
/**
* Command to be send via the MAX!Cube protocol.
*
* @author Andreas Heil (info@aheil.de)
* @author Marcel Verpaalen
* @since 1.4.0
*/
public class S_Command {
private String baseString = "000440000000";
private boolean[] bits = null;
private String rfAddress = null;
private int roomId = -1;
/**
* Creates a new instance of the MAX! protocol S command.
*
* @param rfAddress
* the RF address the command is for
* @param roomId
* the room ID the RF address is mapped to
* @param setpointTemperature
* the desired setpoint temperature for the device.
*/
public S_Command(String rfAddress, int roomId, ThermostatModeType mode, double setpointTemperature) {
this.rfAddress = rfAddress;
this.roomId = roomId;
// Temperature setpoint, Temp uses 6 bits (bit 0:5),
// 20 deg C = bits 101000 = dec 40/2 = 20 deg C,
// you need 8 bits to send so add the 2 bits below (sample 10101000 = hex A8)
// bit 0,1 = 00 = Auto weekprog (no temp is needed)
int setpointValue = (int) (setpointTemperature * 2);
bits = Utils.getBits(setpointValue);
// default to perm setting
// AB => bit mapping
// 01 = Permanent
// 10 = Temporarily
if (mode.equals(ThermostatModeType.MANUAL)){
bits[7] = false; // A (MSB)
bits[6] = true; // B
} else if (mode.equals(ThermostatModeType.BOOST)){
bits[7] = true; // A (MSB)
bits[6] = true; // B
} else
{
bits[7] = false ; // A (MSB)
bits[6] = false; // B
}
}
/**
* Creates a new instance of the MAX! protocol S command.
*
* @param rfAddress
* the RF address the command is for
* @param roomId
* the room ID the RF address is mapped to
* @param mode
* the desired mode for the device.
*/
public S_Command(String rfAddress, int roomId, ThermostatModeType mode) {
this.rfAddress = rfAddress;
this.roomId = roomId;
// default to perm setting
// AB => bit mapping
// 01 = Permanent
// 10 = Temporarily
switch (mode) {
case VACATION:
case MANUAL:
//not implemented
break;
case AUTOMATIC:
bits = Utils.getBits(0);
break;
case BOOST:
bits = Utils.getBits(255);
break;
default:
// no further modes supported
}
}
/**
* Returns the Base64 encoded command string to be sent via the MAX!
* protocol.
*
* @return the string representing the command
*/
public String getCommandString() {
String commandString = baseString + rfAddress + Utils.toHex(roomId) + Utils.toHex(bits);
String encodedString = Base64.encodeBase64String(Utils.hexStringToByteArray(commandString));
return "s:" + encodedString;
}
} | epl-1.0 |
Yakindu/statecharts | test-plugins/org.yakindu.sct.generator.c.test/src/org/yakindu/sct/generator/c/test/AllCSpecificTests.java | 1030 | /**
* Copyright (c) 2014-2018 committers of YAKINDU 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:
* committers of YAKINDU - initial API and implementation
*/
package org.yakindu.sct.generator.c.test;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
/**
* Suite of all test cases that are specific to the C code generator and which are not defined by the
* set of cross target language tests.
*
* @author terfloth
*/
@RunWith(Suite.class)
@SuiteClasses({
ActiveBeforeInit.class,
OperationsWithoutBracesCustom.class,
InternalEventLifeCycleTest_Naming.class,
PedanticNoLocalEventsTest.class,
VariadicOperations.class,
StateNumTest.class,
TracingTest.class,
InEventQueueTest.class
})
public class AllCSpecificTests {
}
| epl-1.0 |
sleshchenko/che | plugins/plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/client/branch/BranchViewImpl.java | 9107 | /*
* Copyright (c) 2012-2018 Red Hat, Inc.
* 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:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.ide.ext.git.client.branch;
import static com.google.gwt.event.dom.client.KeyCodes.KEY_BACKSPACE;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ChangeEvent;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyPressEvent;
import com.google.gwt.safehtml.shared.SafeHtmlBuilder;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.ListBox;
import com.google.gwt.user.client.ui.ScrollPanel;
import com.google.gwt.user.client.ui.UIObject;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import elemental.dom.Element;
import elemental.html.TableCellElement;
import elemental.html.TableElement;
import java.util.List;
import java.util.stream.Collectors;
import javax.validation.constraints.NotNull;
import org.eclipse.che.api.git.shared.Branch;
import org.eclipse.che.ide.FontAwesome;
import org.eclipse.che.ide.ext.git.client.GitLocalizationConstant;
import org.eclipse.che.ide.ext.git.client.GitResources;
import org.eclipse.che.ide.ui.list.FilterableSimpleList;
import org.eclipse.che.ide.ui.list.SimpleList;
import org.eclipse.che.ide.ui.window.Window;
import org.eclipse.che.ide.util.dom.Elements;
import org.vectomatic.dom.svg.ui.SVGResource;
/**
* The implementation of {@link BranchView}.
*
* @author Andrey Plotnikov
* @author Igor Vinokur
*/
@Singleton
public class BranchViewImpl extends Window implements BranchView {
interface BranchViewImplUiBinder extends UiBinder<Widget, BranchViewImpl> {}
private static BranchViewImplUiBinder ourUiBinder = GWT.create(BranchViewImplUiBinder.class);
Button btnClose;
Button btnRename;
Button btnDelete;
Button btnCreate;
Button btnCheckout;
@UiField ScrollPanel branchesPanel;
@UiField ListBox localRemoteFilter;
@UiField Label searchFilterLabel;
@UiField Label searchFilterIcon;
@UiField(provided = true)
final GitResources res;
@UiField(provided = true)
final GitLocalizationConstant locale;
private FilterableSimpleList<Branch> branchesList;
private ActionDelegate delegate;
@Inject
protected BranchViewImpl(
GitResources resources,
GitLocalizationConstant locale,
org.eclipse.che.ide.Resources coreRes) {
this.res = resources;
this.locale = locale;
this.ensureDebugId("git-branches-window");
setTitle(locale.branchTitle());
setWidget(ourUiBinder.createAndBindUi(this));
searchFilterIcon.getElement().setInnerHTML(FontAwesome.SEARCH);
TableElement branchElement = Elements.createTableElement();
branchElement.setAttribute("style", "width: 100%");
SimpleList.ListEventDelegate<Branch> listBranchesDelegate =
new SimpleList.ListEventDelegate<Branch>() {
public void onListItemClicked(Element itemElement, Branch itemData) {
branchesList.getSelectionModel().setSelectedItem(itemData);
delegate.onBranchSelected(itemData);
}
public void onListItemDoubleClicked(Element listItemBase, Branch itemData) {}
};
SimpleList.ListItemRenderer<Branch> listBranchesRenderer =
new SimpleList.ListItemRenderer<Branch>() {
@Override
public void render(Element itemElement, Branch itemData) {
TableCellElement label = Elements.createTDElement();
SafeHtmlBuilder sb = new SafeHtmlBuilder();
sb.appendHtmlConstant("<table><tr><td>");
sb.appendHtmlConstant(
"<div id=\""
+ UIObject.DEBUG_ID_PREFIX
+ "git-branches-"
+ itemData.getDisplayName()
+ "\">");
sb.appendEscaped(itemData.getDisplayName());
sb.appendHtmlConstant("</td>");
if (itemData.isActive()) {
SVGResource icon = res.currentBranch();
sb.appendHtmlConstant("<td><img src=\"" + icon.getSafeUri().asString() + "\"></td>");
}
sb.appendHtmlConstant("</tr></table>");
label.setInnerHTML(sb.toSafeHtml().asString());
itemElement.appendChild(label);
}
@Override
public Element createElement() {
return Elements.createTRElement();
}
};
branchesList =
FilterableSimpleList.create(
(SimpleList.View) branchElement,
coreRes.defaultSimpleListCss(),
listBranchesRenderer,
listBranchesDelegate,
this::onFilterChanged);
this.branchesPanel.add(branchesList);
this.localRemoteFilter.addItem("All", "all");
this.localRemoteFilter.addItem("Local", "local");
this.localRemoteFilter.addItem("Remote", "remote");
createButtons();
}
private void onFilterChanged(String filter) {
if (branchesList.getSelectionModel().getSelectedItem() == null) {
delegate.onBranchUnselected();
}
delegate.onSearchFilterChanged(filter);
}
@UiHandler("localRemoteFilter")
public void onLocalRemoteFilterChanged(ChangeEvent event) {
delegate.onLocalRemoteFilterChanged();
}
private void createButtons() {
btnClose =
createButton(locale.buttonClose(), "git-branches-close", event -> delegate.onClose());
addButtonToFooter(btnClose);
btnRename =
createButton(
locale.buttonRename(), "git-branches-rename", event -> delegate.onRenameClicked());
addButtonToFooter(btnRename);
btnDelete =
createButton(
locale.buttonDelete(), "git-branches-delete", event -> delegate.onDeleteClicked());
addButtonToFooter(btnDelete);
btnCreate =
createButton(
locale.buttonCreate(), "git-branches-create", event -> delegate.onCreateClicked());
addButtonToFooter(btnCreate);
btnCheckout =
createButton(
locale.buttonCheckout(),
"git-branches-checkout",
event -> delegate.onCheckoutClicked());
addButtonToFooter(btnCheckout);
}
@Override
protected void onKeyDownEvent(KeyDownEvent event) {
if (event.getNativeEvent().getKeyCode() == KEY_BACKSPACE) {
branchesList.removeLastCharacter();
}
}
@Override
protected void onKeyPressEvent(KeyPressEvent event) {
branchesList.addCharacterToFilter(String.valueOf(event.getCharCode()));
}
@Override
protected void onEscapeKey() {
if (branchesList.getFilter().isEmpty()) {
super.onEscapeKey();
} else {
branchesList.resetFilter();
}
}
@Override
protected void onEnterClicked() {
if (isWidgetFocused(btnClose)) {
delegate.onClose();
return;
}
if (isWidgetFocused(btnRename)) {
delegate.onRenameClicked();
return;
}
if (isWidgetFocused(btnDelete)) {
delegate.onDeleteClicked();
return;
}
if (isWidgetFocused(btnCreate)) {
delegate.onCreateClicked();
return;
}
if (isWidgetFocused(btnCheckout)) {
delegate.onCheckoutClicked();
}
}
@Override
public void setDelegate(ActionDelegate delegate) {
this.delegate = delegate;
}
@Override
public void setBranches(@NotNull List<Branch> branches) {
branchesList.render(
branches.stream().collect(Collectors.toMap(Branch::getDisplayName, branch -> branch)));
if (branchesList.getSelectionModel().getSelectedItem() == null) {
delegate.onBranchUnselected();
}
}
@Override
public void setEnableDeleteButton(boolean enabled) {
btnDelete.setEnabled(enabled);
}
@Override
public void setEnableCheckoutButton(boolean enabled) {
btnCheckout.setEnabled(enabled);
}
@Override
public void setEnableRenameButton(boolean enabled) {
btnRename.setEnabled(enabled);
}
@Override
public String getFilterValue() {
return localRemoteFilter.getSelectedValue();
}
@Override
public void closeDialogIfShowing() {
if (super.isShowing()) {
this.hide();
delegate.onClose();
}
}
@Override
public void showDialogIfClosed() {
if (!super.isShowing()) {
this.show(btnCreate);
}
}
@Override
public void setTextToSearchFilterLabel(String filter) {
searchFilterLabel.setText(filter.isEmpty() ? locale.branchSearchFilterLabel() : filter);
}
@Override
public void clearSearchFilter() {
branchesList.clearFilter();
}
@Override
public void setFocus() {
super.focus();
}
@Override
public void onClose() {
closeDialogIfShowing();
}
}
| epl-1.0 |
elucash/eclipse-oxygen | org.eclipse.jdt.core/src/org/eclipse/jdt/internal/compiler/ast/ModuleStatement.java | 846 | /*******************************************************************************
* Copyright (c) 2016 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 org.eclipse.jdt.internal.compiler.ast;
/**
* Just a marker class to represent statements that can occur in a module declaration
*
*/
public abstract class ModuleStatement extends ASTNode {
public int declarationEnd;
public int declarationSourceStart;
public int declarationSourceEnd;
}
| epl-1.0 |
oxmcvusd/eclipse-integration-gradle | org.springsource.ide.eclipse.gradle.ui/src/org/springsource/ide/eclipse/gradle/ui/actions/RefreshSourceFoldersAction.java | 1765 | /*******************************************************************************
* Copyright (c) 2012, 2014 Pivotal Software, Inc.
* 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:
* Pivotal Software, Inc. - initial API and implementation
*******************************************************************************/
package org.springsource.ide.eclipse.gradle.ui.actions;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.OperationCanceledException;
import org.eclipse.jface.action.IAction;
import org.springsource.ide.eclipse.gradle.core.GradleProject;
import org.springsource.ide.eclipse.gradle.core.util.ErrorHandler;
import org.springsource.ide.eclipse.gradle.core.util.GradleRunnable;
import org.springsource.ide.eclipse.gradle.core.util.JobUtil;
/**
* Action that causes the projects source folders to be reconfigured.
*
* @author Kris De Volder
*/
public class RefreshSourceFoldersAction extends RefreshAction {
public RefreshSourceFoldersAction() {
}
public void run(IAction action) {
final GradleProject project = getGradleProject();
if (project!=null) {
JobUtil.schedule(new GradleRunnable("Refresh "+project.getName()) {
@Override
public void doit(IProgressMonitor monitor) throws OperationCanceledException, CoreException {
ErrorHandler eh = ErrorHandler.forRefreshSourceFolders();
project.invalidateGradleModel();
project.refreshSourceFolders(eh, monitor);
eh.rethrowAsCore();
}
});
}
}
}
| epl-1.0 |
Mark-Booth/daq-eclipse | uk.ac.diamond.org.apache.activemq/org/apache/activemq/command/ConsumerControl.java | 3588 | /**
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.activemq.command;
import org.apache.activemq.state.CommandVisitor;
/**
* Used to start and stop transports as well as terminating clients.
*
* @openwire:marshaller code="17"
*
*/
public class ConsumerControl extends BaseCommand {
public static final byte DATA_STRUCTURE_TYPE = CommandTypes.CONSUMER_CONTROL;
protected ConsumerId consumerId;
protected boolean close;
protected boolean stop;
protected boolean start;
protected boolean flush;
protected int prefetch;
protected ActiveMQDestination destination;
/**
* @openwire:property version=6
* @return Returns the destination.
*/
public ActiveMQDestination getDestination() {
return destination;
}
public void setDestination(ActiveMQDestination destination) {
this.destination = destination;
}
public byte getDataStructureType() {
return DATA_STRUCTURE_TYPE;
}
public Response visit(CommandVisitor visitor) throws Exception {
return visitor.processConsumerControl(this);
}
/**
* @openwire:property version=1
* @return Returns the close.
*/
public boolean isClose() {
return close;
}
/**
* @param close The close to set.
*/
public void setClose(boolean close) {
this.close = close;
}
/**
* @openwire:property version=1
* @return Returns the consumerId.
*/
public ConsumerId getConsumerId() {
return consumerId;
}
/**
* @param consumerId The consumerId to set.
*/
public void setConsumerId(ConsumerId consumerId) {
this.consumerId = consumerId;
}
/**
* @openwire:property version=1
* @return Returns the prefetch.
*/
public int getPrefetch() {
return prefetch;
}
/**
* @param prefetch The prefetch to set.
*/
public void setPrefetch(int prefetch) {
this.prefetch = prefetch;
}
/**
* @openwire:property version=2
* @return the flush
*/
public boolean isFlush() {
return this.flush;
}
/**
* @param flush the flush to set
*/
public void setFlush(boolean flush) {
this.flush = flush;
}
/**
* @openwire:property version=2
* @return the start
*/
public boolean isStart() {
return this.start;
}
/**
* @param start the start to set
*/
public void setStart(boolean start) {
this.start = start;
}
/**
* @openwire:property version=2
* @return the stop
*/
public boolean isStop() {
return this.stop;
}
/**
* @param stop the stop to set
*/
public void setStop(boolean stop) {
this.stop = stop;
}
}
| epl-1.0 |
parraman/micobs | mclev/es.uah.aut.srg.micobs.mclev/src/es/uah/aut/srg/micobs/mclev/mclevslib/MStringParamSLSPSwitch.java | 1002 | /*******************************************************************************
* Copyright (c) 2013-2015 UAH Space Research Group.
* 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:
* MICOBS SRG Team - Initial API and implementation
******************************************************************************/
package es.uah.aut.srg.micobs.mclev.mclevslib;
import es.uah.aut.srg.micobs.common.MStringParameter;
/**
* A representation of a string attribute of a service library whose default
* value is defined depending on the different supported platforms.
*
* @see es.uah.aut.srg.micobs.mclev.mclevslib.mclevslibPackage#getMStringParamSLSPSwitch()
* @model
* @generated
*/
public interface MStringParamSLSPSwitch extends MStringParameter, MParameterSLSPSwitch {
} | epl-1.0 |
lunifera/lunifera-ecview-addons | org.lunifera.ecview.semantic.uimodel/src/org/lunifera/ecview/semantic/uimodel/UiField.java | 1676 | /**
* Copyright (c) 2011 - 2015, Lunifera GmbH (Gross Enzersdorf), Loetz KG (Heidelberg)
* 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:
* Florian Pirchner - Initial implementation
*/
package org.lunifera.ecview.semantic.uimodel;
import org.eclipse.emf.common.util.EList;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Ui Field</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.lunifera.ecview.semantic.uimodel.UiField#getValidators <em>Validators</em>}</li>
* </ul>
* </p>
*
* @see org.lunifera.ecview.semantic.uimodel.UiModelPackage#getUiField()
* @model interface="true" abstract="true"
* @generated
*/
public interface UiField extends UiEmbeddable {
/**
* Returns the value of the '<em><b>Validators</b></em>' containment reference list.
* The list contents are of type {@link org.lunifera.ecview.semantic.uimodel.UiValidator}.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Validators</em>' containment reference list isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Validators</em>' containment reference list.
* @see org.lunifera.ecview.semantic.uimodel.UiModelPackage#getUiField_Validators()
* @model containment="true" resolveProxies="true"
* @generated
*/
EList<UiValidator> getValidators();
} // UiField
| epl-1.0 |
kgibm/open-liberty | dev/com.ibm.ws.microprofile.reactive.messaging_fat/fat/src/com/ibm/ws/microprofile/reactive/messaging/fat/suite/TlsTests.java | 1464 | /*******************************************************************************
* Copyright (c) 2019, 2021 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.microprofile.reactive.messaging.fat.suite;
import org.junit.ClassRule;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import org.junit.runners.Suite.SuiteClasses;
import com.ibm.ws.microprofile.reactive.messaging.fat.kafka.containers.KafkaTlsContainer;
import com.ibm.ws.microprofile.reactive.messaging.fat.kafka.tls.KafkaTlsTest;
import componenttest.containers.ExternalTestServiceDockerClientStrategy;
/**
* Suite for tests which run against a TLS enabled kafka broker
*/
@RunWith(Suite.class)
@SuiteClasses({ KafkaTlsTest.class,
})
public class TlsTests {
//Required to ensure we calculate the correct strategy each run even when
//switching between local and remote docker hosts.
static {
ExternalTestServiceDockerClientStrategy.setupTestcontainers();
}
@ClassRule
public static KafkaTlsContainer kafkaContainer = new KafkaTlsContainer();
}
| epl-1.0 |
willrogers/dawnsci | org.eclipse.dawnsci.nexus/src/org/eclipse/dawnsci/nexus/impl/NXshapeImpl.java | 1992 | /*-
*******************************************************************************
* Copyright (c) 2015 Diamond Light Source Ltd.
* 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
*
* This file was auto-generated from the NXDL XML definition.
* Generated at: 2015-09-29T13:43:53.722+01:00
*******************************************************************************/
package org.eclipse.dawnsci.nexus.impl;
import org.eclipse.dawnsci.analysis.api.dataset.IDataset;
import org.eclipse.dawnsci.analysis.dataset.impl.Dataset;
import org.eclipse.dawnsci.nexus.*;
/**
* This is the description of the general shape and size of a
* component, which may be made up of ``numobj`` separate
* elements - it is used by the :ref:`NXgeometry` class
*
* @version 1.0
*/
public class NXshapeImpl extends NXobjectImpl implements NXshape {
private static final long serialVersionUID = 1L; // no state in this class, so always compatible
public static final String NX_SHAPE = "shape";
public static final String NX_SIZE = "size";
public static final String NX_DIRECTION = "direction";
protected NXshapeImpl(long oid) {
super(oid);
}
@Override
public Class<? extends NXobject> getNXclass() {
return NXshape.class;
}
@Override
public NXbaseClass getNXbaseClass() {
return NXbaseClass.NX_SHAPE;
}
@Override
public IDataset getShape() {
return getDataset(NX_SHAPE);
}
public void setShape(IDataset shape) {
setDataset(NX_SHAPE, shape);
}
@Override
public IDataset getSize() {
return getDataset(NX_SIZE);
}
public void setSize(IDataset size) {
setDataset(NX_SIZE, size);
}
@Override
public IDataset getDirection() {
return getDataset(NX_DIRECTION);
}
public void setDirection(IDataset direction) {
setDataset(NX_DIRECTION, direction);
}
}
| epl-1.0 |
FTSRG/mondo-sam | eu.mondo.sam.core/src/main/java/eu/mondo/sam/core/publishers/FilePublisher.java | 2745 | package eu.mondo.sam.core.publishers;
import java.io.File;
import java.io.IOException;
import org.apache.commons.io.FileUtils;
import eu.mondo.sam.core.results.BenchmarkResult;
import eu.mondo.sam.core.results.formatters.FormatException;
import eu.mondo.sam.core.results.formatters.ResultFormatter;
public class FilePublisher implements Publisher {
protected FilenameFactory factory;
protected ResultFormatter formatter;
protected String resultPath;
protected String extension;
private FilePublisher(Builder builder) {
this.factory = builder.factory;
this.formatter = builder.formatter;
this.resultPath = builder.resultPath;
this.extension = builder.extension;
}
@Override
public void publish(final BenchmarkResult benchmarkResult) throws IOException {
String filePath = getFullname();
String formattedResult;
try {
formattedResult = formatter.format(benchmarkResult);
} catch (FormatException e) {
throw new IOException(e);
}
File dir = new File(resultPath);
dir.mkdir();
File file = new File(filePath);
FileUtils.writeStringToFile(file, formattedResult, "UTF-8");
}
public String getExtension() {
return extension;
}
public void setExtension(String extension) {
this.extension = extension;
}
public String getResultPath() {
return resultPath;
}
public void setResultPath(String resultPath) {
this.resultPath = resultPath;
}
public String getFullname() {
// add some validation
return resultPath + factory.getFilename() + "." + extension;
}
public static class Builder {
private FilenameFactory factory;
private ResultFormatter formatter;
private String resultPath;
private String resultPathDefault = "../results/";
private String extension;
private String extensionDefault = "json";
public Builder filenameFactory(final FilenameFactory filenameFactory) {
this.factory = filenameFactory;
return this;
}
public Builder formatter(final ResultFormatter formatter) {
this.formatter = formatter;
return this;
}
public Builder resultPath(final String resultPath) {
this.resultPath = resultPath;
return this;
}
public Builder extension(final String extension) {
this.extension = extension;
return this;
}
public FilePublisher build() {
if (factory == null) {
throw new IllegalStateException("FilenameFactory is not initialized!");
}
if (formatter == null) {
throw new IllegalStateException("Formatter is not initialized!");
}
if (resultPath == null || resultPath.isEmpty()) {
// log warning
resultPath = resultPathDefault;
}
if (extension == null || extension.isEmpty()) {
// log warning
extension = extensionDefault;
}
return new FilePublisher(this);
}
}
}
| epl-1.0 |
Genuitec/piplug | com.genuitec.piplug.tools.ui/src/com/genuitec/piplug/tools/ui/views/ExtensionNameComparator.java | 472 | package com.genuitec.piplug.tools.ui.views;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerComparator;
import com.genuitec.piplug.tools.model.PiPlugExtension;
public class ExtensionNameComparator extends ViewerComparator {
@Override
public int compare(Viewer viewer, Object e1, Object e2) {
PiPlugExtension a1 = (PiPlugExtension) e1;
PiPlugExtension a2 = (PiPlugExtension) e2;
return a1.compareTo(a2);
}
}
| epl-1.0 |
DavidGutknecht/elexis-3-base | bundles/org.apache.solr/src/org/apache/solr/client/solrj/io/eval/ConversionEvaluator.java | 6450 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.solr.client.solrj.io.eval;
import java.io.IOException;
import java.util.Locale;
import org.apache.solr.client.solrj.io.stream.expr.StreamExpression;
import org.apache.solr.client.solrj.io.stream.expr.StreamExpressionParameter;
import org.apache.solr.client.solrj.io.stream.expr.StreamFactory;
public class ConversionEvaluator extends RecursiveNumericEvaluator implements OneValueWorker {
protected static final long serialVersionUID = 1L;
private interface Converter {
public double convert(double value);
}
enum LENGTH_CONSTANT {MILES, YARDS, FEET, INCHES, MILLIMETERS, CENTIMETERS, METERS, KILOMETERS};
private LENGTH_CONSTANT from;
private LENGTH_CONSTANT to;
private Converter converter;
public ConversionEvaluator(StreamExpression expression, StreamFactory factory) throws IOException{
super(expression, factory);
if(3 != containedEvaluators.size()){
throw new IOException(String.format(Locale.ROOT,"Invalid expression %s - expecting exactly 3 parameters but found %d", super.toExpression(constructingFactory), containedEvaluators.size()));
}
if(containedEvaluators.subList(0, 2).stream().anyMatch(item -> !(item instanceof RawValueEvaluator) && !(item instanceof FieldValueEvaluator))){
throw new IOException(String.format(Locale.ROOT,"Invalid expression %s - first two parameters must be strings", super.toExpression(constructingFactory)));
}
String fromString = containedEvaluators.get(0).toExpression(factory).toString().toUpperCase(Locale.ROOT);
String toString = containedEvaluators.get(1).toExpression(factory).toString().toUpperCase(Locale.ROOT);
try {
from = LENGTH_CONSTANT.valueOf(fromString);
to = LENGTH_CONSTANT.valueOf(toString);
this.converter = constructConverter(from, to);
} catch (IllegalArgumentException e) {
throw new IOException(String.format(Locale.ROOT,"Invalid expression %s - '%s' and '%s' are not both valid conversion types", super.toExpression(constructingFactory), fromString, toString));
}
// Remove evaluators 0 and 1 because we don't actually want those used
containedEvaluators = containedEvaluators.subList(2, 3);
}
@Override
public Object doWork(Object value) throws IOException{
if(null == value){
return null;
}
return converter.convert(((Number)value).doubleValue());
}
private Converter constructConverter(LENGTH_CONSTANT from, LENGTH_CONSTANT to) throws IOException {
switch(from) {
case INCHES:
switch(to) {
case MILLIMETERS:
return (double value) -> value * 25.4;
case CENTIMETERS:
return (double value) -> value * 2.54;
case METERS:
return (double value) -> value * 0.0254;
default:
throw new EvaluatorException(String.format(Locale.ROOT, "No conversion available from %s to %s", from, to));
}
case FEET:
switch(to) {
case METERS:
return (double value) -> value * .30;
default:
throw new EvaluatorException(String.format(Locale.ROOT, "No conversion available from %s to %s", from, to));
}
case YARDS:
switch(to) {
case METERS:
return (double value) -> value * .91;
case KILOMETERS:
return (double value) -> value * 0.00091;
default:
throw new EvaluatorException(String.format(Locale.ROOT, "No conversion available from %s to %s", from, to));
}
case MILES:
switch(to) {
case KILOMETERS:
return (double value) -> value * 1.61;
default:
throw new EvaluatorException(String.format(Locale.ROOT, "No conversion available from %s to %s", from, to));
}
case MILLIMETERS:
switch (to) {
case INCHES:
return (double value) -> value * 0.039;
default:
throw new EvaluatorException(String.format(Locale.ROOT, "No conversion available from %s to %s", from, to));
}
case CENTIMETERS:
switch(to) {
case INCHES:
return (double value) -> value * 0.39;
default:
throw new EvaluatorException(String.format(Locale.ROOT, "No conversion available from %s to %s", from, to));
}
case METERS:
switch(to) {
case FEET:
return (double value) -> value * 3.28;
default:
throw new EvaluatorException(String.format(Locale.ROOT, "No conversion available from %s to %s", from, to));
}
case KILOMETERS:
switch(to) {
case MILES:
return (double value) -> value * 0.62;
case FEET:
return (double value) -> value * 3280.8;
default:
throw new EvaluatorException(String.format(Locale.ROOT, "No conversion available from %s to %s", from, to));
}
default:
throw new EvaluatorException(String.format(Locale.ROOT, "No conversion available from %s to %s", from, to));
}
}
@Override
public StreamExpressionParameter toExpression(StreamFactory factory) throws IOException {
StreamExpression expression = new StreamExpression(factory.getFunctionName(getClass()));
expression.addParameter(from.toString().toLowerCase(Locale.ROOT));
expression.addParameter(to.toString().toLowerCase(Locale.ROOT));
for(StreamEvaluator evaluator : containedEvaluators){
expression.addParameter(evaluator.toExpression(factory));
}
return expression;
}
}
| epl-1.0 |
sonatype/nexus-public | components/nexus-common/src/main/java/org/sonatype/nexus/common/guice/TypeConverterSupport.java | 2304 | /*
* Sonatype Nexus (TM) Open Source Version
* Copyright (c) 2008-present Sonatype, Inc.
* All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions.
*
* This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0,
* which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html.
*
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks
* of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the
* Eclipse Foundation. All other trademarks are the property of their respective owners.
*/
package org.sonatype.nexus.common.guice;
import com.google.inject.AbstractModule;
import com.google.inject.Key;
import com.google.inject.ProvisionException;
import com.google.inject.TypeLiteral;
import com.google.inject.matcher.Matchers;
import com.google.inject.name.Names;
import com.google.inject.spi.TypeConverter;
import org.eclipse.sisu.inject.TypeArguments;
/**
* Support for {@link TypeConverter} implementations.
*
* @since 3.0
*/
public abstract class TypeConverterSupport<T>
extends AbstractModule
implements TypeConverter
{
private boolean bound;
@Override
public void configure() {
if (!bound) {
// Explicitly bind module instance under a specific sub-type (not Module as Guice forbids that)
bind(Key.get(TypeConverterSupport.class, Names.named(getClass().getName()))).toInstance(this);
bound = true;
}
// make sure we pick up the right super type argument, i.e. Foo from TypeConverterSupport<Foo>
final TypeLiteral<?> superType = TypeLiteral.get(getClass()).getSupertype(TypeConverterSupport.class);
convertToTypes(Matchers.only(TypeArguments.get(superType, 0)), this);
}
public Object convert(final String value, final TypeLiteral<?> toType) {
try {
return doConvert(value, toType);
}
catch (Exception e) {
throw new ProvisionException(String.format("Unable to convert value: %s due to: %s", value, e)); //NON-NLS
}
}
protected abstract Object doConvert(String value, TypeLiteral<?> toType) throws Exception;
}
| epl-1.0 |
opendaylight/bgpcep | pcep/base-parser/src/main/java/org/opendaylight/protocol/pcep/parser/object/PCEPErrorObjectParser.java | 4833 | /*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.protocol.pcep.parser.object;
import static com.google.common.base.Preconditions.checkArgument;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import java.util.List;
import org.opendaylight.protocol.pcep.spi.AbstractObjectWithTlvsParser;
import org.opendaylight.protocol.pcep.spi.ObjectUtil;
import org.opendaylight.protocol.pcep.spi.PCEPDeserializerException;
import org.opendaylight.protocol.pcep.spi.PCEPErrors;
import org.opendaylight.protocol.pcep.spi.TlvRegistry;
import org.opendaylight.protocol.pcep.spi.VendorInformationTlvRegistry;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.Object;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.ObjectHeader;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.Tlv;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.pcep.error.object.ErrorObject;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.pcep.error.object.ErrorObjectBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.pcep.error.object.error.object.Tlvs;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.pcep.error.object.error.object.TlvsBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.req.missing.tlv.ReqMissing;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev181109.vendor.information.tlvs.VendorInformationTlv;
import org.opendaylight.yangtools.yang.common.netty.ByteBufUtils;
/**
* Parser for {@link ErrorObject}.
*/
public final class PCEPErrorObjectParser extends AbstractObjectWithTlvsParser<ErrorObjectBuilder> {
private static final int CLASS = 13;
private static final int TYPE = 1;
private static final int FLAGS_F_LENGTH = 1;
private static final int RESERVED = 1;
public PCEPErrorObjectParser(final TlvRegistry tlvReg, final VendorInformationTlvRegistry viTlvReg) {
super(tlvReg, viTlvReg, CLASS, TYPE);
}
@Override
public ErrorObject parseObject(final ObjectHeader header, final ByteBuf bytes) throws PCEPDeserializerException {
checkArgument(bytes != null && bytes.isReadable(), "Array of bytes is mandatory. Can't be null or empty.");
bytes.skipBytes(FLAGS_F_LENGTH + RESERVED);
final ErrorObjectBuilder builder = new ErrorObjectBuilder()
.setIgnore(header.getIgnore())
.setProcessingRule(header.getProcessingRule())
.setType(ByteBufUtils.readUint8(bytes))
.setValue(ByteBufUtils.readUint8(bytes));
parseTlvs(builder, bytes.slice());
return builder.build();
}
@Override
public void addTlv(final ErrorObjectBuilder builder, final Tlv tlv) {
if (tlv instanceof ReqMissing
&& PCEPErrors.SYNC_PATH_COMP_REQ_MISSING.getErrorType().equals(builder.getType())) {
builder.setTlvs(new TlvsBuilder().setReqMissing((ReqMissing) tlv).build());
}
}
@Override
public void serializeObject(final Object object, final ByteBuf buffer) {
checkArgument(object instanceof ErrorObject, "Wrong instance of PCEPObject. Passed %s. Needed ErrorObject.",
object.getClass());
final ErrorObject errObj = (ErrorObject) object;
final ByteBuf body = Unpooled.buffer();
body.writeZero(FLAGS_F_LENGTH + RESERVED);
ByteBufUtils.writeMandatory(body, errObj.getType(), "Type");
ByteBufUtils.writeMandatory(body, errObj.getValue(), "Value");
serializeTlvs(errObj.getTlvs(), body);
ObjectUtil.formatSubobject(TYPE, CLASS, object.getProcessingRule(), object.getIgnore(), body, buffer);
}
public void serializeTlvs(final Tlvs tlvs, final ByteBuf body) {
if (tlvs != null) {
if (tlvs.getReqMissing() != null) {
serializeTlv(tlvs.getReqMissing(), body);
}
serializeVendorInformationTlvs(tlvs.getVendorInformationTlv(), body);
}
}
@Override
protected void addVendorInformationTlvs(final ErrorObjectBuilder builder, final List<VendorInformationTlv> tlvs) {
if (!tlvs.isEmpty()) {
builder.setTlvs(new TlvsBuilder(builder.getTlvs()).setVendorInformationTlv(tlvs).build());
}
}
}
| epl-1.0 |
RobotML/RobotML-SDK-Juno | plugins/robotml/org.eclipse.papyrus.robotml.diagram.interfacedef/src-gen/org/eclipse/papyrus/robotml/diagram/interfacedef/preferences/CommentPreferencePage.java | 1123 | /*****************************************************************************
* Copyright (c) 2012 CEA LIST.
*
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the CeCILL-C Free Software License v1.0
* which accompanies this distribution, and is available at
* http://www.cecill.info/licences/Licence_CeCILL-C_V1-en.html
*
* Contributors:
* Saadia DHOUIB (CEA LIST) - Initial API and implementation
*
*****************************************************************************/
package org.eclipse.papyrus.robotml.diagram.interfacedef.preferences;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.papyrus.robotml.diagram.interfacedef.edit.part.InterfaceDefEditPart;
public class CommentPreferencePage extends InterfaceDefNodePreferencePage {
public static String prefKey = InterfaceDefEditPart.DIAGRAM_ID + "_Comment";
public CommentPreferencePage() {
super();
setPreferenceKey(InterfaceDefEditPart.DIAGRAM_ID + "_Comment"); //$NON-NLS-1$
}
public static void initDefaults(IPreferenceStore store) {
}
}
| epl-1.0 |
PlegmaLabs/openhab | bundles/binding/org.openhab.binding.sonos/src/main/java/org/openhab/binding/sonos/internal/SonosZonePlayer.java | 54954 | /**
* Copyright (c) 2010-2014, openHAB.org 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.openhab.binding.sonos.internal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Duration;
import org.joda.time.Period;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;
import org.openhab.binding.sonos.SonosCommandType;
import org.openhab.binding.sonos.internal.SonosBinding.SonosZonePlayerState;
import org.openhab.io.net.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.teleal.cling.UpnpService;
import org.teleal.cling.controlpoint.ActionCallback;
import org.teleal.cling.controlpoint.SubscriptionCallback;
import org.teleal.cling.model.action.ActionArgumentValue;
import org.teleal.cling.model.action.ActionException;
import org.teleal.cling.model.action.ActionInvocation;
import org.teleal.cling.model.gena.CancelReason;
import org.teleal.cling.model.gena.GENASubscription;
import org.teleal.cling.model.message.UpnpResponse;
import org.teleal.cling.model.meta.Action;
import org.teleal.cling.model.meta.RemoteDevice;
import org.teleal.cling.model.meta.Service;
import org.teleal.cling.model.meta.StateVariable;
import org.teleal.cling.model.meta.StateVariableTypeDetails;
import org.teleal.cling.model.state.StateVariableValue;
import org.teleal.cling.model.types.Datatype;
import org.teleal.cling.model.types.InvalidValueException;
import org.teleal.cling.model.types.UDAServiceId;
import org.teleal.cling.model.types.UDN;
import org.teleal.cling.model.types.UnsignedIntegerFourBytes;
import org.xml.sax.SAXException;
/**
* Internal data structure which carries the connection details of one Sonos player
* (there could be several)
*
* @author Karel Goderis
* @since 1.1.0
*
*/
class SonosZonePlayer {
private static Logger logger = LoggerFactory.getLogger(SonosZonePlayer.class);
protected final int interval = 600;
private boolean isConfigured = false;
/** the default socket timeout when requesting an url */
private static final int SO_TIMEOUT = 5000;
private RemoteDevice device = null;
private UDN udn;
private String id;
private DateTime lastOPMLQuery;
private SonosZonePlayerState savedState = null;
static protected UpnpService upnpService;
protected SonosBinding sonosBinding;
private Map<String, StateVariableValue> stateMap = Collections.synchronizedMap(new HashMap<String,StateVariableValue>());
/**
* @return the stateMap
*/
public Map<String, StateVariableValue> getStateMap() {
return stateMap;
}
public boolean isConfigured() {
return isConfigured;
}
SonosZonePlayer(String id, SonosBinding binding) {
if( binding != null) {
this.id = id;
sonosBinding = binding;
}
}
private void enableGENASubscriptions(){
if(device!=null && isConfigured()) {
// Create a GENA subscription of each service for this device, if supported by the device
List<SonosCommandType> subscriptionCommands = SonosCommandType.getSubscriptions();
List<String> addedSubscriptions = new ArrayList<String>();
for(SonosCommandType c : subscriptionCommands){
Service service = device.findService(new UDAServiceId(c.getService()));
if(service != null && !addedSubscriptions.contains(c.getService())) {
SonosPlayerSubscriptionCallback callback = new SonosPlayerSubscriptionCallback(service,interval);
addedSubscriptions.add(c.getService());
upnpService.getControlPoint().execute(callback);
}
}
}
}
protected boolean isUpdatedValue(String valueName,StateVariableValue newValue) {
if(newValue != null && valueName != null) {
StateVariableValue oldValue = stateMap.get(valueName);
if(newValue.getValue()== null) {
// we will *not* store an empty value, thank you.
return false;
} else {
if(oldValue == null) {
// there was nothing stored before
return true;
} else {
if (oldValue.getValue() == null) {
// something was defined, but no value present
return true;
} else {
if(newValue.getValue().equals(oldValue.getValue())) {
return false;
} else {
return true;
}
}
}
}
}
return false;
}
protected void processStateVariableValue(String valueName,StateVariableValue newValue) {
if(newValue!=null && isUpdatedValue(valueName,newValue)) {
Map<String, StateVariableValue> mapToProcess = new HashMap<String, StateVariableValue>();
mapToProcess.put(valueName,newValue);
stateMap.putAll(mapToProcess);
sonosBinding.processVariableMap(device,mapToProcess);
}
}
/**
* @return the device
*/
public RemoteDevice getDevice() {
return device;
}
/**
* @param device the device to set
*/
public void setDevice(RemoteDevice device) {
this.device = device;
if(upnpService !=null && device!=null) {
isConfigured = true;
enableGENASubscriptions();
}
}
public class SonosPlayerSubscriptionCallback extends SubscriptionCallback {
public SonosPlayerSubscriptionCallback(Service service) {
super(service);
}
public SonosPlayerSubscriptionCallback(Service service,
int requestedDurationSeconds) {
super(service, requestedDurationSeconds);
}
@Override
public void established(GENASubscription sub) {
}
@Override
protected void failed(GENASubscription subscription,
UpnpResponse responseStatus,
Exception exception,
String defaultMsg) {
}
public void eventReceived(GENASubscription sub) {
// get the device linked to this service linked to this subscription
Map<String, StateVariableValue> values = sub.getCurrentValues();
Map<String, StateVariableValue> mapToProcess = new HashMap<String, StateVariableValue>();
Map<String, StateVariableValue> parsedValues = null;
// now, lets deal with the specials - some UPNP responses require some XML parsing
// or we need to update our internal data structure
// or are things we want to store for further reference
for(String stateVariable : values.keySet()){
if(stateVariable.equals("LastChange") && service.getServiceType().getType().equals("AVTransport")){
try {
parsedValues = SonosXMLParser.getAVTransportFromXML(values.get(stateVariable).toString());
for(String someValue : parsedValues.keySet()) {
// logger.debug("Lastchange parsed into {}:{}",someValue,parsedValues.get(someValue));
if(isUpdatedValue(someValue,parsedValues.get(someValue))){
mapToProcess.put(someValue,parsedValues.get(someValue));
}
}
} catch (SAXException e) {
logger.error("Could not parse AVTransport from String {}",values.get(stateVariable).toString());
}
} else if(stateVariable.equals("LastChange") && service.getServiceType().getType().equals("RenderingControl")){
try {
parsedValues = SonosXMLParser.getRenderingControlFromXML(values.get(stateVariable).toString());
for(String someValue : parsedValues.keySet()) {
if(isUpdatedValue(someValue,parsedValues.get(someValue))){
mapToProcess.put(someValue,parsedValues.get(someValue));
}
}
} catch (SAXException e) {
logger.error("Could not parse RenderingControl from String {}",values.get(stateVariable).toString());
}
} else if(isUpdatedValue(stateVariable,values.get(stateVariable))){
mapToProcess.put(stateVariable, values.get(stateVariable));
}
}
if(isConfigured) {
stateMap.putAll(mapToProcess);
sonosBinding.processVariableMap(device,mapToProcess);
}
}
public void eventsMissed(GENASubscription sub, int numberOfMissedEvents) {
logger.warn("Missed events: " + numberOfMissedEvents);
}
@Override
protected void ended(GENASubscription subscription,
CancelReason reason, UpnpResponse responseStatus) {
if(device!=null && isConfigured()) {
//rebooting the GENA subscription
Service service = subscription.getService();
SonosPlayerSubscriptionCallback callback = new SonosPlayerSubscriptionCallback(service,interval);
upnpService.getControlPoint().execute(callback);
}
}
}
public void setService(UpnpService service) {
if(upnpService == null) {
upnpService = service;
}
if(upnpService !=null && device!=null) {
isConfigured = true;
enableGENASubscriptions();
}
}
public String getModel() {
if(device!=null) {
return device.getDetails().getModelDetails().getModelNumber();
} else {
return "Unknown";
}
}
/**
* @return the udn
*/
public UDN getUdn() {
return udn;
}
/**
* @param udn the udn to set
*/
public void setUdn(UDN udn) {
this.udn = udn;
}
public String getId() {
return id;
}
@Override
public String toString() {
return "Sonos [udn=" + udn + ", device=" + device +"]";
}
public boolean play() {
if(isConfigured()) {
Service service = device.findService(new UDAServiceId("AVTransport"));
Action action = service.getAction("Play");
ActionInvocation invocation = new ActionInvocation(action);
invocation.setInput("Speed", "1");
executeActionInvocation(invocation);
return true;
} else {
return false;
}
}
public boolean playRadio(String station){
if(isConfigured()) {
List<SonosEntry> stations = getFavoriteRadios();
SonosEntry theEntry = null;
// search for the appropriate radio based on its name (title)
for(SonosEntry someStation : stations){
if(someStation.getTitle().equals(station)){
theEntry = someStation;
break;
}
}
// set the URI of the group coordinator
if(theEntry != null) {
SonosZonePlayer coordinator = sonosBinding.getCoordinatorForZonePlayer(this);
coordinator.setCurrentURI(theEntry);
coordinator.play();
return true;
}
else {
return false;
}
} else {
return false;
}
}
public boolean playPlayList(String playlist){
if(isConfigured()) {
List<SonosEntry> playlists = getPlayLists();
SonosEntry theEntry = null;
// search for the appropriate play list based on its name (title)
for(SonosEntry somePlaylist : playlists){
if(somePlaylist.getTitle().equals(playlist)){
theEntry = somePlaylist;
break;
}
}
// set the URI of the group coordinator
if(theEntry != null) {
SonosZonePlayer coordinator = sonosBinding.getCoordinatorForZonePlayer(this);
//coordinator.setCurrentURI(theEntry);
coordinator.addURIToQueue(theEntry);
if(stateMap != null && isConfigured()) {
StateVariableValue firstTrackNumberEnqueued = stateMap.get("FirstTrackNumberEnqueued");
if(firstTrackNumberEnqueued!=null) {
coordinator.seek("TRACK_NR", firstTrackNumberEnqueued.getValue().toString());
}
}
coordinator.play();
return true;
}
else {
return false;
}
} else {
return false;
}
}
public boolean stop() {
if(isConfigured()) {
Service service = device.findService(new UDAServiceId("AVTransport"));
Action action = service.getAction("Stop");
ActionInvocation invocation = new ActionInvocation(action);
executeActionInvocation(invocation);
return true;
} else {
return false;
}
}
public boolean pause() {
if(isConfigured()) {
Service service = device.findService(new UDAServiceId("AVTransport"));
Action action = service.getAction("Pause");
ActionInvocation invocation = new ActionInvocation(action);
executeActionInvocation(invocation);
return true;
} else {
return false;
}
}
public boolean next() {
if(isConfigured()) {
Service service = device.findService(new UDAServiceId("AVTransport"));
Action action = service.getAction("Next");
ActionInvocation invocation = new ActionInvocation(action);
executeActionInvocation(invocation);
return true;
} else {
return false;
}
}
public boolean previous() {
if(isConfigured()) {
Service service = device.findService(new UDAServiceId("AVTransport"));
Action action = service.getAction("Previous");
ActionInvocation invocation = new ActionInvocation(action);
executeActionInvocation(invocation);
return true;
} else {
return false;
}
}
public String getZoneName() {
if(stateMap != null && isConfigured()) {
StateVariableValue value = stateMap.get("ZoneName");
if(value != null) {
return value.getValue().toString();
}
}
return null;
}
public String getZoneGroupID() {
if(stateMap != null && isConfigured()) {
StateVariableValue value = stateMap.get("LocalGroupUUID");
if(value != null) {
return value.getValue().toString();
}
}
return null;
}
public boolean isGroupCoordinator() {
if(stateMap != null && isConfigured()) {
StateVariableValue value = stateMap.get("GroupCoordinatorIsLocal");
if(value != null) {
return (Boolean) value.getValue();
}
}
return false;
}
public SonosZonePlayer getCoordinator(){
return sonosBinding.getCoordinatorForZonePlayer(this);
}
public boolean isCoordinator() {
return this.equals(getCoordinator());
}
public boolean addMember(SonosZonePlayer newMember) {
if(newMember != null && isConfigured()) {
SonosEntry entry = new SonosEntry("", "", "", "", "", "", "", "x-rincon:"+udn.getIdentifierString());
return newMember.setCurrentURI(entry);
} else {
return false;
}
}
public boolean removeMember(SonosZonePlayer oldMember){
if(oldMember != null && isConfigured()) {
oldMember.becomeStandAlonePlayer();
SonosEntry entry = new SonosEntry("", "", "", "", "", "", "", "x-rincon-queue:"+oldMember.getUdn().getIdentifierString()+"#0");
return oldMember.setCurrentURI(entry);
} else {
return false;
}
}
public boolean becomeStandAlonePlayer() {
if(isConfigured()) {
Service service = device.findService(new UDAServiceId("AVTransport"));
Action action = service.getAction("BecomeCoordinatorOfStandaloneGroup");
ActionInvocation invocation = new ActionInvocation(action);
executeActionInvocation(invocation);
return true;
} else {
return false;
}
}
public boolean setMute(String string) {
if(string != null && isConfigured()) {
Service service = device.findService(new UDAServiceId("RenderingControl"));
Action action = service.getAction("SetMute");
ActionInvocation invocation = new ActionInvocation(action);
try {
invocation.setInput("Channel", "Master");
if(string.equals("ON") || string.equals("OPEN") || string.equals("UP") ) {
invocation.setInput("DesiredMute", "True");
} else
if(string.equals("OFF") || string.equals("CLOSED") || string.equals("DOWN") ) {
invocation.setInput("DesiredMute", "False");
} else {
return false;
}
} catch (InvalidValueException ex) {
logger.error("Action Invalid Value Exception {}",ex.getMessage());
} catch (NumberFormatException ex) {
logger.error("Action Invalid Value Format Exception {}",ex.getMessage());
}
executeActionInvocation(invocation);
return true;
} else {
return false;
}
}
public String getMute(){
if(stateMap != null && isConfigured()) {
StateVariableValue value = stateMap.get("MuteMaster");
if(value != null) {
return value.getValue().toString();
}
}
return null;
}
public boolean setVolume(String value) {
if(value != null && isConfigured()) {
Service service = device.findService(new UDAServiceId("RenderingControl"));
Action action = service.getAction("SetVolume");
ActionInvocation invocation = new ActionInvocation(action);
try {
String newValue = value;
if(value.equals("INCREASE")) {
int i = Integer.valueOf(this.getVolume());
newValue = String.valueOf(Math.min(100, i+1));
} else if (value.equals("DECREASE")) {
int i = Integer.valueOf(this.getVolume());
newValue = String.valueOf(Math.max(0, i-1));
} else if (value.equals("ON")) {
newValue = "100";
} else if (value.equals("OFF")) {
newValue = "0";
} else {
newValue = value;
}
invocation.setInput("Channel", "Master");
invocation.setInput("DesiredVolume",newValue);
} catch (InvalidValueException ex) {
logger.error("Action Invalid Value Exception {}",ex.getMessage());
} catch (NumberFormatException ex) {
logger.error("Action Invalid Value Format Exception {}",ex.getMessage());
}
executeActionInvocation(invocation);
return true;
} else {
return false;
}
}
public String getVolume() {
if(stateMap != null && isConfigured()) {
StateVariableValue value = stateMap.get("VolumeMaster");
if(value != null) {
return value.getValue().toString();
}
}
return null;
}
public boolean updateTime() {
if(isConfigured()) {
Service service = device.findService(new UDAServiceId("AlarmClock"));
Action action = service.getAction("GetTimeNow");
ActionInvocation invocation = new ActionInvocation(action);
executeActionInvocation(invocation);
return true;
} else {
return false;
}
}
public String getTime() {
if(isConfigured()) {
updateTime();
if(stateMap != null) {
StateVariableValue value = stateMap.get("CurrentLocalTime");
if(value != null) {
return value.getValue().toString();
}
}
}
return null;
}
protected void executeActionInvocation(ActionInvocation invocation) {
if(invocation != null) {
new ActionCallback.Default(invocation, upnpService.getControlPoint()).run();
ActionException anException = invocation.getFailure();
if(anException!= null && anException.getMessage()!=null) {
logger.warn(anException.getMessage());
}
Map<String, ActionArgumentValue> result = invocation.getOutputMap();
Map<String, StateVariableValue> mapToProcess = new HashMap<String, StateVariableValue>();
if(result != null) {
// only process the variables that have changed value
for(String variable : result.keySet()) {
ActionArgumentValue newArgument = result.get(variable);
StateVariable newVariable = new StateVariable(variable,new StateVariableTypeDetails(newArgument.getDatatype()));
StateVariableValue newValue = new StateVariableValue(newVariable, newArgument.getValue());
if(isUpdatedValue(variable,newValue)) {
mapToProcess.put(variable, newValue);
}
}
stateMap.putAll(mapToProcess);
sonosBinding.processVariableMap(device,mapToProcess);
}
}
}
public boolean updateRunningAlarmProperties() {
if(stateMap != null && isConfigured()) {
Service service = device.findService(new UDAServiceId("AVTransport"));
Action action = service.getAction("GetRunningAlarmProperties");
ActionInvocation invocation = new ActionInvocation(action);
executeActionInvocation(invocation);
// for this property we would like to "compile" a more friendly variable.
// this newly created "variable" is also store in the stateMap
StateVariableValue alarmID = stateMap.get("AlarmID");
StateVariableValue groupID = stateMap.get("GroupID");
StateVariableValue loggedStartTime = stateMap.get("LoggedStartTime");
String newStringValue = null;
if(alarmID != null && loggedStartTime != null) {
newStringValue = alarmID.getValue() + " - " + loggedStartTime.getValue();
} else {
newStringValue = "No running alarm";
}
StateVariable newVariable = new StateVariable("RunningAlarmProperties",new StateVariableTypeDetails(Datatype.Builtin.STRING.getDatatype()));
StateVariableValue newValue = new StateVariableValue(newVariable, newStringValue);
processStateVariableValue(newVariable.getName(),newValue);
return true;
} else {
return false;
}
}
public String getRunningAlarmProperties() {
if(isConfigured()) {
updateRunningAlarmProperties();
if(stateMap != null) {
StateVariableValue value = stateMap.get("RunningAlarmProperties");
if(value != null) {
return value.getValue().toString();
}
}
}
return null;
}
public boolean updateZoneInfo() {
if(stateMap != null && isConfigured()) {
Service service = device.findService(new UDAServiceId("DeviceProperties"));
Action action = service.getAction("GetZoneInfo");
ActionInvocation invocation = new ActionInvocation(action);
executeActionInvocation(invocation);
Service anotherservice = device.findService(new UDAServiceId("DeviceProperties"));
Action anotheraction = service.getAction("GetZoneAttributes");
ActionInvocation anotherinvocation = new ActionInvocation(anotheraction);
executeActionInvocation(anotherinvocation);
// anotherservice = device.findService(new UDAServiceId("ZoneGroupTopology"));
// anotheraction = service.getAction("GetZoneGroupState");
// anotherinvocation = new ActionInvocation(anotheraction);
// executeActionInvocation(anotherinvocation);
return true;
} else {
return false;
}
}
public String getMACAddress() {
if(isConfigured()) {
updateZoneInfo();
if(stateMap != null) {
StateVariableValue value = stateMap.get("MACAddress");
if(value != null) {
return value.getValue().toString();
}
}
}
return null;
}
public boolean setLed(String string) {
if(string != null && isConfigured()) {
Service service = device.findService(new UDAServiceId("DeviceProperties"));
Action action = service.getAction("SetLEDState");
ActionInvocation invocation = new ActionInvocation(action);
try {
if(string.equals("ON") || string.equals("OPEN") || string.equals("UP") ) {
invocation.setInput("DesiredLEDState", "On");
} else
if(string.equals("OFF") || string.equals("CLOSED") || string.equals("DOWN") ) {
invocation.setInput("DesiredLEDState", "Off");
} else {
return false;
}
} catch (InvalidValueException ex) {
logger.error("Action Invalid Value Exception {}",ex.getMessage());
} catch (NumberFormatException ex) {
logger.error("Action Invalid Value Format Exception {}",ex.getMessage());
}
executeActionInvocation(invocation);
return true;
} else {
return false;
}
}
public boolean updateLed() {
if(isConfigured()) {
Service service = device.findService(new UDAServiceId("DeviceProperties"));
Action action = service.getAction("GetLEDState");
ActionInvocation invocation = new ActionInvocation(action);
executeActionInvocation(invocation);
return true;
}
else {
return false;
}
}
public boolean getLed() {
if(isConfigured()) {
updateLed();
if(stateMap != null) {
StateVariableValue variable = stateMap.get("CurrentLEDState");
if(variable != null) {
return variable.getValue().equals("On") ? true : false;
}
}
}
return false;
}
public String getCurrentZoneName() {
if(isConfigured()) {
updateCurrentZoneName();
if(stateMap != null) {
StateVariableValue variable = stateMap.get("CurrentZoneName");
if(variable != null) {
return variable.getValue().toString();
}
}
}
return null;
}
public boolean updateCurrentZoneName() {
if(isConfigured()) {
Service service = device.findService(new UDAServiceId("DeviceProperties"));
Action action = service.getAction("GetZoneAttributes");
ActionInvocation invocation = new ActionInvocation(action);
executeActionInvocation(invocation);
return true;
}
else {
return false;
}
}
public boolean updatePosition() {
if(isConfigured()) {
Service service = device.findService(new UDAServiceId("AVTransport"));
Action action = service.getAction("GetPositionInfo");
ActionInvocation invocation = new ActionInvocation(action);
executeActionInvocation(invocation);
return true;
}
else {
return false;
}
}
public String getPosition() {
if(stateMap != null && isConfigured()) {
updatePosition();
if(stateMap != null) {
StateVariableValue variable = stateMap.get("RelTime");
if(variable != null) {
return variable.getValue().toString();
}
}
}
return null;
}
public boolean setPosition(String relTime) {
return seek("REL_TIME",relTime);
}
public boolean setPositionTrack(long tracknr) {
return seek("TRACK_NR",Long.toString(tracknr));
}
protected boolean seek(String unit, String target) {
if(isConfigured() && unit != null && target != null) {
Service service = device.findService(new UDAServiceId("AVTransport"));
Action action = service.getAction("Seek");
ActionInvocation invocation = new ActionInvocation(action);
try {
invocation.setInput("InstanceID","0");
invocation.setInput("Unit", unit);
invocation.setInput("Target", target);
} catch (InvalidValueException ex) {
logger.error("Action Invalid Value Exception {}",ex.getMessage());
} catch (NumberFormatException ex) {
logger.error("Action Invalid Value Format Exception {}",ex.getMessage());
}
executeActionInvocation(invocation);
return true;
}
return false;
}
public Boolean isLineInConnected() {
if(stateMap != null && isConfigured()) {
StateVariableValue statusLineIn = stateMap.get("LineInConnected");
if(statusLineIn != null) {
return (Boolean) statusLineIn.getValue();
}
}
return null;
}
public Boolean isAlarmRunning() {
if(stateMap != null && isConfigured()) {
StateVariableValue status = stateMap.get("AlarmRunning");
if(status!=null) {
return status.getValue().equals("1") ? true : false;
}
}
return null;
}
public String getTransportState() {
if(stateMap != null && isConfigured()) {
StateVariableValue status = stateMap.get("TransportState");
if(status != null) {
return status.getValue().toString();
}
}
return null;
}
public boolean addURIToQueue(String URI, String meta,int desiredFirstTrack, boolean enqueueAsNext) {
if(isConfigured() && URI != null && meta != null) {
Service service = device.findService(new UDAServiceId("AVTransport"));
Action action = service.getAction("AddURIToQueue");
ActionInvocation invocation = new ActionInvocation(action);
try {
invocation.setInput("InstanceID","0");
invocation.setInput("EnqueuedURI",URI);
invocation.setInput("EnqueuedURIMetaData",meta);
invocation.setInput("DesiredFirstTrackNumberEnqueued",new UnsignedIntegerFourBytes(desiredFirstTrack));
invocation.setInput("EnqueueAsNext",enqueueAsNext);
} catch (InvalidValueException ex) {
logger.error("Action Invalid Value Exception {}",ex.getMessage());
} catch (NumberFormatException ex) {
logger.error("Action Invalid Value Format Exception {}",ex.getMessage());
}
executeActionInvocation(invocation);
return true;
}
return false;
}
public String getCurrentURI(){
updateMediaInfo();
if(stateMap != null && isConfigured()) {
StateVariableValue status = stateMap.get("CurrentURI");
if(status != null) {
return status.getValue().toString();
}
}
return null;
}
public long getCurrenTrackNr() {
if(stateMap != null && isConfigured()) {
updatePosition();
if(stateMap != null) {
StateVariableValue variable = stateMap.get("Track");
if(variable != null) {
return ((UnsignedIntegerFourBytes)variable.getValue()).getValue();
}
}
}
return (long) -1;
}
public boolean updateMediaInfo(){
if(isConfigured()) {
Service service = device.findService(new UDAServiceId("AVTransport"));
Action action = service.getAction("GetMediaInfo");
ActionInvocation invocation = new ActionInvocation(action);
try {
invocation.setInput("InstanceID","0");
} catch (InvalidValueException ex) {
logger.error("Action Invalid Value Exception {}",ex.getMessage());
} catch (NumberFormatException ex) {
logger.error("Action Invalid Value Format Exception {}",ex.getMessage());
}
executeActionInvocation(invocation);
return true;
}
return false;
}
public boolean addURIToQueue(SonosEntry newEntry) {
return addURIToQueue(newEntry.getRes(),SonosXMLParser.compileMetadataString(newEntry),1,true);
}
public boolean setCurrentURI(String URI, String URIMetaData ) {
if(URI != null && URIMetaData != null && isConfigured()) {
Service service = device.findService(new UDAServiceId("AVTransport"));
Action action = service.getAction("SetAVTransportURI");
ActionInvocation invocation = new ActionInvocation(action);
try {
invocation.setInput("InstanceID","0");
invocation.setInput("CurrentURI",URI);
invocation.setInput("CurrentURIMetaData", URIMetaData);
} catch (InvalidValueException ex) {
logger.error("Action Invalid Value Exception {}",ex.getMessage());
} catch (NumberFormatException ex) {
logger.error("Action Invalid Value Format Exception {}",ex.getMessage());
}
executeActionInvocation(invocation);
return true;
} else {
return false;
}
}
public boolean setCurrentURI(SonosEntry newEntry) {
return setCurrentURI(newEntry.getRes(),SonosXMLParser.compileMetadataString(newEntry));
}
public boolean updateCurrentURIFormatted() {
if(stateMap != null && isConfigured()) {
String currentURI = null;
SonosMetaData currentURIMetaData = null;
SonosMetaData currentTrack = null;
if(!isGroupCoordinator()) {
currentURI = getCoordinator().getCurrentURI();
currentURIMetaData = getCoordinator().getCurrentURIMetadata();
currentTrack = getCoordinator().getTrackMetadata();
} else {
currentURI = getCurrentURI();
currentURIMetaData = getCurrentURIMetadata();
currentTrack = getTrackMetadata();
}
if(currentURI != null) {
String resultString = null;
String artist = null;
String album = null;
String title = null;
if(currentURI.contains("x-sonosapi-stream")) {
//TODO: Get partner ID for openhab.org
String stationID = StringUtils.substringBetween(currentURI, ":s", "?sid");
StateVariable newVariable = new StateVariable("StationID",new StateVariableTypeDetails(Datatype.Builtin.STRING.getDatatype()));
StateVariableValue newValue = new StateVariableValue(newVariable, stationID);
if(this.isUpdatedValue("StationID", newValue) || lastOPMLQuery ==null || lastOPMLQuery.plusMinutes(1).isBeforeNow()) {
processStateVariableValue(newVariable.getName(),newValue);
String url = "http://opml.radiotime.com/Describe.ashx?c=nowplaying&id=" + stationID + "&partnerId=IAeIhU42&serial=" + getMACAddress();
String response = HttpUtil.executeUrl("GET", url, SO_TIMEOUT);
//logger.debug("RadioTime Response: {}",response);
lastOPMLQuery = DateTime.now();
List<String> fields = null;
try {
fields = SonosXMLParser.getRadioTimeFromXML(response);
} catch (SAXException e) {
logger.error("Could not parse RadioTime from String {}",response);
}
resultString = new String();
if(fields != null && fields.size()>1) {
Iterator<String> listIterator = fields.listIterator();
while(listIterator.hasNext()){
String field = listIterator.next();
resultString = resultString + field;
if(listIterator.hasNext()) {
resultString = resultString + " - ";
}
}
}
} else {
resultString = stateMap.get("CurrentURIFormatted").getValue().toString();
title = stateMap.get("CurrentTitle").getValue().toString();
}
} else {
if(currentTrack != null) {
if(!currentTrack.getTitle().contains("x-sonosapi-stream")) {
if (currentTrack.getAlbumArtist().equals("")) {
resultString = currentTrack.getCreator() + " - " + currentTrack.getAlbum() + " - " + currentTrack.getTitle();
artist = currentTrack.getCreator();
} else {
resultString = currentTrack.getAlbumArtist() + " - " + currentTrack.getAlbum() + " - " + currentTrack.getTitle();
artist = currentTrack.getAlbumArtist();
}
album = currentTrack.getAlbum();
title = currentTrack.getTitle();
}
} else {
resultString = "";
}
}
StateVariable newVariable = new StateVariable("CurrentURIFormatted",new StateVariableTypeDetails(Datatype.Builtin.STRING.getDatatype()));
StateVariableValue newValue = new StateVariableValue(newVariable, resultString);
processStateVariableValue(newVariable.getName(),newValue);
// update individual variables
newVariable = new StateVariable("CurrentArtist",new StateVariableTypeDetails(Datatype.Builtin.STRING.getDatatype()));
if (artist != null) {
newValue = new StateVariableValue(newVariable, artist);
} else {
newValue = new StateVariableValue(newVariable, " ");
}
processStateVariableValue(newVariable.getName(), newValue);
newVariable = new StateVariable("CurrentTitle",new StateVariableTypeDetails(Datatype.Builtin.STRING.getDatatype()));
if (title != null) {
newValue = new StateVariableValue(newVariable, title);
} else {
newValue = new StateVariableValue(newVariable, " ");
}
processStateVariableValue(newVariable.getName(), newValue);
newVariable = new StateVariable("CurrentAlbum",new StateVariableTypeDetails(Datatype.Builtin.STRING.getDatatype()));
if (album != null) {
newValue = new StateVariableValue(newVariable, album);
} else {
newValue = new StateVariableValue(newVariable, " ");
}
processStateVariableValue(newVariable.getName(), newValue);
return true;
}
}
return false;
}
public String getCurrentURIFormatted(){
updateCurrentURIFormatted();
if(stateMap != null && isConfigured()) {
StateVariableValue status = stateMap.get("CurrentURIFormatted");
if(status != null) {
return status.getValue().toString();
}
}
return null;
}
public String getCurrentURIMetadataAsString() {
if(stateMap != null && isConfigured()) {
StateVariableValue value = stateMap.get("CurrentTrackMetaData");
if(value != null) {
return value.getValue().toString();
}
}
return null;
}
public SonosMetaData getCurrentURIMetadata(){
if(stateMap != null && isConfigured()) {
StateVariableValue value = stateMap.get("CurrentURIMetaData");
SonosMetaData currentTrack = null;
if(value != null) {
try {
if(((String)value.getValue()).length()!=0) {
currentTrack = SonosXMLParser.getMetaDataFromXML((String)value.getValue());
}
} catch (SAXException e) {
logger.error("Could not parse MetaData from String {}",value.getValue().toString());
}
return currentTrack;
} else {
return null;
}
} else {
return null;
}
}
public SonosMetaData getTrackMetadata(){
if(stateMap != null && isConfigured()) {
StateVariableValue value = stateMap.get("CurrentTrackMetaData");
SonosMetaData currentTrack = null;
if(value != null) {
try {
if(((String)value.getValue()).length()!=0) {
currentTrack = SonosXMLParser.getMetaDataFromXML((String)value.getValue());
}
} catch (SAXException e) {
logger.error("Could not parse MetaData from String {}",value.getValue().toString());
}
return currentTrack;
} else {
return null;
}
} else {
return null;
}
}
public SonosMetaData getEnqueuedTransportURIMetaData(){
if(stateMap != null && isConfigured()) {
StateVariableValue value = stateMap.get("EnqueuedTransportURIMetaData");
SonosMetaData currentTrack = null;
if(value != null) {
try {
if(((String)value.getValue()).length()!=0) {
currentTrack = SonosXMLParser.getMetaDataFromXML((String)value.getValue());
}
} catch (SAXException e) {
logger.error("Could not parse MetaData from String {}",value.getValue().toString());
}
return currentTrack;
} else {
return null;
}
} else {
return null;
}
}
public String getCurrentVolume(){
if(stateMap != null && isConfigured()) {
StateVariableValue status = stateMap.get("VolumeMaster");
return status.getValue().toString();
} else {
return null;
}
}
protected List<SonosEntry> getEntries(String type, String filter){
List<SonosEntry> resultList = null;
if(isConfigured()) {
long startAt = 0;
Service service = device.findService(new UDAServiceId("ContentDirectory"));
Action action = service.getAction("Browse");
ActionInvocation invocation = new ActionInvocation(action);
try {
invocation.setInput("ObjectID",type);
invocation.setInput("BrowseFlag","BrowseDirectChildren");
invocation.setInput("Filter", filter);
invocation.setInput("StartingIndex",new UnsignedIntegerFourBytes(startAt));
invocation.setInput("RequestedCount",new UnsignedIntegerFourBytes( 200));
invocation.setInput("SortCriteria","");
} catch (InvalidValueException ex) {
logger.error("Action Invalid Value Exception {}",ex.getMessage());
} catch (NumberFormatException ex) {
logger.error("Action Invalid Value Format Exception {}",ex.getMessage());
}
// Execute this action synchronously
new ActionCallback.Default(invocation, upnpService.getControlPoint()).run();
Long totalMatches = ((UnsignedIntegerFourBytes) invocation.getOutput("TotalMatches").getValue()).getValue();
Long initialNumberReturned = ((UnsignedIntegerFourBytes) invocation.getOutput("NumberReturned").getValue()).getValue();
String initialResult = (String) invocation.getOutput("Result").getValue();
try {
resultList = SonosXMLParser.getEntriesFromString(initialResult);
} catch (SAXException e) {
logger.error("Could not parse Entries from String {}",initialResult);
}
startAt = startAt + initialNumberReturned;
while(startAt<totalMatches){
invocation = new ActionInvocation(action);
try {
invocation.setInput("ObjectID",type);
invocation.setInput("BrowseFlag","BrowseDirectChildren");
invocation.setInput("Filter", filter);
invocation.setInput("StartingIndex",new UnsignedIntegerFourBytes(startAt));
invocation.setInput("RequestedCount",new UnsignedIntegerFourBytes( 200));
invocation.setInput("SortCriteria","");
} catch (InvalidValueException ex) {
logger.error("Action Invalid Value Exception {}",ex.getMessage());
} catch (NumberFormatException ex) {
logger.error("Action Invalid Value Format Exception {}",ex.getMessage());
}
// Execute this action synchronously
new ActionCallback.Default(invocation, upnpService.getControlPoint()).run();
String result = (String) invocation.getOutput("Result").getValue();
int numberReturned = (Integer) invocation.getOutput("NumberReturned").getValue();
try {
resultList.addAll(SonosXMLParser.getEntriesFromString(result));
} catch (SAXException e) {
logger.error("Could not parse Entries from String {}",result);
}
startAt = startAt + numberReturned;
}
}
return resultList;
}
public List<SonosEntry> getArtists( String filter){
return getEntries("A:",filter);
}
public List<SonosEntry> getArtists(){
return getEntries("A:","dc:title,res,dc:creator,upnp:artist,upnp:album");
}
public List<SonosEntry> getAlbums(String filter){
return getEntries("A:ALBUM",filter);
}
public List<SonosEntry> getAlbums(){
return getEntries("A:ALBUM","dc:title,res,dc:creator,upnp:artist,upnp:album");
}
public List<SonosEntry> getTracks( String filter){
return getEntries("A:TRACKS",filter);
}
public List<SonosEntry> getTracks(){
return getEntries("A:TRACKS","dc:title,res,dc:creator,upnp:artist,upnp:album");
}
public List<SonosEntry> getQueue(String filter){
return getEntries("Q:0",filter);
}
public List<SonosEntry> getQueue(){
return getEntries("Q:0","dc:title,res,dc:creator,upnp:artist,upnp:album");
}
public List<SonosEntry> getPlayLists(String filter){
return getEntries("SQ:",filter);
}
public List<SonosEntry> getPlayLists(){
return getEntries("SQ:","dc:title,res,dc:creator,upnp:artist,upnp:album");
}
public List<SonosEntry> getFavoriteRadios(String filter){
return getEntries("R:0/0",filter);
}
public List<SonosEntry> getFavoriteRadios(){
return getEntries("R:0/0","dc:title,res,dc:creator,upnp:artist,upnp:album");
}
public List<SonosAlarm> getCurrentAlarmList(){
List<SonosAlarm> sonosAlarms = null;
if(isConfigured()) {
Service service = device.findService(new UDAServiceId("AlarmClock"));
Action action = service.getAction("ListAlarms");
ActionInvocation invocation = new ActionInvocation(action);
executeActionInvocation(invocation);
try {
sonosAlarms = SonosXMLParser.getAlarmsFromStringResult(invocation.getOutput("CurrentAlarmList").toString());
} catch (SAXException e) {
logger.error("Could not parse Alarms from String {}",invocation.getOutput("CurrentAlarmList").toString());
}
}
return sonosAlarms;
}
public boolean updateAlarm(SonosAlarm alarm) {
if(alarm != null && isConfigured()) {
Service service = device.findService(new UDAServiceId("AlarmClock"));
Action action = service.getAction("ListAlarms");
ActionInvocation invocation = new ActionInvocation(action);
DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm:ss");
PeriodFormatter pFormatter= new PeriodFormatterBuilder()
.printZeroAlways()
.appendHours()
.appendSeparator(":")
.appendMinutes()
.appendSeparator(":")
.appendSeconds()
.toFormatter();
try {
invocation.setInput("ID",Integer.toString(alarm.getID()));
invocation.setInput("StartLocalTime",formatter.print(alarm.getStartTime()));
invocation.setInput("Duration",pFormatter.print(alarm.getDuration()));
invocation.setInput("Recurrence",alarm.getRecurrence());
invocation.setInput("RoomUUID",alarm.getRoomUUID());
invocation.setInput("ProgramURI",alarm.getProgramURI());
invocation.setInput("ProgramMetaData",alarm.getProgramMetaData());
invocation.setInput("PlayMode",alarm.getPlayMode());
invocation.setInput("Volume",Integer.toString(alarm.getVolume()));
if(alarm.getIncludeLinkedZones()) {
invocation.setInput("IncludeLinkedZones","1");
} else {
invocation.setInput("IncludeLinkedZones","0");
}
if(alarm.getEnabled()) {
invocation.setInput("Enabled", "1");
} else {
invocation.setInput("Enabled", "0");
}
} catch (InvalidValueException ex) {
logger.error("Action Invalid Value Exception {}",ex.getMessage());
} catch (NumberFormatException ex) {
logger.error("Action Invalid Value Format Exception {}",ex.getMessage());
}
executeActionInvocation(invocation);
return true;
}
else {
return false;
}
}
public boolean setAlarm(String alarmSwitch) {
if(alarmSwitch.equals("ON") || alarmSwitch.equals("OPEN") || alarmSwitch.equals("UP") ) {
return setAlarm(true);
} else
if(alarmSwitch.equals("OFF") || alarmSwitch.equals("CLOSED") || alarmSwitch.equals("DOWN") ) {
return setAlarm(false);
} else {
return false;
}
}
public boolean setAlarm(boolean alarmSwitch) {
List<SonosAlarm> sonosAlarms = getCurrentAlarmList();
if(isConfigured()) {
// find the nearest alarm - take the current time from the Sonos System, not the system where openhab is running
String currentLocalTime = getTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
DateTime currentDateTime = fmt.parseDateTime(currentLocalTime);
Duration shortestDuration = Period.days(10).toStandardDuration();
SonosAlarm firstAlarm = null;
for(SonosAlarm anAlarm : sonosAlarms) {
Duration duration = new Duration(currentDateTime,anAlarm.getStartTime());
if(anAlarm.getStartTime().isBefore(currentDateTime.plus(shortestDuration)) && anAlarm.getRoomUUID().equals(udn.getIdentifierString())) {
shortestDuration = duration;
firstAlarm = anAlarm;
}
}
// Set the Alarm
if(firstAlarm != null) {
if(alarmSwitch) {
firstAlarm.setEnabled(true);
} else {
firstAlarm.setEnabled(false);
}
return updateAlarm(firstAlarm);
} else {
return false;
}
} else {
return false;
}
}
public boolean snoozeAlarm(int minutes){
if(isAlarmRunning() && isConfigured()) {
Service service = device.findService(new UDAServiceId("AVTransport"));
Action action = service.getAction("SnoozeAlarm");
ActionInvocation invocation = new ActionInvocation(action);
Period snoozePeriod = Period.minutes(minutes);
PeriodFormatter pFormatter= new PeriodFormatterBuilder()
.printZeroAlways()
.appendHours()
.appendSeparator(":")
.appendMinutes()
.appendSeparator(":")
.appendSeconds()
.toFormatter();
try {
invocation.setInput("Duration",pFormatter.print(snoozePeriod));
} catch (InvalidValueException ex) {
logger.error("Action Invalid Value Exception {}",ex.getMessage());
} catch (NumberFormatException ex) {
logger.error("Action Invalid Value Format Exception {}",ex.getMessage());
}
executeActionInvocation(invocation);
return true;
} else {
logger.warn("There is no alarm running on {} ",this);
return false;
}
}
public boolean publicAddress(){
//check if sourcePlayer has a line-in connected
if(isLineInConnected() && isConfigured()) {
//first remove this player from its own group if any
becomeStandAlonePlayer();
List<SonosZoneGroup> currentSonosZoneGroups = new ArrayList<SonosZoneGroup>(sonosBinding.getSonosZoneGroups().size());
for(SonosZoneGroup grp : sonosBinding.getSonosZoneGroups()){
currentSonosZoneGroups.add((SonosZoneGroup) grp.clone());
}
//add all other players to this new group
for(SonosZoneGroup group : currentSonosZoneGroups){
for(String player : group.getMembers()){
SonosZonePlayer somePlayer = sonosBinding.getPlayerForID(player);
if(somePlayer != this){
somePlayer.becomeStandAlonePlayer();
somePlayer.stop();
addMember(somePlayer);
}
}
}
//set the URI of the group to the line-in
//TODO : check if this needs to be set on the group coordinator or can be done on any member
SonosZonePlayer coordinator = getCoordinator();
SonosEntry entry = new SonosEntry("", "", "", "", "", "", "", "x-rincon-stream:"+udn.getIdentifierString());
coordinator.setCurrentURI(entry);
coordinator.play();
return true;
} else {
logger.warn("Line-in of {} is not connected",this);
return false;
}
}
public boolean saveQueue(String name, String queueID) {
if(name != null && queueID != null && isConfigured()) {
Service service = device.findService(new UDAServiceId("AVTransport"));
Action action = service.getAction("SaveQueue");
ActionInvocation invocation = new ActionInvocation(action);
try {
invocation.setInput("Title", name);
invocation.setInput("ObjectID", queueID);
} catch (InvalidValueException ex) {
logger.error("Action Invalid Value Exception {}",ex.getMessage());
} catch (NumberFormatException ex) {
logger.error("Action Invalid Value Format Exception {}",ex.getMessage());
}
executeActionInvocation(invocation);
return true;
} else {
return false;
}
}
/**
* Play a given url to music in one of the music libraries.
*
* @param url in the format of //host/folder/filename.mp3
* @return true if the url started to play
*/
public boolean playURI(String url) {
if (!isConfigured) {
return false;
}
SonosZonePlayer coordinator = sonosBinding
.getCoordinatorForZonePlayer(this);
// stop whatever is currently playing
coordinator.stop();
// clear any tracks which are pending in the queue
coordinator.removeAllTracksFromQueue();
// add the new track we want to play to the queue
if (!url.startsWith("x-")) {
// default to file based url
url = "x-file-cifs:" + url;
}
coordinator.addURIToQueue(url, "", 0, true);
// set the current playlist to our new queue
coordinator.setCurrentURI("x-rincon-queue:" + udn.getIdentifierString()
+ "#0", "");
// take the system off mute
coordinator.setMute("OFF");
// start jammin'
return coordinator.play();
}
/**
* Play music from the line-in of the Player given its name or UDN
*
* @param udn
* @return true if the sonos device started to play
*/
public boolean playLineIn(String remotePlayerName) {
if (!isConfigured) {
return false;
}
SonosZonePlayer coordinator = sonosBinding.getCoordinatorForZonePlayer(this);
SonosZonePlayer remotePlayer = sonosBinding.getPlayerForID(remotePlayerName);
// stop whatever is currently playing
coordinator.stop();
// set the
coordinator.setCurrentURI("x-rincon-stream:" + remotePlayer.getUdn().getIdentifierString(), "");
// take the system off mute
coordinator.setMute("OFF");
// start jammin'
return coordinator.play();
}
/**
* Clear all scheduled music from the current queue.
*
* @return true if no error occurred.
*/
public boolean removeAllTracksFromQueue() {
if (!isConfigured) {
return false;
}
Service service = device.findService(new UDAServiceId("AVTransport"));
Action action = service.getAction("RemoveAllTracksFromQueue");
ActionInvocation invocation = new ActionInvocation(action);
try {
invocation.setInput("InstanceID", "0");
} catch (InvalidValueException ex) {
logger.error("Action Invalid Value Exception {}", ex.getMessage());
} catch (NumberFormatException ex) {
logger.error("Action Invalid Value Format Exception {}",
ex.getMessage());
}
executeActionInvocation(invocation);
return true;
}
/**
* Save the state (track, position etc) of the Sonos Zone player.
*
* @return true if no error occurred.
*/
protected boolean saveState() {
synchronized (this) {
savedState = sonosBinding.new SonosZonePlayerState();
String currentURI = getCurrentURI();
if (currentURI != null) {
if (currentURI.contains("x-sonosapi-stream:")) {
// we are streaming music
SonosMetaData track = getTrackMetadata();
SonosMetaData current = getCurrentURIMetadata();
if (track != null) {
savedState.entry = new SonosEntry("",
current.getTitle(), "", "",
track.getAlbumArtUri(), "",
current.getUpnpClass(), currentURI);
}
} else if (currentURI.contains("x-rincon:")) {
// we are a slave to some coordinator
savedState.entry = new SonosEntry("", "", "", "",
"", "", "", currentURI);
} else if (currentURI.contains("x-rincon-stream:")) {
// we are streaming from the Line In connection
savedState.entry = new SonosEntry("", "", "", "",
"", "", "", currentURI);
} else if (currentURI.contains("x-rincon-queue:")) {
// we are playing something that sits in the queue
SonosMetaData queued = getEnqueuedTransportURIMetaData();
if (queued != null) {
savedState.track = getCurrenTrackNr();
if (queued.getUpnpClass().contains(
"object.container.playlistContainer")) {
// we are playing a real 'saved' playlist
List<SonosEntry> playLists = getPlayLists();
for (SonosEntry someList : playLists) {
if (someList.getTitle().equals(
queued.getTitle())) {
savedState.entry = new SonosEntry(
someList.getId(),
someList.getTitle(),
someList.getParentId(), "",
"", "",
someList.getUpnpClass(),
someList.getRes());
break;
}
}
} else if (queued.getUpnpClass().contains(
"object.container")) {
// we are playing some other sort of
// 'container' - we will save that to a
// playlist for our convenience
logger.debug(
"Save State for a container of type {}",
queued.getUpnpClass());
// save the playlist
String existingList = "";
List<SonosEntry> playLists = getPlayLists();
for (SonosEntry someList : playLists) {
if (someList.getTitle().equals(
"openHAB-" + getUdn())) {
existingList = someList.getId();
break;
}
}
saveQueue(
"openHAB-" + getUdn(),
existingList);
// get all the playlists and a ref to our
// saved list
playLists = getPlayLists();
for (SonosEntry someList : playLists) {
if (someList.getTitle().equals(
"openHAB-" + getUdn())) {
savedState.entry = new SonosEntry(
someList.getId(),
someList.getTitle(),
someList.getParentId(), "",
"", "",
someList.getUpnpClass(),
someList.getRes());
break;
}
}
}
} else {
savedState.entry = new SonosEntry("", "", "",
"", "", "", "", "x-rincon-queue:"
+ getUdn()
.getIdentifierString()
+ "#0");
}
}
savedState.transportState = getTransportState();
savedState.volume = getCurrentVolume();
savedState.relTime = getPosition();
} else {
savedState.entry = null;
}
return true;
}
}
/**
* Restore the state (track, position etc) of the Sonos Zone player.
*
* @return true if no error occurred.
*/
protected boolean restoreState() {
synchronized (this) {
if (savedState != null) {
// put settings back
setVolume(savedState.volume);
if (isCoordinator()) {
if (savedState.entry != null) {
// check if we have a playlist to deal with
if (savedState.entry
.getUpnpClass()
.contains(
"object.container.playlistContainer")) {
addURIToQueue(
savedState.entry.getRes(),
SonosXMLParser
.compileMetadataString(savedState.entry),
0, true);
SonosEntry entry = new SonosEntry(
"",
"",
"",
"",
"",
"",
"",
"x-rincon-queue:"
+ getUdn()
.getIdentifierString()
+ "#0");
setCurrentURI(entry);
setPositionTrack(savedState.track);
} else {
setCurrentURI(savedState.entry);
setPosition(savedState.relTime);
}
if (savedState.transportState
.equals("PLAYING")) {
play();
} else if (savedState.transportState
.equals("STOPPED")) {
stop();
} else if (savedState.transportState
.equals("PAUSED_PLAYBACK")) {
pause();
}
}
}
}
return true;
}
}
} | epl-1.0 |
paulianttila/openhab2 | bundles/org.openhab.binding.enocean/src/main/java/org/openhab/binding/enocean/internal/handler/EnOceanClassicDeviceHandler.java | 10512 | /**
* 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.enocean.internal.handler;
import static org.openhab.binding.enocean.internal.EnOceanBindingConstants.*;
import java.util.Set;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;
import org.eclipse.jdt.annotation.NonNull;
import org.openhab.binding.enocean.internal.config.EnOceanActuatorConfig;
import org.openhab.binding.enocean.internal.config.EnOceanChannelRockerSwitchConfigBase.SwitchMode;
import org.openhab.binding.enocean.internal.config.EnOceanChannelRockerSwitchListenerConfig;
import org.openhab.binding.enocean.internal.config.EnOceanChannelVirtualRockerSwitchConfig;
import org.openhab.binding.enocean.internal.eep.EEP;
import org.openhab.binding.enocean.internal.eep.EEPFactory;
import org.openhab.binding.enocean.internal.eep.EEPType;
import org.openhab.binding.enocean.internal.messages.BasePacket;
import org.openhab.core.library.types.OnOffType;
import org.openhab.core.library.types.StopMoveType;
import org.openhab.core.library.types.StringType;
import org.openhab.core.library.types.UpDownType;
import org.openhab.core.thing.Channel;
import org.openhab.core.thing.ChannelUID;
import org.openhab.core.thing.CommonTriggerEvents;
import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingStatusDetail;
import org.openhab.core.thing.ThingTypeUID;
import org.openhab.core.thing.link.ItemChannelLinkRegistry;
import org.openhab.core.thing.type.ChannelTypeUID;
import org.openhab.core.types.Command;
import org.openhab.core.types.RefreshType;
import org.openhab.core.util.HexUtils;
/**
*
* @author Daniel Weber - Initial contribution
* This class defines base functionality for sending eep messages. This class extends EnOceanBaseSensorHandler
* class as most actuator things send status or response messages, too.
*/
public class EnOceanClassicDeviceHandler extends EnOceanBaseActuatorHandler {
// List of thing types which support sending of eep messages
public static final Set<ThingTypeUID> SUPPORTED_THING_TYPES = Set.of(THING_TYPE_CLASSICDEVICE);
private StringType lastTriggerEvent = StringType.valueOf(CommonTriggerEvents.DIR1_PRESSED);
ScheduledFuture<?> releaseFuture = null;
public EnOceanClassicDeviceHandler(Thing thing, ItemChannelLinkRegistry itemChannelLinkRegistry) {
super(thing, itemChannelLinkRegistry);
}
@Override
void initializeConfig() {
super.initializeConfig();
((EnOceanActuatorConfig) config).broadcastMessages = true;
((EnOceanActuatorConfig) config).enoceanId = EMPTYENOCEANID;
}
@Override
public long getEnOceanIdToListenTo() {
return 0;
}
@Override
public void channelLinked(@NonNull ChannelUID channelUID) {
super.channelLinked(channelUID);
// if linked channel is a listening channel => put listener
Channel channel = getThing().getChannel(channelUID);
addListener(channel);
}
@Override
public void thingUpdated(Thing thing) {
super.thingUpdated(thing);
// it seems that there does not exist a channel update callback
// => remove all listeners and add them again
getBridgeHandler().removePacketListener(this);
this.getThing().getChannels().forEach(c -> {
if (isLinked(c.getUID()) && !addListener(c)) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, "Wrong channel configuration");
}
});
}
@Override
public void channelUnlinked(@NonNull ChannelUID channelUID) {
super.channelUnlinked(channelUID);
// if unlinked channel is listening channel => remove listener
Channel channel = getThing().getChannel(channelUID);
removeListener(channel);
}
protected boolean addListener(Channel channel) {
if (channel == null) {
return true;
}
ChannelTypeUID channelTypeUID = channel.getChannelTypeUID();
String id = channelTypeUID == null ? "" : channelTypeUID.getId();
if (id.startsWith(CHANNEL_ROCKERSWITCHLISTENER_START)) {
EnOceanChannelRockerSwitchListenerConfig config = channel.getConfiguration()
.as(EnOceanChannelRockerSwitchListenerConfig.class);
try {
getBridgeHandler().addPacketListener(this, Long.parseLong(config.enoceanId, 16));
return true;
} catch (NumberFormatException e) {
}
return false;
}
return true;
}
protected void removeListener(Channel channel) {
if (channel == null) {
return;
}
ChannelTypeUID channelTypeUID = channel.getChannelTypeUID();
String id = channelTypeUID == null ? "" : channelTypeUID.getId();
if (id.startsWith(CHANNEL_ROCKERSWITCHLISTENER_START)) {
EnOceanChannelRockerSwitchListenerConfig config = channel.getConfiguration()
.as(EnOceanChannelRockerSwitchListenerConfig.class);
try {
getBridgeHandler().removePacketListener(this, Long.parseLong(config.enoceanId, 16));
} catch (NumberFormatException e) {
}
}
}
@Override
protected Predicate<Channel> channelFilter(EEPType eepType, byte[] senderId) {
return c -> {
ChannelTypeUID channelTypeUID = c.getChannelTypeUID();
String id = channelTypeUID == null ? "" : channelTypeUID.getId();
return id.startsWith(CHANNEL_ROCKERSWITCHLISTENER_START)
&& c.getConfiguration().as(EnOceanChannelRockerSwitchListenerConfig.class).enoceanId
.equalsIgnoreCase(HexUtils.bytesToHex(senderId));
};
}
@SuppressWarnings("unlikely-arg-type")
private StringType convertToReleasedCommand(StringType command) {
return command.equals(CommonTriggerEvents.DIR1_PRESSED) ? StringType.valueOf(CommonTriggerEvents.DIR1_RELEASED)
: StringType.valueOf(CommonTriggerEvents.DIR2_RELEASED);
}
private StringType convertToPressedCommand(Command command, SwitchMode switchMode) {
if (command instanceof StringType) {
return (StringType) command;
} else if (command instanceof OnOffType) {
switch (switchMode) {
case RockerSwitch:
return (command == OnOffType.ON) ? StringType.valueOf(CommonTriggerEvents.DIR1_PRESSED)
: StringType.valueOf(CommonTriggerEvents.DIR2_PRESSED);
case ToggleDir1:
return StringType.valueOf(CommonTriggerEvents.DIR1_PRESSED);
case ToggleDir2:
return StringType.valueOf(CommonTriggerEvents.DIR2_PRESSED);
default:
return null;
}
} else if (command instanceof UpDownType) {
switch (switchMode) {
case RockerSwitch:
return (command == UpDownType.UP) ? StringType.valueOf(CommonTriggerEvents.DIR1_PRESSED)
: StringType.valueOf(CommonTriggerEvents.DIR2_PRESSED);
case ToggleDir1:
return StringType.valueOf(CommonTriggerEvents.DIR1_PRESSED);
case ToggleDir2:
return StringType.valueOf(CommonTriggerEvents.DIR2_PRESSED);
default:
return null;
}
} else if (command instanceof StopMoveType) {
if (command == StopMoveType.STOP) {
return lastTriggerEvent;
}
}
return null;
}
@Override
public void handleCommand(@NonNull ChannelUID channelUID, @NonNull Command command) {
// We must have a valid sendingEEPType and sender id to send commands
if (sendingEEPType == null || senderId == null || command == RefreshType.REFRESH) {
return;
}
String channelId = channelUID.getId();
Channel channel = getThing().getChannel(channelUID);
if (channel == null) {
return;
}
ChannelTypeUID channelTypeUID = channel.getChannelTypeUID();
String channelTypeId = (channelTypeUID != null) ? channelTypeUID.getId() : "";
if (channelTypeId.contains("Listener")) {
return;
}
EnOceanChannelVirtualRockerSwitchConfig channelConfig = channel.getConfiguration()
.as(EnOceanChannelVirtualRockerSwitchConfig.class);
StringType result = convertToPressedCommand(command, channelConfig.getSwitchMode());
if (result != null) {
lastTriggerEvent = result;
EEP eep = EEPFactory.createEEP(sendingEEPType);
if (eep.setSenderId(senderId).setDestinationId(destinationId).convertFromCommand(channelId, channelTypeId,
result, id -> this.getCurrentState(id), channel.getConfiguration()).hasData()) {
BasePacket press = eep.setSuppressRepeating(getConfiguration().suppressRepeating).getERP1Message();
getBridgeHandler().sendMessage(press, null);
if (channelConfig.duration > 0) {
releaseFuture = scheduler.schedule(() -> {
if (eep.convertFromCommand(channelId, channelTypeId, convertToReleasedCommand(lastTriggerEvent),
id -> this.getCurrentState(id), channel.getConfiguration()).hasData()) {
BasePacket release = eep.getERP1Message();
getBridgeHandler().sendMessage(release, null);
}
}, channelConfig.duration, TimeUnit.MILLISECONDS);
}
}
}
}
@Override
public void handleRemoval() {
if (releaseFuture != null && !releaseFuture.isDone()) {
releaseFuture.cancel(true);
}
releaseFuture = null;
super.handleRemoval();
}
}
| epl-1.0 |
krasv/flowr | commons/ant/org.flowr.ant.tasks/src/main/java/org/flowr/ant/tasks/TailStringTask.java | 1637 | /**
* DB Systel GmbH / i.S.A. Dresden GmbH & Co. KG (c) 2010
*/
package org.flowr.ant.tasks;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.PropertyHelper;
/**
* Ant task evaluating the lead part before a specified separator.
*<p>usage:</p>
* <pre>
* <tailString property="<i>result.prop.name</i>" separator="<i>anySeparatorText</i>" last="<i>true|false, default==false</i>" text="<i>any text or ${property.to.scan}</i>" />
* </pre>
* <p>Sample</p>
*<pre>
* <property name="build.version.full" value="1.0.0.201101012359" /><br>
* <tailString property="build.version" separator="." last="true" text="${build.version.full}" /><br>
* <echo message="build.version = ${build.version}" /><br>
*
* results "build.version = 201101012359"
*</pre>
* @author SvenKrause
*
*/
public class TailStringTask extends AbstractSeparatorbasedStringTask {
private boolean last;
/**
* @param last the last to set
*/
public void setLast(boolean last) {
this.last = last;
}
@Override
public void init() throws BuildException {
super.init();
last = false;
}
@Override
public void execute() throws BuildException {
validate();
PropertyHelper ph = PropertyHelper.getPropertyHelper(this.getProject());
int indexOf = last ? text.lastIndexOf(separator) : text.indexOf(separator);
if (indexOf != -1) {
String lead = text.substring(indexOf + separator.length(), text.length());
ph.setProperty("", propName, lead, true);
} else {
ph.setProperty("", propName, "", true);
}
}
}
| epl-1.0 |
ControlSystemStudio/cs-studio | thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/annotations/src/test/java/org/hibernate/test/annotations/indexcoll/IndexedCollectionTest.java | 18621 | //$Id: IndexedCollectionTest.java 18638 2010-01-26 20:11:51Z steve.ebersole@jboss.com $
package org.hibernate.test.annotations.indexcoll;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.dialect.HSQLDialect;
import org.hibernate.junit.RequiresDialect;
import org.hibernate.mapping.Collection;
import org.hibernate.mapping.Column;
import org.hibernate.test.annotations.TestCase;
/**
* Test index collections
*
* @author Emmanuel Bernard
*/
public class IndexedCollectionTest extends TestCase {
public void testJPA2DefaultMapColumns() throws Exception {
isDefaultKeyColumnPresent( Atmosphere.class.getName(), "gasesDef", "_KEY" );
isDefaultKeyColumnPresent( Atmosphere.class.getName(), "gasesPerKeyDef", "_KEY" );
isNotDefaultKeyColumnPresent( Atmosphere.class.getName(), "gasesDefLeg", "_KEY" );
}
public void testJPA2DefaultIndexColumns() throws Exception {
isDefaultKeyColumnPresent( Drawer.class.getName(), "dresses", "_ORDER" );
}
private void isDefaultKeyColumnPresent(String collectionOwner, String propertyName, String suffix) {
assertTrue( "Could not find " + propertyName + suffix,
isDefaultColumnPresent(collectionOwner, propertyName, suffix) );
}
private boolean isDefaultColumnPresent(String collectionOwner, String propertyName, String suffix) {
final Collection collection = getCfg().getCollectionMapping( collectionOwner + "." + propertyName );
final Iterator columnIterator = collection.getCollectionTable().getColumnIterator();
boolean hasDefault = false;
while ( columnIterator.hasNext() ) {
Column column = (Column) columnIterator.next();
if ( (propertyName + suffix).equals( column.getName() ) ) hasDefault = true;
}
return hasDefault;
}
private void isNotDefaultKeyColumnPresent(String collectionOwner, String propertyName, String suffix) {
assertFalse( "Could not find " + propertyName + suffix,
isDefaultColumnPresent(collectionOwner, propertyName, suffix) );
}
public void testFkList() throws Exception {
Wardrobe w = new Wardrobe();
Drawer d1 = new Drawer();
Drawer d2 = new Drawer();
w.setDrawers( new ArrayList<Drawer>() );
w.getDrawers().add( d1 );
w.getDrawers().add( d2 );
Session s;
Transaction tx;
s = openSession();
tx = s.beginTransaction();
s.persist( w );
s.flush();
s.clear();
w = (Wardrobe) s.get( Wardrobe.class, w.getId() );
assertNotNull( w );
assertNotNull( w.getDrawers() );
List<Drawer> result = w.getDrawers();
assertEquals( 2, result.size() );
assertEquals( d2.getId(), result.get( 1 ).getId() );
result.remove( d1 );
s.flush();
d1 = (Drawer) s.merge( d1 );
result.add( d1 );
s.flush();
s.clear();
w = (Wardrobe) s.get( Wardrobe.class, w.getId() );
assertNotNull( w );
assertNotNull( w.getDrawers() );
result = w.getDrawers();
assertEquals( 2, result.size() );
assertEquals( d1.getId(), result.get( 1 ).getId() );
s.delete( result.get( 0 ) );
s.delete( result.get( 1 ) );
s.delete( w );
s.flush();
tx.rollback();
s.close();
}
public void testJoinedTableList() throws Exception {
Wardrobe w = new Wardrobe();
w.setDrawers( new ArrayList<Drawer>() );
Drawer d = new Drawer();
w.getDrawers().add( d );
Dress d1 = new Dress();
Dress d2 = new Dress();
d.setDresses( new ArrayList<Dress>() );
d.getDresses().add( d1 );
d.getDresses().add( d2 );
Session s;
Transaction tx;
s = openSession();
tx = s.beginTransaction();
s.persist( d1 );
s.persist( d2 );
s.persist( w );
s.flush();
s.clear();
d = (Drawer) s.get( Drawer.class, d.getId() );
assertNotNull( d );
assertNotNull( d.getDresses() );
List<Dress> result = d.getDresses();
assertEquals( 2, result.size() );
assertEquals( d2.getId(), result.get( 1 ).getId() );
result.remove( d1 );
s.flush();
d1 = (Dress) s.merge( d1 );
result.add( d1 );
s.flush();
s.clear();
d = (Drawer) s.get( Drawer.class, d.getId() );
assertNotNull( d );
assertNotNull( d.getDresses() );
result = d.getDresses();
assertEquals( 2, result.size() );
assertEquals( d1.getId(), result.get( 1 ).getId() );
s.delete( result.get( 0 ) );
s.delete( result.get( 1 ) );
s.delete( d );
s.flush();
tx.rollback();
s.close();
}
public void testMapKey() throws Exception {
Session s;
Transaction tx;
s = openSession();
tx = s.beginTransaction();
Software hibernate = new Software();
hibernate.setName( "Hibernate" );
Version v1 = new Version();
v1.setCodeName( "HumbaHumba" );
v1.setNumber( "1.0" );
v1.setSoftware( hibernate );
Version v2 = new Version();
v2.setCodeName( "Copacabana" );
v2.setNumber( "2.0" );
v2.setSoftware( hibernate );
Version v4 = new Version();
v4.setCodeName( "Dreamland" );
v4.setNumber( "4.0" );
v4.setSoftware( hibernate );
Map<String, Version> link = new HashMap<String, Version>();
link.put( v1.getCodeName(), v1 );
link.put( v2.getCodeName(), v2 );
link.put( v4.getCodeName(), v4 );
hibernate.setVersions( link );
s.persist( hibernate );
s.persist( v1 );
s.persist( v2 );
s.persist( v4 );
s.flush();
s.clear();
hibernate = (Software) s.get( Software.class, "Hibernate" );
assertEquals( 3, hibernate.getVersions().size() );
assertEquals( "1.0", hibernate.getVersions().get( "HumbaHumba" ).getNumber() );
assertEquals( "2.0", hibernate.getVersions().get( "Copacabana" ).getNumber() );
hibernate.getVersions().remove( v4.getCodeName() );
s.flush();
s.clear();
hibernate = (Software) s.get( Software.class, "Hibernate" );
assertEquals( "So effect on collection changes", 3, hibernate.getVersions().size() );
for ( Version v : hibernate.getVersions().values() ) {
s.delete( v );
}
s.delete( hibernate );
s.flush();
tx.rollback();
s.close();
}
public void testDefaultMapKey() throws Exception {
Session s;
Transaction tx;
s = openSession();
tx = s.beginTransaction();
AddressBook book = new AddressBook();
book.setOwner( "Emmanuel" );
AddressEntryPk helene = new AddressEntryPk( "Helene", "Michau" );
AddressEntry heleneEntry = new AddressEntry();
heleneEntry.setBook( book );
heleneEntry.setCity( "Levallois" );
heleneEntry.setStreet( "Louis Blanc" );
heleneEntry.setPerson( helene );
AddressEntryPk primeMinister = new AddressEntryPk( "Dominique", "Villepin" );
AddressEntry primeMinisterEntry = new AddressEntry();
primeMinisterEntry.setBook( book );
primeMinisterEntry.setCity( "Paris" );
primeMinisterEntry.setStreet( "Hotel Matignon" );
primeMinisterEntry.setPerson( primeMinister );
book.getEntries().put( helene, heleneEntry );
book.getEntries().put( primeMinister, primeMinisterEntry );
s.persist( book );
s.flush();
s.clear();
book = (AddressBook) s.get( AddressBook.class, book.getId() );
assertEquals( 2, book.getEntries().size() );
assertEquals( heleneEntry.getCity(), book.getEntries().get( helene ).getCity() );
AddressEntryPk fake = new AddressEntryPk( "Fake", "Fake" );
book.getEntries().put( fake, primeMinisterEntry );
s.flush();
s.clear();
book = (AddressBook) s.get( AddressBook.class, book.getId() );
assertEquals( 2, book.getEntries().size() );
assertNull( book.getEntries().get( fake ) );
s.delete( book );
s.flush();
tx.rollback();
s.close();
}
public void testMapKeyToEntity() throws Exception {
Session s;
Transaction tx;
s = openSession();
tx = s.beginTransaction();
AlphabeticalDirectory m = new AlphabeticalDirectory();
m.setName( "M" );
AlphabeticalDirectory v = new AlphabeticalDirectory();
v.setName( "V" );
s.persist( m );
s.persist( v );
AddressBook book = new AddressBook();
book.setOwner( "Emmanuel" );
AddressEntryPk helene = new AddressEntryPk( "Helene", "Michau" );
AddressEntry heleneEntry = new AddressEntry();
heleneEntry.setBook( book );
heleneEntry.setCity( "Levallois" );
heleneEntry.setStreet( "Louis Blanc" );
heleneEntry.setPerson( helene );
heleneEntry.setDirectory( m );
AddressEntryPk primeMinister = new AddressEntryPk( "Dominique", "Villepin" );
AddressEntry primeMinisterEntry = new AddressEntry();
primeMinisterEntry.setBook( book );
primeMinisterEntry.setCity( "Paris" );
primeMinisterEntry.setStreet( "Hotel Matignon" );
primeMinisterEntry.setPerson( primeMinister );
primeMinisterEntry.setDirectory( v );
book.getEntries().put( helene, heleneEntry );
book.getEntries().put( primeMinister, primeMinisterEntry );
s.persist( book );
s.flush();
s.clear();
book = (AddressBook) s.get( AddressBook.class, book.getId() );
assertEquals( 2, book.getEntries().size() );
assertEquals( heleneEntry.getCity(), book.getEntries().get( helene ).getCity() );
assertEquals( "M", book.getEntries().get( helene ).getDirectory().getName() );
s.delete( book );
tx.rollback();
s.close();
}
@RequiresDialect(HSQLDialect.class)
public void testComponentSubPropertyMapKey() throws Exception {
Session s;
Transaction tx;
s = openSession();
tx = s.beginTransaction();
AddressBook book = new AddressBook();
book.setOwner( "Emmanuel" );
AddressEntryPk helene = new AddressEntryPk( "Helene", "Michau" );
AddressEntry heleneEntry = new AddressEntry();
heleneEntry.setBook( book );
heleneEntry.setCity( "Levallois" );
heleneEntry.setStreet( "Louis Blanc" );
heleneEntry.setPerson( helene );
AddressEntryPk primeMinister = new AddressEntryPk( "Dominique", "Villepin" );
AddressEntry primeMinisterEntry = new AddressEntry();
primeMinisterEntry.setBook( book );
primeMinisterEntry.setCity( "Paris" );
primeMinisterEntry.setStreet( "Hotel Matignon" );
primeMinisterEntry.setPerson( primeMinister );
book.getEntries().put( helene, heleneEntry );
book.getEntries().put( primeMinister, primeMinisterEntry );
s.persist( book );
s.flush();
s.clear();
book = (AddressBook) s.get( AddressBook.class, book.getId() );
assertEquals( 2, book.getLastNameEntries().size() );
assertEquals( heleneEntry.getCity(), book.getLastNameEntries().get( "Michau" ).getCity() );
AddressEntryPk fake = new AddressEntryPk( "Fake", "Fake" );
book.getEntries().put( fake, primeMinisterEntry );
s.flush();
s.clear();
book = (AddressBook) s.get( AddressBook.class, book.getId() );
assertEquals( 2, book.getEntries().size() );
assertNull( book.getEntries().get( fake ) );
s.delete( book );
tx.rollback();
s.close();
}
public void testMapKeyOnManyToMany() throws Exception {
Session s;
s = openSession();
s.getTransaction().begin();
News airplane = new News();
airplane.setTitle( "Crash!" );
airplane.setDetail( "An airplaned crashed." );
s.persist( airplane );
Newspaper lemonde = new Newspaper();
lemonde.setName( "Lemonde" );
lemonde.getNews().put( airplane.getTitle(), airplane );
s.persist( lemonde );
s.flush();
s.clear();
lemonde = (Newspaper) s.get( Newspaper.class, lemonde.getId() );
assertEquals( 1, lemonde.getNews().size() );
News news = lemonde.getNews().get( airplane.getTitle() );
assertNotNull( news );
assertEquals( airplane.getTitle(), news.getTitle() );
s.delete( lemonde );
s.delete( news );
s.getTransaction().rollback();
s.close();
}
public void testMapKeyOnManyToManyOnId() throws Exception {
Session s;
s = openSession();
s.getTransaction().begin();
News hibernate1 = new News();
hibernate1.setTitle( "#1 ORM solution in the Java world" );
hibernate1.setDetail( "Well, that's no news ;-)" );
s.persist( hibernate1 );
PressReleaseAgency schwartz = new PressReleaseAgency();
schwartz.setName( "Schwartz" );
schwartz.getProvidedNews().put( hibernate1.getId(), hibernate1 );
s.persist( schwartz );
s.flush();
s.clear();
schwartz = (PressReleaseAgency) s.get( PressReleaseAgency.class, schwartz.getId() );
assertEquals( 1, schwartz.getProvidedNews().size() );
News news = schwartz.getProvidedNews().get( hibernate1.getId() );
assertNotNull( news );
assertEquals( hibernate1.getTitle(), news.getTitle() );
s.delete( schwartz );
s.delete( news );
s.getTransaction().rollback();
s.close();
}
public void testMapKeyAndIdClass() throws Exception {
Session s = openSession();
Transaction tx = s.beginTransaction();
Painter picasso = new Painter();
Painting laVie = new Painting( "La Vie", "Picasso", 50, 20 );
picasso.getPaintings().put( "La Vie", laVie );
Painting famille = new Painting( "La Famille du Saltimbanque", "Picasso", 50, 20 );
picasso.getPaintings().put( "La Famille du Saltimbanque", famille );
s.persist( picasso );
s.flush();
s.clear();
picasso = (Painter) s.get( Painter.class, picasso.getId() );
Painting painting = picasso.getPaintings().get( famille.getName() );
assertNotNull( painting );
assertEquals( painting.getName(), famille.getName() );
s.delete( picasso );
tx.rollback();
s.close();
}
public void testRealMap() throws Exception {
Session s = openSession();
Transaction tx = s.beginTransaction();
Atmosphere atm = new Atmosphere();
Atmosphere atm2 = new Atmosphere();
GasKey key = new GasKey();
key.setName( "O2" );
Gas o2 = new Gas();
o2.name = "oxygen";
atm.gases.put( "100%", o2 );
atm.gasesPerKey.put( key, o2 );
atm2.gases.put( "100%", o2 );
atm2.gasesPerKey.put( key, o2 );
s.persist( key );
s.persist( atm );
s.persist( atm2 );
s.flush();
s.clear();
atm = (Atmosphere) s.get( Atmosphere.class, atm.id );
key = (GasKey) s.get( GasKey.class, key.getName() );
assertEquals( 1, atm.gases.size() );
assertEquals( o2.name, atm.gases.get( "100%" ).name );
assertEquals( o2.name, atm.gasesPerKey.get( key ).name );
tx.rollback();
s.close();
}
public void testTemporalKeyMap() throws Exception {
Session s = openSession();
Transaction tx = s.beginTransaction();
Atmosphere atm = new Atmosphere();
atm.colorPerDate.put( new Date(1234567000), "red" );
s.persist( atm );
s.flush();
s.clear();
atm = (Atmosphere) s.get( Atmosphere.class, atm.id );
assertEquals( 1, atm.colorPerDate.size() );
final Date date = atm.colorPerDate.keySet().iterator().next();
final long diff = new Date( 1234567000 ).getTime() - date.getTime();
assertTrue( "24h diff max", diff > 0 && diff < 24*60*60*1000 );
tx.rollback();
s.close();
}
public void testEnumKeyType() throws Exception {
Session s = openSession();
Transaction tx = s.beginTransaction();
Atmosphere atm = new Atmosphere();
atm.colorPerLevel.put( Atmosphere.Level.HIGH, "red" );
s.persist( atm );
s.flush();
s.clear();
atm = (Atmosphere) s.get( Atmosphere.class, atm.id );
assertEquals( 1, atm.colorPerLevel.size() );
assertEquals( "red", atm.colorPerLevel.get(Atmosphere.Level.HIGH) );
tx.rollback();
s.close();
}
public void testMapKeyEntityEntity() throws Exception {
Session s = openSession();
Transaction tx = s.beginTransaction();
AddressBook book = new AddressBook();
s.persist( book );
AddressEntry entry = new AddressEntry();
entry.setCity( "Atlanta");
AddressEntryPk pk = new AddressEntryPk("Coca", "Cola" );
entry.setPerson( pk );
entry.setBook( book );
AlphabeticalDirectory ad = new AlphabeticalDirectory();
ad.setName( "C");
s.persist( ad );
entry.setDirectory( ad );
s.persist( entry );
book.getDirectoryEntries().put( ad, entry );
s.flush();
s.clear();
book = (AddressBook) s.get( AddressBook.class, book.getId() );
assertEquals( 1, book.getDirectoryEntries().size() );
assertEquals( "C", book.getDirectoryEntries().keySet().iterator().next().getName() );
tx.rollback();
s.close();
}
public void testEntityKeyElementTarget() throws Exception {
Session s = openSession();
Transaction tx = s.beginTransaction();
Atmosphere atm = new Atmosphere();
Gas o2 = new Gas();
o2.name = "oxygen";
atm.composition.put( o2, 94.3 );
s.persist( o2 );
s.persist( atm );
s.flush();
s.clear();
atm = (Atmosphere) s.get( Atmosphere.class, atm.id );
assertTrue( ! Hibernate.isInitialized( atm.composition ) );
assertEquals( 1, atm.composition.size() );
assertEquals( o2.name, atm.composition.keySet().iterator().next().name );
tx.rollback();
s.close();
}
public void testSortedMap() {
Session s = openSession();
Transaction tx = s.beginTransaction();
Training training = new Training();
Trainee trainee = new Trainee();
trainee.setName( "Jim" );
Trainee trainee2 = new Trainee();
trainee2.setName( "Emmanuel" );
s.persist( trainee );
s.persist( trainee2 );
training.getTrainees().put( "Jim", trainee );
training.getTrainees().put( "Emmanuel", trainee2 );
s.persist( training );
s.flush();
s.clear();
training = (Training) s.get( Training.class, training.getId() );
assertEquals( "Emmanuel", training.getTrainees().firstKey() );
assertEquals( "Jim", training.getTrainees().lastKey() );
tx.rollback();
s.close();
}
public void testMapKeyLoad() throws Exception {
Session s;
Transaction tx;
s = openSession();
tx = s.beginTransaction();
Software hibernate = new Software();
hibernate.setName( "Hibernate" );
Version v1 = new Version();
v1.setCodeName( "HumbaHumba" );
v1.setNumber( "1.0" );
v1.setSoftware( hibernate );
hibernate.addVersion( v1 );
s.persist( hibernate );
s.persist( v1 );
s.flush();
s.clear();
hibernate = (Software) s.get( Software.class, "Hibernate" );
assertEquals(1, hibernate.getVersions().size() );
Version v2 = new Version();
v2.setCodeName( "HumbaHumba2" );
v2.setNumber( "2.0" );
v2.setSoftware( hibernate );
hibernate.addVersion( v2 );
assertEquals( "One loaded persisted version, and one just added", 2, hibernate.getVersions().size() );
s.flush();
s.clear();
hibernate = (Software) s.get( Software.class, "Hibernate" );
for ( Version v : hibernate.getVersions().values() ) {
s.delete( v );
}
s.delete( hibernate );
tx.rollback();
s.close();
}
public IndexedCollectionTest(String x) {
super( x );
}
protected Class[] getAnnotatedClasses() {
return new Class[]{
Wardrobe.class,
Drawer.class,
Dress.class,
Software.class,
Version.class,
AddressBook.class,
AddressEntry.class,
AddressEntryPk.class, //should be silently ignored
Newspaper.class,
News.class,
PressReleaseAgency.class,
Painter.class,
Painting.class,
Atmosphere.class,
Gas.class,
AlphabeticalDirectory.class,
GasKey.class,
Trainee.class,
Training.class
};
}
}
| epl-1.0 |
martinmathewhuawei/daylight-cisco-ctrl | opendaylight/sal/api/src/main/java/org/opendaylight/controller/sal/action/SetNwSrc.java | 2034 |
/*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.controller.sal.action;
import java.net.InetAddress;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
/**
* Set network source address action
*/
@XmlRootElement
@XmlAccessorType(XmlAccessType.NONE)
public class SetNwSrc extends Action {
InetAddress address;
/* Dummy constructor for JAXB */
private SetNwSrc () {
}
public SetNwSrc(InetAddress address) {
type = ActionType.SET_NW_SRC;
this.address = address;
}
/**
* Returns the network address this action will set
*
* @return InetAddress
*/
public InetAddress getAddress() {
return address;
}
@XmlElement (name="address")
public String getAddressAsString() {
return address.getHostAddress();
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (!super.equals(obj))
return false;
if (getClass() != obj.getClass())
return false;
SetNwSrc other = (SetNwSrc) obj;
if (address == null) {
if (other.address != null)
return false;
} else if (!address.equals(other.address))
return false;
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + ((address == null) ? 0 : address.hashCode());
return result;
}
@Override
public String toString() {
return type + "[address = " + address + "]";
}
}
| epl-1.0 |
Tasktop/code2cloud.server | com.tasktop.c2c.server/com.tasktop.c2c.server.profile.web.ui/src/main/java/com/tasktop/c2c/server/profile/web/ui/client/presenter/AbstractProfilePresenter.java | 1611 | /*******************************************************************************
* Copyright (c) 2010, 2012 Tasktop Technologies
* Copyright (c) 2010, 2011 SpringSource, a division of VMware
*
* 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:
* Tasktop Technologies - initial API and implementation
******************************************************************************/
package com.tasktop.c2c.server.profile.web.ui.client.presenter;
import net.customware.gwt.dispatch.client.DispatchAsync;
import com.google.gwt.user.client.ui.IsWidget;
import com.tasktop.c2c.server.common.profile.web.client.AppState;
import com.tasktop.c2c.server.common.profile.web.client.ProfileServiceAsync;
import com.tasktop.c2c.server.common.web.client.presenter.AbstractPresenter;
import com.tasktop.c2c.server.common.web.client.view.CommonGinjector;
import com.tasktop.c2c.server.profile.web.ui.client.ProfileEntryPoint;
public abstract class AbstractProfilePresenter extends AbstractPresenter {
protected AbstractProfilePresenter(IsWidget view) {
super(view);
}
public AppState getAppState() {
return ProfileEntryPoint.getInstance().getAppState();
}
public ProfileServiceAsync getProfileService() {
return ProfileEntryPoint.getInstance().getProfileService();
}
protected DispatchAsync getDispatchService() {
return CommonGinjector.get.instance().getDispatchService();
}
}
| epl-1.0 |
xeviox-com/blackstrap | src/com/xeviox/commons/conditions/Clauses.java | 4145 | /*******************************************************************************
* Copyright (c) 2013 EclipseSource 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:
* EclipseSource - initial API and implementation
* Benjamin Pabst - further development
******************************************************************************/
package com.xeviox.commons.conditions;
import java.lang.reflect.InvocationTargetException;
public final class Clauses {
public static class Clause {
private final boolean condition;
public Clause(boolean condition) {
this.condition = condition;
}
public void throwIllegalState() {
if (condition) {
throw new IllegalStateException();
}
}
public void throwIllegalState(final String message) {
if (condition) {
throw new IllegalStateException(message);
}
}
public void throwNullPointer() {
if (condition) {
throw new NullPointerException();
}
}
public void throwNullPointer(final String message) {
if (condition) {
throw new NullPointerException(message);
}
}
public void throwIllegalArgument() {
if (condition) {
throw new IllegalArgumentException();
}
}
public void throwIllegalArgument(final String message) {
if (condition) {
throw new IllegalArgumentException(message);
}
}
public <T extends RuntimeException> void doThrow(T rt) {
if (condition) {
throw rt;
}
}
public void doThrow(Class<? extends RuntimeException> clazz) {
if (!condition) {
return;
}
try {
throw clazz.newInstance();
}
catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException(e);
}
}
public void doThrow(Class<? extends RuntimeException> clazz, final String message) {
if (!condition) {
return;
}
try {
throw clazz.getDeclaredConstructor(String.class).newInstance(message);
}
catch (InstantiationException | IllegalAccessException | NoSuchMethodException
| InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
private static Clause TRUE_CLAUSE = new Clause(true);
private static Clause FALSE_CLAUSE = new Clause(false);
public static Clause when(boolean condition) {
return condition ? TRUE_CLAUSE : FALSE_CLAUSE;
}
public static Clause whenNot(boolean condition) {
return when(!condition);
}
public static Clause whenNull(Object object) {
return when(object == null);
}
/**
* Performs a null check and returns the given reference.
*
* @param reference
* @return reference
* @throws NullPointerException if reference is null.
*/
public static <T> T nullChecked(final T reference) {
whenNull(reference).throwNullPointer();
return reference;
}
/**
* Performs a null check and returns the given reference.
*
* @param reference
* @param message Additional message to be added to the {@link NullPointerException}.
* @return
* @throws NullPointerException if reference is null.
*/
public static <T> T nullChecked(final T reference, final String message) {
whenNull(reference).throwNullPointer(message);
return reference;
}
private Clauses() {
// prevent instantiation
}
} | epl-1.0 |
ObeoNetwork/M2Doc | plugins/org.obeonetwork.m2doc/src-gen/org/obeonetwork/m2doc/template/IGenerateable.java | 1253 | /**
* Copyright (c) 2016 Obeo.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v2.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v20.html
*
* Contributors:
* Obeo - initial API and implementation
*/
package org.obeonetwork.m2doc.template;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>IGenerateable</b></em>'.
* <!-- end-user-doc -->
*
* @see org.obeonetwork.m2doc.template.TemplatePackage#getIGenerateable()
* @model interface="true" abstract="true"
* @generated
*/
public interface IGenerateable extends EObject {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated
*/
String copyright = " Copyright (c) 2016 Obeo. \r\n All rights reserved. This program and the accompanying materials\r\n are made available under the terms of the Eclipse Public License v2.0\r\n which accompanies this distribution, and is available at\r\n http://www.eclipse.org/legal/epl-v20.html\r\n \r\n Contributors:\r\n Obeo - initial API and implementation";
} // IGenerateable
| epl-1.0 |
djelinek/reddeer | plugins/org.eclipse.reddeer.swt/src/org/eclipse/reddeer/swt/api/CTabItem.java | 1464 | /*******************************************************************************
* Copyright (c) 2017 Red Hat, Inc and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat Inc. - initial API and implementation
*******************************************************************************/
package org.eclipse.reddeer.swt.api;
import org.eclipse.reddeer.core.reference.ReferencedComposite;
/**
* API for CTab item manipulation.
*
* @author Vlado Pakan
*
*/
public interface CTabItem extends Item<org.eclipse.swt.custom.CTabItem>, ReferencedComposite {
/**
* Activates CTab item.
*/
void activate();
/**
* Closes CTabItem.
*/
void close();
/**
* Find outs whether the close button should be shown or not.
*
* @return true if the close button should be shown
*/
boolean isShowClose();
/**
* Returns true if the tab is visible
* @return true if the tab is visible
*/
boolean isShowing();
/**
* Returns parent folder {@link CTabFolder}
* @return parent folder
*/
CTabFolder getFolder();
/**
* Gets tooltip text of CTabItem
* @return tooltip text of CTabItem
*/
String getToolTipText();
/**
* Checks if tab item is active
* @return
*/
boolean isActive();
}
| epl-1.0 |
debabratahazra/DS | designstudio/components/page/core/com.odcgroup.page.model.dsl/src/com/odcgroup/page/resource/exception/RootWidgetNullException.java | 433 | package com.odcgroup.page.resource.exception;
import org.eclipse.emf.common.util.URI;
/**
* Thrown if a PageDSLResource is loaded and no root widget is present
*
* @author amc
*
*/
public class RootWidgetNullException extends PageDSLResourceLoadException {
private static final long serialVersionUID = -9131994957243179862L;
public RootWidgetNullException(URI uri) {
super(uri, "Root widget not present (null)");
}
}
| epl-1.0 |
lijz36/YuanFresh | V_1.0/YuanFresh/src/app/yuanfresh/lijz/beans/PingJia_Info.java | 2160 | package app.yuanfresh.lijz.beans;
public class PingJia_Info {
private String goods_id; //商品ID
private String evaluate_score; //满意度
private String evaluate_comment; //评论内容
private String store_desccredit; //发货速度
private String store_servicecredit; //服务态度
private String store_deliverycredit; //发货速度
private String geval_image; //评论图片
public PingJia_Info(String goods_id, String evaluate_score,
String evaluate_comment, String store_desccredit,
String store_servicecredit, String store_deliverycredit,
String geval_image) {
this.goods_id = goods_id;
this.evaluate_score = evaluate_score;
this.evaluate_comment = evaluate_comment;
this.store_desccredit = store_desccredit;
this.store_servicecredit = store_servicecredit;
this.store_deliverycredit = store_deliverycredit;
this.geval_image = geval_image;
}
public String getGoods_id() {
return goods_id;
}
public void setGoods_id(String goods_id) {
this.goods_id = goods_id;
}
public String getEvaluate_score() {
return evaluate_score;
}
public void setEvaluate_score(String evaluate_score) {
this.evaluate_score = evaluate_score;
}
public String getEvaluate_comment() {
return evaluate_comment;
}
public void setEvaluate_comment(String evaluate_comment) {
this.evaluate_comment = evaluate_comment;
}
public String getStore_desccredit() {
return store_desccredit;
}
public void setStore_desccredit(String store_desccredit) {
this.store_desccredit = store_desccredit;
}
public String getStore_servicecredit() {
return store_servicecredit;
}
public void setStore_servicecredit(String store_servicecredit) {
this.store_servicecredit = store_servicecredit;
}
public String getStore_deliverycredit() {
return store_deliverycredit;
}
public void setStore_deliverycredit(String store_deliverycredit) {
this.store_deliverycredit = store_deliverycredit;
}
public String getGeval_image() {
return geval_image;
}
public void setGeval_image(String geval_image) {
this.geval_image = geval_image;
}
}
| epl-1.0 |
sonatype/nexus-public | components/nexus-repository-services/src/main/java/org/sonatype/nexus/repository/search/query/SearchResultComponentGenerator.java | 1090 | /*
* Sonatype Nexus (TM) Open Source Version
* Copyright (c) 2008-present Sonatype, Inc.
* All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions.
*
* This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0,
* which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html.
*
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks
* of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the
* Eclipse Foundation. All other trademarks are the property of their respective owners.
*/
package org.sonatype.nexus.repository.search.query;
import java.util.Set;
import org.sonatype.nexus.repository.search.ComponentSearchResult;
/**
*
*
* @since 3.14
*/
public interface SearchResultComponentGenerator
{
ComponentSearchResult from(ComponentSearchResult hit, Set<String> componentIdSet);
}
| epl-1.0 |
devjunix/libjt400-java | src/com/ibm/as400/access/AS400PackedDecimal.java | 24379 | ///////////////////////////////////////////////////////////////////////////////
//
// JTOpen (IBM Toolbox for Java - OSS version)
//
// Filename: AS400PackedDecimal.java
//
// The source code contained herein is licensed under the IBM Public License
// Version 1.0, which has been approved by the Open Source Initiative.
// Copyright (C) 1997-2004 International Business Machines Corporation and
// others. All rights reserved.
//
///////////////////////////////////////////////////////////////////////////////
package com.ibm.as400.access;
import java.math.BigDecimal;
import java.math.BigInteger;
/**
* Provides a converter between a BigDecimal object and a packed decimal format floating point number.
**/
public class AS400PackedDecimal implements AS400DataType
{
static final long serialVersionUID = 4L;
private int digits_;
private int scale_;
private static final long defaultValue = 0;
static final boolean HIGH_NIBBLE = true;
static final boolean LOW_NIBBLE = false;
private boolean useDouble_ = false;
/**
* Constructs an AS400PackedDecimal object.
* @param numDigits The number of digits in the packed decimal number. It must be greater than or equal to one and less than or equal to thirty-one.
* @param numDecimalPositions The number of decimal positions in the packed decimal number. It must be greater than or equal to zero and less than or equal to <i>numDigits</i>.
**/
public AS400PackedDecimal(int numDigits, int numDecimalPositions)
{
// check for valid input
if (numDigits < 1 || numDigits > 63) // @M0C - changed the upper limit here from 31 for JDBC support
{
throw new ExtendedIllegalArgumentException("numDigits (" + String.valueOf(numDigits) + ")", ExtendedIllegalArgumentException.RANGE_NOT_VALID);
}
if (numDecimalPositions < 0 || numDecimalPositions > numDigits)
{
throw new ExtendedIllegalArgumentException("numDecimalPositions (" + String.valueOf(numDecimalPositions) + ")", ExtendedIllegalArgumentException.RANGE_NOT_VALID);
}
// set instance variables
this.digits_ = numDigits;
this.scale_ = numDecimalPositions;
}
/**
* Creates a new AS400PackedDecimal object that is identical to the current instance.
* @return The new object.
**/
public Object clone()
{
try
{
return super.clone(); // Object.clone does not throw exception
}
catch (CloneNotSupportedException e)
{
Trace.log(Trace.ERROR, "Unexpected cloning error", e);
throw new InternalErrorException(InternalErrorException.UNKNOWN);
}
}
/**
* Returns the byte length of the data type.
* @return The number of bytes in the IBM i representation of the data type.
**/
public int getByteLength()
{
return this.digits_/2+1;
}
/**
* Returns a Java object representing the default value of the data type.
* @return The BigDecimal object with a value of zero.
**/
public Object getDefaultValue()
{
return BigDecimal.valueOf(defaultValue);
}
/**
* Returns {@link com.ibm.as400.access.AS400DataType#TYPE_PACKED TYPE_PACKED}.
* @return <tt>AS400DataType.TYPE_PACKED</tt>.
**/
public int getInstanceType()
{
return AS400DataType.TYPE_PACKED;
}
/**
* Returns the Java class that corresponds with this data type.
* @return <tt>BigDecimal.class</tt>.
**/
public Class getJavaType()
{
return BigDecimal.class;
}
/**
* Returns the total number of digits in the packed decimal number.
* @return The number of digits.
**/
public int getNumberOfDigits()
{
return this.digits_;
}
/**
* Returns the number of decimal positions in the packed decimal number.
* @return The number of decimal positions.
**/
public int getNumberOfDecimalPositions()
{
return this.scale_;
}
/**
* Indicates if a {@link java.lang.Double Double} object or a
* {@link java.math.BigDecimal BigDecimal} object will be returned
* on a call to {@link #toObject toObject()}.
* @return true if a Double will be returned, false if a BigDecimal
* will be returned. The default is false.
**/
public boolean isUseDouble()
{
return useDouble_;
}
/**
* Sets whether to return a {@link java.lang.Double Double} object or a
* {@link java.math.BigDecimal BigDecimal} object on a call to
* {@link #toObject toObject()}.
* @see com.ibm.as400.access.AS400ZonedDecimal#setUseDouble
**/
public void setUseDouble(boolean b)
{
useDouble_ = b;
}
/**
* Converts the specified Java object to IBM i format.
* @param javaValue The object corresponding to the data type. It must be an instance of BigDecimal and the BigDecimal must have a less than or equal to number of digits and a less than or equal to number of decimal places.
* @return The IBM i representation of the data type.
**/
public byte[] toBytes(Object javaValue)
{
byte[] as400Value = new byte[this.digits_/2+1];
this.toBytes(javaValue, as400Value, 0);
return as400Value;
}
/**
* Converts the specified Java object into IBM i format in the specified byte array.
* @param javaValue The object corresponding to the data type. It must be an instance of BigDecimal and the BigDecimal must have a less than or equal to number of digits and a less than or equal to number of decimal places.
* @param as400Value The array to receive the data type in IBM i format. There must be enough space to hold the IBM i value.
* @return The number of bytes in the IBM i representation of the data type.
**/
public int toBytes(Object javaValue, byte[] as400Value)
{
return this.toBytes(javaValue, as400Value, 0);
}
/**
* Converts the specified Java object into IBM i format in the specified byte array.
* @param javaValue An object corresponding to the data type. It must be an instance of BigDecimal and the BigDecimal must have a less than or equal to number of digits and a less than or equal to number of decimal places.
* @param as400Value The array to receive the data type in IBM i format. There must be enough space to hold the IBM i value.
* @param offset The offset into the byte array for the start of the IBM i value. It must be greater than or equal to zero.
* @return The number of bytes in the IBM i representation of the data type.
**/
public int toBytes(Object javaValue, byte[] as400Value, int offset)
{
int outDigits = this.digits_;
int outDecimalPlaces = this.scale_;
int outLength = outDigits/2+1;
// verify input
BigDecimal inValue = null;
try {
inValue = (BigDecimal)javaValue; // Let this line throw ClassCastException
}
catch (ClassCastException e) {
Trace.log(Trace.ERROR, "ClassCastException when attempting to cast a " + javaValue.getClass().getName() + " to a BigDecimal", e);
throw e;
}
if (inValue.scale() > outDecimalPlaces) // Let this line throw NullPointerException
{
throw new ExtendedIllegalArgumentException("javaValue (" + javaValue.toString() + ")", ExtendedIllegalArgumentException.LENGTH_NOT_VALID);
}
// read the sign
int sign = inValue.signum();
// get just the digits from BigDecimal, "normalize" away sign, decimal place etc.
char[] inChars = inValue.abs().movePointRight(outDecimalPlaces).toBigInteger().toString().toCharArray();
// Check overall length
int inLength = inChars.length;
if (inLength > outDigits)
{
throw new ExtendedIllegalArgumentException("javaValue (" + javaValue.toString() + ")", ExtendedIllegalArgumentException.LENGTH_NOT_VALID);
}
int inPosition = 0; // position in char[]
// calculate number of leading zero's
int leadingZeros = (outDigits % 2 == 0) ? (outDigits - inLength + 1) : (outDigits - inLength);
// write correct number of leading zero's, allow ArrayIndexException to be thrown below
for (int i=0; i<leadingZeros-1; i+=2)
{
as400Value[offset++] = 0;
}
// if odd number of leading zero's, write leading zero and first digit
if (leadingZeros > 0)
{
if (leadingZeros % 2 != 0)
{
as400Value[offset++] = (byte)(inChars[inPosition++] & 0x000F);
}
}
else if (Trace.traceOn_)
{
Trace.log(Trace.DIAGNOSTIC, "The calculated number of leading zeros is negative.", leadingZeros);
}
int firstNibble;
int secondNibble;
// place all the digits except last one
while (inPosition < inChars.length-1)
{
firstNibble = (inChars[inPosition++] & 0x000F) << 4;
secondNibble = inChars[inPosition++] & 0x000F;
as400Value[offset++] = (byte)(firstNibble + secondNibble);
}
// place last digit and sign nibble
firstNibble = (inChars[inPosition++] & 0x000F) << 4;
if (sign != -1)
{
as400Value[offset++] = (byte)(firstNibble + 0x000F);
}
else
{
as400Value[offset++] = (byte)(firstNibble + 0x000D);
}
return outLength;
}
// @E0A
/**
* Converts the specified Java object to IBM i format.
*
* @param doubleValue The value to be converted to IBM i format. If the decimal part
* of this value needs to be truncated, it will be rounded towards
* zero. If the integral part of this value needs to be truncated,
* an exception will be thrown.
* @return The IBM i representation of the data type.
**/
public byte[] toBytes(double doubleValue)
{
byte[] as400Value = new byte[digits_/2+1];
toBytes(doubleValue, as400Value, 0);
return as400Value;
}
// @E0A
/**
* Converts the specified Java object into IBM i format in
* the specified byte array.
*
* @param doubleValue The value to be converted to IBM i format. If the decimal part
* of this value needs to be truncated, it will be rounded towards
* zero. If the integral part of this value needs to be truncated,
* an exception will be thrown.
* @param as400Value The array to receive the data type in IBM i format. There must
* be enough space to hold the IBM i value.
* @return The number of bytes in the IBM i representation of the data type.
**/
public int toBytes(double doubleValue, byte[] as400Value)
{
return toBytes(doubleValue, as400Value, 0);
}
// @E0A
/**
* Converts the specified Java object into IBM i format in
* the specified byte array.
*
* @param doubleValue The value to be converted to IBM i format. If the decimal part
* of this value needs to be truncated, it will be rounded towards
* zero. If the integral part of this value needs to be truncated,
* an exception will be thrown.
* @param as400Value The array to receive the data type in IBM i format.
* There must be enough space to hold the IBM i value.
* @param offset The offset into the byte array for the start of the IBM i value.
* It must be greater than or equal to zero.
* @return The number of bytes in the IBM i representation of the data type.
**/
public int toBytes(double doubleValue, byte[] as400Value, int offset)
{
// GOAL: For performance reasons, we need to do this conversion
// without creating any Java objects (e.g., BigDecimals,
// Strings).
// If the number is too big, we can't do anything with it.
double absValue = Math.abs(doubleValue);
if (absValue > Long.MAX_VALUE)
throw new ExtendedIllegalArgumentException("doubleValue", ExtendedIllegalArgumentException.LENGTH_NOT_VALID);
// Extract the normalized value. This is the value represented by
// two longs (one for each side of the decimal point). Using longs
// here improves the quality of the algorithm as well as the
// performance of arithmetic operations. We may need to use an
// "effective" scale due to the lack of precision representable
// by a long.
long leftSide = (long)absValue;
int effectiveScale = (scale_ > 15) ? 15 : scale_;
long rightSide = (long)Math.round((absValue - (double)leftSide) * Math.pow(10, effectiveScale));
// Ok, now we are done with any double arithmetic!
int length = digits_/2;
int b = offset + length;
boolean nibble = true; // true for left nibble, false for right nibble.
// If the effective scale is different than the actual scale,
// then pad with zeros.
int scaleDifference = scale_ - effectiveScale;
for (int i = 1; i <= scaleDifference; ++i) {
if (nibble) {
as400Value[b] &= (byte)(0x000F);
--b;
}
else {
as400Value[b] &= (byte)(0x00F0);
}
nibble = !nibble;
}
// Compute the bytes for the right side of the decimal point.
int nextDigit;
for (int i = 1; i <= effectiveScale; ++i) {
nextDigit = (int)(rightSide % 10);
if (nibble) {
as400Value[b] &= (byte)(0x000F);
as400Value[b] |= ((byte)nextDigit << 4);
--b;
}
else {
as400Value[b] &= (byte)(0x00F0);
as400Value[b] |= (byte)nextDigit;
}
nibble = !nibble;
rightSide /= 10;
}
// Compute the bytes for the left side of the decimal point.
int leftSideDigits = digits_ - scale_;
for (int i = 1; i <= leftSideDigits; ++i) {
nextDigit = (int)(leftSide % 10);
if (nibble) {
as400Value[b] &= (byte)(0x000F);
as400Value[b] |= ((byte)nextDigit << 4);
--b;
}
else {
as400Value[b] &= (byte)(0x00F0);
as400Value[b] |= (byte)nextDigit;
}
nibble = !nibble;
leftSide /= 10;
}
// Zero out the left part of the value, if needed.
while (b >= offset) {
if (nibble) {
as400Value[b] &= (byte)(0x000F);
--b;
}
else {
as400Value[b] &= (byte)(0x00F0);
}
nibble = !nibble;
}
// Fix the sign.
b = offset + length;
as400Value[b] &= (byte)(0x00F0);
as400Value[b] |= (byte)((doubleValue >= 0) ? 0x000F : 0x000D);
// If left side still has digits, then the value was too big
// to fit.
if (leftSide > 0)
throw new ExtendedIllegalArgumentException("doubleValue", ExtendedIllegalArgumentException.LENGTH_NOT_VALID);
return length+1;
}
// @E0A
/**
* Converts the specified IBM i data type to a Java double value. If the
* decimal part of the value needs to be truncated to be represented by a
* Java double value, then it is rounded towards zero. If the integral
* part of the value needs to be truncated to be represented by a Java
* double value, then it converted to either Double.POSITIVE_INFINITY
* or Double.NEGATIVE_INFINITY.
*
* @param as400Value The array containing the data type in IBM i format.
* The entire data type must be represented.
* @return The Java double value corresponding to the data type.
**/
public double toDouble(byte[] as400Value)
{
return toDouble(as400Value, 0);
}
// @E0A
/**
* Converts the specified IBM i data type to a Java double value. If the
* decimal part of the value needs to be truncated to be represented by a
* Java double value, then it is rounded towards zero. If the integral
* part of the value needs to be truncated to be represented by a Java
* double value, then it converted to either Double.POSITIVE_INFINITY
* or Double.NEGATIVE_INFINITY.
*
* @param as400Value The array containing the data type in IBM i format.
* The entire data type must be represented.
* @param offset The offset into the byte array for the start of the IBM i value.
* It must be greater than or equal to zero.
* @return The Java double value corresponding to the data type.
**/
public double toDouble(byte[] as400Value, int offset)
{
// Check the offset to prevent bogus NumberFormatException message.
if (offset < 0)
throw new ArrayIndexOutOfBoundsException(String.valueOf(offset));
// Compute the value.
double doubleValue = 0;
double multiplier = Math.pow(10, -scale_);
int rightMostOffset = offset + digits_/2;
boolean nibble = true; // true for left nibble, false for right nibble.
for(int i = rightMostOffset; i >= offset;) {
if (nibble) {
doubleValue += (byte)((as400Value[i] & 0x00F0) >> 4) * multiplier;
--i;
}
else {
doubleValue += ((byte)(as400Value[i] & 0x000F)) * multiplier;
}
multiplier *= 10;
nibble = ! nibble;
}
// Determine the sign.
switch(as400Value[rightMostOffset] & 0x000F) {
case 0x000B:
case 0x000D:
// Negative.
doubleValue *= -1;
break;
case 0x000A:
case 0x000C:
case 0x000E:
case 0x000F:
// Positive.
break;
default:
throwNumberFormatException(LOW_NIBBLE, rightMostOffset,
as400Value[rightMostOffset] & 0x00FF,
as400Value);
}
return doubleValue;
}
/**
* Converts the specified IBM i data type to a Java object.
* @param as400Value The array containing the data type in IBM i format. The entire data type must be represented.
* @return The BigDecimal object corresponding to the data type.
**/
public Object toObject(byte[] as400Value) {
return this.toObject(as400Value, 0);
}
/**
* Converts the specified IBM i data type to a Java object.
* @param as400Value The array containing the data type in IBM i format. The entire data type must be represented and the data type must have valid packed decimal format.
* @param offset The offset into the byte array for the start of the IBM i value. It must be greater than or equal to zero.
* @return The BigDecimal object corresponding to the data type.
**/
public Object toObject(byte[] as400Value, int offset) {
return toObject(as400Value, offset, false);
}
public Object toObject(byte[] as400Value, int offset, boolean ignoreErrors) { /*@Q2C*/
int startOffset = offset;
if (useDouble_) return new Double(toDouble(as400Value, offset));
// Check offset to prevent bogus NumberFormatException message
if (offset < 0)
{
if (ignoreErrors) { /*@Q2A*/
return null;
} else {
throw new ArrayIndexOutOfBoundsException(String.valueOf(offset));
}
}
int numDigits = this.digits_;
int inputSize = numDigits/2+1;
// even number of digits will have a leading zero
if (numDigits%2 == 0) ++numDigits;
char[] outputData = null;
int outputPosition = 0; // position in char[]
// read the sign nibble, allow ArrayIndexException to be thrown
int nibble = (as400Value[offset+inputSize-1] & 0x0F);
switch (nibble)
{
case 0x0B: // valid negative sign bits
case 0x0D:
outputData = new char[numDigits+1];
outputData[outputPosition++] = '-';
break;
case 0x0A: // valid positive sign bits
case 0x0C:
case 0x0E:
case 0x0F:
outputData = new char[numDigits];
break;
default: // others invalid
if (ignoreErrors) { /*@Q2A*/
return null;
} else {
throwNumberFormatException(LOW_NIBBLE, offset+inputSize-1,
as400Value[offset+inputSize-1] & 0xFF,
as400Value);
}
return null;
}
// read all the digits except last one
while (outputPosition < (outputData.length-1))
{
nibble = (as400Value[offset] & 0xFF) >>> 4;
if (nibble > 0x09) {
if (ignoreErrors) { /*@Q2A*/
return null;
} else {
throwNumberFormatException(HIGH_NIBBLE, offset,
as400Value[offset] & 0xFF,
as400Value);
}
}
outputData[outputPosition] = (char)(nibble | 0x0030);
outputPosition++;
nibble = (as400Value[offset] & 0x0F);
if (nibble > 0x09) {
if (Trace.traceOn_) Trace.log(Trace.ERROR,
" outputPosition="+outputPosition+
" outputData.length="+outputData.length +
" numDigits = "+numDigits +
" this.digits = "+this.digits_ +
" offset = "+offset+
" startOffset = "+startOffset);
if (ignoreErrors) { /*@Q2A*/
return null;
} else {
throwNumberFormatException(LOW_NIBBLE, offset,
as400Value[offset] & 0xFF,
as400Value);
}
}
offset++;
outputData[outputPosition] = (char)(nibble | 0x0030);
outputPosition++;
}
// read last digit
nibble = (as400Value[offset] & 0xFF) >>> 4;
if (nibble > 0x09) {
if (ignoreErrors) { /*@Q2A*/
return null;
} else {
throwNumberFormatException(HIGH_NIBBLE, offset,
as400Value[offset] & 0xFF,
as400Value);
}
}
outputData[outputPosition] = (char)(nibble | 0x0030);
// construct New BigDecimal object
return new BigDecimal(new BigInteger(new String(outputData)), this.scale_);
}
static final void throwNumberFormatException(boolean highNibble, int byteOffset, int byteValue, byte[] fieldBytes) throws NumberFormatException
{
String text;
if (highNibble) {
text = ResourceBundleLoader.getText("EXC_HIGH_NIBBLE_NOT_VALID", Integer.toString(byteOffset), byteToString(byteValue));
}
else {
text = ResourceBundleLoader.getText("EXC_LOW_NIBBLE_NOT_VALID", Integer.toString(byteOffset), byteToString(byteValue));
}
if (Trace.traceOn_) Trace.log(Trace.ERROR, "Byte sequence is not valid for a field of type 'packed decimal':", fieldBytes);
NumberFormatException nfe = new NumberFormatException(text);
if (Trace.traceOn_) Trace.log(Trace.ERROR, nfe);
throw nfe;
}
private static final String byteToString(int byteVal)
{
int leftDigitValue = (byteVal >>> 4) & 0x0F;
int rightDigitValue = byteVal & 0x0F;
char[] digitChars = new char[2];
// 0x30 = '0', 0x41 = 'A'
digitChars[0] = leftDigitValue < 0x0A ? (char)(0x30 + leftDigitValue) : (char)(leftDigitValue - 0x0A + 0x41);
digitChars[1] = rightDigitValue < 0x0A ? (char)(0x30 + rightDigitValue) : (char)(rightDigitValue - 0x0A + 0x41);
return new String(digitChars);
}
}
| epl-1.0 |
andriusvelykis/proofprocess | org.ai4fm.proofprocess/src/org/ai4fm/proofprocess/Intent.java | 2381 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package org.ai4fm.proofprocess;
import org.eclipse.emf.cdo.CDOObject;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Intent</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* <ul>
* <li>{@link org.ai4fm.proofprocess.Intent#getName <em>Name</em>}</li>
* <li>{@link org.ai4fm.proofprocess.Intent#getDescription <em>Description</em>}</li>
* </ul>
* </p>
*
* @see org.ai4fm.proofprocess.ProofProcessPackage#getIntent()
* @model
* @extends CDOObject
* @generated
*/
public interface Intent extends CDOObject {
/**
* Returns the value of the '<em><b>Name</b></em>' attribute.
* The default value is <code>""</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Name</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Name</em>' attribute.
* @see #setName(String)
* @see org.ai4fm.proofprocess.ProofProcessPackage#getIntent_Name()
* @model default="" required="true"
* @generated
*/
String getName();
/**
* Sets the value of the '{@link org.ai4fm.proofprocess.Intent#getName <em>Name</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Name</em>' attribute.
* @see #getName()
* @generated
*/
void setName(String value);
/**
* Returns the value of the '<em><b>Description</b></em>' attribute.
* The default value is <code>""</code>.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Description</em>' attribute isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Description</em>' attribute.
* @see #setDescription(String)
* @see org.ai4fm.proofprocess.ProofProcessPackage#getIntent_Description()
* @model default="" required="true"
* @generated
*/
String getDescription();
/**
* Sets the value of the '{@link org.ai4fm.proofprocess.Intent#getDescription <em>Description</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Description</em>' attribute.
* @see #getDescription()
* @generated
*/
void setDescription(String value);
} // Intent
| epl-1.0 |
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs | foundation/eclipselink.core.test/src/org/eclipse/persistence/testing/models/collections/map/AggregateMapValue.java | 1297 | /*******************************************************************************
* Copyright (c) 1998, 2013 Oracle and/or its affiliates. All rights reserved.
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0
* which accompanies this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* tware - initial implementation
******************************************************************************/
package org.eclipse.persistence.testing.models.collections.map;
public class AggregateMapValue {
private int value;
public int getValue(){
return value;
}
public void setValue(int value){
this.value = value;
}
public boolean equals(Object object){
if (!(object instanceof AggregateMapValue)){
return false;
} else {
return ((AggregateMapValue)object).getValue() == this.value;
}
}
public int hashCode(){
return value;
}
}
| epl-1.0 |
riuvshin/che-plugins | plugin-runner/che-plugin-runner-ext-runner/src/main/java/org/eclipse/che/ide/ext/runner/client/manager/button/ButtonWidgetImpl.java | 3851 | /*******************************************************************************
* Copyright (c) 2012-2015 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.ide.ext.runner.client.manager.button;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseOutEvent;
import com.google.gwt.event.dom.client.MouseOutHandler;
import com.google.gwt.event.dom.client.MouseOverEvent;
import com.google.gwt.event.dom.client.MouseOverHandler;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.SimpleLayoutPanel;
import com.google.gwt.user.client.ui.Widget;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import org.eclipse.che.ide.ext.runner.client.RunnerResources;
import org.eclipse.che.ide.ext.runner.client.manager.tooltip.TooltipWidget;
import org.vectomatic.dom.svg.ui.SVGResource;
import javax.validation.constraints.NotNull;
/**
* Class provides view representation of button.
*
* @author Dmitry Shnurenko
*/
public class ButtonWidgetImpl extends Composite implements ButtonWidget, ClickHandler, MouseOverHandler, MouseOutHandler {
interface ButtonWidgetImplUiBinder extends UiBinder<Widget, ButtonWidgetImpl> {
}
private static final int TOP_TOOLTIP_SHIFT = 35;
private static final ButtonWidgetImplUiBinder UI_BINDER = GWT.create(ButtonWidgetImplUiBinder.class);
@UiField
SimpleLayoutPanel image;
@UiField(provided = true)
final RunnerResources resources;
private final TooltipWidget tooltip;
private ActionDelegate delegate;
private boolean isEnable;
@Inject
public ButtonWidgetImpl(RunnerResources resources,
TooltipWidget tooltip,
@NotNull @Assisted String prompt,
@NotNull @Assisted SVGResource image) {
this.resources = resources;
this.tooltip = tooltip;
this.tooltip.setDescription(prompt);
initWidget(UI_BINDER.createAndBindUi(this));
this.image.getElement().appendChild(image.getSvg().getElement());
addDomHandler(this, ClickEvent.getType());
addDomHandler(this, MouseOutEvent.getType());
addDomHandler(this, MouseOverEvent.getType());
}
/** {@inheritDoc} */
@Override
public void setDisable() {
isEnable = false;
image.addStyleName(resources.runnerCss().opacityButton());
}
/** {@inheritDoc} */
@Override
public void setEnable() {
isEnable = true;
image.removeStyleName(resources.runnerCss().opacityButton());
}
/** {@inheritDoc} */
@Override
public void setDelegate(@NotNull ActionDelegate delegate) {
this.delegate = delegate;
}
/** {@inheritDoc} */
@Override
public void onClick(ClickEvent event) {
if (isEnable) {
delegate.onButtonClicked();
}
}
/** {@inheritDoc} */
@Override
public void onMouseOut(MouseOutEvent mouseOutEvent) {
tooltip.hide();
}
/** {@inheritDoc} */
@Override
public void onMouseOver(MouseOverEvent event) {
tooltip.setPopupPosition(getAbsoluteLeft(), getAbsoluteTop() + TOP_TOOLTIP_SHIFT);
tooltip.show();
}
} | epl-1.0 |
t2health/BSPAN---Bluetooth-Sensor-Processing-for-Android | AndroidSpineServer/src/spine/datamodel/ShimmerData.java | 6167 | /*****************************************************************
SPINE - Signal Processing In-Node Environment is a framework that
allows dynamic on node configuration for feature extraction and a
OtA protocol for the management for WSN
Copyright (C) 2007 Telecom Italia S.p.A.
GNU Lesser General Public License
This library is free software; you can redistribute
modify it under the terms of the sub-license (below).
*****************************************************************/
/*****************************************************************
BSPAN - BlueTooth Sensor Processing for Android is a framework
that extends the SPINE framework to work on Android and the
Android Bluetooth communication services.
Copyright (C) 2011 The National Center for Telehealth and
Technology
Eclipse Public License 1.0 (EPL-1.0)
This library is free software; you can redistribute it and/or
modify it under the terms of the Eclipse Public License as
published by the Free Software Foundation, version 1.0 of the
License.
The Eclipse Public License is a reciprocal license, under
Section 3. REQUIREMENTS iv) states that source code for the
Program is available from such Contributor, and informs licensees
how to obtain it in a reasonable manner on or through a medium
customarily used for software exchange.
Post your updates and modifications to our GitHub or email to
t2@tee2.org.
This library is distributed WITHOUT ANY WARRANTY; without
the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the Eclipse Public License 1.0 (EPL-1.0)
for more details.
You should have received a copy of the Eclipse Public License
along with this library; if not,
visit http://www.opensource.org/licenses/EPL-1.0
*****************************************************************/
package spine.datamodel;
import android.content.Context;
public class ShimmerData extends Data {
private static final long serialVersionUID = 1L;
public static final int NUM_AXES = 8;
public static final int AXIS_X = 0;
public static final int AXIS_Y = 1;
public static final int AXIS_Z = 2;
// GSR Range
public static final byte HW_RES_40K = 0;
public static final byte HW_RES_287K = 1;
public static final byte HW_RES_1M = 2;
public static final byte HW_RES_3M3 = 3;
public static final byte AUTORANGE = 4;
// Sampling rates
public static final byte SAMPLING1000HZ = 1;
public static final byte SAMPLING500HZ = 2;
public static final byte SAMPLING250HZ = 4;
public static final byte SAMPLING200HZ = 5;
public static final byte SAMPLING166HZ = 6;
public static final byte SAMPLING125HZ = 8;
public static final byte SAMPLING100HZ = 10;
public static final byte SAMPLING50HZ = 20;
public static final byte SAMPLING10HZ = 100;
public static final byte SAMPLING0HZOFF = 25;
// packet types
public static final byte DATAPACKET = 0X00;
public static final byte INQUIRYCOMMAND = 0X01;
public static final byte INQUIRYRESPONSE = 0X02;
public static final byte GETSAMPLINGRATECOMMAND = 0X03;
public static final byte SAMPLINGRATERESPONSE = 0X04;
public static final byte SETSAMPLINGRATECOMMAND = 0X05;
public static final byte TOGGLELEDCOMMAND = 0X06;
public static final byte STARTSTREAMINGCOMMAND = 0X07;
public static final byte SETSENSORSCOMMAND = 0X08;
public static final byte SETACCELRANGECOMMAND = 0X09;
public static final byte ACCELRANGERESPONSE = 0X0A;
public static final byte GETACCELRANGECOMMAND = 0X0B;
public static final byte SET5VREGULATORCOMMAND = 0X0C;
public static final byte SETPOWERMUXCOMMAND = 0X0D;
public static final byte SETCONFIGSETUPBYTE0COMMAND = 0X0E;
public static final byte CONFIGSETUPBYTE0RESPONSE = 0X0F;
public static final byte GETCONFIGSETUPBYTE0COMMAND = 0X10;
public static final byte SETACCELCALIBRATIONCOMMAND = 0X11;
public static final byte ACCELCALIBRATIONRESPONSE = 0X12;
public static final byte GETACCELCALIBRATIONCOMMAND = 0X13;
public static final byte SETGYROCALIBRATIONCOMMAND = 0X14;
public static final byte GYROCALIBRATIONRESPONSE = 0X15;
public static final byte GETGYROCALIBRATIONCOMMAND = 0X16;
public static final byte SETMAGCALIBRATIONCOMMAND = 0X17;
public static final byte MAGCALIBRATIONRESPONSE = 0X18;
public static final byte GETMAGCALIBRATIONCOMMAND = 0X19;
public static final byte STOPSTREAMINGCOMMAND = 0X20;
public static final byte SETGSRRANGECOMMAND = 0X21;
public static final byte GSRRANGERESPONSE = 0X22;
public static final byte GETGSRRANGECOMMAND = 0X23;
public static final byte GETSHIMMERVERSIONCOMMAND = 0X24;
public static final byte SHIMMERVERSIONRESPONSE = 0X25;
public static final byte ACKCOMMANDPROCESSED = (byte) 0XFF;
public int timestamp;
public int gsr;
public int emg;
public int ecg;
public int vUnreg;
public int vReg;
public int gsrRange;
public int SamplingRate;
public int[] accel = new int[NUM_AXES];
public int accelRange;
public int ecgRaLL;
public int ecgLaLL;
private Node node;
public byte functionCode;
public byte sensorCode;
public byte packetType;
public ShimmerData(Context aContext) {
}
public ShimmerData( byte functionCode, byte sensorCode, byte packetType) {
this.functionCode = functionCode;
this.sensorCode = sensorCode;
this.packetType = packetType;
}
public String getLogDataLine() {
String line = ""; // Comment
line += this.timestamp + ", ";
line += this.accel[AXIS_X] + ", ";
line += this.gsrRange + ", ";
line += this.gsr;
return line;
}
public String getLogDataLineHeader() {
String line = "timestamp, accelX, range, gsr"; // Comment
return line;
}
}
| epl-1.0 |
shalomeir/tctm | src/edu/kaist/irlab/classify/tui/Vectors2InfoForExp.java | 17146 | /*
* Copyright (c) 2014. Seonggyu Lee. All Rights Reserved.
* User: Seonggyu Lee
* Date: 14. 5. 15 오후 8:10
* Created Date : $today.year.month.day
* Last Modified : 14. 5. 15 오후 8:10
* User email: shalomeir@gmail.com
*/
package edu.kaist.irlab.classify.tui;
import cc.mallet.types.*;
import cc.mallet.util.CommandOption;
import cc.mallet.util.MalletLogger;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.logging.Logger;
/**
* Writing SVM Light style text.
@author Andrew McCallum <a href="mailto:mccallum@cs.umass.edu">mccallum@cs.umass.edu</a>
*/
public class Vectors2InfoForExp
{
private static Logger logger = MalletLogger.getLogger(Vectors2InfoForExp.class.getName());
static CommandOption.File inputFile = new CommandOption.File
(Vectors2InfoForExp.class, "input", "FILE", true, new File("-"),
"Read the instance list from this file; Using - indicates stdin.", null);
// static CommandOption.File weightedinputFile = new CommandOption.File
// (Vectors2InfoForExp.class, "weightedinput", "FILE", true, new File("-"),
// "Read the serialized typetopicweight double[] array from this file; Using - indicates stdin.", null);
static CommandOption.File outputFile = new CommandOption.File
(Vectors2InfoForExp.class, "output", "FILE", true, new File("text.vectors"),
"Write the SVM Style instance list to this file; Using - indicates stdout.", null);
// static CommandOption.File weightedoutputFile = new CommandOption.File
// (Vectors2InfoForExp.class, "weightedoutput", "FILE", true, new File("text.vectors"),
// "Write the SVM Style instance list to this file, and this is weighted type; Using - indicates stdout.", null);
static CommandOption.File featureFile = new CommandOption.File
(Vectors2InfoForExp.class, "featureoutput", "FILE", true, new File("text.vectors"),
"Write the feature dictonary to this file; Using - indicates stdout.", null);
static CommandOption.File statsFile = new CommandOption.File
(Vectors2InfoForExp.class, "statsoutput", "FILE", true, new File("text.vectors"),
"Write the statistics for this instance lists to this file; Using - indicates stdout.", null);
static CommandOption.Integer printInfogain = new CommandOption.Integer
(Vectors2InfoForExp.class, "print-infogain", "N", false, 0,
"Print top N words by information gain, sorted.", null);
static CommandOption.Boolean printLabels = new CommandOption.Boolean
(Vectors2InfoForExp.class, "print-labels", "[TRUE|FALSE]", false, false,
"Print class labels known to instance list, one per line.", null);
static CommandOption.Boolean printFileNames = new CommandOption.Boolean
(Vectors2InfoForExp.class, "print-FileNames", "[TRUE|FALSE]", false, true,
"Print file name with start character # after feature list.", null);
static CommandOption.String printMatrix = new CommandOption.String
(Vectors2InfoForExp.class, "print-matrix", "STRING", false, "sic",
"Print word/document matrix in the specified format (a|s)(b|i)(n|w|c|e), for (all vs. sparse), (binary vs. integer), (number vs. word vs. combined vs. empty)", null)
{
public void parseArg(java.lang.String arg) {
if (arg == null) arg = this.defaultValue;
//System.out.println("pa arg=" + arg);
// sanity check the raw printing options (a la Rainbow)
char c0 = arg.charAt(0);
char c1 = arg.charAt(1);
char c2 = arg.charAt(2);
if (arg.length() != 3 ||
(c0 != 's' && c0 != 'a') ||
(c1 != 'b' && c1 != 'i') ||
(c2 != 'n' && c2 != 'w' && c2 != 'c' && c2 != 'e')) {
throw new IllegalArgumentException("Illegal argument = " + arg + " in --print-matrix=" +arg);
}
value = arg;
}
};
static CommandOption.String encoding = new CommandOption.String
(Vectors2InfoForExp.class, "encoding", "STRING", true, Charset.defaultCharset().displayName(),
"Character encoding for input file", null);
public static void main (String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
// Process the command-line options
CommandOption.setSummary (Vectors2InfoForExp.class,
"A tool for printing information about instance lists of feature vectors.");
CommandOption.process (Vectors2InfoForExp.class, args);
// Print some helpful messages for error cases
if (args.length == 0) {
CommandOption.getList(Vectors2InfoForExp.class).printUsage(false);
System.exit (-1);
}
if (false && !inputFile.wasInvoked()) {
System.err.println ("You must specify an input instance list, with --input.");
System.exit (-1);
}
// Write classifications to the output file
PrintStream out = null;
if (outputFile.value.toString().equals ("-")) {
out = System.out;
}
else {
out = new PrintStream(outputFile.value, encoding.value);
}
// Write classifications to the output file
PrintStream featureOut = null;
if (featureFile.value.toString().equals ("-")) {
featureOut = System.out;
}
else {
featureOut = new PrintStream(featureFile.value, encoding.value);
}
// Write classifications to the output file
PrintStream statsOut = null;
if (statsFile.value.toString().equals ("-")) {
statsOut = System.out;
}
else {
statsOut = new PrintStream(statsFile.value, encoding.value);
}
// Read the InstanceList
InstanceList instances = InstanceList.load (inputFile.value);
//Read the searialized typetopicweight double[] array
// double[] typeTopicWeight = readStopwordsObject(weightedinputFile.value);
if (printLabels.value) {
Alphabet labelAlphabet = instances.getTargetAlphabet ();
for (int i = 0; i < labelAlphabet.size(); i++) {
System.out.println (labelAlphabet.lookupObject (i));
}
System.out.print ("\n");
}
if (statsFile.value.exists()) {
StringBuilder output = new StringBuilder();
output.append("#This is a statistics file for instance List file extrated same time. : "+outputFile.value.toString()+"\n");
int numInstances = instances.size();
Alphabet labelAlphabet = instances.getTargetAlphabet ();
int numClasses = labelAlphabet.size();
int numFeatures = instances.getDataAlphabet().size();
output.append("numInstances : "+numInstances+"\n");
output.append("numClasses : "+numClasses+"\n");
output.append("numFeatures : "+numFeatures+"\n");
output.append("#label statistics(Labelnum\tLabelname\tLabelInstancesNum)"+"\n");
//label 별 instance number 계산하기
Integer[] labelStats = new Integer[labelAlphabet.size()];
Arrays.fill(labelStats, 0);
for (int i = 0; i < instances.size(); i++) {
Instance instance = instances.get(i);
FeatureVector fv = (FeatureVector) instance.getData();
Label target = (Label) instance.getTarget();
labelStats[target.getIndex()]++;
}
int fullNumInstances = 0;
for (int i = 0; i < labelAlphabet.size(); i++) {
int labelInstancesNum = labelStats[i];
output.append((Integer)(i+1)+"\t"+labelAlphabet.lookupObject (i)+"\t"+labelInstancesNum+"\n");
fullNumInstances += labelInstancesNum;
}
output.append("*Full Label Instatnce List Number : "+fullNumInstances);
statsOut.println(output);
if (! statsFile.value.toString().equals ("-")) {
statsOut.close();
}
}
if (featureFile.value.exists()) {
StringBuilder output = new StringBuilder();
output.append("#This is feature List and Number of lines are same as feature word. So Next Line word's feature number is 1."); //dictionary[0]=1
featureOut.println(output);
Alphabet alphabet = instances.getDataAlphabet();
for (int i = 0; i < alphabet.size(); i++) {
output = new StringBuilder();
output.append(alphabet.lookupObject(i));
featureOut.println(output);
}
if (! featureFile.value.toString().equals ("-")) {
featureOut.close();
}
}
if (printInfogain.value > 0) {
InfoGain ig = new InfoGain (instances);
for (int i = 0; i < printInfogain.value; i++) {
System.out.println (""+i+" "+ig.getObjectAtRank(i));
}
System.out.print ("\n");
}
if (outputFile.value.exists()) {
printSVMStyleList(instances, out);
}
// if (weightedoutputFile.value.exists()) {
// printWeightedSVMStyleList(instances, out, typeTopicWeight);
// }
if (printMatrix.wasInvoked()) {
printInstanceList(instances, printMatrix.value);
}
}
/** print an instance list according to the SVM Style format */
private static void printSVMStyleList(InstanceList instances, PrintStream out) {
int numInstances = instances.size();
Alphabet labelAlphabet = instances.getTargetAlphabet ();
int numClasses = labelAlphabet.size();
int numFeatures = instances.getDataAlphabet().size();
Alphabet dataAlphabet = instances.getDataAlphabet();
double[] counts = new double[numFeatures];
double count;
StringBuilder output = new StringBuilder();
output.append("#This is svm light style Instance List. First column is a label(=target class, 0 means hidden.) Feature size : "+numFeatures+". Number of instances : "+numInstances+"."); //dictionary[0]=1
out.println(output);
for (int i = 0; i < instances.size(); i++) {
Instance instance = instances.get(i);
output = new StringBuilder();// line 출력용
if (instance.getData() instanceof FeatureVector) {
FeatureVector fv = (FeatureVector) instance.getData ();
// output.append(instance.getTarget());//text 용
Label target = (Label) instance.getTarget();
output.append((Integer)(target.getIndex()+1));//number (+1 은 실제 label number는 1부터 시작하므로)
// Sparse: Print features with non-zero values only.
for (int l = 0; l < fv.numLocations(); l++) {
int fvi = fv.indexAtLocation(l);
output.append(" "+(Integer)(fvi+1)+":"+(fv.valueAtLocation(l)));//Same +1 for vocabulary
//System.out.print(" " + dataAlphabet.lookupObject(j) + " " + ((int) fv.valueAtLocation(j)));
}
}
else {
throw new IllegalArgumentException ("Printing is supported for FeatureVector for SVM Style list, found " + instance.getData().getClass());
}
if(printFileNames.value) output.append(" #"+instance.getName());
out.println(output);
}
if (! outputFile.value.toString().equals ("-")) {
out.close();
}
}
/** print an instance list according to the SVM Style format */
private static void printWeightedSVMStyleList(InstanceList instances, PrintStream out, double[] typeTopicWeight ) {
int numInstances = instances.size();
Alphabet labelAlphabet = instances.getTargetAlphabet ();
int numClasses = labelAlphabet.size();
int numFeatures = instances.getDataAlphabet().size();
Alphabet dataAlphabet = instances.getDataAlphabet();
double[] counts = new double[numFeatures];
double count;
StringBuilder output = new StringBuilder();
output.append("#This is svm light style Instance List. First column is a label(=target class, 0 means hidden.) Feature size : "+numFeatures+". Number of instances : "+numInstances+"."); //dictionary[0]=1
out.println(output);
for (int i = 0; i < instances.size(); i++) {
Instance instance = instances.get(i);
output = new StringBuilder();// line 출력용
if (instance.getData() instanceof FeatureVector) {
FeatureVector fv = (FeatureVector) instance.getData ();
// output.append(instance.getTarget());//text 용
Label target = (Label) instance.getTarget();
output.append((Integer)(target.getIndex()+1));//number (+1 은 실제 label number는 1부터 시작하므로)
// Sparse: Print features with non-zero values only.
for (int l = 0; l < fv.numLocations(); l++) {
int fvi = fv.indexAtLocation(l);
output.append(" "+(Integer)(fvi+1)+":"+(fv.valueAtLocation(l)));//Same +1 for vocabulary
//System.out.print(" " + dataAlphabet.lookupObject(j) + " " + ((int) fv.valueAtLocation(j)));
}
}
else {
throw new IllegalArgumentException ("Printing is supported for FeatureVector for SVM Style list, found " + instance.getData().getClass());
}
if(printFileNames.value) output.append(" #"+instance.getName());
out.println(output);
}
if (! outputFile.value.toString().equals ("-")) {
out.close();
}
}
/** print an instance list according to the format string */
private static void printInstanceList(InstanceList instances, String formatString) {
int numInstances = instances.size();
int numClasses = instances.getTargetAlphabet().size();
int numFeatures = instances.getDataAlphabet().size();
Alphabet dataAlphabet = instances.getDataAlphabet();
double[] counts = new double[numFeatures];
double count;
for (int i = 0; i < instances.size(); i++) {
Instance instance = instances.get(i);
if (instance.getData() instanceof FeatureVector) {
FeatureVector fv = (FeatureVector) instance.getData ();
System.out.print(instance.getName() + " " + instance.getTarget());
if (formatString.charAt(0) == 'a') {
// Dense: Print all features, even those with value 0.
for (int fvi=0; fvi<numFeatures; fvi++){
printFeature(dataAlphabet.lookupObject(fvi), fvi, fv.value(fvi), formatString);
}
}
else {
// Sparse: Print features with non-zero values only.
for (int l = 0; l < fv.numLocations(); l++) {
int fvi = fv.indexAtLocation(l);
printFeature(dataAlphabet.lookupObject(fvi), fvi, fv.valueAtLocation(l), formatString);
//System.out.print(" " + dataAlphabet.lookupObject(j) + " " + ((int) fv.valueAtLocation(j)));
}
}
}
else if (instance.getData() instanceof FeatureSequence) {
FeatureSequence featureSequence = (FeatureSequence) instance.getData();
StringBuilder output = new StringBuilder();
output.append(instance.getName() + " " + instance.getTarget());
for (int position = 0; position < featureSequence.size(); position++) {
int featureIndex = featureSequence.getIndexAtPosition(position);
char featureFormat = formatString.charAt(2);
if (featureFormat == 'w') {
output.append(" " + dataAlphabet.lookupObject(featureIndex));
}
else if (featureFormat == 'n') {
output.append(" " + featureIndex);
}
else if (featureFormat == 'c') {
output.append(" " + dataAlphabet.lookupObject(featureIndex) + ":" + featureIndex);
}
}
System.out.println(output);
}
else {
throw new IllegalArgumentException ("Printing is supported for FeatureVector and FeatureSequence data, found " + instance.getData().getClass());
}
System.out.println();
}
System.out.println();
return; // counts;
}
/* helper for printInstanceList. prints a single feature within an instance */
private static void printFeature(Object o, int fvi, double featureValue, String formatString) {
// print object n,w,c,e
char c1 = formatString.charAt(2);
if (c1 == 'w') { // word
System.out.print(" " + o);
} else if (c1 == 'n') { // index of word
System.out.print(" " + fvi);
} else if (c1 == 'c') { //word and index
System.out.print(" " + o + ":" + fvi);
} else if (c1 == 'e'){ //no word identity
}
char c2 = formatString.charAt(1);
if (c2 == 'i') { // integer count
System.out.print(" " + ((int)(featureValue + .5)));
} else if (c2 == 'b') { // boolean present/not present
System.out.print(" " + ((featureValue>0.5) ? "1" : "0"));
}
}
public static double[] readStopwordsObject(File parameterFile) throws IOException, ClassNotFoundException {
ObjectInputStream in = new ObjectInputStream(new FileInputStream(parameterFile)); // object 쓰기위한 스트림
double[] typeTopicWeightObject = (double[]) in.readObject();
in.close();
return typeTopicWeightObject;
}
}
| epl-1.0 |
openmapsoftware/mappingtools | openmap-mapper-lib/src/main/java/com/openMap1/mapper/core/TranslationSummaryItem.java | 4491 | package com.openMap1.mapper.core;
import java.util.Vector;
/**
* Data item that gives one row of the Translation Summary View
* after running a translation test.
*
* @author robert
*
*/
public class TranslationSummaryItem implements SortableRow{
/**
* Make a new TranslationSummaryItem , before recording anything in it
* @param resultCode
*/
public TranslationSummaryItem(String resultCode)
{
this.resultCode = resultCode;
translationIssues = new Vector<TranslationIssue>();
sourceItemCount = 0;
resultItemCount = 0;
}
/**
* column titles for the Translation Summary View
*/
static public String[] columnTitle = {
"Code",
"Steps",
"Source items",
"Percent",
"Issues"
};
/**
* column widths for the Translation Summary View
*/
static public int[] columnWidth = {50,50,80,60,60};
static int CODE = 0;
static int STEPS = 1;
static int SOURCE_ITEMS = 2;
static int PERCENT_FIT = 3;
static int ISSUES = 4;
/**
* int constants STRING, NUMBER defined in RowSorter which define how
* each column is to be sorted
*/
public static int[] sortType()
{
int len = columnTitle.length;
int[] sType = new int[len];
sType[CODE] = STRING;
sType[STEPS] = NUMBER;
sType[SOURCE_ITEMS] = NUMBER;
sType[PERCENT_FIT] = NUMBER;
sType[ISSUES] = NUMBER;
return sType;
}
/**
* @param col column index
* @return column contents for the Translation Summary View
*/
public String cellContents(int col)
{
String cell = "";
if (col == CODE) cell = resultCode();
if (col == STEPS) cell = new Integer(resultCode().length() -1).toString();
if (col == SOURCE_ITEMS) cell = new Integer(sourceItemCount).toString();
if (col == PERCENT_FIT) cell = new Integer(percentFit()).toString();
if (col == ISSUES) cell = new Integer(translationIssues.size()).toString();
return cell;
}
/**
* for an object to serve as a sortable row for class RowSorter,
* it must be able to present the cell contents as a Vector.
* @return
*/
public Vector<?> rowVector()
{
Vector<String> row = new Vector<String>();
for (int i = 0; i < columnTitle.length;i++) row.add(cellContents(i));
return row;
}
/**
* @return coded name of the translation test result that this summarises,
* such as 'AB'
*/
public String resultCode() {return resultCode;}
private String resultCode;
/**
* @return number of information items (objects, links, or attribute values)
* in the first source of the translation chain giving the result
*/
public int sourceItemCount() {return sourceItemCount;}
public void setSourceItemCount(int sourceItemCount) {this.sourceItemCount = sourceItemCount;}
private int sourceItemCount;
/**
* @return number of information items (objects, links, or attribute values)
* in the final result of the translation chain, which exactly match the
* corresponding information items in the source
*/
public int resultItemCount() {return resultItemCount;}
public void setResultItemCount(int resultItemCount) {this.resultItemCount = resultItemCount;}
private int resultItemCount;
/**
* @return the matching result item count as a percentage of the source item count
*/
public int percentFit()
{
if (sourceItemCount == 0) return 0;
double numerator = 100*resultItemCount;
double denominator = sourceItemCount;
return (new Double(numerator/denominator).intValue());
}
/**
* @return the distinct translation issues detected
*/
public Vector<TranslationIssue> translationIssues() {return translationIssues;}
private Vector<TranslationIssue> translationIssues;
/** record a validation issue */
public void addValidationIssue(ValidationIssue vi) {translationIssues.add(vi);}
/** record a compilation issue */
public void addCompilationIssue(CompilationIssue ci) {translationIssues.add(ci);}
/** record a runtime issue */
public void addRunIssue(RunIssue ri) {translationIssues.add(ri);}
/** record a schema mismatch in a result */
public void addSchemaMismatch(SchemaMismatch sm) {translationIssues.add(sm);}
/** record a structure mismatch in a result */
public void addStructureMismatch(StructureMismatch sm) {translationIssues.add(sm);}
/** record a semantic mismatch in a result */
public void addSemanticMismatch(SemanticMismatch sm) {translationIssues.add(sm);}
}
| epl-1.0 |
opendaylight/vtn | manager/it/util/src/main/java/org/opendaylight/vtn/manager/it/util/action/SetDscpVerifier.java | 2520 | /*
* Copyright (c) 2015 NEC Corporation. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.vtn.manager.it.util.action;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import java.util.ListIterator;
import org.opendaylight.vtn.manager.it.util.packet.Inet4Factory;
import org.opendaylight.vtn.manager.it.util.packet.EthernetFactory;
import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.SetNwTosActionCase;
import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.action.set.nw.tos.action._case.SetNwTosAction;
import org.opendaylight.yang.gen.v1.urn.opendaylight.action.types.rev131112.action.list.Action;
/**
* {@code SetDscpVerifier} is a utility class used to verify a SET_NW_TOS
* (DSCP) action.
*/
public final class SetDscpVerifier extends ActionVerifier {
/**
* The DSCP value to be set.
*/
private final short dscp;
/**
* Ensure that the specified action is an expected SET_NW_TOS action.
*
* @param it Action list iterator.
* @param d Expected DSCP value.
*/
public static void verify(ListIterator<Action> it, short d) {
SetNwTosActionCase act = verify(it, SetNwTosActionCase.class);
SetNwTosAction snta = act.getSetNwTosAction();
Integer value = snta.getTos();
assertNotNull(value);
assertEquals(d, value.shortValue());
}
/**
* Construct a new instance.
*
* @param d The DSCP value to be set.
*/
public SetDscpVerifier(short d) {
dscp = d;
}
/**
* Return the DSCP value to be set.
*
* @return The DSCP value to be set.
*/
public short setDscp() {
return dscp;
}
// ActionVerifier
/**
* {@inheritDoc}
*/
@Override
public void verify(EthernetFactory efc, ListIterator<Action> it) {
Inet4Factory i4fc = getFactory(efc, Inet4Factory.class);
if (i4fc != null) {
verify(it, dscp);
}
}
/**
* {@inheritDoc}
*/
@Override
public void apply(EthernetFactory efc) {
Inet4Factory i4fc = getFactory(efc, Inet4Factory.class);
if (i4fc != null) {
i4fc.setDscp(dscp);
}
}
}
| epl-1.0 |
subclipse/subclipse | bundles/subclipse.ui/src/org/tigris/subversion/subclipse/ui/subscriber/RevertSynchronizeAction.java | 6541 | /**
* ***************************************************************************** Copyright (c) 2004,
* 2006 Subclipse project 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
*
* <p>Contributors: Subclipse project committers - initial API and implementation
* ****************************************************************************
*/
package org.tigris.subversion.subclipse.ui.subscriber;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.eclipse.compare.structuremergeviewer.IDiffElement;
import org.eclipse.core.resources.IContainer;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.widgets.TreeItem;
import org.eclipse.team.core.synchronize.FastSyncInfoFilter;
import org.eclipse.team.core.synchronize.SyncInfo;
import org.eclipse.team.internal.ui.synchronize.ChangeSetDiffNode;
import org.eclipse.team.ui.synchronize.ISynchronizeModelElement;
import org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration;
import org.eclipse.team.ui.synchronize.SynchronizeModelAction;
import org.eclipse.team.ui.synchronize.SynchronizeModelOperation;
import org.tigris.subversion.subclipse.core.ISVNLocalResource;
import org.tigris.subversion.subclipse.core.SVNException;
import org.tigris.subversion.subclipse.core.resources.SVNWorkspaceRoot;
import org.tigris.subversion.subclipse.core.util.Util;
import org.tigris.subversion.subclipse.ui.ISVNUIConstants;
import org.tigris.subversion.subclipse.ui.SVNUIPlugin;
public class RevertSynchronizeAction extends SynchronizeModelAction {
private String url;
@SuppressWarnings("rawtypes")
private HashMap statusMap;
public RevertSynchronizeAction(String text, ISynchronizePageConfiguration configuration) {
super(text, configuration);
}
/* (non-Javadoc)
* @see org.eclipse.team.ui.synchronize.SynchronizeModelAction#getSyncInfoFilter()
*/
protected FastSyncInfoFilter getSyncInfoFilter() {
return new FastSyncInfoFilter() {
@SuppressWarnings("rawtypes")
public boolean select(SyncInfo info) {
SyncInfoDirectionFilter outgoingFilter =
new SyncInfoDirectionFilter(new int[] {SyncInfo.OUTGOING, SyncInfo.CONFLICTING});
if (!outgoingFilter.select(info)) return false;
IStructuredSelection selection = getStructuredSelection();
Iterator iter = selection.iterator();
boolean removeUnAdded =
SVNUIPlugin.getPlugin()
.getPreferenceStore()
.getBoolean(ISVNUIConstants.PREF_REMOVE_UNADDED_RESOURCES_ON_REPLACE);
while (iter.hasNext()) {
ISynchronizeModelElement element = (ISynchronizeModelElement) iter.next();
IResource resource = element.getResource();
if (resource == null) continue;
if (resource.isLinked()) return false;
if (!removeUnAdded) {
ISVNLocalResource svnResource = SVNWorkspaceRoot.getSVNResourceFor(resource);
try {
if (!svnResource.isManaged()) return false;
} catch (SVNException e) {
return false;
}
}
}
return true;
}
};
}
@SuppressWarnings({"rawtypes", "unchecked"})
protected SynchronizeModelOperation getSubscriberOperation(
ISynchronizePageConfiguration configuration, IDiffElement[] elements) {
statusMap = new HashMap();
url = null;
IStructuredSelection selection = getStructuredSelection();
if (selection.size() == 1) {
ISynchronizeModelElement element = (ISynchronizeModelElement) selection.getFirstElement();
IResource resource = element.getResource();
if (resource != null) {
ISVNLocalResource svnResource = SVNWorkspaceRoot.getSVNResourceFor(resource);
try {
url = svnResource.getStatus().getUrlString();
if ((url == null) || (resource.getType() == IResource.FILE))
url = Util.getParentUrl(svnResource);
} catch (SVNException e) {
SVNUIPlugin.log(IStatus.ERROR, e.getMessage(), e);
}
}
}
List selectedResources = new ArrayList(elements.length);
for (int i = 0; i < elements.length; i++) {
if (elements[i] instanceof ISynchronizeModelElement) {
selectedResources.add(((ISynchronizeModelElement) elements[i]).getResource());
}
}
IResource[] resources = new IResource[selectedResources.size()];
selectedResources.toArray(resources);
boolean changeSetMode = isChangeSetMode();
List<IResource> topSelection = new ArrayList<IResource>();
if (!changeSetMode) {
Iterator iter = selection.iterator();
while (iter.hasNext()) {
ISynchronizeModelElement element = (ISynchronizeModelElement) iter.next();
topSelection.add(element.getResource());
}
}
IResource[] topSelectionArray;
if (changeSetMode) {
topSelectionArray = resources;
} else {
topSelectionArray = new IResource[topSelection.size()];
topSelection.toArray(topSelectionArray);
}
for (IResource resource : resources) {
ISVNLocalResource svnResource = SVNWorkspaceRoot.getSVNResourceFor(resource);
if (svnResource != null) {
try {
if (resource instanceof IContainer) {
statusMap.put(resource, svnResource.getStatus().getPropStatus());
} else {
statusMap.put(resource, svnResource.getStatus().getTextStatus());
}
} catch (SVNException e) {
// ignore
}
}
}
RevertSynchronizeOperation revertOperation =
new RevertSynchronizeOperation(configuration, elements, url, resources, statusMap);
revertOperation.setSelectedResources(topSelectionArray);
return revertOperation;
}
private boolean isChangeSetMode() {
Viewer viewer = getConfiguration().getPage().getViewer();
if (viewer instanceof TreeViewer) {
TreeItem[] items = ((TreeViewer) viewer).getTree().getItems();
for (TreeItem item : items) {
if (item.getData() instanceof ChangeSetDiffNode) {
return true;
}
}
}
return false;
}
}
| epl-1.0 |
Romenig/iVProg_2 | src/usp/ime/line/ivprog/IVPSystemFactory.java | 2904 | /**
* Instituto de Matemática e Estatística da Universidade de São Paulo (IME-USP)
* iVProg is a open source and free software of Laboratório de Informática na
* Educação (LInE) licensed under GNU GPL2.0 license.
* Prof. Dr. Leônidas de Oliveira Brandão - leo@ime.usp.br
* Romenig da Silva Ribeiro - romenig@ime.usp.br | romenig@gmail.com
* @author Romenig
*/
package usp.ime.line.ivprog;
import java.util.HashMap;
import java.util.Vector;
import usp.ime.line.ivprog.model.IVPDomainConverter;
import usp.ime.line.ivprog.model.IVPDomainModel;
import usp.ime.line.ivprog.model.utils.Services;
import usp.ime.line.ivprog.view.domaingui.IVPAuthoringGUI;
import usp.ime.line.ivprog.view.domaingui.IVPDomainGUI;
import ilm.framework.SystemFactory;
import ilm.framework.assignment.model.AssignmentState;
import ilm.framework.config.SystemConfig;
import ilm.framework.domain.DomainConverter;
import ilm.framework.domain.DomainGUI;
import ilm.framework.domain.DomainModel;
import ilm.framework.gui.AuthoringGUI;
/**
* @author Romenig
*
*/
public class IVPSystemFactory extends SystemFactory {
/*
* (non-Javadoc)
*
* @see ilm.framework.SystemFactory#createDomainModel()
*/
protected DomainModel createDomainModel() {
IVPDomainModel model = new IVPDomainModel();
Services.getService().getController().setModel(model);
return model;
}
/*
* (non-Javadoc)
*
* @see ilm.framework.SystemFactory#createDomainConverter()
*/
protected DomainConverter createDomainConverter() {
IVPDomainConverter converter = new IVPDomainConverter();
return converter;
}
/*
* (non-Javadoc)
*
* @see
* ilm.framework.SystemFactory#createDomainGUI(ilm.framework.config.SystemConfig
* , ilm.framework.domain.DomainModel)
*/
public DomainGUI createDomainGUI(SystemConfig config, DomainModel domainModel) {
IVPDomainGUI gui = new IVPDomainGUI();
gui.initDomainActionList(domainModel);
Services.getService().getController().setCurrentDomainGUI(gui);
return gui;
}
/*
* (non-Javadoc)
*
* @see
* ilm.framework.SystemFactory#createAuthoringGUI(ilm.framework.domain.DomainGUI
* , java.lang.String, ilm.framework.assignment.model.AssignmentState,
* ilm.framework.assignment.model.AssignmentState,
* ilm.framework.assignment.model.AssignmentState, java.util.HashMap,
* java.util.HashMap)
*/
public AuthoringGUI createAuthoringGUI(DomainGUI domainGUI, String proposition, AssignmentState initial, AssignmentState current,
AssignmentState expected, HashMap config, HashMap metadata) {
IVPAuthoringGUI gui = new IVPAuthoringGUI();
return gui;
}
protected Vector getIlmModuleList() {
Vector list = new Vector();
// list.add(new ScriptModule());
// list.add(new ExampleTracingTutorModule());
// list.add(new ScormModule());
return list;
}
}
| gpl-2.0 |
actiontech/dble | src/main/java/com/actiontech/dble/plan/common/field/num/FieldMedium.java | 849 | /*
* Copyright (C) 2016-2022 ActionTech.
* License: http://www.gnu.org/licenses/gpl.html GPL version 2 or higher.
*/
package com.actiontech.dble.plan.common.field.num;
import com.actiontech.dble.plan.common.item.FieldTypes;
import com.actiontech.dble.plan.common.item.Item.ItemResult;
/**
* mediumint(%d) |unsigned |zerofilled
*
* @author ActionTech
*/
public class FieldMedium extends FieldNum {
public FieldMedium(String name, String dbName, String table, String orgTable, int charsetIndex, int fieldLength, int decimals, long flags) {
super(name, dbName, table, orgTable, charsetIndex, fieldLength, decimals, flags);
}
@Override
public ItemResult resultType() {
return ItemResult.INT_RESULT;
}
@Override
public FieldTypes fieldType() {
return FieldTypes.MYSQL_TYPE_INT24;
}
}
| gpl-2.0 |
intelie/esper | esper/src/main/java/com/espertech/esper/epl/core/StreamTypeServiceImpl.java | 18945 | /**************************************************************************************
* Copyright (C) 2008 EsperTech, Inc. All rights reserved. *
* http://esper.codehaus.org *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
**************************************************************************************/
package com.espertech.esper.epl.core;
import com.espertech.esper.client.EventPropertyDescriptor;
import com.espertech.esper.client.EventType;
import com.espertech.esper.collection.Pair;
import com.espertech.esper.core.EPServiceProviderSPI;
import com.espertech.esper.epl.parse.ASTFilterSpecHelper;
import com.espertech.esper.event.EventTypeSPI;
import com.espertech.esper.util.LevenshteinDistance;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* Implementation that provides stream number and property type information.
*/
public class StreamTypeServiceImpl implements StreamTypeService
{
private final EventType[] eventTypes;
private final String[] streamNames;
private final boolean[] isIStreamOnly;
private final String engineURIQualifier;
private boolean isStreamZeroUnambigous;
private boolean requireStreamNames;
private boolean isOnDemandStreams;
/**
* Ctor.
* @param engineURI engine URI
* @param isOnDemandStreams
*/
public StreamTypeServiceImpl(String engineURI, boolean isOnDemandStreams)
{
this(new EventType[0], new String[0], new boolean[0], engineURI, isOnDemandStreams);
}
/**
* Ctor.
* @param eventType a single event type for a single stream
* @param streamName the stream name of the single stream
* @param engineURI engine URI
* @param isIStreamOnly true for no datawindow for stream
*/
public StreamTypeServiceImpl (EventType eventType, String streamName, boolean isIStreamOnly, String engineURI)
{
this(new EventType[] {eventType}, new String[] {streamName}, new boolean[] {isIStreamOnly}, engineURI, false);
}
/**
* Ctor.
* @param eventTypes - array of event types, one for each stream
* @param streamNames - array of stream names, one for each stream
* @param isIStreamOnly true for no datawindow for stream
* @param engineURI - engine URI
* @param isOnDemandStreams - true to indicate that all streams are on-demand pull-based
*/
public StreamTypeServiceImpl(EventType[] eventTypes, String[] streamNames, boolean[] isIStreamOnly, String engineURI, boolean isOnDemandStreams)
{
this.eventTypes = eventTypes;
this.streamNames = streamNames;
this.isIStreamOnly = isIStreamOnly;
this.isOnDemandStreams = isOnDemandStreams;
if (engineURI == null || EPServiceProviderSPI.DEFAULT_ENGINE_URI.equals(engineURI))
{
engineURIQualifier = EPServiceProviderSPI.DEFAULT_ENGINE_URI__QUALIFIER;
}
else
{
engineURIQualifier = engineURI;
}
if (eventTypes.length != streamNames.length)
{
throw new IllegalArgumentException("Number of entries for event types and stream names differs");
}
}
/**
* Ctor.
* @param namesAndTypes is the ordered list of stream names and event types available (stream zero to N)
* @param isStreamZeroUnambigous indicates whether when a property is found in stream zero and another stream an exception should be
* thrown or the stream zero should be assumed
* @param engineURI uri of the engine
* @param requireStreamNames is true to indicate that stream names are required for any non-zero streams (for subqueries)
*/
public StreamTypeServiceImpl (LinkedHashMap<String, Pair<EventType, String>> namesAndTypes, String engineURI, boolean isStreamZeroUnambigous, boolean requireStreamNames)
{
this.isStreamZeroUnambigous = isStreamZeroUnambigous;
this.requireStreamNames = requireStreamNames;
this.engineURIQualifier = engineURI;
this.isIStreamOnly = new boolean[namesAndTypes.size()];
eventTypes = new EventType[namesAndTypes.size()] ;
streamNames = new String[namesAndTypes.size()] ;
int count = 0;
for (Map.Entry<String, Pair<EventType, String>> entry : namesAndTypes.entrySet())
{
streamNames[count] = entry.getKey();
eventTypes[count] = entry.getValue().getFirst();
count++;
}
}
public void setRequireStreamNames(boolean requireStreamNames) {
this.requireStreamNames = requireStreamNames;
}
public boolean isOnDemandStreams() {
return isOnDemandStreams;
}
public EventType[] getEventTypes()
{
return eventTypes;
}
public String[] getStreamNames()
{
return streamNames;
}
public boolean[] getIStreamOnly() {
return isIStreamOnly;
}
public int getStreamNumForStreamName(String streamWildcard) {
for (int i = 0; i < streamNames.length; i++) {
if (streamWildcard.equals(streamNames[i])) {
return i;
}
}
return -1;
}
public PropertyResolutionDescriptor resolveByPropertyName(String propertyName)
throws DuplicatePropertyException, PropertyNotFoundException
{
if (propertyName == null)
{
throw new IllegalArgumentException("Null property name");
}
PropertyResolutionDescriptor desc = findByPropertyName(propertyName);
if ((requireStreamNames) && (desc.getStreamNum() != 0))
{
throw new PropertyNotFoundException("Property named '" + propertyName + "' must be prefixed by a stream name, use the stream name itself or use the as-clause to name the stream with the property in the format \"stream.property\"", null);
}
return desc;
}
public PropertyResolutionDescriptor resolveByStreamAndPropName(String streamName, String propertyName)
throws PropertyNotFoundException, StreamNotFoundException
{
if (streamName == null)
{
throw new IllegalArgumentException("Null property name");
}
if (propertyName == null)
{
throw new IllegalArgumentException("Null property name");
}
return findByStreamAndEngineName(propertyName, streamName);
}
public PropertyResolutionDescriptor resolveByStreamAndPropName(String streamAndPropertyName) throws DuplicatePropertyException, PropertyNotFoundException
{
if (streamAndPropertyName == null)
{
throw new IllegalArgumentException("Null stream and property name");
}
PropertyResolutionDescriptor desc;
try
{
// first try to resolve as a property name
desc = findByPropertyName(streamAndPropertyName);
}
catch (PropertyNotFoundException ex)
{
// Attempt to resolve by extracting a stream name
int index = ASTFilterSpecHelper.unescapedIndexOfDot(streamAndPropertyName);
if (index == -1)
{
throw ex;
}
String streamName = streamAndPropertyName.substring(0, index);
String propertyName = streamAndPropertyName.substring(index + 1, streamAndPropertyName.length());
try
{
// try to resolve a stream and property name
desc = findByStreamAndEngineName(propertyName, streamName);
}
catch (StreamNotFoundException e)
{
// Consider the engine URI as a further prefix
Pair<String, String> propertyNoEnginePair = getIsEngineQualified(propertyName, streamName);
if (propertyNoEnginePair == null)
{
throw ex;
}
try
{
return findByStreamNameOnly(propertyNoEnginePair.getFirst(), propertyNoEnginePair.getSecond());
}
catch (StreamNotFoundException e1)
{
throw ex;
}
}
return desc;
}
return desc;
}
private PropertyResolutionDescriptor findByPropertyName(String propertyName)
throws DuplicatePropertyException, PropertyNotFoundException
{
int index = 0;
int foundIndex = 0;
int foundCount = 0;
EventType streamType = null;
for (int i = 0; i < eventTypes.length; i++)
{
if (eventTypes[i] != null)
{
Class propertyType = null;
boolean found = false;
if (eventTypes[i].isProperty(propertyName)) {
propertyType = eventTypes[i].getPropertyType(propertyName);
found = true;
}
else {
// mapped(expression) or array(expression) are not property names but expressions against a property by name "mapped" or "array"
EventPropertyDescriptor descriptor = eventTypes[i].getPropertyDescriptor(propertyName);
if (descriptor != null) {
found = true;
propertyType = descriptor.getPropertyType();
}
}
if (found) {
streamType = eventTypes[i];
foundCount++;
foundIndex = index;
// If the property could be resolved from stream 0 then we don't need to look further
if ((i == 0) && isStreamZeroUnambigous)
{
return new PropertyResolutionDescriptor(streamNames[0], eventTypes[0], propertyName, 0, propertyType);
}
}
}
index++;
}
if (foundCount > 1)
{
throw new DuplicatePropertyException("Property named '" + propertyName + "' is ambigous as is valid for more then one stream");
}
if (streamType == null)
{
Pair<Integer, String> possibleMatch = findLevMatch(propertyName);
String message = "Property named '" + propertyName + "' is not valid in any stream";
throw new PropertyNotFoundException(message, possibleMatch);
}
return new PropertyResolutionDescriptor(streamNames[foundIndex], eventTypes[foundIndex], propertyName, foundIndex, streamType.getPropertyType(propertyName));
}
private Pair<Integer, String> findLevMatch(String propertyName)
{
String bestMatch = null;
int bestMatchDiff = Integer.MAX_VALUE;
for (int i = 0; i < eventTypes.length; i++)
{
if (eventTypes[i] == null)
{
continue;
}
EventPropertyDescriptor[] props = eventTypes[i].getPropertyDescriptors();
for (int j = 0; j < props.length; j++)
{
int diff = LevenshteinDistance.computeLevenshteinDistance(propertyName, props[j].getPropertyName());
if (diff < bestMatchDiff)
{
bestMatchDiff = diff;
bestMatch = props[j].getPropertyName();
}
}
}
if (bestMatchDiff < Integer.MAX_VALUE)
{
return new Pair<Integer, String>(bestMatchDiff, bestMatch);
}
return null;
}
private Pair<Integer, String> findLevMatch(String propertyName, EventType eventType)
{
String bestMatch = null;
int bestMatchDiff = Integer.MAX_VALUE;
EventPropertyDescriptor[] props = eventType.getPropertyDescriptors();
for (int j = 0; j < props.length; j++)
{
int diff = LevenshteinDistance.computeLevenshteinDistance(propertyName, props[j].getPropertyName());
if (diff < bestMatchDiff)
{
bestMatchDiff = diff;
bestMatch = props[j].getPropertyName();
}
}
if (bestMatchDiff < Integer.MAX_VALUE)
{
return new Pair<Integer, String>(bestMatchDiff, bestMatch);
}
return null;
}
private PropertyResolutionDescriptor findByStreamAndEngineName(String propertyName, String streamName)
throws PropertyNotFoundException, StreamNotFoundException
{
PropertyResolutionDescriptor desc;
try
{
desc = findByStreamNameOnly(propertyName, streamName);
}
catch (PropertyNotFoundException ex)
{
Pair<String, String> propertyNoEnginePair = getIsEngineQualified(propertyName, streamName);
if (propertyNoEnginePair == null)
{
throw ex;
}
return findByStreamNameOnly(propertyNoEnginePair.getFirst(), propertyNoEnginePair.getSecond());
}
catch (StreamNotFoundException ex)
{
Pair<String, String> propertyNoEnginePair = getIsEngineQualified(propertyName, streamName);
if (propertyNoEnginePair == null)
{
throw ex;
}
return findByStreamNameOnly(propertyNoEnginePair.getFirst(), propertyNoEnginePair.getSecond());
}
return desc;
}
private Pair<String, String> getIsEngineQualified(String propertyName, String streamName) {
// If still not found, test for the stream name to contain the engine URI
if (!streamName.equals(engineURIQualifier))
{
return null;
}
int index = ASTFilterSpecHelper.unescapedIndexOfDot(propertyName);
if (index == -1)
{
return null;
}
String streamNameNoEngine = propertyName.substring(0, index);
String propertyNameNoEngine = propertyName.substring(index + 1, propertyName.length());
return new Pair<String, String>(propertyNameNoEngine, streamNameNoEngine);
}
private PropertyResolutionDescriptor findByStreamNameOnly(String propertyName, String streamName)
throws PropertyNotFoundException, StreamNotFoundException
{
int index = 0;
EventType streamType = null;
// Stream name resultion examples:
// A) select A1.price from Event.price as A2 => mismatch stream name, cannot resolve
// B) select Event1.price from Event2.price => mismatch event type name, cannot resolve
// C) select default.Event2.price from Event2.price => possible prefix of engine name
for (int i = 0; i < eventTypes.length; i++)
{
if (eventTypes[i] == null)
{
index++;
continue;
}
if ((streamNames[i] != null) && (streamNames[i].equals(streamName)))
{
streamType = eventTypes[i];
break;
}
// If the stream name is the event type name, that is also acceptable
if ((eventTypes[i].getName() != null) && (eventTypes[i].getName().equals(streamName)))
{
streamType = eventTypes[i];
break;
}
index++;
}
if (streamType == null)
{
// find a near match, textually
String bestMatch = null;
int bestMatchDiff = Integer.MAX_VALUE;
for (int i = 0; i < eventTypes.length; i++)
{
if (streamNames[i] != null)
{
int diff = LevenshteinDistance.computeLevenshteinDistance(streamNames[i], streamName);
if (diff < bestMatchDiff)
{
bestMatchDiff = diff;
bestMatch = streamNames[i];
}
}
if (eventTypes[i] == null)
{
continue;
}
// If the stream name is the event type name, that is also acceptable
if (eventTypes[i].getName() != null)
{
int diff = LevenshteinDistance.computeLevenshteinDistance(eventTypes[i].getName(), streamName);
if (diff < bestMatchDiff)
{
bestMatchDiff = diff;
bestMatch = eventTypes[i].getName();
}
}
}
Pair<Integer, String> suggestion = null;
if (bestMatchDiff < Integer.MAX_VALUE)
{
suggestion = new Pair<Integer, String>(bestMatchDiff, bestMatch);
}
throw new StreamNotFoundException("Failed to find a stream named '" + streamName + "'", suggestion);
}
Class propertyType = streamType.getPropertyType(propertyName);
if (propertyType == null)
{
EventPropertyDescriptor desc = streamType.getPropertyDescriptor(propertyName);
if (desc == null) {
Pair<Integer, String> possibleMatch = findLevMatch(propertyName, streamType);
String message = "Property named '" + propertyName + "' is not valid in stream '" + streamName + "'";
throw new PropertyNotFoundException(message, possibleMatch);
}
propertyType = desc.getPropertyType();
}
return new PropertyResolutionDescriptor(streamName, streamType, propertyName, index, propertyType);
}
public String getEngineURIQualifier() {
return engineURIQualifier;
}
public boolean hasPropertyAgnosticType() {
for (EventType type : eventTypes) {
if (type instanceof EventTypeSPI) {
EventTypeSPI spi = (EventTypeSPI) type;
if (spi.getMetadata().isPropertyAgnostic()) {
return true;
}
}
}
return false;
}
}
| gpl-2.0 |
Ankama/harvey | src/com/ankamagames/dofus/harvey/engine/numeric/bytes/sets/classes/CommonDegenerateContinuousByteSetBridge.java | 967 | /**
*
*/
package com.ankamagames.dofus.harvey.engine.numeric.bytes.sets.classes;
import com.ankamagames.dofus.harvey.engine.common.sets.interfaces.IContinuousBound;
import com.ankamagames.dofus.harvey.engine.numeric.bytes.sets.interfaces.ICommonContinuousByteSet;
import com.ankamagames.dofus.harvey.engine.numeric.bytes.sets.interfaces.IIByteBound;
import com.ankamagames.dofus.harvey.engine.numeric.bytes.sets.interfaces.IIByteBoundFactory;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* @author sgros
*
*/
@NonNullByDefault
public class CommonDegenerateContinuousByteSetBridge<Bound extends IContinuousBound<Bound>&IIByteBound, Type extends ICommonContinuousByteSet<Bound, ?, ?, ?>>
extends CommonDegenerateByteSetBridge<Bound, Type>
{
public CommonDegenerateContinuousByteSetBridge(final byte value, final IIByteBoundFactory<Bound> boundFactory, final Type emptySet, final Type bridged)
{
super(value, boundFactory, emptySet, bridged);
}
} | gpl-2.0 |
10211509/maketaobao | app/src/main/java/nobugs/team/shopping/mvp/interactor/ProductInteractorImpl.java | 1294 | package nobugs.team.shopping.mvp.interactor;
import java.util.List;
import nobugs.team.shopping.mvp.model.Product;
import nobugs.team.shopping.repo.RepoCallback;
import nobugs.team.shopping.repo.Repository;
/**
* Created by xiayong on 2015/8/31.
*/
public class ProductInteractorImpl implements ProductInteractor {
@Override
public void getProducts(String shopId, final Callback callback) {
Repository.getInstance().getProductList(Integer.parseInt(shopId),new RepoCallback.GetList<Product>(){
@Override
public void onGotDataListSuccess(List<Product> products) {
callback.onSuccess(products);
}
@Override
public void onError(int errType, String errMsg) {
callback.onFailure();
}
});
}
@Override
public void getProductUnit(final TypeCallback callback) {
Repository.getInstance().getUnitList(new RepoCallback.GetList<String>() {
@Override
public void onGotDataListSuccess(List<String> strings) {
callback.onTypeSuccess(strings);
}
@Override
public void onError(int errType, String errMsg) {
callback.onFailure();
}
});
}
}
| gpl-2.0 |
christianbors/snapshot-plugin | src/main/java/org/ssanalytics/snapshotplugin/domainModel/crawlerData/sqlWrapper/shared/SharedLocationSql.java | 1646 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.ssanalytics.snapshotplugin.domainModel.crawlerData.sqlWrapper.shared;
import org.ssanalytics.snapshotplugin.domainModel.crawlerData.contract.shared.ISharedLocation;
import org.ssanalytics.snapshotplugin.domainModel.crawlerData.sqlWrapper.superClasses.AbstractBaseDomainSql;
/**
*
* @author chw
*/
public class SharedLocationSql extends AbstractBaseDomainSql implements ISharedLocation {
private Double longitude;
private Double latitude;
private String city;
private String zip;
private String state;
private String country;
private String street;
public SharedLocationSql(Double longitude, Double latitude, String city, String street, String zip, String country, String state){
this.longitude = longitude;
this.latitude = latitude;
this.city = city;
this.street = street;
this.zip = zip;
this.country = country;
this.state = state;
}
@Override
public Double getLongitude() {
return this.longitude;
}
@Override
public Double getLatitude() {
return this.latitude;
}
@Override
public String getCity() {
return this.city;
}
@Override
public String getCountry() {
return this.country;
}
@Override
public String getStreet() {
return this.street;
}
@Override
public String getZip() {
return this.zip;
}
@Override
public String getState() {
return this.state;
}
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | mediatek/packages/apps/RCSe/core/src/com/mediatek/rcse/mvc/ModelImpl.java | 102722 | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein
* is confidential and proprietary to MediaTek Inc. and/or its licensors.
* Without the prior written permission of MediaTek inc. and/or its licensors,
* any reproduction, modification, use or disclosure of MediaTek Software,
* and information contained herein, in whole or in part, shall be strictly prohibited.
*
* MediaTek Inc. (C) 2012. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER ON
* AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR NONINFRINGEMENT.
* NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH RESPECT TO THE
* SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY, INCORPORATED IN, OR
* SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES TO LOOK ONLY TO SUCH
* THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO. RECEIVER EXPRESSLY ACKNOWLEDGES
* THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES
* CONTAINED IN MEDIATEK SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK
* SOFTWARE RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S ENTIRE AND
* CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE RELEASED HEREUNDER WILL BE,
* AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE MEDIATEK SOFTWARE AT ISSUE,
* OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE CHARGE PAID BY RECEIVER TO
* MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek Software")
* have been modified by MediaTek Inc. All revisions are subject to any receiver's
* applicable license agreements with MediaTek Inc.
*/
package com.mediatek.rcse.mvc;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.os.ParcelUuid;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import com.mediatek.rcse.activities.ChatScreenActivity;
import com.mediatek.rcse.activities.PluginProxyActivity;
import com.mediatek.rcse.activities.SettingsFragment;
import com.mediatek.rcse.activities.widgets.ContactsListManager;
import com.mediatek.rcse.activities.widgets.UnreadMessagesContainer;
import com.mediatek.rcse.api.CapabilityApi;
import com.mediatek.rcse.api.CapabilityApi.ICapabilityListener;
import com.mediatek.rcse.api.Logger;
import com.mediatek.rcse.api.Participant;
import com.mediatek.rcse.api.RegistrationApi;
import com.mediatek.rcse.api.RegistrationApi.IRegistrationStatusListener;
import com.mediatek.rcse.fragments.ChatFragment;
import com.mediatek.rcse.interfaces.ChatController;
import com.mediatek.rcse.interfaces.ChatModel.IChat;
import com.mediatek.rcse.interfaces.ChatModel.IChatManager;
import com.mediatek.rcse.interfaces.ChatModel.IChatMessage;
import com.mediatek.rcse.interfaces.ChatView;
import com.mediatek.rcse.interfaces.ChatView.IChatEventInformation.Information;
import com.mediatek.rcse.interfaces.ChatView.IChatWindow;
import com.mediatek.rcse.interfaces.ChatView.IFileTransfer;
import com.mediatek.rcse.interfaces.ChatView.IFileTransfer.Status;
import com.mediatek.rcse.interfaces.ChatView.IGroupChatWindow;
import com.mediatek.rcse.interfaces.ChatView.IOne2OneChatWindow;
import com.mediatek.rcse.plugin.message.PluginGroupChatWindow;
import com.mediatek.rcse.service.ApiManager;
import com.mediatek.rcse.service.RcsNotification;
import com.orangelabs.rcs.R;
import com.orangelabs.rcs.core.ims.service.im.chat.imdn.ImdnDocument;
import com.orangelabs.rcs.core.ims.service.im.filetransfer.FileSharingError;
import com.orangelabs.rcs.platform.AndroidFactory;
import com.orangelabs.rcs.provider.eab.ContactsManager;
import com.orangelabs.rcs.provider.messaging.RichMessagingData;
import com.orangelabs.rcs.provider.settings.RcsSettings;
import com.orangelabs.rcs.service.api.client.ClientApiException;
import com.orangelabs.rcs.service.api.client.capability.Capabilities;
import com.orangelabs.rcs.service.api.client.eventslog.EventsLogApi;
import com.orangelabs.rcs.service.api.client.messaging.IChatSession;
import com.orangelabs.rcs.service.api.client.messaging.IFileTransferEventListener;
import com.orangelabs.rcs.service.api.client.messaging.IFileTransferSession;
import com.orangelabs.rcs.service.api.client.messaging.InstantMessage;
import com.orangelabs.rcs.service.api.client.messaging.MessagingApi;
import com.orangelabs.rcs.service.api.client.messaging.MessagingApiIntents;
import com.orangelabs.rcs.utils.PhoneUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TreeSet;
import java.util.UUID;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.atomic.AtomicReference;
/**
* This is the virtual Module part in the MVC pattern
*/
public class ModelImpl implements IChatManager {
public static final String TAG = "ModelImpl";
private static final String CONTACT_NAME = "contactDisplayname";
private static final String INTENT_MESSAGE = "messages";
private static final String EMPTY_STRING = "";
private static final String COMMA = ", ";
private static final String SEMICOLON = ";";
public static final Timer TIMER = new Timer();
public static final int INDEXT_ONE = 1;
private static int sIdleTimeout = 0;
private static final IChatManager INSTANCE = new ModelImpl();
private static final HandlerThread CHAT_WORKER_THREAD = new HandlerThread("Chat Worker");
static {
CHAT_WORKER_THREAD.start();
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>() {
@Override
protected Void doInBackground(Void... arg0) {
sIdleTimeout = RcsSettings.getInstance().getIsComposingTimeout() * 1000;
return null;
}
};
task.execute();
}
// The map retains Object&IChat&List<Participant>
private final Map<Object, IChat> mChatMap = new HashMap<Object, IChat>();
public static IChatManager getInstance() {
return INSTANCE;
}
@Override
public IChat addChat(List<Participant> participants, Object chatTag) {
Logger.d(TAG, "addChat() entry, participants: " + participants + " chatTag: " + chatTag);
int size = 0;
IChat chat = null;
ParcelUuid parcelUuid = null;
if (chatTag == null) {
UUID uuid = UUID.randomUUID();
parcelUuid = new ParcelUuid(uuid);
} else {
parcelUuid = (ParcelUuid) chatTag;
}
Logger.d(TAG, "addChat() parcelUuid: " + parcelUuid + ",participants = " + participants);
if (null != participants && participants.size() > 0) {
size = participants.size();
if (size > 1) {
chat = new GroupChat(this, null, participants, parcelUuid);
mChatMap.put(parcelUuid, chat);
IGroupChatWindow chatWindow = ViewImpl.getInstance().addGroupChatWindow(parcelUuid,
((GroupChat) chat).getParticipantInfos());
((GroupChat) chat).setChatWindow(chatWindow);
} else {
chat = getOne2OneChat(participants.get(0));
if (null == chat) {
Logger.i(TAG, "addChat() The one-2-one chat with " + participants
+ "doesn't exist.");
Participant participant = participants.get(0);
chat = new One2OneChat(this, null, participant, parcelUuid);
mChatMap.put(parcelUuid, chat);
String number = participant.getContact();
if (ContactsListManager.getInstance().isLocalContact(number)
|| ContactsListManager.getInstance().isStranger(number)) {
Logger.d(TAG, "addChat() the number is local or stranger" + number);
} else {
CapabilityApi capabilityApi = ApiManager.getInstance()
.getCapabilityApi();
Logger.d(TAG,
"addChat() the number is not local or stranger"
+ number + ", capabilityApi= "
+ capabilityApi);
if (capabilityApi != null) {
Capabilities capability = capabilityApi
.getContactCapabilities(number);
Logger.d(TAG, "capability = " + capability);
if (capability != null) {
if (capability.isSupportedRcseContact()) {
ContactsListManager.getInstance()
.setStrangerList(number, true);
} else {
ContactsListManager.getInstance()
.setStrangerList(number, false);
}
}
}
}
IOne2OneChatWindow chatWindow = ViewImpl.getInstance().addOne2OneChatWindow(
parcelUuid, participants.get(0));
((One2OneChat) chat).setChatWindow(chatWindow);
} else {
Logger.i(TAG, "addChat() The one-2-one chat with " + participants
+ "has existed.");
ViewImpl.getInstance().switchChatWindowByTag(
(ParcelUuid) (((One2OneChat) chat).mTag));
}
}
}
Logger.d(TAG, "addChat(),the chat is " + chat);
return chat;
}
private IChat addChat(List<Participant> participants) {
return addChat(participants, null);
}
public IChat getOne2oneChatByContact(String contact) {
Logger.i(TAG, "getOne2oneChatByContact() contact: " + contact);
IChat chat = null;
if (TextUtils.isEmpty(contact)) {
return chat;
}
ArrayList<Participant> participant = new ArrayList<Participant>();
participant.add(new Participant(contact, contact));
chat = addChat(participant, null);
return chat;
}
private IChat getOne2OneChat(Participant participant) {
Logger.i(TAG, "getOne2OneChat() entry the participant is " + participant);
Collection<IChat> chats = mChatMap.values();
for (IChat chat : chats) {
if (chat instanceof One2OneChat && ((One2OneChat) chat).isDuplicated(participant)) {
Logger.d(TAG, "getOne2OneChat() find the 1-2-1 chat with " + participant
+ " has existed");
return chat;
}
}
Logger.d(TAG, "getOne2OneChat() could not find the 1-2-1 chat with " + participant);
return null;
}
private void switchGroupChat(IChat chat) {
Logger.d(TAG, "switchGroupChat() entry, chat: " + chat);
ParcelUuid tag = (ParcelUuid) (((GroupChat) chat).mTag);
ViewImpl.getInstance().switchChatWindowByTag(tag);
Logger.d(TAG, "switchGroupChat() exit, tag: " + tag);
}
@Override
public IChat getChat(Object tag) {
Logger.v(TAG, "getChat(),tag = " + tag);
if (tag instanceof ParcelUuid) {
Logger.v(TAG, "tgetChat(),tag instanceof ParcelUuid");
} else {
Logger.v(TAG, "tgetChat(),tag not instanceof ParcelUuid");
}
if (tag == null) {
Logger.v(TAG, "tag is null so return null");
return null;
}
if (mChatMap.isEmpty()) {
Logger.v(TAG, "mChatMap is empty so no chat exist");
return null;
}
IChat chat = mChatMap.get(tag);
Logger.v(TAG, "return chat = " + chat);
return chat;
}
@Override
public List<IChat> listAllChat() {
List<IChat> list = new ArrayList<IChat>();
if (mChatMap.isEmpty()) {
Logger.w(TAG, "mChatMap is empty");
return list;
}
Collection<IChat> collection = mChatMap.values();
Iterator<IChat> iter = collection.iterator();
while (iter.hasNext()) {
IChat chat = iter.next();
if (chat != null) {
Logger.w(TAG, "listAllChat()-IChat is empty");
list.add(chat);
}
}
return list;
}
@Override
public boolean removeChat(Object tag) {
if (tag == null) {
Logger.w(TAG, "removeChat()-The tag is null");
return false;
}
ParcelUuid uuid = new ParcelUuid(UUID.fromString(tag.toString()));
IChat chat = mChatMap.remove(uuid);
if (chat != null) {
((ChatImpl) chat).onDestroy();
mOutGoingFileTransferManager.onChatDestroy(tag);
ViewImpl.getInstance().removeChatWindow(((ChatImpl) chat).getChatWindow());
return true;
} else {
Logger.d(TAG, "removeChat()-The chat is null");
return false;
}
}
/**
* Remove group chat, but does not close the window associated with the
* chat.
*
* @param tag The tag of the group chat to be removed.
* @return True if success, else false.
*/
public boolean quitGroupChat(Object tag) {
Logger.d(TAG, "quitGroupChat() entry, with tag is " + tag);
if (tag == null) {
Logger.w(TAG, "quitGroupChat() tag is null");
return false;
}
IChat chat = getChat(tag);
if (chat instanceof GroupChat) {
((GroupChat) chat).onQuit();
mOutGoingFileTransferManager.onChatDestroy(tag);
return true;
} else {
Logger.d(TAG, "quitGroupChat() chat is null");
return false;
}
}
/**
* when there is not not file transfer capability, cancel all the file
* transfer
*
* @param tag The tag of the chat.
* @param reason the reason for file transfer not available.
*/
public void handleFileTransferNotAvailable(Object tag, int reason) {
Logger.d(TAG, "handleFileTransferNotAvailable() entry, with tag is " + tag + " reason is "
+ reason);
if (tag == null) {
Logger.w(TAG, "handleFileTransferNotAvailable() tag is null");
} else {
mOutGoingFileTransferManager.clearTransferWithTag(tag, reason);
}
}
/**
* remove chat according the relevant participant
*
* @param the participant of the chat
*/
public void removeChatByContact(Participant participant) {
IChat chat = getOne2OneChat(participant);
Logger.v(TAG, "removeChatByContact(),participant = " + participant
+ ", chat = " + chat);
if (chat != null) {
removeChat((ChatImpl) chat);
}
}
private boolean removeChat(final ChatImpl chat) {
if (mChatMap.isEmpty()) {
Logger.w(TAG, "removeChat()-mChatMap is empty");
return false;
}
if (!mChatMap.containsValue(chat)) {
Logger.w(TAG, "removeChat()-mChatMap didn't contains this IChat");
return false;
} else {
Logger.v(TAG, "mchatMap size is " + mChatMap.size());
mChatMap.values().remove(chat);
Logger.v(TAG, "After removded mchatMap size is " + mChatMap.size() + ", chat = "
+ chat);
if (chat != null) {
chat.onDestroy();
mOutGoingFileTransferManager.onChatDestroy(chat.mTag);
ViewImpl.getInstance().removeChatWindow(chat.getChatWindow());
}
return true;
}
}
/**
* Clear all the chat messages. Include clear all the messages in date base
* ,clear messages in all the chat window and clear the last message in each
* chat list item.
*/
public void clearAllChatHistory() {
ContentResolver contentResolver =
ApiManager.getInstance().getContext().getContentResolver();
contentResolver.delete(RichMessagingData.CONTENT_URI, null, null);
List<IChat> list = INSTANCE.listAllChat();
int size = list.size();
Logger.d(TAG, "clearAllChatHistory(), the size of the chat list is " + size);
for (int i = 0; i < size; i++) {
IChat chat = list.get(i);
if (chat != null) {
((ChatImpl) chat).clearChatWindowAndList();
}
}
}
/**
* This class is the implementation of a chat message used in model part
*/
private static class ChatMessage implements IChatMessage {
private InstantMessage mInstantMessage;
public ChatMessage(InstantMessage instantMessage) {
mInstantMessage = instantMessage;
}
@Override
public InstantMessage getInstantMessage() {
return mInstantMessage;
}
}
/**
* This class is the implementation of a sent chat message used in model
* part
*/
public static class ChatMessageSent extends ChatMessage {
public ChatMessageSent(InstantMessage instantMessage) {
super(instantMessage);
}
}
/**
* This class is the implementation of a received chat message used in model
* part
*/
public static class ChatMessageReceived extends ChatMessage {
public ChatMessageReceived(InstantMessage instantMessage) {
super(instantMessage);
}
}
/**
* The call-back method of the interface called when the unread message
* number changed
*/
public interface UnreadMessageListener {
/**
* The call-back method to update the unread message when the number of
* unread message changed
*
* @param chatWindowTag The chat window tag indicates which to update
* @param clear Whether cleared all unread message
*/
void onUnreadMessageNumberChanged(Object chatWindowTag, boolean clear);
}
/**
* It's a implementation of IChat, it indicates a specify chat model.
*/
public abstract class ChatImpl implements IChat, IRegistrationStatusListener,
ICapabilityListener {
private static final String TAG = "ChatImpl";
// Chat message list
private final List<IChatMessage> mMessageList = new LinkedList<IChatMessage>();
protected final AtomicReference<IChatSession> mCurrentSession =
new AtomicReference<IChatSession>();
protected ComposingManager mComposingManager = new ComposingManager();
protected Object mTag = null;
protected boolean mIsInBackground = true;
protected IChatWindow mChatWindow = null;
protected List<InstantMessage> mReceivedInBackgroundToBeDisplayed =
new ArrayList<InstantMessage>();
protected List<InstantMessage> mReceivedInBackgroundToBeRead =
new ArrayList<InstantMessage>();
protected RegistrationApi mRegistrationApi = null;
protected Thread mWorkerThread = CHAT_WORKER_THREAD;
protected Handler mWorkerHandler = new Handler(CHAT_WORKER_THREAD.getLooper());
/**
* Clear all the messages in chat Window and the latest message in chat
* list.
*/
public void clearChatWindowAndList() {
Logger.d(TAG, "clearChatWindowAndList() entry");
mChatWindow.removeAllMessages();
Logger.d(TAG, "clearChatWindowAndList() exit");
}
/**
* Set chat window for this chat.
*
* @param chatWindow The chat window to be set.
*/
public void setChatWindow(IChatWindow chatWindow) {
Logger.d(TAG, "setChatWindow entry");
mChatWindow = chatWindow;
}
/**
* Add the unread message of this chat
*
* @param message The unread message to add
*/
protected void addUnreadMessage(InstantMessage message) {
if (message.isImdnDisplayedRequested()) {
Logger.d(TAG, "mReceivedInBackgroundToBeDisplayed = "
+ mReceivedInBackgroundToBeDisplayed);
if (mReceivedInBackgroundToBeDisplayed != null) {
mReceivedInBackgroundToBeDisplayed.add(message);
if (mTag instanceof UUID) {
ParcelUuid parcelUuid = new ParcelUuid((UUID) mTag);
UnreadMessagesContainer.getInstance().add(parcelUuid);
} else {
UnreadMessagesContainer.getInstance().add((ParcelUuid) mTag);
}
UnreadMessagesContainer.getInstance().loadLatestUnreadMessage();
}
} else {
Logger.d(TAG, "mReceivedInBackgroundToBeRead = "
+ mReceivedInBackgroundToBeRead);
if (mReceivedInBackgroundToBeRead != null) {
mReceivedInBackgroundToBeRead.add(message);
if (mTag instanceof UUID) {
ParcelUuid parcelUuid = new ParcelUuid((UUID) mTag);
UnreadMessagesContainer.getInstance().add(parcelUuid);
} else {
UnreadMessagesContainer.getInstance().add(
(ParcelUuid) mTag);
}
UnreadMessagesContainer.getInstance()
.loadLatestUnreadMessage();
}
}
}
/**
* Get unread messages of this chat.
*
* @return The unread messages.
*/
public List<InstantMessage> getUnreadMessages() {
if (mReceivedInBackgroundToBeDisplayed != null
&& mReceivedInBackgroundToBeDisplayed.size() > 0) {
return mReceivedInBackgroundToBeDisplayed;
} else {
return mReceivedInBackgroundToBeRead;
}
}
/**
* Clear all the unread message of this chat
*/
protected void clearUnreadMessage() {
Logger.v(TAG,
"clearUnreadMessage(): mReceivedInBackgroundToBeDisplayed = "
+ mReceivedInBackgroundToBeDisplayed
+ ", mReceivedInBackgroundToBeRead = "
+ mReceivedInBackgroundToBeRead);
if (null != mReceivedInBackgroundToBeDisplayed) {
mReceivedInBackgroundToBeDisplayed.clear();
UnreadMessagesContainer.getInstance().remove((ParcelUuid) mTag);
UnreadMessagesContainer.getInstance().loadLatestUnreadMessage();
}
if (null != mReceivedInBackgroundToBeRead) {
mReceivedInBackgroundToBeRead.clear();
UnreadMessagesContainer.getInstance().remove((ParcelUuid) mTag);
UnreadMessagesContainer.getInstance().loadLatestUnreadMessage();
}
}
protected ChatImpl(Object tag) {
mTag = tag;
// register IRegistrationStatusListener
ApiManager apiManager = ApiManager.getInstance();
Logger.v(TAG, "ChatImpl() entry: apiManager = " + apiManager);
if (null != apiManager) {
mRegistrationApi = ApiManager.getInstance().getRegistrationApi();
Logger.v(TAG, "mRegistrationApi = " + mRegistrationApi);
if (mRegistrationApi != null) {
mRegistrationApi.addRegistrationStatusListener(this);
}
CapabilityApi capabilityApi = ApiManager.getInstance().getCapabilityApi();
Logger.v(TAG, "capabilityApi = " + capabilityApi);
if (capabilityApi != null) {
capabilityApi.registerCapabilityListener(this);
}
}
}
/**
* Get the chat tag of current chat
*
* @return The chat tag of current chat
*/
public Object getChatTag() {
return mTag;
}
protected void onPause() {
Logger.v(TAG, "onPause() entry, tag: " + mTag);
mIsInBackground = true;
}
protected void onResume() {
Logger.v(TAG, "onResume() entry, tag: " + mTag);
mIsInBackground = false;
if (mChatWindow != null) {
mChatWindow.updateAllMsgAsRead();
}
markUnreadMessageDisplayed();
loadChatMessages(One2OneChat.LOAD_ZERO_SHOW_HEADER);
}
protected synchronized void onDestroy() {
this.queryCapabilities();
ApiManager apiManager = ApiManager.getInstance();
Logger.v(TAG, "onDestroy() apiManager = " + apiManager);
if (null != apiManager) {
CapabilityApi capabilityApi = ApiManager.getInstance().getCapabilityApi();
Logger.v(TAG, "onDestroy() capabilityApi = " + capabilityApi);
if (capabilityApi != null) {
capabilityApi.unregisterCapabilityListener(this);
}
}
Logger.v(TAG, "onDestroy() mRegistrationApi = " + mRegistrationApi
+ ",mCurrentSession = " + mCurrentSession.get());
if (mRegistrationApi != null) {
mRegistrationApi.removeRegistrationStatusListener(this);
}
if (mCurrentSession.get() != null) {
try {
terminateSession();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
/**
* Return the IChatWindow
*
* @return IChatWindow
*/
IChatWindow getChatWindow() {
return mChatWindow;
}
protected void markMessageAsDisplayed(InstantMessage msg) {
Logger.d(TAG, "markMessageAsDisplayed() entry");
if (msg == null) {
Logger.d(TAG, "markMessageAsDisplayed(),msg is null");
return;
}
try {
IChatSession tmpChatSession = mCurrentSession.get();
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(ApiManager.getInstance()
.getContext());
boolean isSendReadReceiptChecked =
settings.getBoolean(SettingsFragment.RCS_SEND_READ_RECEIPT, true);
Logger.d(TAG, "markMessageAsDisplayed() ,the value of isSendReadReceiptChecked is "
+ isSendReadReceiptChecked);
if (tmpChatSession == null) {
Logger.d(TAG, "markMessageAsDisplayed() ,tmpChatSession is null");
return;
}
Logger.d(TAG,
"markMessageAsDisplayed() ,the value of isSendReadReceiptChecked is "
+ isSendReadReceiptChecked);
if (isSendReadReceiptChecked) {
if (tmpChatSession.isStoreAndForward()) {
Logger.v(TAG,
"markMessageAsDisplayed(),send displayed message by sip message");
tmpChatSession.setMessageDisplayedStatusBySipMessage(tmpChatSession
.getReferredByHeader(), msg.getMessageId(),
ImdnDocument.DELIVERY_STATUS_DISPLAYED);
} else {
Logger.v(TAG,
"markMessageAsDisplayed(),send displayed message by msrp message");
tmpChatSession.setMessageDeliveryStatus(msg.getMessageId(),
ImdnDocument.DELIVERY_STATUS_DISPLAYED);
}
}
} catch (RemoteException e) {
e.printStackTrace();
}
Logger.d(TAG, "markMessageAsDisplayed() exit");
}
protected void markMessageAsRead(InstantMessage msg) {
Logger.d(TAG, "markMessageAsRead() entry");
EventsLogApi events = null;
if (ApiManager.getInstance() != null) {
events = ApiManager.getInstance().getEventsLogApi();
events.markChatMessageAsRead(msg.getMessageId(), true);
}
Logger.d(TAG, "markMessageAsRead() exit");
}
protected void markUnreadMessageDisplayed() {
Logger.v(TAG, "markUnreadMessageDisplayed() entry");
int size = mReceivedInBackgroundToBeDisplayed.size();
for (int i = 0; i < size; i++) {
InstantMessage msg = mReceivedInBackgroundToBeDisplayed.get(i);
markMessageAsDisplayed(msg);
Logger.v(TAG, "The message " + msg.getTextMessage() + " is displayed");
}
size = mReceivedInBackgroundToBeRead.size();
for (int i = 0; i < size; i++) {
InstantMessage msg = mReceivedInBackgroundToBeRead.get(i);
markMessageAsRead(msg);
Logger.v(TAG, "The message " + msg.getTextMessage() + " is read");
}
clearUnreadMessage();
Logger.v(TAG, "markUnreadMessageDisplayed() exit");
}
private void terminateSession() throws RemoteException {
if (mCurrentSession.get() != null) {
mCurrentSession.get().cancelSession();
mCurrentSession.set(null);
Logger.i(TAG, "terminateSession()---mCurrentSession cancel and is null");
}
}
protected void reloadMessage(InstantMessage message, int messageType, int status) {
Logger.w(TAG, "reloadMessage() sub-class needs to override this method");
}
protected void reloadFileTransfer(FileStruct fileStruct, int transferType, int status) {
Logger.w(TAG, "reloadFileTransfer() sub-class needs to override this method");
}
protected class ComposingManager {
private static final int ACT_STATE_TIME_OUT = 60 * 1000;
private boolean mIsComposing = false;
private static final int STARTING_COMPOSING = 1;
private static final int STILL_COMPOSING = 2;
private static final int MESSAGE_WAS_SENT = 3;
private static final int ACTIVE_MESSAGE_REFRESH = 4;
private static final int IS_IDLE = 5;
private ComposingHandler mWorkerHandler =
new ComposingHandler(CHAT_WORKER_THREAD.getLooper());
public ComposingManager() {
}
protected class ComposingHandler extends Handler {
public static final String TAG = "ComposingHandler";
public ComposingHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
Logger.i(TAG, "handleMessage() the msg is:" + msg.what);
switch (msg.what) {
case STARTING_COMPOSING:
if (setIsComposing(true)) {
mIsComposing = true;
mWorkerHandler.sendEmptyMessageDelayed(IS_IDLE, sIdleTimeout);
mWorkerHandler.sendEmptyMessageDelayed(ACTIVE_MESSAGE_REFRESH,
ACT_STATE_TIME_OUT);
} else {
Logger.d(TAG,
"STARTING_COMPOSING-> failed to set isComposing to true");
}
break;
case STILL_COMPOSING:
mWorkerHandler.removeMessages(IS_IDLE);
mWorkerHandler.sendEmptyMessageDelayed(IS_IDLE, sIdleTimeout);
break;
case MESSAGE_WAS_SENT:
if (setIsComposing(false)) {
mComposingManager.hasNoText();
mWorkerHandler.removeMessages(IS_IDLE);
mWorkerHandler.removeMessages(ACTIVE_MESSAGE_REFRESH);
} else {
Logger.d(TAG,
"MESSAGE_WAS_SENT-> failed to set isComposing to false");
}
break;
case ACTIVE_MESSAGE_REFRESH:
if (setIsComposing(true)) {
mWorkerHandler.sendEmptyMessageDelayed(ACTIVE_MESSAGE_REFRESH,
ACT_STATE_TIME_OUT);
} else {
Logger
.d(TAG,
"ACTIVE_MESSAGE_REFRESH-> failed to set isComposing to true");
}
break;
case IS_IDLE:
if (setIsComposing(false)) {
mComposingManager.hasNoText();
mWorkerHandler.removeMessages(ACTIVE_MESSAGE_REFRESH);
} else {
Logger.d(TAG, "IS_IDLE-> failed to set isComposing to false");
}
break;
default:
Logger.i(TAG, "handlemessage()--message" + msg.what);
break;
}
}
}
public void hasText(Boolean isEmpty) {
Logger.d(TAG, "hasText() entry the edit is " + isEmpty);
if (isEmpty) {
mWorkerHandler.sendEmptyMessage(MESSAGE_WAS_SENT);
} else {
if (!mIsComposing) {
mWorkerHandler.sendEmptyMessage(STARTING_COMPOSING);
} else {
mWorkerHandler.sendEmptyMessage(STILL_COMPOSING);
}
}
}
public void hasNoText() {
mIsComposing = false;
}
public void messageWasSent() {
mWorkerHandler.sendEmptyMessage(MESSAGE_WAS_SENT);
}
}
protected boolean setIsComposing(boolean isComposing) {
if (mCurrentSession.get() == null) {
Logger.e(TAG, "setIsComposing() -- The chat with the tag " + " doesn't exist!");
return false;
} else {
try {
mCurrentSession.get().setIsComposingStatus(isComposing);
} catch (RemoteException e) {
e.printStackTrace();
}
return true;
}
}
@Override
public IChatMessage getSentChatMessage(int index) {
if (index < 0 || index > mMessageList.size()) {
return null;
}
return mMessageList.get(index);
}
@Override
public int getChatMessageCount() {
return mMessageList.size();
}
@Override
public List<IChatMessage> listAllChatMessages() {
return mMessageList;
}
@Override
public abstract void loadChatMessages(int count);
@Override
public boolean removeMessage(int index) {
if (index < 0 || index > mMessageList.size()) {
return false;
}
mMessageList.remove(index);
return true;
}
@Override
public boolean removeMessages(int start, int end) {
if (start < 0 || start > mMessageList.size()) {
return false;
}
return true;
}
/**
* Check capabilities before inviting a chat
*/
protected abstract void checkCapabilities();
/**
* Query capabilities after terminating a chat
*/
protected abstract void queryCapabilities();
@Override
public void hasTextChanged(boolean isEmpty) {
mComposingManager.hasText(isEmpty);
}
@Override
public abstract void onCapabilityChanged(String contact, Capabilities capabilities);
@Override
public abstract void onStatusChanged(boolean status);
}
private boolean isChatExisted(Participant participant) {
Logger.v(TAG, "isHaveChat() The participant is " + participant);
boolean bIsHaveChat = false;
// Find the chat in the chat list
Collection<IChat> chatList = mChatMap.values();
if (chatList != null) {
for (IChat chat : chatList) {
if (chat instanceof One2OneChat) {
if (null != participant && (((One2OneChat) chat).isDuplicated(participant))) {
bIsHaveChat = true;
}
}
}
}
Logger.i(TAG, "isHaveChat() end, bIsHaveChat = " + bIsHaveChat);
return bIsHaveChat;
}
@Override
public boolean handleInvitation(Intent intent, boolean isCheckSessionExist) {
Logger.v(TAG, "handleInvitation entry");
String action = null;
if (intent == null) {
Logger.d(TAG, "handleInvitation intent is null");
return false;
} else {
action = intent.getAction();
}
if (MessagingApiIntents.CHAT_SESSION_REPLACED.equalsIgnoreCase(action)) {
Logger.d(TAG, " handleInvitation() the action is CHAT_SESSION_REPLACED ");
} else if (MessagingApiIntents.CHAT_INVITATION.equalsIgnoreCase(action)) {
return handleChatInvitation(intent, isCheckSessionExist);
}
Logger.v(TAG, "handleInvitation exit: action = " + action);
return false;
}
private boolean handleChatInvitation(Intent intent, boolean isCheckSessionExist) {
ApiManager instance = ApiManager.getInstance();
String sessionId = intent.getStringExtra("sessionId");
if (instance != null) {
MessagingApi messageApi = instance.getMessagingApi();
if (messageApi != null) {
try {
IChatSession chatSession = messageApi.getChatSession(sessionId);
if (chatSession == null) {
Logger.e(TAG, "The getChatSession is null");
return false;
}
List<String> participants = chatSession.getInivtedParticipants();
if (participants == null || participants.size() == 0) {
Logger.e(TAG, "The getParticipants is null, or size is 0");
return false;
}
int participantCount = participants.size();
ArrayList<InstantMessage> messages =
intent.getParcelableArrayListExtra(INTENT_MESSAGE);
ArrayList<IChatMessage> chatMessages = new ArrayList<IChatMessage>();
if (null != messages) {
int size = messages.size();
for (int i = 0; i < size; i++) {
InstantMessage msg = messages.get(i);
Logger.d(TAG, "InstantMessage:" + msg);
if (msg != null) {
chatMessages.add(new ChatMessageReceived(msg));
}
}
}
if (participantCount == 1) {
List<Participant> participantsList = new ArrayList<Participant>();
String remoteParticipant = participants.get(0);
String number = PhoneUtils.extractNumberFromUri(remoteParticipant);
String name = intent.getStringExtra(CONTACT_NAME);
Participant fromSessionParticipant = new Participant(number, name);
participantsList.add(fromSessionParticipant);
if (!isCheckSessionExist) {
IChat currentChat = addChat(participantsList);
currentChat.handleInvitation(chatSession, chatMessages);
return true;
} else {
if (isChatExisted(fromSessionParticipant)) {
IChat currentChat = addChat(participantsList);
currentChat.handleInvitation(chatSession, chatMessages);
Logger.v(TAG, "handleInvitation exit with true");
return true;
} else {
Logger.v(TAG, "handleInvitation exit with false");
return false;
}
}
} else if (participantCount > 1) {
List<Participant> participantsList = new ArrayList<Participant>();
for (int i = 0; i < participantCount; i++) {
String remoteParticipant = participants.get(i);
String number = PhoneUtils.extractNumberFromUri(remoteParticipant);
String name = number;
if (PhoneUtils.isANumber(number)) {
name = ContactsListManager.getInstance().getDisplayNameByPhoneNumber(number);
} else {
Logger
.e(TAG, "the participant " + number
+ " is not a real number");
}
Participant fromSessionParticipant = new Participant(number, name);
participantsList.add(fromSessionParticipant);
}
String chatId = intent.getStringExtra(RcsNotification.CHAT_ID);
ParcelUuid tag = (ParcelUuid) intent
.getParcelableExtra(ChatScreenActivity.KEY_CHAT_TAG);
IChat chat = getGroupChat(chatId);
if (chat == null) {
chat = addChat(participantsList, tag);
} else {
// restart chat.
chatMessages.clear();
}
chat.handleInvitation(chatSession, chatMessages);
return true;
} else {
Logger.e(TAG, "Illegal paticipants");
return false;
}
} catch (ClientApiException e) {
Logger.e(TAG, "getChatSession fail");
e.printStackTrace();
} catch (RemoteException e) {
Logger.e(TAG, "getParticipants fail");
e.printStackTrace();
}
}
}
return false;
}
@Override
public boolean handleFileTransferInvitation(String sessionId) {
ApiManager instance = ApiManager.getInstance();
if (instance != null) {
MessagingApi messageApi = instance.getMessagingApi();
if (messageApi != null) {
try {
IFileTransferSession fileTransferSession =
messageApi.getFileTransferSession(sessionId);
if (fileTransferSession == null) {
Logger.e(TAG,
"handleFileTransferInvitation-The getFileTransferSession is null");
return false;
}
List<Participant> participantsList = new ArrayList<Participant>();
String number =
PhoneUtils.extractNumberFromUri(fileTransferSession.getRemoteContact());
// Get the contact name from contact list
String name = EMPTY_STRING;
Logger.e(TAG, "handleFileTransferInvitation, number = " + name);
if (null != number) {
String tmpContact = ContactsListManager.getInstance().getDisplayNameByPhoneNumber(number);
if (tmpContact != null) {
name = tmpContact;
} else {
name = number;
}
}
Participant fromSessionParticipant = new Participant(number, name);
participantsList.add(fromSessionParticipant);
if (isChatExisted(fromSessionParticipant)) {
IChat chat = addChat(participantsList);
((One2OneChat) chat).addReceiveFileTransfer(fileTransferSession);
if (!((One2OneChat) chat).mIsInBackground) {
Logger.v(TAG, "handleFileTransferInvitation()" +
"-handleInvitation exit with true, is the current chat!");
return true;
} else {
Logger.v(TAG, "handleFileTransferInvitation()" +
"-handleInvitation exit with true, is not the current chat!");
return false;
}
} else {
Logger.v(TAG,
"handleFileTransferInvitation-handleInvitation exit with false");
IChat chat = addChat(participantsList);
((One2OneChat) chat).addReceiveFileTransfer(fileTransferSession);
return false;
}
} catch (ClientApiException e) {
Logger.e(TAG, "handleFileTransferInvitation-getChatSession fail");
e.printStackTrace();
} catch (RemoteException e) {
Logger.e(TAG, "handleFileTransferInvitation-getParticipants fail");
e.printStackTrace();
}
}
}
return false;
}
@Override
public void handleMessageDeliveryStatus(String contact, String msgId,
String status, long timeStamp) {
IChat chat = getOne2OneChat(new Participant(contact, contact));
Logger.d(TAG, "handleMessageDeliveryStatus() entry, contact:" + contact
+ " msgId:" + msgId + " status:" + status + " ,timeStamp: "
+ timeStamp + ",chat = " + chat);
if (null != chat) {
((One2OneChat) chat).onMessageDelivered(msgId, status, timeStamp);
}
}
/**
* Called by the controller when the user needs to cancel an on-going file
* transfer
*
* @param tag The chat window tag where the file transfer is in
* @param fileTransferTag The tag indicating which file transfer will be
* canceled
*/
public void handleCancelFileTransfer(Object tag, Object fileTransferTag) {
Logger.v(TAG, "handleCancelFileTransfer(),tag = " + tag + ",fileTransferTag = "
+ fileTransferTag);
IChat chat = getChat(tag);
if (chat == null) {
chat = getOne2oneChatByContact((String) tag);
}
if (chat instanceof One2OneChat) {
One2OneChat oneOneChat = ((One2OneChat) chat);
oneOneChat.handleCancelFileTransfer(fileTransferTag);
}
Logger.d(TAG, "handleCancelFileTransfer() it's a sent file transfer");
mOutGoingFileTransferManager.cancelFileTransfer(fileTransferTag);
}
/**
* Called by the controller when the user needs to resend a file
*
* @param fileTransferTag The tag of file which the user needs to resend
*/
public void handleResendFileTransfer(Object fileTransferTag) {
mOutGoingFileTransferManager.resendFileTransfer(fileTransferTag);
}
/**
* This class represents a file structure used to be shared
*/
public static class FileStruct {
public static final String TAG = "FileStruct";
/**
* Generate a file struct instance using a session and a path, this
* method should only be called for Received File Transfer
*
* @param fileTransferSession The session of the file transfer
* @param filePath The path of the file
* @return The file struct instance
* @throws RemoteException
*/
public static FileStruct from(IFileTransferSession fileTransferSession, String filePath)
throws RemoteException {
FileStruct fileStruct = null;
String fileName = fileTransferSession.getFilename();
long fileSize = fileTransferSession.getFilesize();
String sessionId = fileTransferSession.getSessionID();
Date date = new Date();
fileStruct = new FileStruct(filePath, fileName, fileSize, sessionId, date);
return fileStruct;
}
/**
* Generate a file struct instance using a path, this method should only
* be called for Sent File Transfer
*
* @param filePath The path of the file
* @return The file struct instance
*/
public static FileStruct from(String filePath) {
FileStruct fileStruct = null;
File file = new File(filePath);
if (file.exists()) {
Date date = new Date();
fileStruct =
new FileStruct(filePath, file.getName(), file.length(), new ParcelUuid(UUID
.randomUUID()), date);
}
Logger.d(TAG, "from() fileStruct: " + fileStruct);
return fileStruct;
}
public FileStruct(String filePath, String name, long size, Object fileTransferTag, Date date) {
mFilePath = filePath;
mName = name;
mSize = size;
mFileTransferTag = fileTransferTag;
mDate = (Date) date.clone();
}
public FileStruct(String filePath, String name, long size, Object fileTransferTag, Date date, String remote) {
mFilePath = filePath;
mName = name;
mSize = size;
mFileTransferTag = fileTransferTag;
mDate = (Date) date.clone();
mRemote = remote;
}
public String mFilePath = null;
public String mName = null;
public long mSize = -1;
public Object mFileTransferTag = null;
public Date mDate = null;
public String mRemote = null;
public String toString() {
return TAG + "file path is " + mFilePath + " file name is " + mName + " size is "
+ mSize + " FileTransferTag is " + mFileTransferTag + " date is " + mDate;
}
}
/**
* This class represents a chat event structure used to be shared
*/
public static class ChatEventStruct {
public static final String TAG = "ChatEventStruct";
public ChatEventStruct(Information info, Object relatedInfo, Date dt) {
information = info;
relatedInformation = relatedInfo;
date = (Date) dt.clone();
}
public Information information = null;
public Object relatedInformation = null;
public Date date = null;
public String toString() {
return TAG + "information is " + information + " relatedInformation is "
+ relatedInformation + " date is " + date;
}
}
/**
* Clear all history of the chats, include both one2one chat and group chat.
*
* @return True if successfully clear, false otherwise.
*/
public boolean clearAllHistory() {
Logger.d(TAG, "clearAllHistory() entry");
ControllerImpl controller = ControllerImpl.getInstance();
boolean result = false;
if (null != controller) {
Message controllerMessage = controller.obtainMessage(
ChatController.EVENT_CLEAR_CHAT_HISTORY, null, null);
controllerMessage.sendToTarget();
result = true;
}
Logger.d(TAG, "clearAllHistory() exit with result = " + result);
return result;
}
/**
* Called by the controller when the user needs to start a file transfer
*
* @param target The tag of the chat window in which the file transfer
* starts or the contact to receive this file
* @param filePath The path of the file to be transfered
*/
public void handleSendFileTransferInvitation(Object target, String filePath,
Object fileTransferTag) {
Logger.d(TAG, "handleSendFileTransferInvitation() user starts to send file " + filePath
+ " to target " + target + ", fileTransferTag: " + fileTransferTag);
IChat chat = null;
if (target instanceof String) {
String contact = (String) target;
List<Participant> participants = new ArrayList<Participant>();
participants.add(new Participant(contact,contact));
chat = addChat(participants);
} else {
chat = getChat(target);
}
Logger.d(TAG, "handleSendFileTransferInvitation() chat: " + chat);
if (chat instanceof One2OneChat) {
Participant participant = ((One2OneChat) chat).getParticipant();
Logger.d(TAG, "handleSendFileTransferInvitation() user starts to send file " + filePath
+ " to " + participant + ", fileTransferTag: " + fileTransferTag);
mOutGoingFileTransferManager.onAddSentFileTransfer(((One2OneChat) chat).generateSentFileTransfer(
filePath, fileTransferTag));
}
}
/**
* This class describe one single out-going file transfer, and control the
* status itself
*/
public static class SentFileTransfer {
private static final String TAG = "SentFileTransfer";
public static final String KEY_FILE_TRANSFER_TAG = "file transfer tag";
protected Object mChatTag = null;
protected Object mFileTransferTag = null;
protected FileStruct mFileStruct = null;
protected IFileTransfer mFileTransfer = null;
protected IFileTransferSession mFileTransferSession = null;
protected IFileTransferEventListener mFileTransferListener = null;
protected Participant mParticipant = null;
public SentFileTransfer(Object chatTag, IOne2OneChatWindow one2OneChat,
String filePath, Participant participant, Object fileTransferTag) {
Logger.d(TAG, "SentFileTransfer() constructor chatTag is "
+ chatTag + " one2OneChat is " + one2OneChat
+ " filePath is " + filePath + "fileTransferTag: "
+ fileTransferTag);
if (null != chatTag && null != one2OneChat && null != filePath
&& null != participant) {
mChatTag = chatTag;
mFileTransferTag = (fileTransferTag != null ? fileTransferTag
: UUID.randomUUID());
mFileStruct = new FileStruct(filePath,
extractFileNameFromPath(filePath), 0, mFileTransferTag,
new Date());
mFileTransfer = one2OneChat.addSentFileTransfer(mFileStruct);
mFileTransfer.setStatus(Status.PENDING);
mParticipant = participant;
}
}
protected void send() {
ApiManager instance = ApiManager.getInstance();
if (instance != null) {
MessagingApi messageApi = instance.getMessagingApi();
if (messageApi != null) {
try {
mFileTransferSession =
messageApi.transferFile(mParticipant.getContact(),
mFileStruct.mFilePath);
if (null != mFileTransferSession) {
mFileStruct.mSize = mFileTransferSession.getFilesize();
String sessionId = mFileTransferSession.getSessionID();
mFileTransfer.updateTag(sessionId,
mFileStruct.mSize);
mFileTransferTag = sessionId;
mFileStruct.mFileTransferTag = sessionId;
mFileTransferListener = new FileTransferSenderListener();
mFileTransferSession.addSessionListener(mFileTransferListener);
mFileTransfer.setStatus(Status.WAITING);
setNotification();
} else {
Logger.e(TAG,
"send() failed, mFileTransferSession is null, filePath is "
+ mFileStruct.mFilePath);
onFailed();
onFileTransferFinished(IOnSendFinishListener.Result.REMOVABLE);
}
} catch (ClientApiException e) {
e.printStackTrace();
onFailed();
onFileTransferFinished(IOnSendFinishListener.Result.REMOVABLE);
} catch (RemoteException e) {
e.printStackTrace();
onFailed();
onFileTransferFinished(IOnSendFinishListener.Result.REMOVABLE);
}
}
}
}
private void onPrepareResend() {
Logger.d(TAG, "onPrepareResend() file " + mFileStruct.mFilePath
+ " to " + mParticipant);
if (null != mFileTransfer) {
mFileTransfer.setStatus(Status.PENDING);
}
}
private void onCancel() {
Logger.d(TAG, "onCancel() entry: mFileTransfer = " + mFileTransfer);
if (null != mFileTransfer) {
mFileTransfer.setStatus(Status.CANCEL);
}
}
private void onFailed() {
Logger.d(TAG, "onFailed() entry: mFileTransfer = " + mFileTransfer);
if (null != mFileTransfer) {
mFileTransfer.setStatus(Status.FAILED);
}
}
private void onNotAvailable(int reason) {
Logger.d(TAG, "onNotAvailable() reason is " + reason);
if (One2OneChat.FILETRANSFER_ENABLE_OK == reason) {
return;
} else {
switch (reason) {
case One2OneChat.FILETRANSFER_DISABLE_REASON_REMOTE:
onFailed();
break;
case One2OneChat.FILETRANSFER_DISABLE_REASON_CAPABILITY_FAILED:
case One2OneChat.FILETRANSFER_DISABLE_REASON_NOT_REGISTER:
onCancel();
break;
default:
Logger.w(TAG, "onNotAvailable() unknown reason " + reason);
break;
}
}
}
private void onDestroy() {
Logger.d(TAG, "onDestroy() sent file transfer mFilePath "
+ ((null == mFileStruct) ? null : mFileStruct.mFilePath)
+ " mFileTransferSession = " + mFileTransferSession
+ ", mFileTransferListener = " + mFileTransferListener);
if (null != mFileTransferSession) {
try {
if (null != mFileTransferListener) {
mFileTransferSession
.removeSessionListener(mFileTransferListener);
}
cancelNotification();
mFileTransferSession.cancelSession();
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
protected void onFileTransferFinished(
IOnSendFinishListener.Result result) {
Logger.d(TAG, "onFileTransferFinished() mFileStruct = "
+ mFileStruct + ", file = "
+ ((null == mFileStruct) ? null : mFileStruct.mFilePath)
+ ", mOnSendFinishListener = " + mOnSendFinishListener
+ ", mFileTransferListener = " + mFileTransferListener
+ ", result = " + result);
if (null != mOnSendFinishListener) {
mOnSendFinishListener.onSendFinish(SentFileTransfer.this,
result);
if (null != mFileTransferSession) {
try {
if (null != mFileTransferListener) {
mFileTransferSession
.removeSessionListener(mFileTransferListener);
}
} catch (RemoteException e) {
e.printStackTrace();
}
}
}
}
public static String extractFileNameFromPath(String filePath) {
if (null != filePath) {
int lastDashIndex = filePath.lastIndexOf("/");
if (-1 != lastDashIndex && lastDashIndex < filePath.length() - 1) {
String fileName = filePath.substring(lastDashIndex + 1);
return fileName;
} else {
Logger.e(TAG, "extractFileNameFromPath() invalid file path:" + filePath);
return null;
}
} else {
Logger.e(TAG, "extractFileNameFromPath() filePath is null");
return null;
}
}
/**
* File transfer session event listener
*/
private class FileTransferSenderListener extends IFileTransferEventListener.Stub {
private static final String TAG = "FileTransferSenderListener";
// Session is started
@Override
public void handleSessionStarted() {
Logger.d(TAG, "handleSessionStarted() this file is " + mFileStruct.mFilePath);
}
// Session has been aborted
@Override
public void handleSessionAborted() {
Logger.v(TAG,
"File transfer handleSessionAborted(): mFileTransfer = "
+ mFileTransfer);
if (mParticipant == null) {
Logger.d(TAG,
"FileTransferSenderListener handleSessionAborted mParticipant is null");
return;
}
if (mFileTransfer != null) {
mFileTransfer.setStatus(Status.CANCEL);
IChat chat = ModelImpl.getInstance().getChat(mChatTag);
Logger.v(TAG, "handleSessionAborted(): chat = " + chat);
if (chat instanceof ChatImpl) {
((ChatImpl) chat).checkCapabilities();
}
}
try {
mFileTransferSession.removeSessionListener(this);
} catch (RemoteException e) {
e.printStackTrace();
}
mFileTransferSession = null;
onFileTransferFinished(IOnSendFinishListener.Result.REMOVABLE);
}
// Session has been terminated by remote
@Override
public void handleSessionTerminatedByRemote() {
Logger.v(TAG,
"File transfer handleSessionTerminatedByRemote(): mFileTransfer = "
+ mFileTransfer);
if (mFileTransfer != null) {
mFileTransfer.setStatus(Status.CANCELED);
IChat chat = ModelImpl.getInstance().getChat(mChatTag);
Log.v(TAG, "chat = " + chat);
if (chat instanceof ChatImpl) {
((ChatImpl) chat).checkCapabilities();
}
}
mFileTransferSession = null;
onFileTransferFinished(IOnSendFinishListener.Result.REMOVABLE);
}
// File transfer progress
@Override
public void handleTransferProgress(final long currentSize, final long totalSize) {
// Because of can't received file transfered callback, so add
// current size equals total size change status to finished
Logger.d(TAG, "handleTransferProgress() the file "
+ mFileStruct.mFilePath + " with " + mParticipant
+ " is transferring, currentSize is " + currentSize
+ " total size is " + totalSize + ", mFileTransfer = "
+ mFileTransfer);
if (mFileTransfer != null) {
if (currentSize < totalSize) {
mFileTransfer
.setStatus(com.mediatek.rcse.interfaces.ChatView.IFileTransfer.Status.TRANSFERING);
mFileTransfer.setProgress(currentSize);
updateNotification(currentSize);
} else {
mFileTransfer
.setStatus(com.mediatek.rcse.interfaces.ChatView.IFileTransfer.Status.FINISHED);
onFileTransferFinished(IOnSendFinishListener.Result.REMOVABLE);
}
}
}
// File transfer error
@Override
public void handleTransferError(final int error) {
Logger.v(TAG, "handleTransferError(),error = " + error + ", mFileTransfer ="
+ mFileTransfer);
switch (error) {
case FileSharingError.SESSION_INITIATION_FAILED:
Logger.d(TAG,
"handleTransferError(), the file transfer invitation is failed.");
if (mFileTransfer != null) {
mFileTransfer.setStatus(ChatView.IFileTransfer.Status.FAILED);
}
onFileTransferFinished(IOnSendFinishListener.Result.REMOVABLE);
break;
case FileSharingError.SESSION_INITIATION_TIMEOUT:
Logger.d(TAG,
"handleTransferError(), the file transfer invitation is failed.");
if (mFileTransfer != null) {
mFileTransfer.setStatus(ChatView.IFileTransfer.Status.TIMEOUT);
}
onFileTransferFinished(IOnSendFinishListener.Result.REMOVABLE);
break;
case FileSharingError.SESSION_INITIATION_DECLINED:
Logger.d(TAG,
"handleTransferError(), your file transfer invitation has been rejected");
if (mFileTransfer != null) {
mFileTransfer.setStatus(ChatView.IFileTransfer.Status.REJECTED);
}
onFileTransferFinished(IOnSendFinishListener.Result.RESENDABLE);
break;
case FileSharingError.SESSION_INITIATION_CANCELLED:
Logger.d(TAG,
"handleTransferError(), your file transfer invitation has been rejected");
if (mFileTransfer != null) {
mFileTransfer.setStatus(ChatView.IFileTransfer.Status.TIMEOUT);
}
onFileTransferFinished(IOnSendFinishListener.Result.REMOVABLE);
break;
default:
Logger.e(TAG, "handleTransferError() unknown error " + error);
onFailed();
onFileTransferFinished(IOnSendFinishListener.Result.REMOVABLE);
break;
}
}
// File has been transfered
@Override
public void handleFileTransfered(final String fileName) {
Logger.d(TAG, "handleFileTransfered() entry, fileName is "
+ fileName + ", mFileTransfer = " + mFileTransfer);
if (mFileTransfer != null) {
mFileTransfer
.setStatus(com.mediatek.rcse.interfaces.ChatView.IFileTransfer.Status.FINISHED);
}
onFileTransferFinished(IOnSendFinishListener.Result.REMOVABLE);
}
}
private NotificationManager getNotificationManager() {
ApiManager apiManager = ApiManager.getInstance();
if (null != apiManager) {
Context context = apiManager.getContext();
if (null != context) {
Object systemService = context.getSystemService(Context.NOTIFICATION_SERVICE);
return (NotificationManager) systemService;
} else {
Logger.e(TAG, "getNotificationManager() context is null");
return null;
}
} else {
Logger.e(TAG, "getNotificationManager() apiManager is null");
return null;
}
}
private int getNotificationId() {
if (null != mFileTransferTag) {
return mFileTransferTag.hashCode();
} else {
Logger.w(TAG, "getNotificationId() mFileTransferTag: " + mFileTransferTag);
return 0;
}
}
private void setNotification() {
updateNotification(0);
}
private void updateNotification(long currentSize) {
Logger.d(TAG, "updateNotification() entry, currentSize is "
+ currentSize + ", mFileTransferTag is " + mFileTransferTag
+ ", mFileStruct = " + mFileStruct);
NotificationManager notificationManager = getNotificationManager();
if (null != notificationManager) {
if (null != mFileStruct) {
Context context = ApiManager.getInstance().getContext();
Notification.Builder builder = new Notification.Builder(context);
builder
.setProgress((int) mFileStruct.mSize, (int) currentSize,
currentSize < 0);
String title =
context.getResources().getString(
R.string.ft_progress_bar_title,
ContactsListManager.getInstance().getDisplayNameByPhoneNumber(
mParticipant
.getContact()));
builder.setContentTitle(title);
builder.setAutoCancel(false);
builder.setContentText(extractFileNameFromPath(mFileStruct.mFilePath));
builder.setContentInfo(buildPercentageLabel(context, mFileStruct.mSize,
currentSize));
builder.setSmallIcon(R.drawable.rcs_notify_file_transfer);
PendingIntent pendingIntent;
if (Logger.getIsIntegrationMode()) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SENDTO);
Uri uri = Uri.parse(PluginProxyActivity.MMSTO + mParticipant.getContact());
intent.setData(uri);
pendingIntent =
PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
} else {
Intent intent = new Intent(context, ChatScreenActivity.class);
intent.putExtra(ChatScreenActivity.KEY_CHAT_TAG, (ParcelUuid) mChatTag);
pendingIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
}
builder.setContentIntent(pendingIntent);
notificationManager.notify(getNotificationId(), builder.getNotification());
}
}
}
private void cancelNotification() {
NotificationManager notificationManager = getNotificationManager();
Logger.d(TAG, "cancelNotification() entry, mFileTransferTag is "
+ mFileTransferTag + ",notificationManager = "
+ notificationManager);
if (null != notificationManager) {
notificationManager.cancel(getNotificationId());
}
}
private static String buildPercentageLabel(Context context, long totalBytes,
long currentBytes) {
if (totalBytes <= 0) {
return null;
} else {
final int percent = (int) (100 * currentBytes / totalBytes);
return context.getString(R.string.ft_percent, percent);
}
}
protected IOnSendFinishListener mOnSendFinishListener = null;
protected interface IOnSendFinishListener {
static enum Result {
REMOVABLE, // This kind of result indicates that this File
// transfer should be removed from the manager
RESENDABLE
// This kind of result indicates that this File transfer will
// have a chance to be resent in the future
};
void onSendFinish(SentFileTransfer sentFileTransfer, Result result);
}
}
private SentFileTransferManager mOutGoingFileTransferManager = new SentFileTransferManager();
/**
* This class is used to manage the whole sent file transfers and make it
* work in queue
*/
private static class SentFileTransferManager implements SentFileTransfer.IOnSendFinishListener {
private static final String TAG = "SentFileTransferManager";
private static final int MAX_ACTIVATED_SENT_FILE_TRANSFER_NUM = 1;
private ConcurrentLinkedQueue<SentFileTransfer> mPendingList =
new ConcurrentLinkedQueue<SentFileTransfer>();
private CopyOnWriteArrayList<SentFileTransfer> mActiveList =
new CopyOnWriteArrayList<SentFileTransfer>();
private CopyOnWriteArrayList<SentFileTransfer> mResendableList =
new CopyOnWriteArrayList<SentFileTransfer>();
private synchronized void checkNext() {
int activatedNum = mActiveList.size();
if (activatedNum < MAX_ACTIVATED_SENT_FILE_TRANSFER_NUM) {
Logger.d(TAG, "checkNext() current activatedNum is " + activatedNum
+ " will find next file transfer to send");
SentFileTransfer nextFileTransfer = mPendingList.poll();
if (null != nextFileTransfer) {
Logger.d(TAG, "checkNext() next file transfer found, just send it!");
nextFileTransfer.send();
mActiveList.add(nextFileTransfer);
} else {
Logger.d(TAG, "checkNext() next file transfer not found, pending list is null");
}
} else {
Logger.d(TAG, "checkNext() current activatedNum is " + activatedNum
+ " MAX_ACTIVATED_SENT_FILE_TRANSFER_NUM is "
+ MAX_ACTIVATED_SENT_FILE_TRANSFER_NUM
+ " so no need to find next pending file transfer");
}
}
public void onAddSentFileTransfer(SentFileTransfer sentFileTransfer) {
Logger.d(TAG, "onAddSentFileTransfer() entry, sentFileTransfer = "
+ sentFileTransfer);
if (null != sentFileTransfer) {
Logger.d(TAG, "onAddSentFileTransfer() entry, file "
+ sentFileTransfer.mFileStruct + " is going to be sent");
sentFileTransfer.mOnSendFinishListener = this;
mPendingList.add(sentFileTransfer);
checkNext();
}
}
public void onChatDestroy(Object tag) {
Logger.d(TAG, "onChatDestroy entry, tag is " + tag);
clearTransferWithTag(tag, One2OneChat.FILETRANSFER_ENABLE_OK);
}
public void clearTransferWithTag(Object tag, int reason) {
Logger.d(TAG, "onFileTransferNotAvalible() entry tag is " + tag + " reason is "
+ reason);
if (null != tag) {
Logger.d(TAG, "onFileTransferNotAvalible() tag is " + tag);
ArrayList<SentFileTransfer> toBeDeleted = new ArrayList<SentFileTransfer>();
for (SentFileTransfer fileTransfer : mActiveList) {
if (tag.equals(fileTransfer.mChatTag)) {
Logger.d(TAG,
"onFileTransferNotAvalible() sent file transfer with chatTag "
+ tag + " found in activated list");
fileTransfer.onNotAvailable(reason);
fileTransfer.onDestroy();
toBeDeleted.add(fileTransfer);
}
}
if (toBeDeleted.size() > 0) {
Logger
.d(TAG,
"onFileTransferNotAvalible() need to remove some file transfer from activated list");
mActiveList.removeAll(toBeDeleted);
toBeDeleted.clear();
}
for (SentFileTransfer fileTransfer : mPendingList) {
if (tag.equals(fileTransfer.mChatTag)) {
Logger.d(TAG,
"onFileTransferNotAvalible() sent file transfer with chatTag "
+ tag + " found in pending list");
fileTransfer.onNotAvailable(reason);
toBeDeleted.add(fileTransfer);
}
}
if (toBeDeleted.size() > 0) {
Logger
.d(TAG,
"onFileTransferNotAvalible() need to remove some file transfer from pending list");
mPendingList.removeAll(toBeDeleted);
toBeDeleted.clear();
}
for (SentFileTransfer fileTransfer : mResendableList) {
if (tag.equals(fileTransfer.mChatTag)) {
Logger.d(TAG,
"onFileTransferNotAvalible() sent file transfer with chatTag "
+ tag + " found in mResendableList list");
fileTransfer.onNotAvailable(reason);
toBeDeleted.add(fileTransfer);
}
}
if (toBeDeleted.size() > 0) {
Logger.d(TAG, "onFileTransferNotAvalible() " +
"need to remove some file transfer from mResendableList list");
mResendableList.removeAll(toBeDeleted);
toBeDeleted.clear();
}
}
}
public void resendFileTransfer(Object targetFileTransferTag) {
SentFileTransfer fileTransfer = findResendableFileTransfer(targetFileTransferTag);
Logger.d(TAG, "resendFileTransfer() the file transfer with tag "
+ targetFileTransferTag + " is " + fileTransfer);
if (null != fileTransfer) {
fileTransfer.onPrepareResend();
Logger.d(TAG, "resendFileTransfer() the file transfer with tag "
+ targetFileTransferTag
+ " found, remove it from resendable list and add it into pending list");
mResendableList.remove(fileTransfer);
mPendingList.add(fileTransfer);
checkNext();
}
}
public void cancelFileTransfer(Object targetFileTransferTag) {
Logger.d(TAG, "cancelFileTransfer() begin to cancel file transfer with tag "
+ targetFileTransferTag);
SentFileTransfer fileTransfer = findPendingFileTransfer(targetFileTransferTag);
if (null != fileTransfer) {
Logger.d(TAG, "cancelFileTransfer() the target file transfer with tag "
+ targetFileTransferTag + " found in pending list");
fileTransfer.onCancel();
mPendingList.remove(fileTransfer);
} else {
fileTransfer = findActiveFileTransfer(targetFileTransferTag);
Logger.d(TAG,
"cancelFileTransfer() the target file transfer with tag "
+ targetFileTransferTag
+ " found in active list is " + fileTransfer);
if (null != fileTransfer) {
Logger.d(TAG,
"cancelFileTransfer() the target file transfer with tag "
+ targetFileTransferTag
+ " found in active list");
fileTransfer.onCancel();
fileTransfer.onDestroy();
onSendFinish(fileTransfer, Result.REMOVABLE);
}
}
}
@Override
public void onSendFinish(final SentFileTransfer sentFileTransfer, final Result result) {
Logger.d(TAG, "onSendFinish(): sentFileTransfer = "
+ sentFileTransfer + ", result = " + result);
if (mActiveList.contains(sentFileTransfer)) {
sentFileTransfer.cancelNotification();
Logger.d(TAG, "onSendFinish() file transfer " + sentFileTransfer.mFileStruct
+ " with " + sentFileTransfer.mParticipant + " finished with " + result
+ " remove it from activated list");
switch (result) {
case RESENDABLE:
mResendableList.add(sentFileTransfer);
mActiveList.remove(sentFileTransfer);
break;
case REMOVABLE:
mActiveList.remove(sentFileTransfer);
break;
default:
break;
}
checkNext();
}
}
private SentFileTransfer findActiveFileTransfer(Object targetTag) {
Logger.d(TAG, "findActiveFileTransfer entry, targetTag is " + targetTag);
return findFileTransferByTag(mActiveList, targetTag);
}
private SentFileTransfer findPendingFileTransfer(Object targetTag) {
Logger.d(TAG, "findPendingFileTransfer entry, targetTag is " + targetTag);
return findFileTransferByTag(mPendingList, targetTag);
}
private SentFileTransfer findResendableFileTransfer(Object targetTag) {
Logger.d(TAG, "findResendableFileTransfer entry, targetTag is " + targetTag);
return findFileTransferByTag(mResendableList, targetTag);
}
private SentFileTransfer findFileTransferByTag(Collection<SentFileTransfer> whereToFind,
Object targetTag) {
if (null != whereToFind && null != targetTag) {
for (SentFileTransfer sentFileTransfer : whereToFind) {
Object fileTransferTag = sentFileTransfer.mFileTransferTag;
if (targetTag.equals(fileTransferTag)) {
Logger.d(TAG, "findFileTransferByTag() the file transfer with targetTag "
+ targetTag + " found");
return sentFileTransfer;
}
}
Logger.d(TAG, "findFileTransferByTag() not found targetTag " + targetTag);
return null;
} else {
Logger.e(TAG, "findFileTransferByTag() whereToFind is " + whereToFind
+ " targetTag is " + targetTag);
return null;
}
}
}
@Override
public void reloadMessages(String tag, List<Integer> messageIds) {
Logger.d(TAG, "reloadMessages() messageIds: " + messageIds + " tag is " + tag);
ContentResolver contentResolver = AndroidFactory.getApplicationContext()
.getContentResolver();
if (tag != null) {
reloadGroupMessage(tag, messageIds, contentResolver);
} else {
reloadOne2OneMessages(messageIds, contentResolver);
}
}
private void reloadGroupMessage(String tag, List<Integer> messageIds,
ContentResolver contentResolver) {
Logger.d(TAG, "reloadGroupMessage() entry");
int length = PluginGroupChatWindow.GROUP_CONTACT_STRING_BEGINNER.length();
String realTag = tag.substring(length);
ParcelUuid parcelUuid = ParcelUuid.fromString(realTag);
HashSet<Participant> participantList = new HashSet<Participant>();
ArrayList<ReloadMessageInfo> messageList = new ArrayList<ReloadMessageInfo>();
TreeSet<Long> sessionIdList = new TreeSet<Long>();
for (Integer messageId : messageIds) {
ReloadMessageInfo messageInfo =
loadMessageFromId(sessionIdList, messageId, contentResolver);
if (null != messageInfo) {
Object obj = messageInfo.getMessage();
messageList.add(messageInfo);
if (obj instanceof InstantMessage) {
InstantMessage message = (InstantMessage) obj;
String contact = message.getRemote();
contact = PhoneUtils.extractNumberFromUri(contact);
if (!ContactsManager.getInstance().isRcsValidNumber(contact)) {
Logger.d(TAG, "reloadGroupMessage() the contact is not valid user "
+ contact);
continue;
}
Logger.d(TAG, "reloadGroupMessage() the contact is " + contact);
if (!TextUtils.isEmpty(contact)) {
Participant participant = new Participant(contact, contact);
participantList.add(participant);
}
}
}
}
Logger.d(TAG, "reloadGroupMessage() the sessionIdList is " + sessionIdList);
fillParticipantList(sessionIdList, participantList, contentResolver);
Logger.d(TAG, "reloadGroupMessage() participantList is " + participantList);
if (participantList.size() < ChatFragment.GROUP_MIN_MEMBER_NUM) {
Logger.d(TAG, "reloadGroupMessage() not group");
return;
}
IChat chat = mChatMap.get(parcelUuid);
if (chat != null) {
Logger.d(TAG, "reloadGroupMessage() the chat already exist chat is " + chat);
} else {
chat = new GroupChat(this, null, new ArrayList<Participant>(participantList), parcelUuid);
mChatMap.put(parcelUuid, chat);
IGroupChatWindow chatWindow = ViewImpl.getInstance().addGroupChatWindow(parcelUuid,
((GroupChat) chat).getParticipantInfos());
((GroupChat) chat).setChatWindow(chatWindow);
}
for (ReloadMessageInfo messageInfo : messageList) {
if (null != messageInfo) {
InstantMessage message = (InstantMessage) messageInfo.getMessage();
int messageType = messageInfo.getMessageType();
((ChatImpl) chat).reloadMessage(message, messageType, -1);
}
}
}
private void fillParticipantList(TreeSet<Long> sessionIdList,
HashSet<Participant> participantList, ContentResolver contentResolver) {
Logger.d(TAG, "fillParticipantList() entry the sessionIdList is " + sessionIdList
+ " participantList is " + participantList);
for (Long sessionId : sessionIdList) {
Cursor cursor = null;
String[] selectionArg = {
Long.toString(sessionId),
Integer.toString(EventsLogApi.TYPE_GROUP_CHAT_SYSTEM_MESSAGE)
};
try {
cursor = contentResolver.query(RichMessagingData.CONTENT_URI, null,
RichMessagingData.KEY_CHAT_SESSION_ID + "=? AND "
+ RichMessagingData.KEY_TYPE + "=?", selectionArg, null);
if (cursor != null && cursor.moveToFirst()) {
do {
String remote = cursor.getString(cursor
.getColumnIndex(RichMessagingData.KEY_CONTACT));
Logger.d(TAG, "fillParticipantList() the remote is " + remote);
if (remote.length() - INDEXT_ONE <= INDEXT_ONE) {
Logger.e(TAG, "fillParticipantList() the remote is no content");
continue;
}
if (remote.contains(COMMA)) {
Logger.d(TAG, "fillParticipantList() the remote has COMMA ");
String subString = remote.substring(INDEXT_ONE, remote.length()
- INDEXT_ONE);
Logger.d(TAG, "fillParticipantList() the remote is " + subString);
String[] contacts = subString.split(COMMA);
for (String contact : contacts) {
Logger.d(TAG, "fillParticipantList() arraylist the contact is "
+ contact);
Participant participant = new Participant(contact, contact);
participantList.add(participant);
}
} else if (remote.contains(SEMICOLON)) {
Logger.d(TAG, "fillParticipantList() the remote has SEMICOLON ");
String[] contacts = remote.split(SEMICOLON);
for (String contact : contacts) {
Logger.d(TAG, "fillParticipantList() arraylist the contact is "
+ contact);
Participant participant = new Participant(contact, contact);
participantList.add(participant);
}
} else {
Logger.d(TAG, "fillParticipantList() remote is single ");
Participant participant = new Participant(remote, remote);
participantList.add(participant);
}
} while (cursor.moveToNext());
} else {
Logger.e(TAG, "fillParticipantList() the cursor is null");
}
} finally {
if (null != cursor) {
cursor.close();
}
}
}
}
private void reloadOne2OneMessages(List<Integer> messageIds, ContentResolver contentResolver) {
Logger.d(TAG, "reloadOne2OneMessages() entry");
TreeSet<Long> sessionIdList = new TreeSet<Long>();
for (Integer messageId : messageIds) {
ReloadMessageInfo info = loadMessageFromId(sessionIdList, messageId, contentResolver);
if (null != info) {
Object obj = info.getMessage();
int messageType = info.getMessageType();
if (obj instanceof InstantMessage) {
InstantMessage message = (InstantMessage) obj;
int messageStatus = info.getMessageStatus();
String contact = message.getRemote();
contact = PhoneUtils.extractNumberFromUri(contact);
Logger.v(TAG, "reloadOne2OneMessages() : contact = " + contact);
if (!TextUtils.isEmpty(contact)) {
ArrayList<Participant> participantList = new ArrayList<Participant>();
participantList.add(new Participant(contact, contact));
IChat chat = addChat(participantList);
((ChatImpl) chat).reloadMessage(message, messageType, messageStatus);
}
} else if (obj instanceof FileStruct) {
FileStruct fileStruct = (FileStruct) obj;
String contact = fileStruct.mRemote;
Logger.v(TAG, "reloadOne2OneMessages() : contact = " + contact);
if (!TextUtils.isEmpty(contact)) {
ArrayList<Participant> participantList = new ArrayList<Participant>();
participantList.add(new Participant(contact, contact));
IChat chat = addChat(participantList);
((ChatImpl) chat).reloadFileTransfer(fileStruct, messageType, info.getMessageStatus());
}
}
}
}
}
private ReloadMessageInfo loadMessageFromId(TreeSet<Long> sessionIdList, Integer msgId,
ContentResolver contentResolver) {
Logger.d(TAG, "loadMessageFronId() msgId: " + msgId);
Cursor cursor = null;
String[] selectionArg = {msgId.toString()};
try {
cursor = contentResolver.query(RichMessagingData.CONTENT_URI,
null, RichMessagingData.KEY_ID + "=?", selectionArg, null);
if (cursor.moveToFirst()) {
int messageType = cursor.getInt(cursor.getColumnIndex(RichMessagingData.KEY_TYPE));
String messageId = cursor.getString(cursor
.getColumnIndex(RichMessagingData.KEY_MESSAGE_ID));
String remote = cursor.getString(cursor
.getColumnIndex(RichMessagingData.KEY_CONTACT));
String text = cursor.getString(cursor.getColumnIndex(RichMessagingData.KEY_DATA));
long sessionId =
cursor
.getLong(cursor
.getColumnIndex(RichMessagingData.KEY_CHAT_SESSION_ID));
int messageStatus =
cursor.getInt(cursor.getColumnIndex(RichMessagingData.KEY_STATUS));
sessionIdList.add(sessionId);
Date date = new Date();
long timeStamp = cursor.getLong(cursor
.getColumnIndex(RichMessagingData.KEY_TIMESTAMP));
date.setTime(timeStamp);
if (EventsLogApi.TYPE_INCOMING_CHAT_MESSAGE == messageType
|| EventsLogApi.TYPE_OUTGOING_CHAT_MESSAGE == messageType
|| EventsLogApi.TYPE_INCOMING_GROUP_CHAT_MESSAGE == messageType
|| EventsLogApi.TYPE_OUTGOING_GROUP_CHAT_MESSAGE == messageType) {
InstantMessage message = new InstantMessage(messageId, remote, text, false);
message.setDate(date);
Logger.d(TAG, "loadMessageFronId() messageId: " + messageId + " , remote: "
+ remote + " , text: " + text + " , timeStamp: " + timeStamp
+ " , messageType: " + messageType + " , messageStatus: "
+ messageStatus);
ReloadMessageInfo messageInfo =
new ReloadMessageInfo(message, messageType, messageStatus);
return messageInfo;
} else if (EventsLogApi.TYPE_INCOMING_FILE_TRANSFER == messageType
|| EventsLogApi.TYPE_OUTGOING_FILE_TRANSFER == messageType) {
String fileName = cursor.getString(cursor
.getColumnIndex(RichMessagingData.KEY_NAME));
long fileSize = cursor.getLong(cursor
.getColumnIndex(RichMessagingData.KEY_TOTAL_SIZE));
FileStruct fileStruct = new FileStruct(text, fileName, fileSize, messageId,
date, remote);
ReloadMessageInfo fileInfo = new ReloadMessageInfo(fileStruct, messageType, messageStatus);
return fileInfo;
}
return null;
} else {
Logger.w(TAG, "loadMessageFronId() empty cursor");
return null;
}
} finally {
if (null != cursor) {
cursor.close();
}
}
}
@Override
public void closeAllChat() {
Logger.d(TAG, "closeAllChat()");
Collection<IChat> chatSet = mChatMap.values();
List<Object> tagList = new ArrayList<Object>();
for (IChat iChat : chatSet) {
tagList.add(((ChatImpl) iChat).getChatTag());
}
for (Object object : tagList) {
removeChat(object);
}
}
/**
* Get group chat with chat id.
*
* @param chatId The chat id.
* @return The group chat.
*/
public IChat getGroupChat(String chatId) {
Logger.d(TAG, "getGroupChat() entry, chatId: " + chatId);
Collection<IChat> chats = mChatMap.values();
IChat result = null;
for (IChat chat : chats) {
if (chat instanceof GroupChat) {
String id = ((GroupChat) chat).getChatId();
if (id != null && id.equals(chatId)) {
result = chat;
break;
}
}
}
Logger.d(TAG, "getGroupChat() exit, result: " + result);
return result;
}
/**
* Used to reload message information
*/
private static class ReloadMessageInfo {
private Object mMessage;
private int mMessageType;
private int mMessageStatus;
/**
* Constructor
*
* @param message The message
* @param type The message type
* @param status The message status
*/
public ReloadMessageInfo(Object message, int type, int status) {
this.mMessage = message;
this.mMessageType = type;
this.mMessageStatus = status;
}
/**
* Constructor
*
* @param message The message
* @param type The message type
*/
public ReloadMessageInfo(Object message, int type) {
this.mMessage = message;
this.mMessageType = type;
}
/**
* Get the message
*
* @return The message
*/
public Object getMessage() {
return mMessage;
}
/**
* Get the message type
*
* @return The message type
*/
public int getMessageType() {
return mMessageType;
}
/**
* Get the message status
*
* @return The message status
*/
public int getMessageStatus() {
return mMessageStatus;
}
}
}
| gpl-2.0 |
NoNiMad/VoiceFighter | core/src/fr/nonimad/ld32/ScreenGameOver.java | 1751 | package fr.nonimad.ld32;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.ScreenAdapter;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.g2d.GlyphLayout;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Label;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.kotcrab.vis.ui.VisUI;
public class ScreenGameOver extends ScreenAdapter {
private Stage stage = new Stage();
@Override
public void show() {
Gdx.input.setInputProcessor(stage);
TextButton btn_return = new TextButton("Return to Menu", VisUI.getSkin());
btn_return.setPosition(362, 350);
btn_return.setSize(300, 40);
btn_return.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
((LudumDare32)Gdx.app.getApplicationListener()).setScreen(new ScreenMainMenu());
}
});
stage.addActor(btn_return);
Label title = new Label("Game Over", new Label.LabelStyle(Assets.f_mainTitle, Color.WHITE));
title.setPosition(512 - new GlyphLayout(Assets.f_mainTitle, "Game Over").width / 2, 550);
stage.addActor(title);
}
@Override
public void render(float delta) {
Gdx.gl.glClearColor(1, 1, 1, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
stage.act();
stage.draw();
}
@Override
public void hide() {
dispose();
}
@Override
public void dispose() {
stage.dispose();
}
}
| gpl-2.0 |
brunotl/LK8000 | android/src/org/LK8000/BatteryReceiver.java | 1524 | /* Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2016 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
package org.LK8000;
import android.content.Context;
import android.content.Intent;
import android.content.BroadcastReceiver;
import android.os.BatteryManager;
class BatteryReceiver extends BroadcastReceiver {
private static native void setBatteryPercent(int level, int plugged, int status);
@Override public void onReceive(Context context, Intent intent) {
int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, 0);
setBatteryPercent(level, plugged, status);
}
}
| gpl-2.0 |
BIORIMP/biorimp | BIO-RIMP/test_data/code/cio/src/test/java/org/apache/commons/io/DirectoryWalkerTestCase.java | 21473 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.io;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import junit.framework.Assert;
import junit.framework.TestCase;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.NameFileFilter;
import org.apache.commons.io.filefilter.OrFileFilter;
/**
* This is used to test DirectoryWalker for correctness.
*
* @version $Id: DirectoryWalkerTestCase.java 1302748 2012-03-20 01:35:32Z ggregory $
* @see DirectoryWalker
*
*/
public class DirectoryWalkerTestCase extends TestCase {
// Directories
private static final File current = new File(".");
private static final File javaDir = new File("src/main/java");
private static final File orgDir = new File(javaDir, "org");
private static final File apacheDir = new File(orgDir, "apache");
private static final File commonsDir = new File(apacheDir, "commons");
private static final File ioDir = new File(commonsDir, "io");
private static final File outputDir = new File(ioDir, "output");
private static final File[] dirs = new File[] {orgDir, apacheDir, commonsDir, ioDir, outputDir};
// Files
private static final File filenameUtils = new File(ioDir, "FilenameUtils.java");
private static final File ioUtils = new File(ioDir, "IOUtils.java");
private static final File proxyWriter = new File(outputDir, "ProxyWriter.java");
private static final File nullStream = new File(outputDir, "NullOutputStream.java");
private static final File[] ioFiles = new File[] {filenameUtils, ioUtils};
private static final File[] outputFiles = new File[] {proxyWriter, nullStream};
// Filters
private static final IOFileFilter dirsFilter = createNameFilter(dirs);
private static final IOFileFilter iofilesFilter = createNameFilter(ioFiles);
private static final IOFileFilter outputFilesFilter = createNameFilter(outputFiles);
private static final IOFileFilter ioDirAndFilesFilter = new OrFileFilter(dirsFilter, iofilesFilter);
private static final IOFileFilter dirsAndFilesFilter = new OrFileFilter(ioDirAndFilesFilter, outputFilesFilter);
// Filter to exclude SVN files
private static final IOFileFilter NOT_SVN = FileFilterUtils.makeSVNAware(null);
/** Construct the TestCase using the name */
public DirectoryWalkerTestCase(String name) {
super(name);
}
/** Set Up */
@Override
protected void setUp() throws Exception {
super.setUp();
}
/** Tear Down */
@Override
protected void tearDown() throws Exception {
super.tearDown();
}
//-----------------------------------------------------------------------
/**
* Test Filtering
*/
public void testFilter() {
List<File> results = new TestFileFinder(dirsAndFilesFilter, -1).find(javaDir);
assertEquals("Result Size", 1 + dirs.length + ioFiles.length + outputFiles.length, results.size());
assertTrue("Start Dir", results.contains(javaDir));
checkContainsFiles("Dir", dirs, results);
checkContainsFiles("IO File", ioFiles, results);
checkContainsFiles("Output File", outputFiles, results);
}
/**
* Test Filtering and limit to depth 0
*/
public void testFilterAndLimitA() {
List<File> results = new TestFileFinder(NOT_SVN, 0).find(javaDir);
assertEquals("[A] Result Size", 1, results.size());
assertTrue("[A] Start Dir", results.contains(javaDir));
}
/**
* Test Filtering and limit to depth 1
*/
public void testFilterAndLimitB() {
List<File> results = new TestFileFinder(NOT_SVN, 1).find(javaDir);
assertEquals("[B] Result Size", 2, results.size());
assertTrue("[B] Start Dir", results.contains(javaDir));
assertTrue("[B] Org Dir", results.contains(orgDir));
}
/**
* Test Filtering and limit to depth 3
*/
public void testFilterAndLimitC() {
List<File> results = new TestFileFinder(NOT_SVN, 3).find(javaDir);
assertEquals("[C] Result Size", 4, results.size());
assertTrue("[C] Start Dir", results.contains(javaDir));
assertTrue("[C] Org Dir", results.contains(orgDir));
assertTrue("[C] Apache Dir", results.contains(apacheDir));
assertTrue("[C] Commons Dir", results.contains(commonsDir));
}
/**
* Test Filtering and limit to depth 5
*/
public void testFilterAndLimitD() {
List<File> results = new TestFileFinder(dirsAndFilesFilter, 5).find(javaDir);
assertEquals("[D] Result Size", 1 + dirs.length + ioFiles.length, results.size());
assertTrue("[D] Start Dir", results.contains(javaDir));
checkContainsFiles("[D] Dir", dirs, results);
checkContainsFiles("[D] File", ioFiles, results);
}
/**
* Test separate dir and file filters
*/
public void testFilterDirAndFile1() {
List<File> results = new TestFileFinder(dirsFilter, iofilesFilter, -1).find(javaDir);
assertEquals("[DirAndFile1] Result Size", 1 + dirs.length + ioFiles.length, results.size());
assertTrue("[DirAndFile1] Start Dir", results.contains(javaDir));
checkContainsFiles("[DirAndFile1] Dir", dirs, results);
checkContainsFiles("[DirAndFile1] File", ioFiles, results);
}
/**
* Test separate dir and file filters
*/
public void testFilterDirAndFile2() {
List<File> results = new TestFileFinder((IOFileFilter) null, (IOFileFilter) null, -1).find(javaDir);
assertTrue("[DirAndFile2] Result Size", results.size() > 1 + dirs.length + ioFiles.length);
assertTrue("[DirAndFile2] Start Dir", results.contains(javaDir));
checkContainsFiles("[DirAndFile2] Dir", dirs, results);
checkContainsFiles("[DirAndFile2] File", ioFiles, results);
}
/**
* Test separate dir and file filters
*/
public void testFilterDirAndFile3() {
List<File> results = new TestFileFinder(dirsFilter, (IOFileFilter) null, -1).find(javaDir);
List<File> resultDirs = directoriesOnly(results);
assertEquals("[DirAndFile3] Result Size", 1 + dirs.length, resultDirs.size());
assertTrue("[DirAndFile3] Start Dir", results.contains(javaDir));
checkContainsFiles("[DirAndFile3] Dir", dirs, resultDirs);
}
/**
* Test separate dir and file filters
*/
public void testFilterDirAndFile4() {
List<File> results = new TestFileFinder((IOFileFilter) null, iofilesFilter, -1).find(javaDir);
List<File> resultFiles = filesOnly(results);
assertEquals("[DirAndFile4] Result Size", ioFiles.length, resultFiles.size());
assertTrue("[DirAndFile4] Start Dir", results.contains(javaDir));
checkContainsFiles("[DirAndFile4] File", ioFiles, resultFiles);
}
/**
* Test Limiting to current directory
*/
public void testLimitToCurrent() {
List<File> results = new TestFileFinder(null, 0).find(current);
assertEquals("Result Size", 1, results.size());
assertTrue("Current Dir", results.contains(new File(".")));
}
/**
* test an invalid start directory
*/
public void testMissingStartDirectory() {
// TODO is this what we want with invalid directory?
File invalidDir = new File("invalid-dir");
List<File> results = new TestFileFinder(null, -1).find(invalidDir);
assertEquals("Result Size", 1, results.size());
assertTrue("Current Dir", results.contains(invalidDir));
try {
new TestFileFinder(null, -1).find(null);
fail("Null start directory didn't throw Exception");
} catch (NullPointerException ignore) {
// expected result
}
}
/**
* test an invalid start directory
*/
public void testHandleStartDirectoryFalse() {
List<File> results = new TestFalseFileFinder(null, -1).find(current);
assertEquals("Result Size", 0, results.size());
}
// ------------ Convenience Test Methods ------------------------------------
/**
* Check the files in the array are in the results list.
*/
private void checkContainsFiles(String prefix, File[] files, Collection<File> results) {
for (int i = 0; i < files.length; i++) {
assertTrue(prefix + "["+i+"] " + files[i], results.contains(files[i]));
}
}
private void checkContainsString(String prefix, File[] files, Collection<String> results) {
for (int i = 0; i < files.length; i++) {
assertTrue(prefix + "["+i+"] " + files[i], results.contains(files[i].toString()));
}
}
/**
* Extract the directories.
*/
private List<File> directoriesOnly(Collection<File> results) {
List<File> list = new ArrayList<File>(results.size());
for (File file : results) {
if (file.isDirectory()) {
list.add(file);
}
}
return list;
}
/**
* Extract the files.
*/
private List<File> filesOnly(Collection<File> results) {
List<File> list = new ArrayList<File>(results.size());
for (File file : results) {
if (file.isFile()) {
list.add(file);
}
}
return list;
}
/**
* Create an name filter containg the names of the files
* in the array.
*/
private static IOFileFilter createNameFilter(File[] files) {
String[] names = new String[files.length];
for (int i = 0; i < files.length; i++) {
names[i] = files[i].getName();
}
return new NameFileFilter(names);
}
/**
* Test Cancel
*/
public void testCancel() {
String cancelName = null;
// Cancel on a file
try {
cancelName = "DirectoryWalker.java";
new TestCancelWalker(cancelName, false).find(javaDir);
fail("CancelException not thrown for '" + cancelName + "'");
} catch (DirectoryWalker.CancelException cancel) {
assertEquals("File: " + cancelName, cancelName, cancel.getFile().getName());
assertEquals("Depth: " + cancelName, 5, cancel.getDepth());
} catch(IOException ex) {
fail("IOException: " + cancelName + " " + ex);
}
// Cancel on a directory
try {
cancelName = "commons";
new TestCancelWalker(cancelName, false).find(javaDir);
fail("CancelException not thrown for '" + cancelName + "'");
} catch (DirectoryWalker.CancelException cancel) {
assertEquals("File: " + cancelName, cancelName, cancel.getFile().getName());
assertEquals("Depth: " + cancelName, 3, cancel.getDepth());
} catch(IOException ex) {
fail("IOException: " + cancelName + " " + ex);
}
// Suppress CancelException (use same file name as preceeding test)
try {
List<File> results = new TestCancelWalker(cancelName, true).find(javaDir);
File lastFile = results.get(results.size() - 1);
assertEquals("Suppress: " + cancelName, cancelName, lastFile.getName());
} catch(IOException ex) {
fail("Suppress threw " + ex);
}
}
/**
* Test Cancel
*/
public void testMultiThreadCancel() {
String cancelName = "DirectoryWalker.java";
TestMultiThreadCancelWalker walker = new TestMultiThreadCancelWalker(cancelName, false);
// Cancel on a file
try {
walker.find(javaDir);
fail("CancelException not thrown for '" + cancelName + "'");
} catch (DirectoryWalker.CancelException cancel) {
File last = walker.results.get(walker.results.size() - 1);
assertEquals(cancelName, last.getName());
assertEquals("Depth: " + cancelName, 5, cancel.getDepth());
} catch(IOException ex) {
fail("IOException: " + cancelName + " " + ex);
}
// Cancel on a directory
try {
cancelName = "commons";
walker = new TestMultiThreadCancelWalker(cancelName, false);
walker.find(javaDir);
fail("CancelException not thrown for '" + cancelName + "'");
} catch (DirectoryWalker.CancelException cancel) {
assertEquals("File: " + cancelName, cancelName, cancel.getFile().getName());
assertEquals("Depth: " + cancelName, 3, cancel.getDepth());
} catch(IOException ex) {
fail("IOException: " + cancelName + " " + ex);
}
// Suppress CancelException (use same file name as preceeding test)
try {
walker = new TestMultiThreadCancelWalker(cancelName, true);
List<File> results = walker.find(javaDir);
File lastFile = results.get(results.size() - 1);
assertEquals("Suppress: " + cancelName, cancelName, lastFile.getName());
} catch(IOException ex) {
fail("Suppress threw " + ex);
}
}
/**
* Test Filtering
*/
public void testFilterString() {
List<String> results = new TestFileFinderString(dirsAndFilesFilter, -1).find(javaDir);
assertEquals("Result Size", outputFiles.length + ioFiles.length, results.size());
checkContainsString("IO File", ioFiles, results);
checkContainsString("Output File", outputFiles, results);
}
// ------------ Test DirectoryWalker implementation --------------------------
/**
* Test DirectoryWalker implementation that finds files in a directory hierarchy
* applying a file filter.
*/
private static class TestFileFinder extends DirectoryWalker<File> {
protected TestFileFinder(FileFilter filter, int depthLimit) {
super(filter, depthLimit);
}
protected TestFileFinder(IOFileFilter dirFilter, IOFileFilter fileFilter, int depthLimit) {
super(dirFilter, fileFilter, depthLimit);
}
/** find files. */
protected List<File> find(File startDirectory) {
List<File> results = new ArrayList<File>();
try {
walk(startDirectory, results);
} catch(IOException ex) {
Assert.fail(ex.toString());
}
return results;
}
/** Handles a directory end by adding the File to the result set. */
@Override
protected void handleDirectoryEnd(File directory, int depth, Collection<File> results) {
results.add(directory);
}
/** Handles a file by adding the File to the result set. */
@Override
protected void handleFile(File file, int depth, Collection<File> results) {
results.add(file);
}
}
// ------------ Test DirectoryWalker implementation --------------------------
/**
* Test DirectoryWalker implementation that always returns false
* from handleDirectoryStart()
*/
private static class TestFalseFileFinder extends TestFileFinder {
protected TestFalseFileFinder(FileFilter filter, int depthLimit) {
super(filter, depthLimit);
}
/** Always returns false. */
@Override
protected boolean handleDirectory(File directory, int depth, Collection<File> results) {
return false;
}
}
// ------------ Test DirectoryWalker implementation --------------------------
/**
* Test DirectoryWalker implementation that finds files in a directory hierarchy
* applying a file filter.
*/
static class TestCancelWalker extends DirectoryWalker<File> {
private String cancelFileName;
private boolean suppressCancel;
TestCancelWalker(String cancelFileName,boolean suppressCancel) {
super();
this.cancelFileName = cancelFileName;
this.suppressCancel = suppressCancel;
}
/** find files. */
protected List<File> find(File startDirectory) throws IOException {
List<File> results = new ArrayList<File>();
walk(startDirectory, results);
return results;
}
/** Handles a directory end by adding the File to the result set. */
@Override
protected void handleDirectoryEnd(File directory, int depth, Collection<File> results) throws IOException {
results.add(directory);
if (cancelFileName.equals(directory.getName())) {
throw new CancelException(directory, depth);
}
}
/** Handles a file by adding the File to the result set. */
@Override
protected void handleFile(File file, int depth, Collection<File> results) throws IOException {
results.add(file);
if (cancelFileName.equals(file.getName())) {
throw new CancelException(file, depth);
}
}
/** Handles Cancel. */
@Override
protected void handleCancelled(File startDirectory, Collection<File> results,
CancelException cancel) throws IOException {
if (!suppressCancel) {
super.handleCancelled(startDirectory, results, cancel);
}
}
}
/**
* Test DirectoryWalker implementation that finds files in a directory hierarchy
* applying a file filter.
*/
static class TestMultiThreadCancelWalker extends DirectoryWalker<File> {
private String cancelFileName;
private boolean suppressCancel;
private boolean cancelled;
public List<File> results;
TestMultiThreadCancelWalker(String cancelFileName, boolean suppressCancel) {
super();
this.cancelFileName = cancelFileName;
this.suppressCancel = suppressCancel;
}
/** find files. */
protected List<File> find(File startDirectory) throws IOException {
results = new ArrayList<File>();
walk(startDirectory, results);
return results;
}
/** Handles a directory end by adding the File to the result set. */
@Override
protected void handleDirectoryEnd(File directory, int depth, Collection<File> results) throws IOException {
results.add(directory);
assertFalse(cancelled);
if (cancelFileName.equals(directory.getName())) {
cancelled = true;
}
}
/** Handles a file by adding the File to the result set. */
@Override
protected void handleFile(File file, int depth, Collection<File> results) throws IOException {
results.add(file);
assertFalse(cancelled);
if (cancelFileName.equals(file.getName())) {
cancelled = true;
}
}
/** Handles Cancelled. */
@Override
protected boolean handleIsCancelled(File file, int depth, Collection<File> results) throws IOException {
return cancelled;
}
/** Handles Cancel. */
@Override
protected void handleCancelled(File startDirectory, Collection<File> results,
CancelException cancel) throws IOException {
if (!suppressCancel) {
super.handleCancelled(startDirectory, results, cancel);
}
}
}
/**
* Test DirectoryWalker implementation that finds files in a directory hierarchy
* applying a file filter.
*/
private static class TestFileFinderString extends DirectoryWalker<String> {
protected TestFileFinderString(FileFilter filter, int depthLimit) {
super(filter, depthLimit);
}
/** find files. */
protected List<String> find(File startDirectory) {
List<String> results = new ArrayList<String>();
try {
walk(startDirectory, results);
} catch(IOException ex) {
Assert.fail(ex.toString());
}
return results;
}
/** Handles a file by adding the File to the result set. */
@Override
protected void handleFile(File file, int depth, Collection<String> results) {
results.add(file.toString());
}
}
}
| gpl-2.0 |
bitbrain-gaming/craft | core/src/de/bitbrain/craft/models/LearnedRecipe.java | 2512 | /*
* Craft - Crafting game for Android, PC and Browser.
* Copyright (C) 2014 Miguel Gonzalez
*
* 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 de.bitbrain.craft.models;
import de.bitbrain.jpersis.annotations.PrimaryKey;
/**
* Object representation of a learned recipe
*
* @author Miguel Gonzalez <miguel-gonzalez@gmx.de>
* @since 1.0
* @version 1.0
*/
public class LearnedRecipe {
@PrimaryKey(true)
private int id;
private int recipeId;
private int playerId;
public LearnedRecipe() {
}
public LearnedRecipe(int i, int playerId) {
this.recipeId = i;
this.playerId = playerId;
}
/**
* @param id
* the id to set
*/
public void setId(int id) {
this.id = id;
}
/**
* @param itemId
* the itemId to set
*/
public void setRecipeId(int recipeId) {
this.recipeId = recipeId;
}
/**
* @param playerId
* the playerId to set
*/
public void setPlayerId(int playerId) {
this.playerId = playerId;
}
/**
* @return the id
*/
public int getId() {
return id;
}
/**
* @return the itemId
*/
public int getRecipeId() {
return recipeId;
}
/**
* @return the playerId
*/
public int getPlayerId() {
return playerId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + playerId;
result = prime * result + recipeId;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
LearnedRecipe other = (LearnedRecipe) obj;
if (playerId != other.playerId)
return false;
if (recipeId != other.recipeId)
return false;
return true;
}
}
| gpl-2.0 |
Jianchu/checker-framework | framework/src/org/checkerframework/framework/util/element/ClassTypeParamApplier.java | 3118 | package org.checkerframework.framework.util.element;
import com.sun.tools.javac.code.Attribute;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.TargetType;
import javax.lang.model.element.Element;
import javax.lang.model.element.ElementKind;
import org.checkerframework.framework.type.AnnotatedTypeFactory;
import org.checkerframework.framework.type.AnnotatedTypeMirror;
import org.checkerframework.framework.type.AnnotatedTypeMirror.AnnotatedTypeVariable;
import org.checkerframework.javacutil.ErrorReporter;
/**
* Applies the annotations present for a class type parameter onto an AnnotatedTypeVariable. See
* {@link TypeParamElementAnnotationApplier} for details.
*/
public class ClassTypeParamApplier extends TypeParamElementAnnotationApplier {
public static void apply(
AnnotatedTypeVariable type, Element element, AnnotatedTypeFactory typeFactory) {
new ClassTypeParamApplier(type, element, typeFactory).extractAndApply();
}
/**
* @return true if element represents a type parameter for a class
*/
public static boolean accepts(final AnnotatedTypeMirror type, final Element element) {
return element.getKind() == ElementKind.TYPE_PARAMETER
&& element.getEnclosingElement() instanceof Symbol.ClassSymbol;
}
/**
* The class that holds the type parameter element
*/
private final Symbol.ClassSymbol enclosingClass;
ClassTypeParamApplier(
AnnotatedTypeVariable type, Element element, AnnotatedTypeFactory typeFactory) {
super(type, element, typeFactory);
if (!(element.getEnclosingElement() instanceof Symbol.ClassSymbol)) {
ErrorReporter.errorAbort(
"TypeParameter not enclosed by class? Type( "
+ type
+ " ) "
+ "Element ( "
+ element
+ " ) ");
}
enclosingClass = (Symbol.ClassSymbol) element.getEnclosingElement();
}
/**
* @return TargetType.CLASS_TYPE_PARAMETER
*/
@Override
protected TargetType lowerBoundTarget() {
return TargetType.CLASS_TYPE_PARAMETER;
}
/**
* @return TargetType.CLASS_TYPE_PARAMETER_BOUND
*/
@Override
protected TargetType upperBoundTarget() {
return TargetType.CLASS_TYPE_PARAMETER_BOUND;
}
/**
* @return the index of element in the type parameter list of its enclosing class
*/
@Override
public int getElementIndex() {
return enclosingClass.getTypeParameters().indexOf(element);
}
@Override
protected TargetType[] validTargets() {
return new TargetType[] {TargetType.CLASS_EXTENDS};
}
/**
* @return the raw type attributes of the enclosing class
*/
@Override
protected Iterable<Attribute.TypeCompound> getRawTypeAttributes() {
return enclosingClass.getRawTypeAttributes();
}
@Override
protected boolean isAccepted() {
return accepts(type, element);
}
}
| gpl-2.0 |
jaypeeteeB/sKits | src/sKits/cmds/SoupCommand.java | 1325 | package sKits.cmds;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;
import sKits.main.sKitmain;
public class SoupCommand implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
if(!(sender instanceof Player)) {
return false;
}
final Player player = (Player) sender;
player.addPotionEffect(new PotionEffect(PotionEffectType.SLOW, 120, 3));
player.addPotionEffect(new PotionEffect(PotionEffectType.WEAKNESS, 120, 3));
player.addPotionEffect(new PotionEffect(PotionEffectType.BLINDNESS, 120, 3));
Bukkit.getServer().getScheduler().scheduleSyncDelayedTask(sKitmain.inst, new Runnable() {
@Override
public void run() {
// private int i=0;
// for (i=0; i++; i<9)
player.getInventory().addItem(new ItemStack(Material.MUSHROOM_SOUP, 1));
player.sendMessage(ChatColor.DARK_GREEN + "You have been given some soup!");
}
}, 100L);
return true;
}
}
| gpl-2.0 |
donatellosantoro/freESBee | freesbeeWebGE/src/it/unibas/freesbee/ge/web/modello/Utente.java | 2071 | package it.unibas.freesbee.ge.web.modello;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class Utente {
private Log logger = LogFactory.getLog(this.getClass());
private String nomeUtente = "admin";
private String password = "admin";
private String ruolo;
private boolean autenticato;
public static final String AMMINISTRATORE = "amministratore";
public static final String UTENTE_GENERICO = "utente_generico";
public String getNomeUtente() {
return nomeUtente;
}
public void setNomeUtente(String nomeUtente) {
this.nomeUtente = nomeUtente;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRuolo() {
return ruolo;
}
public void setRuolo(String ruolo) {
this.ruolo = ruolo;
}
public boolean isAutenticato() {
return autenticato;
}
public void setAutenticato(boolean autenticato) {
this.autenticato = autenticato;
}
public void verifica(String password){
String hashPasswordFornita = md5hash(password);
if (this.getPassword().equals(hashPasswordFornita)) {
this.setAutenticato(true);
} else {
this.setAutenticato(false);
}
}
public String md5hash(String password) {
String hashString = null;
try {
java.security.MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
byte[] hash = digest.digest(password.getBytes());
hashString = "";
for (int i = 0; i < hash.length; i++) {
hashString += Integer.toHexString(
(hash[i] & 0xFF) | 0x100
).toLowerCase().substring(1,3);
}
} catch (java.security.NoSuchAlgorithmException e) {
logger.error(e);
}
return hashString;
}
}
| gpl-2.0 |
BIORIMP/biorimp | BIO-RIMP/test_data/code/xerces/src/org/apache/wml/WMLBigElement.java | 1426 | /*
* Copyright 1999,2000,2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.wml;
/**
* <p>The interface is modeled after DOM1 Spec for HTML from W3C.
* The DTD used in this DOM model is from
* <a href="http://www.wapforum.org/DTD/wml_1.1.xml">
* http://www.wapforum.org/DTD/wml_1.1.xml</a></p>
*
* <p>'big' element renders the text with big font
* (Section 11.8.1, WAP WML Version 16-Jun-1999)</p>
*
* @version $Id: WMLBigElement.java,v 1.2 2004/02/24 23:34:05 mrglavas Exp $
* @author <a href="mailto:david@topware.com.tw">David Li</a>
*/
public interface WMLBigElement extends WMLElement {
/**
* 'xml:lang' specifics the natural or formal language in which
* the document is written.
* (Section 8.8, WAP WML Version 16-Jun-1999)
*/
public void setXmlLang(String newValue);
public String getXmlLang();
}
| gpl-2.0 |
marty-cz/desktop-basket | src/main/list/structure/BasketListItem.java | 805 | package main.list.structure;
/** Created by martin on 29.7.13. */
public class BasketListItem extends CommonListItem {
private static final long serialVersionUID = -2824687856810769231L;
protected double price;
protected boolean buyed;
public BasketListItem(String name, double price) {
this(name, price, false);
}
public BasketListItem(String name, double price, boolean buyed) {
super(name, "");
this.price = (price < 0.0) ? 0.0 : price;
this.buyed = buyed;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public boolean isBuyed() {
return buyed;
}
public void setBuyed(boolean buyed) {
this.buyed = buyed;
}
@Override
public int getSubItemCount() {
return -1;
}
}
| gpl-2.0 |
babaissarkar/paladin | clz/CLabel.java | 8259 | /*
* CLabel.java
*
* Copyright 2014 Subhraman Sarkar <subhraman@subhraman-Inspiron-660s>
*
* 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 clz;
import java.awt.Color;
import java.awt.Dimension;
import java.io.IOException;
import java.util.Stack;
import javax.imageio.ImageIO;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.border.LineBorder;
public class CLabel extends JLabel {
private static final long serialVersionUID = 1L;
private Stack<Card> cards = new Stack<Card>();
//public static Card ncrd = new Card("No Card", "/images/NCRD.jpg");
private boolean fliped;
private boolean used;
private boolean upside_down;
private String tooltip =
"<html><body>Click to move and click again on another card to paste.<br/>" +
"Move the mouse wheel to use/unuse.</body></html>";
public CLabel() throws IOException {
//this(ncrd);
//System.out.println("Generated");
super(ImageManipulator.scale(
new ImageIcon(
ImageIO.read(CLabel.class.getResourceAsStream("/images/NCRD.jpg"))), 64, 87));
setPreferredSize(new Dimension(64, 87));
}
public CLabel(Card card1) {
super(ImageManipulator.scale(card1.getImCard(), 64, 87));
cards.add(card1);
fliped = false;
used = false;
setUpsideDown(false);
if (card1.name.equalsIgnoreCase("No Card")) {
this.setToolTipText(tooltip);
} else {
StringBuffer effects = new StringBuffer();
effects.append("<html>");
effects.append("<body>");
effects.append("<h1>" + card1.name + "</h1>");
effects.append("<br/>");
effects.append("<p><b>Energy : </b>" + Card.energyToString(card1.energy) + "</p>");
effects.append("<p><b>Type : </b>" + card1.type + "</p>");
effects.append("<p><b>Subtype : </b>" + card1.subtype + "</p>");
effects.append("<p><b>Power : </b>" + card1.power + "</p>");
effects.append("<p><b>Damage : </b>" + card1.damage + "</p>");
effects.append("<p><b>Effects : </b><br/>");
for (String effect : card1.effects) {
effects.append(effect);
effects.append("<br/>");
}
effects.append("</p>");
effects.append("</body>");
effects.append("</html>");
this.setToolTipText(effects.toString());
// this.setToolTipText(card1.name + ","
// + Card.energyToString(card1.energy) + ","
// + Card.energyToString(card1.eno));
}
setPreferredSize(new Dimension(64, 87));
}
public CLabel(String text) {
super(text);
//cards.add(ncrd);
fliped = false;
used = false;
this.setToolTipText(tooltip);
setPreferredSize(new Dimension(64, 87));
}
public CLabel(Icon image) {
super(ImageManipulator.scale(image, 64, 87));
//cards.add(ncrd);
fliped = false;
used = false;
this.setToolTipText(tooltip);
setPreferredSize(new Dimension(64, 87));
}
public CLabel(String text, int horizontalAlignment) {
super(text, horizontalAlignment);
//cards.add(ncrd);
fliped = false;
used = false;
this.setToolTipText(tooltip);
setPreferredSize(new Dimension(64, 87));
}
public CLabel(Icon image, int horizontalAlignment) {
super(ImageManipulator.scale(image, 64, 87), horizontalAlignment);
// cards.add(ncrd);
fliped = false;
used = false;
this.setToolTipText(tooltip);
setPreferredSize(new Dimension(64, 87));
}
public CLabel(String text, Icon image, int horizontalAlignment) {
super(text, ImageManipulator.scale(image, 64, 87), horizontalAlignment);
// cards.add(ncrd);
fliped = false;
used = false;
this.setToolTipText(tooltip);
setPreferredSize(new Dimension(64, 87));
}
public final boolean isUsed() {
return this.used;
}
public final void setUsed(boolean used) {
this.used = used;
}
public Card getCard() {
if (cards.size() > 0) {
Card card2 = cards.lastElement();
super.setIcon(ImageManipulator.scale(cards.lastElement().getImCard(), 64, 87));
return card2;
} else {
return null;
}
}
public Card grCard() {
if (cards.size() > 0) {
Card card2 = cards.pop();
if (cards.size() > 0) {
super.setIcon(ImageManipulator.scale(cards.lastElement().getImCard(), 64, 87));
} else {
// this.setCard(ncrd);
try {
super.setIcon(
ImageManipulator.scale(
new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/images/NCRD.jpg"))), 64, 87
));
} catch(Exception e) {
// What to do if the image is missing?
System.err.println("Missing Resource!");
}
}
return card2;
} else {
return null; // NULL
}
}
public void setCard(Card card0) {
if (card0 != null) {
cards.add(card0);
super.setIcon(ImageManipulator.scale(card0.getImCard(), 64, 87));
if (card0.name.equalsIgnoreCase("No Card")) {
this.setToolTipText(tooltip);
} else {
this.setToolTipText(
card0.name + "," + Card.energyToString(card0.energy) + "," + Card.energyToString(card0.eno));
}
}
}
public void showFullImage() {
this.setIcon(this.getCard().getImCard());
}
public void showNormalImage() {
this.setIcon(ImageManipulator.scale(this.getCard().getImCard(), 64, 87));
}
public void flip() {
//imCard2 = imCard;
Card card = this.getCard();
if (card.bkCard != null) {
if (fliped) {
this.setIcon(ImageManipulator.scale(card.getImCard(), 64, 87));
fliped = false;
} else {
this.setIcon(ImageManipulator.scale(card.bkCard, 64, 87));
fliped = true;
}
}
}
public void use2() {
setUsed(true);
Card c = this.getCard();
if (c.civility.equalsIgnoreCase("Raenid")) {
this.setBorder(new LineBorder(Color.YELLOW, 2));
} else if (c.civility.equalsIgnoreCase("Asarn")) {
this.setBorder(new LineBorder(Color.RED, 2));
} else if (c.civility.equalsIgnoreCase("Mayarth")) {
this.setBorder(new LineBorder(Color.ORANGE, 2));
} else if (c.civility.equalsIgnoreCase("Zivar")) {
this.setBorder(new LineBorder(Color.BLACK, 2));
} else if (c.civility.equalsIgnoreCase("Niaz")) {
this.setBorder(new LineBorder(Color.BLUE, 2));
} else if (c.civility.equalsIgnoreCase("Kshiti")) {
this.setBorder(new LineBorder(Color.GREEN, 2));
} else {
this.setBorder(new LineBorder(Color.DARK_GRAY, 2));
}
repaint();
}
public void unuse2() {
setUsed(false);
this.setBorder(null);
repaint();
}
public void rot_90() {
setUsed(true);
ImageIcon img = ImageManipulator.scale(this.getCard().getImCard(), 64, 87);
ImageIcon rot_img = ImageManipulator.rotate90(img);
this.setIcon(rot_img);
}
public void rot_180() {
ImageIcon img = ImageManipulator.scale(this.getCard().getImCard(), 64, 87);
if (isUpsideDown()) {
setUpsideDown(false);
} else {
setUpsideDown(true);
img = ImageManipulator.flipVert(img);
}
this.setIcon(img);
}
public void rot_0() {
setUsed(false);
ImageIcon img = ImageManipulator.scale(this.getCard().getImCard(), 64, 87);
// Flipping the image if it was flipped before tapping.
if (isUpsideDown()) {
img = ImageManipulator.flipVert(img);
}
this.setIcon(img);
}
// public void flipBack() {
// setUpsideDown(false);
// setOrig();
// }
//
// public void unuse() {
// setUsed(false);
// if (!isUpsideDown()) {
// setOrig();
// } else {
// ImageIcon img = ImageManipulator.scale(this.getIcon(), 64, 87);
// ImageIcon rot_img = ImageManipulator.flipVert(img);
// this.setIcon(rot_img);
// }
// }
//
public void setOrig() {
this.setIcon(ImageManipulator.scale(this.getCard().getImCard(), 64, 87));
}
public boolean isUpsideDown() {
return upside_down;
}
public void setUpsideDown(boolean upside_down) {
this.upside_down = upside_down;
}
}
| gpl-2.0 |
Exiliot/video-conference | ClientSystem/src/sys/vp8/Converter.java | 5166 | package sys.vp8;
import sys.vp8.lib.*;
import sys.vp8.lib.Vp8Library.*;
import org.bridj.*;
public class Converter {
// Converts RGB24 data (packed as ARGB ints) to a VPX YUV I420 image
public static void ConvertRGB24ToI420(int[] rgbData, Pointer<vpx_image_t> img) {
int width = img.get().d_w();
int height = img.get().d_h();
Pointer<Byte> imgY = img.get().planes().get(Vp8Library.VPX_PLANE_Y);
Pointer<Byte> imgU = img.get().planes().get(Vp8Library.VPX_PLANE_U);
Pointer<Byte> imgV = img.get().planes().get(Vp8Library.VPX_PLANE_V);
int i1 = 0;
int uvi = 0;
for (int ypos = 0; ypos < height; ypos += 2) {
for (int xpos = 0; xpos < width; xpos += 2) {
int i2 = i1 + 1;
int i3 = width + i1;
int i4 = width + i2;
int rgb1 = rgbData[i1];
int rgb2 = rgbData[i2];
int rgb3 = rgbData[i3];
int rgb4 = rgbData[i4];
int r1 = unpackR(rgb1);
int g1 = unpackG(rgb1);
int b1 = unpackB(rgb1);
int r2 = unpackR(rgb2);
int g2 = unpackG(rgb2);
int b2 = unpackB(rgb2);
int r3 = unpackR(rgb3);
int g3 = unpackG(rgb3);
int b3 = unpackB(rgb3);
int r4 = unpackR(rgb4);
int g4 = unpackG(rgb4);
int b4 = unpackB(rgb4);
imgY.set(i1, (byte) getY(r1, g1, b1));
imgY.set(i2, (byte) getY(r2, g2, b2));
imgY.set(i3, (byte) getY(r3, g3, b3));
imgY.set(i4, (byte) getY(r4, g4, b4));
int u1 = getU(r1, g1, b1);
int u2 = getU(r2, g2, b2);
int u3 = getU(r3, g3, b3);
int u4 = getU(r4, g4, b4);
int v1 = getV(r1, g1, b1);
int v2 = getV(r2, g2, b2);
int v3 = getV(r3, g3, b3);
int v4 = getV(r4, g4, b4);
imgU.set(uvi, (byte) ((u1 + u2 + u3 + u4) / 4));
imgV.set(uvi, (byte) ((v1 + v2 + v3 + v4) / 4));
i1 += 2;
uvi++;
}
i1 += width;
}
}
// Converts a VPX YUV I420 image to RGB24 data (packed as ARGB ints)
public static void ConvertI420ToRGB24(Pointer<vpx_image_t> img, int[] rgbData) {
int width = img.get().d_w();
int height = img.get().d_h();
Pointer<Byte> imgY = img.get().planes().get(Vp8Library.VPX_PLANE_Y);
Pointer<Byte> imgU = img.get().planes().get(Vp8Library.VPX_PLANE_U);
Pointer<Byte> imgV = img.get().planes().get(Vp8Library.VPX_PLANE_V);
int yPadding = img.get().stride().get(Vp8Library.VPX_PLANE_Y) - width;
int uPadding = img.get().stride().get(Vp8Library.VPX_PLANE_U) - (width / 2);
int vPadding = img.get().stride().get(Vp8Library.VPX_PLANE_V) - (width / 2);
int yi = 0;
int ui = 0;
int vi = 0;
int rgbi = 0;
for (int ypos = 0; ypos < height; ypos++) {
for (int xpos = 0; xpos < width; xpos++) {
int y = imgY.get(yi) & 0xFF;
int u = imgU.get(ui) & 0xFF;
int v = imgV.get(vi) & 0xFF;
int r = getR(y, u, v);
int g = getG(y, u, v);
int b = getB(y, u, v);
rgbData[rgbi++] = packRGB(r, g, b);
yi++;
if (xpos % 2 == 1) {
ui++;
vi++;
}
}
yi += yPadding;
if (ypos % 2 == 0) {
ui -= (width / 2);
vi -= (width / 2);
} else {
ui += uPadding;
vi += vPadding;
}
}
}
private static int unpackR(int rgb) {
return (rgb >> 16) & 0xFF;
}
private static int unpackG(int rgb) {
return (rgb >> 8) & 0xFF;
}
private static int unpackB(int rgb) {
return (rgb >> 0) & 0xFF;
}
private static int packRGB(int r, int g, int b) {
return 0xFF000000
| (r & 0xFF) << 16
| (g & 0xFF) << 8
| (b & 0xFF) << 0;
}
private static int getR(int y, int u, int v) {
return clamp(y + (int) (1.402f * (v - 128)));
}
private static int getG(int y, int u, int v) {
return clamp(y - (int) (0.344f * (u - 128) + 0.714f * (v - 128)));
}
private static int getB(int y, int u, int v) {
return clamp(y + (int) (1.772f * (u - 128)));
}
private static int getY(int r, int g, int b) {
return (int) (0.299f * r + 0.587f * g + 0.114f * b);
}
private static int getU(int r, int g, int b) {
return (int) (-0.169f * r - 0.331f * g + 0.499f * b + 128);
}
private static int getV(int r, int g, int b) {
return (int) (0.499f * r - 0.418f * g - 0.0813f * b + 128);
}
private static int clamp(int value) {
return Math.min(Math.max(value, 0), 255);
}
} | gpl-2.0 |
smarr/Truffle | substratevm/src/com.oracle.svm.hosted/src/com/oracle/svm/hosted/phases/EarlyConstantFoldLoadFieldPlugin.java | 4777 | /*
* Copyright (c) 2020, 2020, 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.oracle.svm.hosted.phases;
import java.util.HashMap;
import java.util.Map;
import org.graalvm.compiler.api.replacements.SnippetReflectionProvider;
import org.graalvm.compiler.nodes.ConstantNode;
import org.graalvm.compiler.nodes.graphbuilderconf.GraphBuilderContext;
import org.graalvm.compiler.nodes.graphbuilderconf.NodePlugin;
import org.graalvm.nativeimage.impl.clinit.ClassInitializationTracking;
import com.oracle.graal.pointsto.infrastructure.OriginalClassProvider;
import com.oracle.svm.core.RuntimeAssertionsSupport;
import com.oracle.svm.util.ReflectionUtil;
import jdk.vm.ci.meta.ConstantReflectionProvider;
import jdk.vm.ci.meta.JavaKind;
import jdk.vm.ci.meta.MetaAccessProvider;
import jdk.vm.ci.meta.ResolvedJavaField;
import jdk.vm.ci.meta.ResolvedJavaType;
/**
* Early constant folding for well-known static fields. These constant foldings do not require and
* {@link ConstantReflectionProvider}.
*/
public class EarlyConstantFoldLoadFieldPlugin implements NodePlugin {
private final ResolvedJavaField isImageBuildTimeField;
private final SnippetReflectionProvider snippetReflection;
private final Map<ResolvedJavaType, ResolvedJavaType> primitiveTypes;
public EarlyConstantFoldLoadFieldPlugin(MetaAccessProvider metaAccess, SnippetReflectionProvider snippetReflection) {
isImageBuildTimeField = metaAccess.lookupJavaField(ReflectionUtil.lookupField(ClassInitializationTracking.class, "IS_IMAGE_BUILD_TIME"));
this.snippetReflection = snippetReflection;
primitiveTypes = new HashMap<>();
for (JavaKind kind : JavaKind.values()) {
if (kind.toBoxedJavaClass() != null) {
primitiveTypes.put(metaAccess.lookupJavaType(kind.toBoxedJavaClass()), metaAccess.lookupJavaType(kind.toJavaClass()));
}
}
}
@Override
public boolean handleLoadStaticField(GraphBuilderContext b, ResolvedJavaField field) {
if (field.equals(isImageBuildTimeField)) {
/*
* Loads of this field are injected into class initializers to provide stack traces when
* a class is wrongly initialized at image build time.
*/
b.addPush(JavaKind.Boolean, ConstantNode.forBoolean(false));
return true;
} else if (field.isSynthetic() && field.getName().startsWith("$assertionsDisabled")) {
/*
* Intercept assertion status: the value of the field during image generation does not
* matter at all (because it is the hosted assertion status), we instead return the
* appropriate runtime assertion status.
*/
Class<?> javaClass = OriginalClassProvider.getJavaClass(snippetReflection, field.getDeclaringClass());
boolean assertionsEnabled = RuntimeAssertionsSupport.singleton().desiredAssertionStatus(javaClass);
b.addPush(JavaKind.Boolean, ConstantNode.forBoolean(!assertionsEnabled));
return true;
}
/*
* Constant fold e.g. `Integer.TYPE`, which is accessed when using the literal `int.class`
* in Java code.
*/
if (field.getName().equals("TYPE")) {
ResolvedJavaType primitiveType = primitiveTypes.get(field.getDeclaringClass());
if (primitiveType != null) {
b.addPush(JavaKind.Object, ConstantNode.forConstant(b.getConstantReflection().asJavaClass(primitiveType), b.getMetaAccess()));
return true;
}
}
return false;
}
}
| gpl-2.0 |
FunLABGIT/FunArduino | src/Modèle/BlocCustom.java | 1071 | /*
* 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 Modèle;
import Controleur.Controleur;
import java.awt.Color;
import vue.Graphique.BlocCustomGraphique;
/**
* Ce bloc permet de créer son propre code.
* @author tancfire
*/
public class BlocCustom extends Bloc{
String code;
public BlocCustom(String code, Controleur ctrl) {
super(TypeBloc.programmation, Color.PINK, new BlocCustomGraphique(), ctrl);
initialisation(code);
init();
}
public BlocCustom(int id, String code, Controleur ctrl) {
super(id, TypeBloc.programmation, Color.PINK, new BlocCustomGraphique(), ctrl);
initialisation(code);
init();
}
private void initialisation(String code)
{
this.code = code;
}
@Override
public void mettreAjourCode() {
sonCodeDebut = code;
acces.setParametre(id, "String", "code", code);
}
}
| gpl-2.0 |
akunft/fastr | com.oracle.truffle.r.library/src/com/oracle/truffle/r/library/fastrGrid/FastRGridExternalLookup.java | 8532 | /*
* Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.truffle.r.library.fastrGrid;
import com.oracle.truffle.r.library.fastrGrid.DisplayList.LGetDisplayListElement;
import com.oracle.truffle.r.library.fastrGrid.DisplayList.LInitDisplayList;
import com.oracle.truffle.r.library.fastrGrid.DisplayList.LSetDisplayListOn;
import com.oracle.truffle.r.library.fastrGrid.PaletteExternals.CPalette;
import com.oracle.truffle.r.library.fastrGrid.PaletteExternals.CPalette2;
import com.oracle.truffle.r.library.fastrGrid.color.Col2RGB;
import com.oracle.truffle.r.library.fastrGrid.color.RGB;
import com.oracle.truffle.r.library.fastrGrid.grDevices.DevCairo;
import com.oracle.truffle.r.library.fastrGrid.grDevices.DevCurr;
import com.oracle.truffle.r.library.fastrGrid.grDevices.DevHoldFlush;
import com.oracle.truffle.r.library.fastrGrid.grDevices.DevOff;
import com.oracle.truffle.r.library.fastrGrid.grDevices.DevSize;
import com.oracle.truffle.r.library.fastrGrid.grDevices.InitWindowedDevice;
import com.oracle.truffle.r.library.fastrGrid.grDevices.SavePlot;
import com.oracle.truffle.r.library.fastrGrid.graphics.CPar;
import com.oracle.truffle.r.nodes.builtin.RExternalBuiltinNode;
import com.oracle.truffle.r.nodes.builtin.RInternalCodeBuiltinNode;
import com.oracle.truffle.r.runtime.RInternalCode;
import com.oracle.truffle.r.runtime.RRuntime;
import com.oracle.truffle.r.runtime.data.RList;
import com.oracle.truffle.r.runtime.data.RNull;
/**
* Implements the lookup for externals replaced by the FastR grid package.
*/
public final class FastRGridExternalLookup {
private FastRGridExternalLookup() {
// only static members
}
public static RExternalBuiltinNode lookupDotExternal(String name) {
switch (name) {
case "devholdflush":
return DevHoldFlush.create();
case "devsize":
return new DevSize();
case "devcur":
return new DevCurr();
case "devoff":
return DevOff.create();
case "PDF":
return new IgnoredGridExternal(RNull.instance);
case "devCairo":
return new DevCairo();
default:
return null;
}
}
public static RExternalBuiltinNode lookupDotExternal2(String name) {
switch (name) {
case "C_par":
return new CPar();
case "savePlot":
return SavePlot.create();
case "X11":
return new InitWindowedDevice();
case "devAskNewPage":
return new IgnoredGridExternal(RRuntime.LOGICAL_FALSE);
default:
return null;
}
}
public static RExternalBuiltinNode lookupDotCall(String name) {
switch (name) {
case "gridDirty":
return new LGridDirty();
case "initGrid":
return LInitGrid.create();
case "newpage":
return new LNewPage();
case "convert":
return LConvert.create();
case "validUnits":
return LValidUnit.create();
case "pretty":
return LPretty.create();
case "stringMetric":
return LStringMetric.create();
// Viewport management
case "upviewport":
return LUpViewPort.create();
case "initViewportStack":
return new LInitViewPortStack();
case "unsetviewport":
return LUnsetViewPort.create();
case "setviewport":
case "downviewport":
case "downvppath":
return getExternalFastRGridBuiltinNode(name);
// Drawing primitives
case "rect":
return LRect.create();
case "lines":
return LLines.create();
case "polygon":
return LPolygon.create();
case "text":
return LText.create();
case "textBounds":
return LTextBounds.create();
case "segments":
return LSegments.create();
case "circle":
return LCircle.create();
case "points":
return LPoints.create();
case "raster":
return LRaster.create();
// Bounds primitive:
case "rectBounds":
return LRectBounds.create();
case "locnBounds":
return LLocnBounds.create();
case "circleBounds":
return LCircleBounds.create();
// Simple grid state access
case "getGPar":
return new GridStateGetNode(GridState::getGpar);
case "setGPar":
return GridStateSetNode.create((state, val) -> state.setGpar((RList) val));
case "getCurrentGrob":
return new GridStateGetNode(GridState::getCurrentGrob);
case "setCurrentGrob":
return GridStateSetNode.create(GridState::setCurrentGrob);
case "currentViewport":
return new GridStateGetNode(GridState::getViewPort);
case "initGPar":
return new LInitGPar();
// Display list stuff
case "getDisplayList":
return new GridStateGetNode(GridState::getDisplayList);
case "setDisplayList":
return GridStateSetNode.create((state, val) -> state.setDisplayList((RList) val));
case "getDLindex":
return new GridStateGetNode(GridState::getDisplayListIndex);
case "setDLindex":
return GridStateSetNode.create((state, val) -> state.setDisplayListIndex(RRuntime.asInteger(val)));
case "setDLelt":
return GridStateSetNode.create(GridState::setDisplayListElement);
case "getDLelt":
return LGetDisplayListElement.create();
case "setDLon":
return LSetDisplayListOn.create();
case "getDLon":
return new GridStateGetNode(state -> RRuntime.asLogical(state.isDisplayListOn()));
case "getEngineDLon":
return new IgnoredGridExternal(RRuntime.LOGICAL_FALSE);
case "initDisplayList":
return new LInitDisplayList();
case "newpagerecording":
return new IgnoredGridExternal(RNull.instance);
// Color conversions
case "col2rgb":
return Col2RGB.create();
case "rgb":
return RGB.create();
case "palette2":
return CPalette2.create();
case "palette":
return CPalette.create();
default:
return null;
}
}
public static RExternalBuiltinNode lookupDotCallGraphics(String name) {
switch (name) {
case "gridDirty":
return new LGridDirty();
case "palette2":
return CPalette2.create();
case "palette":
return CPalette.create();
default:
return null;
}
}
private static RExternalBuiltinNode getExternalFastRGridBuiltinNode(String name) {
return new RInternalCodeBuiltinNode("grid", RInternalCode.loadSourceRelativeTo(LInitGrid.class, "fastrGrid.R"), name);
}
}
| gpl-2.0 |
Ornro/SMA | src/org/ups/sma/interfaces/Stateful.java | 168 | package org.ups.sma.interfaces;
import org.ups.sma.custom.domain.agent.State;
public interface Stateful {
public State getState();
public State getPublicState();
}
| gpl-2.0 |
pltxtra/libvuknob | src_jar/com/ice/tar/TarBuffer.java | 10583 | /*
** Authored by Timothy Gerard Endres
** <mailto:time@gjt.org> <http://www.trustice.com>
**
** This work has been placed into the public domain.
** You may use this work in any way and for any purpose you wish.
**
** THIS SOFTWARE IS PROVIDED AS-IS WITHOUT WARRANTY OF ANY KIND,
** NOT EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY. THE AUTHOR
** OF THIS SOFTWARE, ASSUMES _NO_ RESPONSIBILITY FOR ANY
** CONSEQUENCE RESULTING FROM THE USE, MODIFICATION, OR
** REDISTRIBUTION OF THIS SOFTWARE.
**
*/
package com.ice.tar;
import java.io.*;
/**
* The TarBuffer class implements the tar archive concept
* of a buffered input stream. This concept goes back to the
* days of blocked tape drives and special io devices. In the
* Java universe, the only real function that this class
* performs is to ensure that files have the correct "block"
* size, or other tars will complain.
* <p>
* You should never have a need to access this class directly.
* TarBuffers are created by Tar IO Streams.
*
* @version $Revision: 1.10 $
* @author Timothy Gerard Endres,
* <a href="mailto:time@gjt.org">time@trustice.com</a>.
* @see TarArchive
*/
public
class TarBuffer
extends Object
{
public static final int DEFAULT_RCDSIZE = ( 512 );
public static final int DEFAULT_BLKSIZE = ( DEFAULT_RCDSIZE * 20 );
private InputStream inStream;
private OutputStream outStream;
private byte[] blockBuffer;
private int currBlkIdx;
private int currRecIdx;
private int blockSize;
private int recordSize;
private int recsPerBlock;
private boolean debug;
public
TarBuffer( InputStream inStream )
{
this( inStream, TarBuffer.DEFAULT_BLKSIZE );
}
public
TarBuffer( InputStream inStream, int blockSize )
{
this( inStream, blockSize, TarBuffer.DEFAULT_RCDSIZE );
}
public
TarBuffer( InputStream inStream, int blockSize, int recordSize )
{
this.inStream = inStream;
this.outStream = null;
this.initialize( blockSize, recordSize );
}
public
TarBuffer( OutputStream outStream )
{
this( outStream, TarBuffer.DEFAULT_BLKSIZE );
}
public
TarBuffer( OutputStream outStream, int blockSize )
{
this( outStream, blockSize, TarBuffer.DEFAULT_RCDSIZE );
}
public
TarBuffer( OutputStream outStream, int blockSize, int recordSize )
{
this.inStream = null;
this.outStream = outStream;
this.initialize( blockSize, recordSize );
}
/**
* Initialization common to all constructors.
*/
private void
initialize( int blockSize, int recordSize )
{
this.debug = false;
this.blockSize = blockSize;
this.recordSize = recordSize;
this.recsPerBlock = ( this.blockSize / this.recordSize );
this.blockBuffer = new byte[ this.blockSize ];
if ( this.inStream != null )
{
this.currBlkIdx = -1;
this.currRecIdx = this.recsPerBlock;
}
else
{
this.currBlkIdx = 0;
this.currRecIdx = 0;
}
}
/**
* Get the TAR Buffer's block size. Blocks consist of multiple records.
*/
public int
getBlockSize()
{
return this.blockSize;
}
/**
* Get the TAR Buffer's record size.
*/
public int
getRecordSize()
{
return this.recordSize;
}
/**
* Set the debugging flag for the buffer.
*
* @param debug If true, print debugging output.
*/
public void
setDebug( boolean debug )
{
this.debug = debug;
}
/**
* Determine if an archive record indicate End of Archive. End of
* archive is indicated by a record that consists entirely of null bytes.
*
* @param record The record data to check.
*/
public boolean
isEOFRecord( byte[] record )
{
for ( int i = 0, sz = this.getRecordSize() ; i < sz ; ++i )
if ( record[i] != 0 )
return false;
return true;
}
/**
* Skip over a record on the input stream.
*/
public void
skipRecord()
throws IOException
{
if ( this.debug )
{
System.err.println
( "SkipRecord: recIdx = " + this.currRecIdx
+ " blkIdx = " + this.currBlkIdx );
}
if ( this.inStream == null )
throw new IOException
( "reading (via skip) from an output buffer" );
if ( this.currRecIdx >= this.recsPerBlock )
{
if ( ! this.readBlock() )
return; // UNDONE
}
this.currRecIdx++;
}
/**
* Read a record from the input stream and return the data.
*
* @return The record data.
*/
public byte[]
readRecord()
throws IOException
{
if ( this.debug )
{
System.err.println
( "ReadRecord: recIdx = " + this.currRecIdx
+ " blkIdx = " + this.currBlkIdx );
}
if ( this.inStream == null )
throw new IOException
( "reading from an output buffer" );
if ( this.currRecIdx >= this.recsPerBlock )
{
if ( ! this.readBlock() )
return null;
}
byte[] result = new byte[ this.recordSize ];
System.arraycopy(
this.blockBuffer, (this.currRecIdx * this.recordSize),
result, 0, this.recordSize );
this.currRecIdx++;
return result;
}
/**
* @return false if End-Of-File, else true
*/
private boolean
readBlock()
throws IOException
{
if ( this.debug )
{
System.err.println
( "ReadBlock: blkIdx = " + this.currBlkIdx );
}
if ( this.inStream == null )
throw new IOException
( "reading from an output buffer" );
this.currRecIdx = 0;
int offset = 0;
int bytesNeeded = this.blockSize;
for ( ; bytesNeeded > 0 ; )
{
long numBytes =
this.inStream.read
( this.blockBuffer, offset, bytesNeeded );
//
// NOTE
// We have fit EOF, and the block is not full!
//
// This is a broken archive. It does not follow the standard
// blocking algorithm. However, because we are generous, and
// it requires little effort, we will simply ignore the error
// and continue as if the entire block were read. This does
// not appear to break anything upstream. We used to return
// false in this case.
//
// Thanks to 'Yohann.Roussel@alcatel.fr' for this fix.
//
if ( numBytes == -1 )
break;
offset += numBytes;
bytesNeeded -= numBytes;
if ( numBytes != this.blockSize )
{
if ( this.debug )
{
System.err.println
( "ReadBlock: INCOMPLETE READ " + numBytes
+ " of " + this.blockSize + " bytes read." );
}
}
}
this.currBlkIdx++;
return true;
}
/**
* Get the current block number, zero based.
*
* @return The current zero based block number.
*/
public int
getCurrentBlockNum()
{
return this.currBlkIdx;
}
/**
* Get the current record number, within the current block, zero based.
* Thus, current offset = (currentBlockNum * recsPerBlk) + currentRecNum.
*
* @return The current zero based record number.
*/
public int
getCurrentRecordNum()
{
return this.currRecIdx - 1;
}
/**
* Write an archive record to the archive.
*
* @param record The record data to write to the archive.
*/
public void
writeRecord( byte[] record )
throws IOException
{
if ( this.debug )
{
System.err.println
( "WriteRecord: recIdx = " + this.currRecIdx
+ " blkIdx = " + this.currBlkIdx );
}
if ( this.outStream == null )
throw new IOException
( "writing to an input buffer" );
if ( record.length != this.recordSize )
throw new IOException
( "record to write has length '" + record.length
+ "' which is not the record size of '"
+ this.recordSize + "'" );
if ( this.currRecIdx >= this.recsPerBlock )
{
this.writeBlock();
}
System.arraycopy(
record, 0,
this.blockBuffer, (this.currRecIdx * this.recordSize),
this.recordSize );
this.currRecIdx++;
}
/**
* Write an archive record to the archive, where the record may be
* inside of a larger array buffer. The buffer must be "offset plus
* record size" long.
*
* @param buf The buffer containing the record data to write.
* @param offset The offset of the record data within buf.
*/
public void
writeRecord( byte[] buf, int offset )
throws IOException
{
if ( this.debug )
{
System.err.println
( "WriteRecord: recIdx = " + this.currRecIdx
+ " blkIdx = " + this.currBlkIdx );
}
if ( this.outStream == null )
throw new IOException
( "writing to an input buffer" );
if ( (offset + this.recordSize) > buf.length )
throw new IOException
( "record has length '" + buf.length
+ "' with offset '" + offset
+ "' which is less than the record size of '"
+ this.recordSize + "'" );
if ( this.currRecIdx >= this.recsPerBlock )
{
this.writeBlock();
}
System.arraycopy(
buf, offset,
this.blockBuffer, (this.currRecIdx * this.recordSize),
this.recordSize );
this.currRecIdx++;
}
/**
* Write a TarBuffer block to the archive.
*/
private void
writeBlock()
throws IOException
{
if ( this.debug )
{
System.err.println
( "WriteBlock: blkIdx = " + this.currBlkIdx );
}
if ( this.outStream == null )
throw new IOException
( "writing to an input buffer" );
this.outStream.write( this.blockBuffer, 0, this.blockSize );
this.outStream.flush();
this.currRecIdx = 0;
this.currBlkIdx++;
}
/**
* Flush the current data block if it has any data in it.
*/
private void
flushBlock()
throws IOException
{
if ( this.debug )
{
System.err.println( "TarBuffer.flushBlock() called." );
}
if ( this.outStream == null )
throw new IOException
( "writing to an input buffer" );
// Thanks to 'Todd Kofford <tkofford@bigfoot.com>' for this patch.
// Use a buffer initialized with 0s to initialize everything in the
// blockBuffer after the last current, complete record. This prevents
// any previous data that might have previously existed in the
// blockBuffer from being written to the file.
if ( this.currRecIdx > 0 )
{
int offset = this.currRecIdx * this.recordSize;
byte[] zeroBuffer = new byte[ this.blockSize - offset ];
System.arraycopy
( zeroBuffer, 0, this.blockBuffer, offset, zeroBuffer.length );
this.writeBlock();
}
}
/**
* Close the TarBuffer. If this is an output buffer, also flush the
* current block before closing.
*/
public void
close()
throws IOException
{
if ( this.debug )
{
System.err.println( "TarBuffer.closeBuffer()." );
}
if ( this.outStream != null )
{
this.flushBlock();
if ( this.outStream != System.out
&& this.outStream != System.err )
{
this.outStream.close();
this.outStream = null;
}
}
else if ( this.inStream != null )
{
if ( this.inStream != System.in )
{
this.inStream.close();
this.inStream = null;
}
}
}
}
| gpl-2.0 |
marcb1/droid-ssh | scp/src/main/java/marc/scp/sshutils/ConnectionInfo.java | 769 | package marc.scp.sshutils;
import com.jcraft.jsch.Logger;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.nio.charset.Charset;
public class ConnectionInfo implements Logger
{
static java.util.Hashtable name=new java.util.Hashtable();
static
{
name.put(new Integer(DEBUG), "DEBUG: ");
name.put(new Integer(INFO), "INFO: ");
name.put(new Integer(WARN), "WARN: ");
name.put(new Integer(ERROR), "ERROR: ");
name.put(new Integer(FATAL), "FATAL: ");
}
public boolean isEnabled(int level)
{
return true;
}
public void log(int level, String message)
{
System.err.print(name.get(new Integer(level)));
System.err.println(message);
}
}
| gpl-2.0 |
hempelchen/javatech | src/com/chb/sample/stringobj/StringInternTest.java | 544 | package com.chb.sample.stringobj;
/**
* Created by renen-inc_hempel on 14-3-14.
*/
public class StringInternTest {
public static void main(String[] args) {
// 使用char数组来初始化a,避免在a被创建之前字符串池中已经存在了值为"abcd"的对象
String a = new String(new char[] { 'a', 'b', 'c', 'd' });
String b = a.intern();
if (b == a) {
System.out.println("b被加入了字符串池中,没有新建对象");
} else {
System.out.println("b没被加入字符串池中,新建了对象");
}
}
}
| gpl-2.0 |
srotya/marauder | library-module/src/main/java/org/ambud/marauder/event/MarauderBaseEvent.java | 2474 | /*
* Copyright 2013 Ambud Sharma
*
* 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/>.2
*/
package org.ambud.marauder.event;
import java.util.HashMap;
import java.util.Map;
import org.ambud.marauder.configuration.MarauderParserConstants;
import org.apache.flume.Event;
public abstract class MarauderBaseEvent implements Event {
private Map<String, String> eventHdrs = null;
public MarauderBaseEvent() {
this.eventHdrs = new HashMap<String, String>();
eventHdrs.put(MarauderParserConstants.MARAUDER_KEY_EVENT_TYPE, getEventType().getTypeName());
}
public MarauderBaseEvent(Event event) {
this.eventHdrs = event.getHeaders();
}
/**
* Initialize headers with critical common headers
*/
public void initHdrs(){
getHeaders().put(MarauderParserConstants.MARAUDER_KEY_EVENTID, Integer.toHexString(getSigID()));
getHeaders().put(MarauderParserConstants.MARAUDER_KEY_SOURCE, Integer.toHexString(getSourceAddress()));
getHeaders().put(MarauderParserConstants.MARAUDER_KEY_TIMESTAMP, Integer.toHexString(getTimestamp()));
}
/**
* @return event ID / signature ID (doesn't refer to event serial number but a unique identifier for this event signature)
*/
public abstract int getSigID();
/**
* @return type of event
*/
public abstract MarauderEventTypes getEventType();
/**
* @return hostname of event source
*/
public abstract int getSourceAddress();
/**
* @return timestamp of the event in Epoch seconds
*/
public abstract int getTimestamp();
@Override
public Map<String, String> getHeaders() {
return eventHdrs;
}
@Override
public void setHeaders(Map<String, String> headers) {
if(headers!=null){
this.eventHdrs.putAll(headers);
}
}
@Override
public String toString() {
return "Columns:"+getHeaders();
}
}
| gpl-2.0 |
rex-xxx/mt6572_x201 | mediatek/frameworks/base/tests/net/tests/src/mediatek/net/libcore/external/bouncycastle/asn1/pkcs/SignedData.java | 6631 | /* Copyright Statement:
*
* This software/firmware and related documentation ("MediaTek Software") are
* protected under relevant copyright laws. The information contained herein is
* confidential and proprietary to MediaTek Inc. and/or its licensors. Without
* the prior written permission of MediaTek inc. and/or its licensors, any
* reproduction, modification, use or disclosure of MediaTek Software, and
* information contained herein, in whole or in part, shall be strictly
* prohibited.
*
* MediaTek Inc. (C) 2010. All rights reserved.
*
* BY OPENING THIS FILE, RECEIVER HEREBY UNEQUIVOCALLY ACKNOWLEDGES AND AGREES
* THAT THE SOFTWARE/FIRMWARE AND ITS DOCUMENTATIONS ("MEDIATEK SOFTWARE")
* RECEIVED FROM MEDIATEK AND/OR ITS REPRESENTATIVES ARE PROVIDED TO RECEIVER
* ON AN "AS-IS" BASIS ONLY. MEDIATEK EXPRESSLY DISCLAIMS ANY AND ALL
* WARRANTIES, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE OR
* NONINFRINGEMENT. NEITHER DOES MEDIATEK PROVIDE ANY WARRANTY WHATSOEVER WITH
* RESPECT TO THE SOFTWARE OF ANY THIRD PARTY WHICH MAY BE USED BY,
* INCORPORATED IN, OR SUPPLIED WITH THE MEDIATEK SOFTWARE, AND RECEIVER AGREES
* TO LOOK ONLY TO SUCH THIRD PARTY FOR ANY WARRANTY CLAIM RELATING THERETO.
* RECEIVER EXPRESSLY ACKNOWLEDGES THAT IT IS RECEIVER'S SOLE RESPONSIBILITY TO
* OBTAIN FROM ANY THIRD PARTY ALL PROPER LICENSES CONTAINED IN MEDIATEK
* SOFTWARE. MEDIATEK SHALL ALSO NOT BE RESPONSIBLE FOR ANY MEDIATEK SOFTWARE
* RELEASES MADE TO RECEIVER'S SPECIFICATION OR TO CONFORM TO A PARTICULAR
* STANDARD OR OPEN FORUM. RECEIVER'S SOLE AND EXCLUSIVE REMEDY AND MEDIATEK'S
* ENTIRE AND CUMULATIVE LIABILITY WITH RESPECT TO THE MEDIATEK SOFTWARE
* RELEASED HEREUNDER WILL BE, AT MEDIATEK'S OPTION, TO REVISE OR REPLACE THE
* MEDIATEK SOFTWARE AT ISSUE, OR REFUND ANY SOFTWARE LICENSE FEES OR SERVICE
* CHARGE PAID BY RECEIVER TO MEDIATEK FOR SUCH MEDIATEK SOFTWARE AT ISSUE.
*
* The following software/firmware and/or related documentation ("MediaTek
* Software") have been modified by MediaTek Inc. All revisions are subject to
* any receiver's applicable license agreements with MediaTek Inc.
*/
package org.bouncycastle.asn1.pkcs;
import java.util.Enumeration;
import org.bouncycastle.asn1.ASN1Encodable;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.ASN1Set;
import org.bouncycastle.asn1.BERSequence;
import org.bouncycastle.asn1.DERInteger;
import org.bouncycastle.asn1.DERObject;
import org.bouncycastle.asn1.DERTaggedObject;
/**
* a PKCS#7 signed data object.
*/
public class SignedData
extends ASN1Encodable
implements PKCSObjectIdentifiers
{
private DERInteger version;
private ASN1Set digestAlgorithms;
private ContentInfo contentInfo;
private ASN1Set certificates;
private ASN1Set crls;
private ASN1Set signerInfos;
public static SignedData getInstance(
Object o)
{
if (o instanceof SignedData)
{
return (SignedData)o;
}
else if (o instanceof ASN1Sequence)
{
return new SignedData((ASN1Sequence)o);
}
throw new IllegalArgumentException("unknown object in factory: " + o);
}
public SignedData(
DERInteger _version,
ASN1Set _digestAlgorithms,
ContentInfo _contentInfo,
ASN1Set _certificates,
ASN1Set _crls,
ASN1Set _signerInfos)
{
version = _version;
digestAlgorithms = _digestAlgorithms;
contentInfo = _contentInfo;
certificates = _certificates;
crls = _crls;
signerInfos = _signerInfos;
}
public SignedData(
ASN1Sequence seq)
{
Enumeration e = seq.getObjects();
version = (DERInteger)e.nextElement();
digestAlgorithms = ((ASN1Set)e.nextElement());
contentInfo = ContentInfo.getInstance(e.nextElement());
while (e.hasMoreElements())
{
DERObject o = (DERObject)e.nextElement();
//
// an interesting feature of SignedData is that there appear to be varying implementations...
// for the moment we ignore anything which doesn't fit.
//
if (o instanceof DERTaggedObject)
{
DERTaggedObject tagged = (DERTaggedObject)o;
switch (tagged.getTagNo())
{
case 0:
certificates = ASN1Set.getInstance(tagged, false);
break;
case 1:
crls = ASN1Set.getInstance(tagged, false);
break;
default:
throw new IllegalArgumentException("unknown tag value " + tagged.getTagNo());
}
}
else
{
signerInfos = (ASN1Set)o;
}
}
}
public DERInteger getVersion()
{
return version;
}
public ASN1Set getDigestAlgorithms()
{
return digestAlgorithms;
}
public ContentInfo getContentInfo()
{
return contentInfo;
}
public ASN1Set getCertificates()
{
return certificates;
}
public ASN1Set getCRLs()
{
return crls;
}
public ASN1Set getSignerInfos()
{
return signerInfos;
}
/**
* Produce an object suitable for an ASN1OutputStream.
* <pre>
* SignedData ::= SEQUENCE {
* version Version,
* digestAlgorithms DigestAlgorithmIdentifiers,
* contentInfo ContentInfo,
* certificates
* [0] IMPLICIT ExtendedCertificatesAndCertificates
* OPTIONAL,
* crls
* [1] IMPLICIT CertificateRevocationLists OPTIONAL,
* signerInfos SignerInfos }
* </pre>
*/
public DERObject toASN1Object()
{
ASN1EncodableVector v = new ASN1EncodableVector();
v.add(version);
v.add(digestAlgorithms);
v.add(contentInfo);
if (certificates != null)
{
v.add(new DERTaggedObject(false, 0, certificates));
}
if (crls != null)
{
v.add(new DERTaggedObject(false, 1, crls));
}
v.add(signerInfos);
return new BERSequence(v);
}
}
| gpl-2.0 |
AutuanLiu/Code | MyJava/sourcecode/chapter10/src/proxy1/Call.java | 1541 | package proxy1;
import java.io.*;
public class Call implements Serializable{
private String className; //±íʾÀàÃû
private String methodName; //±íʾ·½·¨Ãû
private Class[] paramTypes; //±íʾ·½·¨²ÎÊýÀàÐÍ
private Object[] params; //±íʾ·½·¨²ÎÊýÖµ
private Object result; //±íʾ·½·¨µÄ·µ»ØÖµ»òÕß·½·¨Å׳öµÄÒì³£
public Call(){}
public Call(String className,String methodName,Class[] paramTypes,
Object[] params){
this.className=className;
this.methodName=methodName;
this.paramTypes=paramTypes;
this.params=params;
}
public String getClassName(){return className;}
public void setClassName(String className){this.className=className;}
public String getMethodName(){return methodName;}
public void setMethodName(String methodName){this.methodName=methodName;}
public Class[] getParamTypes(){return paramTypes;}
public void setParamTypes(Class[] paramTypes){this.paramTypes=paramTypes;}
public Object[] getParams(){return params;}
public void setParams(Object[] params){this.params=params;}
public Object getResult(){return result;}
public void setResult(Object result){this.result=result;}
public String toString(){
return "className="+className+" methodName="+methodName;
}
}
/****************************************************
* ×÷ÕߣºËïÎÀÇÙ *
* À´Ô´£º<<JavaÍøÂç±à³Ì¾«½â>> *
* ¼¼ÊõÖ§³ÖÍøÖ·£ºwww.javathinker.org *
***************************************************/
| gpl-2.0 |
rex-xxx/mt6572_x201 | packages/apps/Exchange/exchange2/tests/src/com/android/exchange/provider/ExchangeDirectoryProviderTests.java | 6940 | /*
* Copyright (C) 2010 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.exchange.provider;
import com.android.emailcommon.mail.PackedString;
import com.android.emailcommon.provider.Account;
import com.android.exchange.provider.GalResult.GalData;
import com.android.exchange.utility.ExchangeTestCase;
import android.content.Context;
import android.database.Cursor;
import android.database.MatrixCursor;
import android.net.Uri;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.Contacts;
import android.test.suitebuilder.annotation.SmallTest;
/**
* You can run this entire test case with:
* runtest -c com.android.exchange.provider.ExchangeDirectoryProviderTests exchange
*/
@SmallTest
public class ExchangeDirectoryProviderTests extends ExchangeTestCase {
public ExchangeDirectoryProviderTests() {
}
// Create a test projection; we should only get back values for display name and email address
private static final String[] GAL_RESULT_PROJECTION =
new String[] {Contacts.DISPLAY_NAME, CommonDataKinds.Email.ADDRESS, Contacts.CONTENT_TYPE,
Contacts.LOOKUP_KEY};
private static final int GAL_RESULT_COLUMN_DISPLAY_NAME = 0;
private static final int GAL_RESULT_COLUMN_EMAIL_ADDRESS = 1;
private static final int GAL_RESULT_COLUMN_CONTENT_TYPE = 2;
private static final int GAL_RESULT_COLUMN_LOOKUP_KEY = 3;
public void testBuildSimpleGalResultCursor() {
GalResult result = new GalResult();
result.addGalData(1, "Alice Aardvark", "alice@aardvark.com");
result.addGalData(2, "Bob Badger", "bob@badger.com");
result.addGalData(3, "Clark Cougar", "clark@cougar.com");
result.addGalData(4, "Dan Dolphin", "dan@dolphin.com");
// Make sure our returned cursor has the expected contents
ExchangeDirectoryProvider provider = new ExchangeDirectoryProvider();
Cursor c = provider.buildGalResultCursor(GAL_RESULT_PROJECTION, result);
assertNotNull(c);
assertEquals(MatrixCursor.class, c.getClass());
assertEquals(4, c.getCount());
for (int i = 0; i < 4; i++) {
GalData data = result.galData.get(i);
assertTrue(c.moveToNext());
assertEquals(data.displayName, c.getString(GAL_RESULT_COLUMN_DISPLAY_NAME));
assertEquals(data.emailAddress, c.getString(GAL_RESULT_COLUMN_EMAIL_ADDRESS));
assertNull(c.getString(GAL_RESULT_COLUMN_CONTENT_TYPE));
}
}
private static final String[][] DISPLAY_NAME_TEST_FIELDS = {
{"Alice", "Aardvark", "Another Name"},
{"Alice", "Aardvark", null},
{"Alice", null, null},
{null, "Aardvark", null},
{null, null, null}
};
private static final int TEST_FIELD_FIRST_NAME = 0;
private static final int TEST_FIELD_LAST_NAME = 1;
private static final int TEST_FIELD_DISPLAY_NAME = 2;
private static final String[] EXPECTED_DISPLAY_NAMES = new String[] {"Another Name",
"Alice Aardvark", "Alice", "Aardvark", null};
private GalResult getTestDisplayNameResult() {
GalResult result = new GalResult();
for (int i = 0; i < DISPLAY_NAME_TEST_FIELDS.length; i++) {
GalData galData = new GalData();
String[] names = DISPLAY_NAME_TEST_FIELDS[i];
galData.put(GalData.FIRST_NAME, names[TEST_FIELD_FIRST_NAME]);
galData.put(GalData.LAST_NAME, names[TEST_FIELD_LAST_NAME]);
galData.put(GalData.DISPLAY_NAME, names[TEST_FIELD_DISPLAY_NAME]);
result.addGalData(galData);
}
return result;
}
public void testDisplayNameLogic() {
GalResult result = getTestDisplayNameResult();
// Make sure our returned cursor has the expected contents
ExchangeDirectoryProvider provider = new ExchangeDirectoryProvider();
Cursor c = provider.buildGalResultCursor(GAL_RESULT_PROJECTION, result);
assertNotNull(c);
assertEquals(MatrixCursor.class, c.getClass());
assertEquals(DISPLAY_NAME_TEST_FIELDS.length, c.getCount());
for (int i = 0; i < EXPECTED_DISPLAY_NAMES.length; i++) {
assertTrue(c.moveToNext());
assertEquals(EXPECTED_DISPLAY_NAMES[i], c.getString(GAL_RESULT_COLUMN_DISPLAY_NAME));
}
}
public void testLookupKeyLogic() {
GalResult result = getTestDisplayNameResult();
// Make sure our returned cursor has the expected contents
ExchangeDirectoryProvider provider = new ExchangeDirectoryProvider();
Cursor c = provider.buildGalResultCursor(GAL_RESULT_PROJECTION, result);
assertNotNull(c);
assertEquals(MatrixCursor.class, c.getClass());
assertEquals(DISPLAY_NAME_TEST_FIELDS.length, c.getCount());
for (int i = 0; i < EXPECTED_DISPLAY_NAMES.length; i++) {
assertTrue(c.moveToNext());
PackedString ps =
new PackedString(Uri.decode(c.getString(GAL_RESULT_COLUMN_LOOKUP_KEY)));
String[] testFields = DISPLAY_NAME_TEST_FIELDS[i];
assertEquals(testFields[TEST_FIELD_FIRST_NAME], ps.get(GalData.FIRST_NAME));
assertEquals(testFields[TEST_FIELD_LAST_NAME], ps.get(GalData.LAST_NAME));
assertEquals(EXPECTED_DISPLAY_NAMES[i], ps.get(GalData.DISPLAY_NAME));
}
}
public void testGetAccountIdByName() {
Context context = getContext(); //getMockContext();
ExchangeDirectoryProvider provider = new ExchangeDirectoryProvider();
// Nothing up my sleeve
assertNull(provider.sAccountIdMap.get("foo@android.com"));
assertNull(provider.sAccountIdMap.get("bar@android.com"));
// Create accounts; the email addresses will be the first argument + "@android.com"
Account acctFoo = setupTestAccount("foo", true);
Account acctBar = setupTestAccount("bar", true);
// Make sure we can retrieve them, and that the map is populated
assertEquals(acctFoo.mId, provider.getAccountIdByName(context, "foo@android.com"));
assertEquals(acctBar.mId, provider.getAccountIdByName(context, "bar@android.com"));
assertEquals((Long)acctFoo.mId, provider.sAccountIdMap.get("foo@android.com"));
assertEquals((Long)acctBar.mId, provider.sAccountIdMap.get("bar@android.com"));
}
}
| gpl-2.0 |
konum/mybatis-dynamicJoin | src/main/java/dynamicJoin/MapperInfo.java | 5792 | package dynamicJoin;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Logger;
import org.xml.sax.Attributes;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;
class MapperInfo {
String tableName;
String aliasTabla;
String select;
private boolean resulMapJoinsExists = false;
private Object entidad;
Map<String, Relation> joins = new HashMap<>();
private static final Logger log = Logger.getLogger( MapperInfo.class.getName() );
private static ConcurrentHashMap<String, MapperInfo> cache = new ConcurrentHashMap<>();
public static <E> MapperInfo getMapperInfo(Object entidad) throws Exception {
String nomEntid = entidad.getClass().getSimpleName();
if (cache.containsKey(nomEntid))
return cache.get(nomEntid);
else {
MapperInfo info = new MapperInfo();
info.entidad = entidad;
info.parseMapper(entidad);
if (info.tableName == null)
throw new JoinException("No sql TableName defined in mapper", entidad.getClass());
if (!info.resulMapJoinsExists)
log.info("No resultMap for joins defined in mapper "+ entidad.getClass().getName());
if (info.aliasTabla == null)
info.aliasTabla = info.tableName;
cache.put(nomEntid, info);
return info;
}
}
private void parseMapper(Object entidad) throws SAXException, IOException {
XMLReader reader = XMLReaderFactory.createXMLReader();
reader.setEntityResolver(new DummyEntityResolver());
reader.setContentHandler(new CustomHandler());
reader.parse(new InputSource(entidad.getClass().getClassLoader()
.getResourceAsStream("mybatis\\mappers\\" + entidad.getClass().getSimpleName() + "Mapper.xml")));
}
private class CustomHandler extends DefaultHandler {
boolean inResultMap = false;
boolean inBaseColumn = false;
boolean inTableName = false;
boolean inAliasTable = false;
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equalsIgnoreCase("resultMap")) {
if (attributes.getValue("id").contains("Joins")) {
resulMapJoinsExists = true;
inResultMap = true;
} else {
inResultMap = false;
}
}
if (qName.equalsIgnoreCase("sql") && attributes.getValue("id").equalsIgnoreCase("Base_Column_List")) {
inBaseColumn = true;
}
if (qName.equalsIgnoreCase("sql") && attributes.getValue("id").equalsIgnoreCase("TableName")) {
inTableName = true;
}
if (qName.equalsIgnoreCase("sql") && attributes.getValue("id").equalsIgnoreCase("AliasTable")) {
inAliasTable = true;
}
if (inResultMap && (qName.equalsIgnoreCase("association") || qName.equalsIgnoreCase("collection"))) {
boolean fieldAnotated = false;
Relation rel = new Relation();
for (Field field : entidad.getClass().getDeclaredFields()) {
if (field.getName().equals(attributes.getValue("property"))
&& field.getAnnotation(JoinableField.class) != null) {
fieldAnotated = true;
rel.foreignColumn = field.getAnnotation(JoinableField.class).foreignColumn();
rel.ownColumn = field.getAnnotation(JoinableField.class).ownColumn();
break;
}
}
if (!fieldAnotated) {
log.info( "The relationship " + attributes.getValue("property") + " for entity "
+ entidad.getClass().getSimpleName()
+ " isn't annotated with JoinableField. Ignoring relationship for dynamic join");
return;
}
validateAttributes(attributes, qName);
if (qName.equalsIgnoreCase("collection"))
rel.clazz = attributes.getValue("ofType");
else
rel.clazz = attributes.getValue("javaType");
rel.ownPrefix = attributes.getValue("columnPrefix");
joins.put(attributes.getValue("property"), rel);
}
}
private void validateAttributes(Attributes attributes, String tipoRelacion) {
if (tipoRelacion.equalsIgnoreCase("collection") && attributes.getValue("ofType") == null)
throw new JoinException("No type defined por relationship " + attributes.getValue("property") + " at resultmap",
entidad.getClass());
if (tipoRelacion.equalsIgnoreCase("association") && attributes.getValue("javaType") == null)
throw new JoinException("No type defined por relationship " + attributes.getValue("property") + " at resultmap",
entidad.getClass());
if (attributes.getValue("columnPrefix") == null)
throw new JoinException("No columnPrefix defined por relationship " + attributes.getValue("property")
+ " at resultmap", entidad.getClass());
}
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equalsIgnoreCase("resultMap")) {
inResultMap = false;
}
}
public void characters(char ch[], int start, int length) throws SAXException {
if (inBaseColumn) {
select = new String(ch, start, length).trim();
inBaseColumn = false;
}
if (inTableName) {
tableName = new String(ch, start, length).trim();
inTableName = false;
}
if (inAliasTable) {
aliasTabla = new String(ch, start, length).trim();
inAliasTable = false;
}
}
}
/**
* Dymmy class for avoiding resolvig dtd
*
* @author ggefaell
*/
private class DummyEntityResolver implements EntityResolver {
public InputSource resolveEntity(String publicID, String systemID) throws SAXException {
return new InputSource(new StringReader(""));
}
}
public String getTableName() {
return tableName;
}
public void setTableName(String tableName) {
this.tableName = tableName;
}
}
| gpl-2.0 |
shevek/qemu-java | qemu-exec/src/main/java/org/anarres/qemu/exec/QEmuMemoryOption.java | 1780 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.anarres.qemu.exec;
import java.io.File;
import java.util.List;
import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
/**
*
* @author shevek
*/
public class QEmuMemoryOption extends AbstractQEmuOption {
// TODO -> Generic package where it can be used for file sizes, etc.
public static enum Magnitude {
UNIT(1L),
KILO(1024L),
MEGA(KILO, 1024L),
GIGA(MEGA, 1024L),
TERA(GIGA, 1024L),
PETA(TERA, 1024L);
private final long multiplier;
Magnitude(@Nonnegative long multiplier) {
this.multiplier = multiplier;
}
Magnitude(@Nonnull Magnitude reference, @Nonnegative long multiplier) {
this.multiplier = reference.multiplier * multiplier;
}
public long toUnit(long amount) {
return multiplier * amount;
}
}
// private final String host;
private final long size;
private File path;
private boolean prealloc;
public QEmuMemoryOption(long size, @Nonnull Magnitude magnitude) {
this.size = magnitude.toUnit(size) / Magnitude.MEGA.multiplier;
}
@Nonnull
public QEmuMemoryOption withPath(File path) {
this.path = path;
return this;
}
@Nonnull
public QEmuMemoryOption withPrealloc(boolean prealloc) {
this.prealloc = prealloc;
return this;
}
@Override
public void appendTo(List<? super String> line) {
add(line, "-m", String.valueOf(size));
if (path != null)
add(line, "-mem-path", path.getAbsolutePath());
if (prealloc)
add(line, "-mem-prealloc");
}
}
| gpl-2.0 |
smeny/JPC | src/main/java/com/github/smeny/jpc/emulator/execution/opcodes/rm/salc.java | 1746 | /*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package com.github.smeny.jpc.emulator.execution.opcodes.rm;
import com.github.smeny.jpc.emulator.execution.*;
import com.github.smeny.jpc.emulator.execution.decoder.*;
import com.github.smeny.jpc.emulator.processor.*;
import com.github.smeny.jpc.emulator.processor.fpu64.*;
import static com.github.smeny.jpc.emulator.processor.Processor.*;
public class salc extends Executable
{
public salc(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
}
public Branch execute(Processor cpu)
{
cpu.r_al.set8((byte)(cpu.cf() ? -1 : 0));
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
} | gpl-2.0 |
isaacl/openjdk-jdk | src/share/classes/com/sun/tools/attach/VirtualMachine.java | 31253 | /*
* Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.tools.attach;
import com.sun.tools.attach.spi.AttachProvider;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.io.IOException;
/**
* A Java virtual machine.
*
* <p> A <code>VirtualMachine</code> represents a Java virtual machine to which this
* Java virtual machine has attached. The Java virtual machine to which it is
* attached is sometimes called the <i>target virtual machine</i>, or <i>target VM</i>.
* An application (typically a tool such as a managemet console or profiler) uses a
* VirtualMachine to load an agent into the target VM. For example, a profiler tool
* written in the Java Language might attach to a running application and load its
* profiler agent to profile the running application. </p>
*
* <p> A VirtualMachine is obtained by invoking the {@link #attach(String) attach} method
* with an identifier that identifies the target virtual machine. The identifier is
* implementation-dependent but is typically the process identifier (or pid) in
* environments where each Java virtual machine runs in its own operating system process.
* Alternatively, a <code>VirtualMachine</code> instance is obtained by invoking the
* {@link #attach(VirtualMachineDescriptor) attach} method with a {@link
* com.sun.tools.attach.VirtualMachineDescriptor VirtualMachineDescriptor} obtained
* from the list of virtual machine descriptors returned by the {@link #list list} method.
* Once a reference to a virtual machine is obtained, the {@link #loadAgent loadAgent},
* {@link #loadAgentLibrary loadAgentLibrary}, and {@link #loadAgentPath loadAgentPath}
* methods are used to load agents into target virtual machine. The {@link
* #loadAgent loadAgent} method is used to load agents that are written in the Java
* Language and deployed in a {@link java.util.jar.JarFile JAR file}. (See
* {@link java.lang.instrument} for a detailed description on how these agents
* are loaded and started). The {@link #loadAgentLibrary loadAgentLibrary} and
* {@link #loadAgentPath loadAgentPath} methods are used to load agents that
* are deployed either in a dynamic library or statically linked into the VM and make use of the <a
* href="../../../../../../../../technotes/guides/jvmti/index.html">JVM Tools
* Interface</a>. </p>
*
* <p> In addition to loading agents a VirtualMachine provides read access to the
* {@link java.lang.System#getProperties() system properties} in the target VM.
* This can be useful in some environments where properties such as
* <code>java.home</code>, <code>os.name</code>, or <code>os.arch</code> are
* used to construct the path to agent that will be loaded into the target VM.
*
* <p> The following example demonstrates how VirtualMachine may be used:</p>
*
* <pre>
*
* // attach to target VM
* VirtualMachine vm = VirtualMachine.attach("2177");
*
* // start management agent
* Properties props = new Properties();
* props.put("com.sun.management.jmxremote.port", "5000");
* vm.startManagementAgent(props);
*
* // detach
* vm.detach();
*
* </pre>
*
* <p> In this example we attach to a Java virtual machine that is identified by
* the process identifier <code>2177</code>. Then the JMX management agent is
* started in the target process using the supplied arguments. Finally, the
* client detaches from the target VM. </p>
*
* <p> A VirtualMachine is safe for use by multiple concurrent threads. </p>
*
* @since 1.6
*/
@jdk.Exported
public abstract class VirtualMachine {
private AttachProvider provider;
private String id;
private volatile int hash; // 0 => not computed
/**
* Initializes a new instance of this class.
*
* @param provider
* The attach provider creating this class.
* @param id
* The abstract identifier that identifies the Java virtual machine.
*
* @throws NullPointerException
* If <code>provider</code> or <code>id</code> is <code>null</code>.
*/
protected VirtualMachine(AttachProvider provider, String id) {
if (provider == null) {
throw new NullPointerException("provider cannot be null");
}
if (id == null) {
throw new NullPointerException("id cannot be null");
}
this.provider = provider;
this.id = id;
}
/**
* Return a list of Java virtual machines.
*
* <p> This method returns a list of Java {@link
* com.sun.tools.attach.VirtualMachineDescriptor} elements.
* The list is an aggregation of the virtual machine
* descriptor lists obtained by invoking the {@link
* com.sun.tools.attach.spi.AttachProvider#listVirtualMachines
* listVirtualMachines} method of all installed
* {@link com.sun.tools.attach.spi.AttachProvider attach providers}.
* If there are no Java virtual machines known to any provider
* then an empty list is returned.
*
* @return The list of virtual machine descriptors.
*/
public static List<VirtualMachineDescriptor> list() {
ArrayList<VirtualMachineDescriptor> l =
new ArrayList<VirtualMachineDescriptor>();
List<AttachProvider> providers = AttachProvider.providers();
for (AttachProvider provider: providers) {
l.addAll(provider.listVirtualMachines());
}
return l;
}
/**
* Attaches to a Java virtual machine.
*
* <p> This method obtains the list of attach providers by invoking the
* {@link com.sun.tools.attach.spi.AttachProvider#providers()
* AttachProvider.providers()} method. It then iterates overs the list
* and invokes each provider's {@link
* com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine(java.lang.String)
* attachVirtualMachine} method in turn. If a provider successfully
* attaches then the iteration terminates, and the VirtualMachine created
* by the provider that successfully attached is returned by this method.
* If the <code>attachVirtualMachine</code> method of all providers throws
* {@link com.sun.tools.attach.AttachNotSupportedException AttachNotSupportedException}
* then this method also throws <code>AttachNotSupportedException</code>.
* This means that <code>AttachNotSupportedException</code> is thrown when
* the identifier provided to this method is invalid, or the identifier
* corresponds to a Java virtual machine that does not exist, or none
* of the providers can attach to it. This exception is also thrown if
* {@link com.sun.tools.attach.spi.AttachProvider#providers()
* AttachProvider.providers()} returns an empty list. </p>
*
* @param id
* The abstract identifier that identifies the Java virtual machine.
*
* @return A VirtualMachine representing the target VM.
*
* @throws SecurityException
* If a security manager has been installed and it denies
* {@link com.sun.tools.attach.AttachPermission AttachPermission}
* <tt>("attachVirtualMachine")</tt>, or another permission
* required by the implementation.
*
* @throws AttachNotSupportedException
* If the <code>attachVirtualmachine</code> method of all installed
* providers throws <code>AttachNotSupportedException</code>, or
* there aren't any providers installed.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>id</code> is <code>null</code>.
*/
public static VirtualMachine attach(String id)
throws AttachNotSupportedException, IOException
{
if (id == null) {
throw new NullPointerException("id cannot be null");
}
List<AttachProvider> providers = AttachProvider.providers();
if (providers.size() == 0) {
throw new AttachNotSupportedException("no providers installed");
}
AttachNotSupportedException lastExc = null;
for (AttachProvider provider: providers) {
try {
return provider.attachVirtualMachine(id);
} catch (AttachNotSupportedException x) {
lastExc = x;
}
}
throw lastExc;
}
/**
* Attaches to a Java virtual machine.
*
* <p> This method first invokes the {@link
* com.sun.tools.attach.VirtualMachineDescriptor#provider() provider()} method
* of the given virtual machine descriptor to obtain the attach provider. It
* then invokes the attach provider's {@link
* com.sun.tools.attach.spi.AttachProvider#attachVirtualMachine(VirtualMachineDescriptor)
* attachVirtualMachine} to attach to the target VM.
*
* @param vmd
* The virtual machine descriptor.
*
* @return A VirtualMachine representing the target VM.
*
* @throws SecurityException
* If a security manager has been installed and it denies
* {@link com.sun.tools.attach.AttachPermission AttachPermission}
* <tt>("attachVirtualMachine")</tt>, or another permission
* required by the implementation.
*
* @throws AttachNotSupportedException
* If the attach provider's <code>attachVirtualmachine</code>
* throws <code>AttachNotSupportedException</code>.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>vmd</code> is <code>null</code>.
*/
public static VirtualMachine attach(VirtualMachineDescriptor vmd)
throws AttachNotSupportedException, IOException
{
return vmd.provider().attachVirtualMachine(vmd);
}
/**
* Detach from the virtual machine.
*
* <p> After detaching from the virtual machine, any further attempt to invoke
* operations on that virtual machine will cause an {@link java.io.IOException
* IOException} to be thrown. If an operation (such as {@link #loadAgent
* loadAgent} for example) is in progress when this method is invoked then
* the behaviour is implementation dependent. In other words, it is
* implementation specific if the operation completes or throws
* <tt>IOException</tt>.
*
* <p> If already detached from the virtual machine then invoking this
* method has no effect. </p>
*
* @throws IOException
* If an I/O error occurs
*/
public abstract void detach() throws IOException;
/**
* Returns the provider that created this virtual machine.
*
* @return The provider that created this virtual machine.
*/
public final AttachProvider provider() {
return provider;
}
/**
* Returns the identifier for this Java virtual machine.
*
* @return The identifier for this Java virtual machine.
*/
public final String id() {
return id;
}
/**
* Loads an agent library.
*
* <p> A <a href="../../../../../../../../technotes/guides/jvmti/index.html">JVM
* TI</a> client is called an <i>agent</i>. It is developed in a native language.
* A JVM TI agent is deployed in a platform specific manner but it is typically the
* platform equivalent of a dynamic library. Alternatively, it may be statically linked into the VM.
* This method causes the given agent library to be loaded into the target
* VM (if not already loaded or if not statically linked into the VM).
* It then causes the target VM to invoke the <code>Agent_OnAttach</code> function
* or, for a statically linked agent named 'L', the <code>Agent_OnAttach_L</code> function
* as specified in the
* <a href="../../../../../../../../technotes/guides/jvmti/index.html"> JVM Tools
* Interface</a> specification. Note that the <code>Agent_OnAttach[_L]</code>
* function is invoked even if the agent library was loaded prior to invoking
* this method.
*
* <p> The agent library provided is the name of the agent library. It is interpreted
* in the target virtual machine in an implementation-dependent manner. Typically an
* implementation will expand the library name into an operating system specific file
* name. For example, on UNIX systems, the name <tt>L</tt> might be expanded to
* <tt>libL.so</tt>, and located using the search path specified by the
* <tt>LD_LIBRARY_PATH</tt> environment variable. If the agent named 'L' is
* statically linked into the VM then the VM must export a function named
* <code>Agent_OnAttach_L</code>.</p>
*
* <p> If the <code>Agent_OnAttach[_L]</code> function in the agent library returns
* an error then an {@link com.sun.tools.attach.AgentInitializationException} is
* thrown. The return value from the <code>Agent_OnAttach[_L]</code> can then be
* obtained by invoking the {@link
* com.sun.tools.attach.AgentInitializationException#returnValue() returnValue}
* method on the exception. </p>
*
* @param agentLibrary
* The name of the agent library.
*
* @param options
* The options to provide to the <code>Agent_OnAttach[_L]</code>
* function (can be <code>null</code>).
*
* @throws AgentLoadException
* If the agent library does not exist, the agent library is not
* statically linked with the VM, or the agent library cannot be
* loaded for another reason.
*
* @throws AgentInitializationException
* If the <code>Agent_OnAttach[_L]</code> function returns an error.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>agentLibrary</code> is <code>null</code>.
*
* @see com.sun.tools.attach.AgentInitializationException#returnValue()
*/
public abstract void loadAgentLibrary(String agentLibrary, String options)
throws AgentLoadException, AgentInitializationException, IOException;
/**
* Loads an agent library.
*
* <p> This convenience method works as if by invoking:
*
* <blockquote><tt>
* {@link #loadAgentLibrary(String, String) loadAgentLibrary}(agentLibrary, null);
* </tt></blockquote>
*
* @param agentLibrary
* The name of the agent library.
*
* @throws AgentLoadException
* If the agent library does not exist, the agent library is not
* statically linked with the VM, or the agent library cannot be
* loaded for another reason.
*
* @throws AgentInitializationException
* If the <code>Agent_OnAttach[_L]</code> function returns an error.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>agentLibrary</code> is <code>null</code>.
*/
public void loadAgentLibrary(String agentLibrary)
throws AgentLoadException, AgentInitializationException, IOException
{
loadAgentLibrary(agentLibrary, null);
}
/**
* Load a native agent library by full pathname.
*
* <p> A <a href="../../../../../../../../technotes/guides/jvmti/index.html">JVM
* TI</a> client is called an <i>agent</i>. It is developed in a native language.
* A JVM TI agent is deployed in a platform specific manner but it is typically the
* platform equivalent of a dynamic library. Alternatively, the native
* library specified by the agentPath parameter may be statically
* linked with the VM. The parsing of the agentPath parameter into
* a statically linked library name is done in a platform
* specific manner in the VM. For example, in UNIX, an agentPath parameter
* of <code>/a/b/libL.so</code> would name a library 'L'.
*
* See the JVM TI Specification for more details.
*
* This method causes the given agent library to be loaded into the target
* VM (if not already loaded or if not statically linked into the VM).
* It then causes the target VM to invoke the <code>Agent_OnAttach</code>
* function or, for a statically linked agent named 'L', the
* <code>Agent_OnAttach_L</code> function as specified in the
* <a href="../../../../../../../../technotes/guides/jvmti/index.html"> JVM Tools
* Interface</a> specification.
* Note that the <code>Agent_OnAttach[_L]</code>
* function is invoked even if the agent library was loaded prior to invoking
* this method.
*
* <p> The agent library provided is the absolute path from which to load the
* agent library. Unlike {@link #loadAgentLibrary loadAgentLibrary}, the library name
* is not expanded in the target virtual machine. </p>
*
* <p> If the <code>Agent_OnAttach[_L]</code> function in the agent library returns
* an error then an {@link com.sun.tools.attach.AgentInitializationException} is
* thrown. The return value from the <code>Agent_OnAttach[_L]</code> can then be
* obtained by invoking the {@link
* com.sun.tools.attach.AgentInitializationException#returnValue() returnValue}
* method on the exception. </p>
*
* @param agentPath
* The full path of the agent library.
*
* @param options
* The options to provide to the <code>Agent_OnAttach[_L]</code>
* function (can be <code>null</code>).
*
* @throws AgentLoadException
* If the agent library does not exist, the agent library is not
* statically linked with the VM, or the agent library cannot be
* loaded for another reason.
*
* @throws AgentInitializationException
* If the <code>Agent_OnAttach[_L]</code> function returns an error.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>agentPath</code> is <code>null</code>.
*
* @see com.sun.tools.attach.AgentInitializationException#returnValue()
*/
public abstract void loadAgentPath(String agentPath, String options)
throws AgentLoadException, AgentInitializationException, IOException;
/**
* Load a native agent library by full pathname.
*
* <p> This convenience method works as if by invoking:
*
* <blockquote><tt>
* {@link #loadAgentPath(String, String) loadAgentPath}(agentLibrary, null);
* </tt></blockquote>
*
* @param agentPath
* The full path to the agent library.
*
* @throws AgentLoadException
* If the agent library does not exist, the agent library is not
* statically linked with the VM, or the agent library cannot be
* loaded for another reason.
*
* @throws AgentInitializationException
* If the <code>Agent_OnAttach[_L]</code> function returns an error.
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>agentPath</code> is <code>null</code>.
*/
public void loadAgentPath(String agentPath)
throws AgentLoadException, AgentInitializationException, IOException
{
loadAgentPath(agentPath, null);
}
/**
* Loads an agent.
*
* <p> The agent provided to this method is a path name to a JAR file on the file
* system of the target virtual machine. This path is passed to the target virtual
* machine where it is interpreted. The target virtual machine attempts to start
* the agent as specified by the {@link java.lang.instrument} specification.
* That is, the specified JAR file is added to the system class path (of the target
* virtual machine), and the <code>agentmain</code> method of the agent class, specified
* by the <code>Agent-Class</code> attribute in the JAR manifest, is invoked. This
* method completes when the <code>agentmain</code> method completes.
*
* @param agent
* Path to the JAR file containing the agent.
*
* @param options
* The options to provide to the agent's <code>agentmain</code>
* method (can be <code>null</code>).
*
* @throws AgentLoadException
* If the agent does not exist, or cannot be started in the manner
* specified in the {@link java.lang.instrument} specification.
*
* @throws AgentInitializationException
* If the <code>agentmain</code> throws an exception
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>agent</code> is <code>null</code>.
*/
public abstract void loadAgent(String agent, String options)
throws AgentLoadException, AgentInitializationException, IOException;
/**
* Loads an agent.
*
* <p> This convenience method works as if by invoking:
*
* <blockquote><tt>
* {@link #loadAgent(String, String) loadAgent}(agent, null);
* </tt></blockquote>
*
* @param agent
* Path to the JAR file containing the agent.
*
* @throws AgentLoadException
* If the agent does not exist, or cannot be started in the manner
* specified in the {@link java.lang.instrument} specification.
*
* @throws AgentInitializationException
* If the <code>agentmain</code> throws an exception
*
* @throws IOException
* If an I/O error occurs
*
* @throws NullPointerException
* If <code>agent</code> is <code>null</code>.
*/
public void loadAgent(String agent)
throws AgentLoadException, AgentInitializationException, IOException
{
loadAgent(agent, null);
}
/**
* Returns the current system properties in the target virtual machine.
*
* <p> This method returns the system properties in the target virtual
* machine. Properties whose key or value is not a <tt>String</tt> are
* omitted. The method is approximately equivalent to the invocation of the
* method {@link java.lang.System#getProperties System.getProperties}
* in the target virtual machine except that properties with a key or
* value that is not a <tt>String</tt> are not included.
*
* <p> This method is typically used to decide which agent to load into
* the target virtual machine with {@link #loadAgent loadAgent}, or
* {@link #loadAgentLibrary loadAgentLibrary}. For example, the
* <code>java.home</code> or <code>user.dir</code> properties might be
* use to create the path to the agent library or JAR file.
*
* @return The system properties
*
* @throws AttachOperationFailedException
* If the target virtual machine is unable to complete the
* attach operation. A more specific error message will be
* given by {@link AttachOperationFailedException#getMessage()}.
*
* @throws IOException
* If an I/O error occurs, a communication error for example,
* that cannot be identified as an error to indicate that the
* operation failed in the target VM.
*
* @see java.lang.System#getProperties
* @see #loadAgentLibrary
* @see #loadAgent
*/
public abstract Properties getSystemProperties() throws IOException;
/**
* Returns the current <i>agent properties</i> in the target virtual
* machine.
*
* <p> The target virtual machine can maintain a list of properties on
* behalf of agents. The manner in which this is done, the names of the
* properties, and the types of values that are allowed, is implementation
* specific. Agent properties are typically used to store communication
* end-points and other agent configuration details. For example, a debugger
* agent might create an agent property for its transport address.
*
* <p> This method returns the agent properties whose key and value is a
* <tt>String</tt>. Properties whose key or value is not a <tt>String</tt>
* are omitted. If there are no agent properties maintained in the target
* virtual machine then an empty property list is returned.
*
* @return The agent properties
*
* @throws AttachOperationFailedException
* If the target virtual machine is unable to complete the
* attach operation. A more specific error message will be
* given by {@link AttachOperationFailedException#getMessage()}.
*
* @throws IOException
* If an I/O error occurs, a communication error for example,
* that cannot be identified as an error to indicate that the
* operation failed in the target VM.
*/
public abstract Properties getAgentProperties() throws IOException;
/**
* Starts the JMX management agent in the target virtual machine.
*
* <p> The configuration properties are the same as those specified on
* the command line when starting the JMX management agent. In the same
* way as on the command line, you need to specify at least the
* {@code com.sun.management.jmxremote.port} property.
*
* <p> See the online documentation for <a
* href="../../../../../../../../technotes/guides/management/agent.html">
* Monitoring and Management Using JMX Technology</a> for further details.
*
* @param agentProperties
* A Properties object containing the configuration properties
* for the agent.
*
* @throws AttachOperationFailedException
* If the target virtual machine is unable to complete the
* attach operation. A more specific error message will be
* given by {@link AttachOperationFailedException#getMessage()}.
*
* @throws IOException
* If an I/O error occurs, a communication error for example,
* that cannot be identified as an error to indicate that the
* operation failed in the target VM.
*
* @throws IllegalArgumentException
* If keys or values in agentProperties are invalid.
*
* @throws NullPointerException
* If agentProperties is null.
*
* @since 1.9
*/
public abstract void startManagementAgent(Properties agentProperties) throws IOException;
/**
* Starts the local JMX management agent in the target virtual machine.
*
* <p> See the online documentation for <a
* href="../../../../../../../../technotes/guides/management/agent.html">
* Monitoring and Management Using JMX Technology</a> for further details.
*
* @return The String representation of the local connector's service address.
* The value can be parsed by the
* {@link javax.management.remote.JMXServiceURL#JMXServiceURL(String)}
* constructor.
*
* @throws AttachOperationFailedException
* If the target virtual machine is unable to complete the
* attach operation. A more specific error message will be
* given by {@link AttachOperationFailedException#getMessage()}.
*
* @throws IOException
* If an I/O error occurs, a communication error for example,
* that cannot be identified as an error to indicate that the
* operation failed in the target VM.
*
* @since 1.9
*/
public abstract String startLocalManagementAgent() throws IOException;
/**
* Returns a hash-code value for this VirtualMachine. The hash
* code is based upon the VirtualMachine's components, and satifies
* the general contract of the {@link java.lang.Object#hashCode()
* Object.hashCode} method.
*
* @return A hash-code value for this virtual machine
*/
public int hashCode() {
if (hash != 0) {
return hash;
}
hash = provider.hashCode() * 127 + id.hashCode();
return hash;
}
/**
* Tests this VirtualMachine for equality with another object.
*
* <p> If the given object is not a VirtualMachine then this
* method returns <tt>false</tt>. For two VirtualMachines to
* be considered equal requires that they both reference the same
* provider, and their {@link VirtualMachineDescriptor#id() identifiers} are equal. </p>
*
* <p> This method satisfies the general contract of the {@link
* java.lang.Object#equals(Object) Object.equals} method. </p>
*
* @param ob The object to which this object is to be compared
*
* @return <tt>true</tt> if, and only if, the given object is
* a VirtualMachine that is equal to this
* VirtualMachine.
*/
public boolean equals(Object ob) {
if (ob == this)
return true;
if (!(ob instanceof VirtualMachine))
return false;
VirtualMachine other = (VirtualMachine)ob;
if (other.provider() != this.provider()) {
return false;
}
if (!other.id().equals(this.id())) {
return false;
}
return true;
}
/**
* Returns the string representation of the <code>VirtualMachine</code>.
*/
public String toString() {
return provider.toString() + ": " + id;
}
}
| gpl-2.0 |
zbutfly/albacore | core/src/main/java/net/butfly/albacore/paral/split/ConvedSpliteratorBase.java | 533 | package net.butfly.albacore.paral.split;
import java.util.Objects;
import java.util.Spliterator;
abstract class ConvedSpliteratorBase<E, E0> extends LockSpliterator<E> {
protected final Spliterator<E0> impl;
protected final int ch;
protected ConvedSpliteratorBase(Spliterator<E0> impl, int ch) {
super();
this.impl = Objects.requireNonNull(impl);
this.ch = impl.characteristics();
}
@Override
public int characteristics() {
return ch;
}
@Override
public long estimateSize() {
return impl.estimateSize();
}
}
| gpl-2.0 |
zyz963272311/testGitHub | rootbase/src/com/liiwin/utils/WSUtils.java | 416 | package com.liiwin.utils;
/**
* <p>标题: webserviceUtil类</p>
* <p>功能: </p>
* <p>所属模块: rootbase</p>
* <p>版权: Copyright © 2017 zyzhu</p>
* <p>公司: xyz.zyzhu</p>
* <p>创建日期:2017年8月11日 下午2:42:53</p>
* <p>类全名:com.liiwin.utils.WSUtils</p>
* 作者:赵玉柱
* 初审:
* 复审:
* 监听使用界面:
* @version 8.0
*/
public class WSUtils
{
}
| gpl-2.0 |
rebeca-lang/org.rebecalang.compiler | src/main/java/org/rebecalang/compiler/modelcompiler/corerebeca/objectmodel/Type.java | 4723 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vhudson-jaxb-ri-2.2-146
// 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: 2021.05.29 at 10:12:22 PM IRDT
//
package org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel;
import java.util.Comparator;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.bind.annotation.XmlType;
import org.rebecalang.compiler.modelcompiler.abstractrebeca.AbstractTypeSystem;
/**
* <p>Java class for Type complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="Type">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="typeSystem" type="{http://rebecalang.org/compiler/modelcompiler/corerebecaexpression}TypeSystem"/>
* </sequence>
* <attribute name="lineNumber" type="{http://www.w3.org/2001/XMLSchema}int" />
* <attribute name="character" type="{http://www.w3.org/2001/XMLSchema}int" />
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "Type", namespace = "http://rebecalang.org/compiler/modelcompiler/corerebecaexpression", propOrder = {
"typeSystem"
})
@XmlSeeAlso({
GenericTypeInstance.class,
GenericType.class,
OrdinaryPrimitiveType.class,
ArrayType.class
})
public class Type {
@XmlElement(required = true)
protected AbstractTypeSystem typeSystem;
@XmlAttribute(name = "lineNumber")
protected Integer lineNumber;
@XmlAttribute(name = "character")
protected Integer character;
/**
* Gets the value of the typeSystem property.
*
* @return
* possible object is
* {@link AbstractTypeSystem }
*
*/
public AbstractTypeSystem getTypeSystem() {
return typeSystem;
}
/**
* Sets the value of the typeSystem property.
*
* @param value
* allowed object is
* {@link AbstractTypeSystem }
*
*/
public void setTypeSystem(AbstractTypeSystem value) {
this.typeSystem = value;
}
/**
* Gets the value of the lineNumber property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getLineNumber() {
return lineNumber;
}
/**
* Sets the value of the lineNumber property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setLineNumber(Integer value) {
this.lineNumber = value;
}
/**
* Gets the value of the character property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getCharacter() {
return character;
}
/**
* Sets the value of the character property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setCharacter(Integer value) {
this.character = value;
}
public String getTypeName() {
return "General-Type";
}
public boolean canTypeCastTo(Type target) {
return this.canTypeUpCastTo(target) || canTypeDownCastTo(target);
}
public boolean canTypeDownCastTo(Type target) {
return target.canTypeUpCastTo(this);
}
public boolean canTypeUpCastTo(Type target) {
return false;
}
public static Comparator<Type> getCastableComparator() {
return new Comparator<Type>() {
public int compare(Type base, Type target) {
if (!base.canTypeUpCastTo(target))
return 1;
return 0;
}
};
}
public static Comparator<Type> getExactComparator() {
return new Comparator<Type>() {
public int compare(Type base, Type target) {
if (base instanceof OrdinaryPrimitiveType) {
if (base != target)
return 1;
} else if (base instanceof ArrayType) {
if (!base.canTypeUpCastTo(target))
return 1;
ArrayType baseArrayType = (ArrayType) base;
ArrayType targetArrayType = (ArrayType) target;
if (baseArrayType.getOrdinaryPrimitiveType() != targetArrayType
.getOrdinaryPrimitiveType()) {
return 1;
}
}
return 0;
}
};
}
}
| gpl-2.0 |
kenyaehrs/Registration | omod/src/main/java/org/openmrs/module/registration/web/controller/patient/RevisitPatientRegistrationController.java | 3049 | /**
* Copyright 2014 Society for Health Information Systems Programmes, India (HISP India)
*
* This file is part of Registration module.
*
* Registration module 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.
* Registration module 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 Registration module. If not, see <http://www.gnu.org/licenses/>.
*
**/
package org.openmrs.module.registration.web.controller.patient;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.DocumentException;
import org.jaxen.JaxenException;
import org.openmrs.module.registration.util.RegistrationConstants;
import org.openmrs.module.registration.util.RegistrationUtils;
import org.openmrs.module.registration.web.controller.util.RegistrationWebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller("RevisitPatientRegistrationController")
@RequestMapping("/revisitPatientRegistration.htm")
public class RevisitPatientRegistrationController {
private static Log logger = LogFactory
.getLog(RevisitPatientRegistrationController.class);
@RequestMapping(method = RequestMethod.GET)
public String showForm(HttpServletRequest request, Model model)
throws JaxenException, DocumentException, IOException {
model.addAttribute("patientIdentifier",
RegistrationUtils.getNewIdentifier());
model.addAttribute(
"referralHospitals",
RegistrationWebUtils
.getSubConcepts(RegistrationConstants.CONCEPT_NAME_PATIENT_REFERRED_FROM));
model.addAttribute(
"referralReasons",
RegistrationWebUtils
.getSubConcepts(RegistrationConstants.CONCEPT_NAME_REASON_FOR_REFERRAL));
RegistrationWebUtils.getAddressData(model);
// model.addAttribute("OPDs",
// RegistrationWebUtils.getSubConcepts(RegistrationConstants.CONCEPT_NAME_OPD_WARD));
// ghanshyam,16-dec-2013,3438 Remove the interdependency
model.addAttribute(
"TEMPORARYCAT",
RegistrationWebUtils
.getSubConcepts(RegistrationConstants.CONCEPT_NAME_MEDICO_LEGAL_CASE));
model.addAttribute("TRIAGE", RegistrationWebUtils
.getSubConcepts(RegistrationConstants.CONCEPT_NAME_TRIAGE));
model.addAttribute(
"OPDs",
RegistrationWebUtils
.getSubConcepts(RegistrationConstants.CONCEPT_NAME_OPD_WARD));
return "/module/registration/patient/revisitPatientRegistration";
}
}
| gpl-2.0 |
Esleelkartea/aon-employee | aonemployee_v2.3.0_src/paquetes descomprimidos/aon.ql-1.9.15-sources/com/code/aon/ql/ast/sql/SqlRenderer.java | 6238 | package com.code.aon.ql.ast.sql;
import java.io.IOException;
import java.io.Writer;
import java.util.Iterator;
import java.util.logging.Logger;
import com.code.aon.ql.Criteria;
import com.code.aon.ql.Order;
import com.code.aon.ql.OrderByList;
import com.code.aon.ql.Projection;
import com.code.aon.ql.ProjectionList;
import com.code.aon.ql.ast.BetweenExpression;
import com.code.aon.ql.ast.ConstantExpression;
import com.code.aon.ql.ast.CriterionVisitor;
import com.code.aon.ql.ast.IdentExpression;
import com.code.aon.ql.ast.LogicalAndExpression;
import com.code.aon.ql.ast.LogicalOrExpression;
import com.code.aon.ql.ast.NotNullExpression;
import com.code.aon.ql.ast.NullExpression;
import com.code.aon.ql.ast.RelationalExpression;
/**
* Visitante de expresiones destinado a obtener una clausa WHERE de una
* sentencia SQL.
*
* @author Consulting & Development. Raúl Trepiana - 19-nov-2003
* @since 1.0
*
*/
public class SqlRenderer implements CriterionVisitor {
/**
* SQL ORDER BY.
*/
private static final String ORDER_BY = " ORDER BY ";
/**
* SQL DESC.
*/
private static final String DESC = " DESC";
/**
* Obtains a suitable <code>Logger</code>.
*/
private static Logger LOGGER = Logger.getLogger(SqlRenderer.class.getName());
/**
* Where the result will be printed.
*/
private Writer out;
/**
* Constructor giving a Writer where the result will be printed.
*
* @param out
* A Writer where the result will be printed.
*/
public SqlRenderer(Writer out) {
this.out = out;
}
/*
* (non-Javadoc)
*
* @see com.code.aon.ql.ast.CriterionVisitor#visitCriteria(com.code.aon.ql.Criteria)
*/
public void visitCriteria(Criteria criteria) {
if (criteria.getExpression() != null) {
criteria.getExpression().accept(this);
}
if (criteria.getOrderByList() != null) {
criteria.getOrderByList().accept(this);
}
}
public void visitProjection(Projection projection) {
throw new UnsupportedOperationException( "Projection not supported" );
}
public void visitProjectionList(ProjectionList projectionList) {
throw new UnsupportedOperationException( "Projection not supported" );
}
/*
* (non-Javadoc)
*
* @see com.code.aon.ql.ast.CriterionVisitor#visitOrderByList(com.code.aon.ql.OrderByList)
*/
public void visitOrderByList(OrderByList orderByList) {
write(ORDER_BY);
Iterator i = orderByList.getOrders().iterator();
while (i.hasNext()) {
Order order = (Order) i.next();
order.accept(this);
if (i.hasNext()) {
write(", ");
}
}
}
/*
* (non-Javadoc)
*
* @see com.code.aon.ql.ast.CriterionVisitor#visitOrder(com.code.aon.ql.Order)
*/
public void visitOrder(Order order) {
order.getExpression().accept(this);
if (!order.isAscending()) {
write(DESC);
}
}
/*
* (non-Javadoc)
*
* @see com.code.aon.ql.ast.CriterionVisitor#visitLogicalOrExpression(com.code.aon.ql.ast.LogicalOrExpression)
*/
public void visitLogicalOrExpression(LogicalOrExpression expression) {
write("( ");
expression.getLeftExpression().accept(this);
write(" or ");
expression.getRightExpression().accept(this);
write(" )");
}
/*
* (non-Javadoc)
*
* @see com.code.aon.ql.ast.CriterionVisitor#visitLogicalAndExpression(com.code.aon.ql.ast.LogicalAndExpression)
*/
public void visitLogicalAndExpression(LogicalAndExpression expression) {
// write( " ");
expression.getLeftExpression().accept(this);
write(" and ");
expression.getRightExpression().accept(this);
// write( " ");
}
/*
* (non-Javadoc)
*
* @see com.code.aon.ql.ast.CriterionVisitor#visitNullExpression(com.code.aon.ql.ast.NullExpression)
*/
public void visitNullExpression(NullExpression expression) {
expression.getExpression().accept(this);
write(" is null ");
}
/*
* (non-Javadoc)
*
* @see com.code.aon.ql.ast.CriterionVisitor#visitNotNullExpression(com.code.aon.ql.ast.NotNullExpression)
*/
public void visitNotNullExpression(NotNullExpression expression) {
expression.getExpression().accept(this);
write(" is not null ");
}
/*
* (non-Javadoc)
*
* @see com.code.aon.ql.ast.CriterionVisitor#visitIdentExpression(com.code.aon.ql.ast.IdentExpression)
*/
public void visitIdentExpression(IdentExpression expression) {
write(expression.getName());
}
/*
* (non-Javadoc)
*
* @see com.code.aon.ql.ast.CriterionVisitor#visitConstantExpression(com.code.aon.ql.ast.ConstantExpression)
*/
public void visitConstantExpression(ConstantExpression expression) {
write("\'" + expression.getData() + "\'"); //$NON-NLS-2$
}
/*
* (non-Javadoc)
*
* @see com.code.aon.ql.ast.CriterionVisitor#visitBetweenExpression(com.code.aon.ql.ast.BetweenExpression)
*/
public void visitBetweenExpression(BetweenExpression expression) {
expression.getLeftExpression().accept(this);
write(" between ");
expression.getMinorExpression().accept(this);
write(" and ");
expression.getMajorExpression().accept(this);
write(" ");
}
/*
* (non-Javadoc)
*
* @see com.code.aon.ql.ast.CriterionVisitor#visitRelationalExpression(com.code.aon.ql.ast.RelationalExpression)
*/
public void visitRelationalExpression(RelationalExpression expression) {
expression.getLeftExpression().accept(this);
int type = expression.getType();
if ((type & RelationalExpression.LT) > 0) {
write(" < ");
} else if ((type & RelationalExpression.GT) > 0) {
write(" > ");
} else if ((type & RelationalExpression.EQ) > 0) {
write(" = ");
} else if ((type & RelationalExpression.NEQ) > 0) {
write(" <> ");
} else if ((type & RelationalExpression.LIKE) > 0) {
write(" LIKE ");
} else if ((type & RelationalExpression.GTE) > 0) {
write(" >= ");
} else if ((type & RelationalExpression.LTE) > 0) {
write(" <= ");
}
expression.getRightExpression().accept(this);
}
/**
* @param str
*/
private void write(String str) {
try {
out.write(str);
} catch (IOException e) {
LOGGER.severe(e.getMessage());
}
}
} | gpl-2.0 |
andreax79/one-neighbor-binary-cellular-automata | src/main/java/com/github/andreax79/meca/Main.java | 13692 | /**
* Copyright (C) 2009 Andrea Bonomi - <andrea.bonomi@gmail.com>
*
* https://github.com/andreax79/one-neighbor-binary-cellular-automata
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.)
*
*/
package com.github.andreax79.meca;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedList;
import java.util.List;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.Option;
import org.apache.commons.cli.OptionBuilder;
import org.apache.commons.cli.OptionGroup;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
import org.apache.commons.cli.PosixParser;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
public class Main {
private static int cellSize = 2;
public static Stats drawRule(int ruleNumber, int size, Boundaries boundaries, UpdatePattern updatePattern, int steps, double alpha) throws IOException {
return drawRule(ruleNumber, size, boundaries, updatePattern, steps, alpha, null, Output.all, ColorScheme.omegaColor);
}
public static Stats drawRule(int ruleNumber, int size, Boundaries boundaries, UpdatePattern updatePattern, int steps, double alpha, String pattern, Output output, ColorScheme colorScheme) throws IOException {
Rule rule = new Rule(ruleNumber);
Row row = new Row(size, rule, boundaries, updatePattern, pattern, alpha); // e.g. 00010011011111
Stats stats = new Stats();
FileOutputStream finalImage = null;
Graphics2D g = null;
BufferedImage img = null;
if (output != Output.noOutput) {
String fileName = "rule"+ruleNumber;
// pattern
if (pattern != null)
fileName += pattern;
// alpha
if (alpha > 0)
fileName += String.format("_a%02d", (int)(alpha*100));
// updatePattern
if (updatePattern != UpdatePattern.synchronous)
fileName += "-" + updatePattern;
fileName += ".jpeg";
File file = new File(fileName);
finalImage = new FileOutputStream(file);
int width = (int) (cellSize*(size+1) * (output == Output.all ? 1.25 : 1));
int height = cellSize*(steps+1);
img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
g = img.createGraphics();
g.setBackground(Color.white);
g.clearRect(0,0,width,height);
g.setColor(Color.black);
}
int startMeansFromStep = 50;
List<Double> densities = new LinkedList<Double>();
double totalDensities = 0;
double prevValue = 0;
double prevDelta = 0;
double prevOnes = 0;
double prevOnesDelta = 0;
for (int t=0; t<steps; t++) {
if (t >= startMeansFromStep) {
double density = row.getDensity();
densities.add(density);
totalDensities+=density;
}
// System.out.println(String.format("%4d", t) + " " + row.toString() + " ones=" + row.getOnes());
if (output != Output.noOutput) {
for (int j=0; j<row.getSize(); j++) {
switch (colorScheme) {
case noColor:
if (row.getCell(j).getState()) {
g.setColor(Color.black);
g.fillRect(j*cellSize,t*cellSize,cellSize,cellSize);
}
break;
case omegaColor:
g.setColor(row.getCell(j).getOmegaColor());
g.fillRect(j*cellSize,t*cellSize,cellSize,cellSize);
break;
case activationColor:
if (row.getCell(j).getState()) {
g.setColor(row.getCell(j).getColor());
g.fillRect(j*cellSize,t*cellSize,cellSize,cellSize);
}
break;
}
}
if (output == Output.all) {
double value = row.getValue();
double delta = Math.abs(value - prevValue);
double ones = row.getOnes();
double onesDelta = Math.abs(ones - prevOnes);
if (t > 0) {
g.setColor(Color.red);
g.drawLine((int)(prevValue*cellSize/4.0)+cellSize*(size+1),(int)((t-1)*cellSize), (int)(value*cellSize/4.0)+cellSize*(size+1),(int)(t*cellSize));
g.setColor(Color.blue);
g.drawLine((int)(prevOnes*cellSize/4.0)+cellSize*(size+1),(int)((t-1)*cellSize), (int)(ones*cellSize/4.0)+cellSize*(size+1),(int)(t*cellSize));
if (t >1) {
g.setColor(Color.orange);
g.drawLine((int)(prevDelta*cellSize/4.0)+cellSize*(size+1),(int)((t-1)*cellSize), (int)(delta*cellSize/4.0)+cellSize*(size+1),(int)(t*cellSize));
g.setColor(Color.cyan);
g.drawLine((int)(prevOnesDelta*cellSize/4.0)+cellSize*(size+1),(int)((t-1)*cellSize), (int)(onesDelta*cellSize/4.0)+cellSize*(size+1),(int)(t*cellSize));
}
}
prevValue = value;
prevDelta = delta;
prevOnes = ones;
prevOnesDelta = onesDelta;
}
}
row = new Row(row);
}
double means = totalDensities / densities.size();
double var = 0;
for (double density : densities)
var += Math.pow(density - means, 2);
var = var / densities.size();
System.out.println("Rule: " + ruleNumber + " Boundaties: " + boundaries + " UpdatePattern: " + updatePattern + " Alpha: " + String.format("%.3f",alpha) + " Means: " + String.format("%.6f",means) + " Variance: " + String.format("%.6f",var));
stats.setMeans(means);
stats.setVariance(var);
if (output != Output.noOutput) {
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(finalImage);
JPEGEncodeParam param = encoder.getDefaultJPEGEncodeParam(img);
param.setQuality(1.0f,true);
encoder.encode(img, param);
finalImage.flush();
finalImage.close();
}
return stats;
}
@SuppressWarnings("static-access")
public static void main(String[] args) {
// create the command line parser
CommandLineParser parser = new PosixParser();
// create the Options
Options options = new Options();
options.addOption("X", "suppress-output", false, "don't create the output file" );
OptionGroup boundariesOptions = new OptionGroup();
boundariesOptions.addOption(new Option("P", "periodic", false, "periodic boundaries (default)" ));
boundariesOptions.addOption(new Option("F", "fixed", false, "fixed-value boundaries" ));
boundariesOptions.addOption(new Option("A", "adiabatic", false, "adiabatic boundaries" ));
boundariesOptions.addOption(new Option("R", "reflective", false, "reflective boundaries" ));
options.addOptionGroup(boundariesOptions);
OptionGroup colorOptions = new OptionGroup();
colorOptions.addOption(new Option("bn", "black-white", false, "black and white color scheme (default)"));
colorOptions.addOption(new Option("ca", "activation-color", false, "activation color scheme" ));
colorOptions.addOption(new Option("co", "omega-color", false, "omega color scheme" ));
options.addOptionGroup(colorOptions);
options.addOption(OptionBuilder.withLongOpt("rule")
.withDescription("rule number (required)")
.hasArg()
.withArgName("rule")
.create());
options.addOption(OptionBuilder.withLongOpt("width")
.withDescription("space width (required)")
.hasArg()
.withArgName("width")
.create());
options.addOption(OptionBuilder.withLongOpt("steps")
.withDescription("number of steps (required)")
.hasArg()
.withArgName("steps")
.create());
options.addOption(OptionBuilder.withLongOpt("alpha")
.withDescription("memory factor (default 0)")
.hasArg()
.withArgName("alpha")
.create());
options.addOption(OptionBuilder.withLongOpt("pattern")
.withDescription("inititial pattern")
.hasArg()
.withArgName("pattern")
.create());
options.addOption("s", "single-seed", false, "single cell seed" );
options.addOption("si", "single-seed-inverse", false, "all 1 except one cell" );
options.addOption(OptionBuilder.withLongOpt("update-patter")
.withDescription("update patter (valid values are " + UpdatePattern.validValues() + ")")
.hasArg()
.withArgName("updatepatter")
.create());
// test
// args = new String[]{ "--rule=10", "--steps=500" , "--width=60", "-P" , "-s" };
try {
// parse the command line arguments
CommandLine line = parser.parse( options, args );
if (!line.hasOption("rule"))
throw new ParseException("no rule number (use --rule=XX)");
int rule;
try {
rule = Integer.parseInt(line.getOptionValue("rule"));
if (rule < 0 || rule > 15)
throw new ParseException("invalid rule number");
} catch (NumberFormatException ex) {
throw new ParseException("invalid rule number");
}
if (!line.hasOption("width"))
throw new ParseException("no space width (use --width=XX)");
int width;
try {
width = Integer.parseInt(line.getOptionValue("width"));
if (width < 1)
throw new ParseException("invalid width");
} catch (NumberFormatException ex) {
throw new ParseException("invalid width");
}
if (!line.hasOption("steps"))
throw new ParseException("no number of steps (use --steps=XX)");
int steps;
try {
steps = Integer.parseInt(line.getOptionValue("steps"));
if (width < 1)
throw new ParseException("invalid number of steps");
} catch (NumberFormatException ex) {
throw new ParseException("invalid number of steps");
}
double alpha = 0;
if (line.hasOption("alpha")) {
try {
alpha = Double.parseDouble(line.getOptionValue("alpha"));
if (alpha < 0 || alpha > 1)
throw new ParseException("invalid alpha");
} catch (NumberFormatException ex) {
throw new ParseException("invalid alpha");
}
}
String pattern = null;
if (line.hasOption("pattern")) {
pattern = line.getOptionValue("pattern");
if (pattern != null)
pattern = pattern.trim();
}
if (line.hasOption("single-seed"))
pattern = "S";
else if (line.hasOption("single-seed-inverse"))
pattern = "SI";
UpdatePattern updatePatter = UpdatePattern.synchronous;
if (line.hasOption("update-patter")) {
try {
updatePatter = UpdatePattern.getUpdatePattern(line.getOptionValue("update-patter"));
} catch (IllegalArgumentException ex) {
throw new ParseException(ex.getMessage());
}
}
Boundaries boundaries = Boundaries.periodic;
if (line.hasOption("periodic"))
boundaries = Boundaries.periodic;
else if (line.hasOption("fixed"))
boundaries = Boundaries.fixed;
else if (line.hasOption("adiabatic"))
boundaries = Boundaries.adiabatic;
else if (line.hasOption("reflective"))
boundaries = Boundaries.reflective;
ColorScheme colorScheme = ColorScheme.noColor;
if (line.hasOption("black-white"))
colorScheme = ColorScheme.noColor;
else if (line.hasOption("activation-color"))
colorScheme = ColorScheme.activationColor;
else if (line.hasOption("omega-color"))
colorScheme = ColorScheme.omegaColor;
Output output = Output.all;
if (line.hasOption("suppress-output"))
output = Output.noOutput;
Main.drawRule(rule, width, boundaries, updatePatter, steps, alpha, pattern, output, colorScheme);
} catch(ParseException ex) {
System.err.println("Copyright (C) 2009 Andrea Bonomi - <andrea.bonomi@gmail.com>");
System.err.println();
System.err.println("https://github.com/andreax79/one-neighbor-binary-cellular-automata");
System.err.println();
System.err.println("This program is free software; you can redistribute it and/or modify it");
System.err.println("under the terms of the GNU General Public License as published by the");
System.err.println("Free Software Foundation; either version 2 of the License, or (at your");
System.err.println("option) any later version.");
System.err.println();
System.err.println("This program is distributed in the hope that it will be useful, but");
System.err.println("WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY");
System.err.println("or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License");
System.err.println("for more details.");
System.err.println();
System.err.println("You should have received a copy of the GNU General Public License along");
System.err.println("with this program; if not, write to the Free Software Foundation, Inc.,");
System.err.println("59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.)");
System.err.println();
System.err.println(ex.getMessage());
HelpFormatter formatter = new HelpFormatter();
formatter.printHelp("main", options);
} catch (IOException ex) {
System.err.println("IO exception:" + ex.getMessage());
}
}
}
| gpl-2.0 |
am1120/CarMechanic | webapp/src/java/utilities/CMRoles.java | 1157 | package utilities;
/**
* A class that contains user's roles
* @author Alexander
*/
public class CMRoles {
public static final int GUEST_USER = 0;
public static final String GUEST_DESCRIPTION = "Guest User";
public static final int SIMPLE_USER = 1;
public static final String SIMPLE_DESCRIPTION = "Simple User";
public static final int MODERATOR_USER = 2;
public static final String MODERATOR_DESCRIPTION = "Moderator User";
public static final int ADMINISTRATOR_USER = 3;
public static final String ADMINISTRATOR_DESCRIPTION = "Administrator User";
public static String getDescription(int role){
switch (role){
case GUEST_USER:
return GUEST_DESCRIPTION;
case SIMPLE_USER:
return SIMPLE_DESCRIPTION;
case MODERATOR_USER:
return MODERATOR_DESCRIPTION;
case ADMINISTRATOR_USER:
return ADMINISTRATOR_DESCRIPTION;
default:
return "Role not defined";
}
}
}
| gpl-2.0 |
zhoulifu/TProfiler | src/main/java/com/taobao/profile/config/ProfConfig.java | 12957 | /**
* (C) 2011-2012 Alibaba Group Holding Limited.
* <p>
* 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.
*/
package com.taobao.profile.config;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import com.taobao.profile.utils.VariableNotFoundException;
/**
* 读取并保存配置
*
* @author xiaodu
* @since 2010-6-22
*/
public class ProfConfig {
/**
* 配置文件名
*/
private static final String CONFIG_FILE_NAME = "profile.properties";
/**
* 默认的配置文件路径,~/.tprofiler/profile.properties
*/
private File DEFAULT_PROFILE_PATH = new File(System.getProperty("user.home"),
"/.tprofiler/" + CONFIG_FILE_NAME);
/**
* 开始profile时间
*/
private String startProfTime;
/**
* 结束profile时间
*/
private String endProfTime;
/**
* log文件路径
*/
private String logFilePath;
/**
* method文件路径
*/
private String methodFilePath;
/**
* sampler文件路径
*/
private String samplerFilePath;
/**
* 不包括的ClassLoader
*/
private String excludeClassLoader;
/**
* 包括的包名
*/
private String includePackageStartsWith;
/**
* 不包括的包名
*/
private String excludePackageStartsWith;
/**
* 每次profile用时
*/
private int eachProfUseTime = -1;
/**
* 两次profile间隔时间
*/
private int eachProfIntervalTime = -1;
/**
* 两次sampler间隔时间
*/
private int samplerIntervalTime = -1;
/**
* 是否用纳秒采集
*/
private boolean needNanoTime;
/**
* 是否忽略get/set方法
*/
private boolean ignoreGetSetMethod;
/**
* 是否进入调试模式
*/
private boolean debugMode;
/**
* Socket端口号配置
*/
private int port;
/**
* 构造方法
*/
public ProfConfig() {
//此时配置文件中的debug参数还未读取,因此使用-Dtprofiler.debug=true来读取,用于开发时调试
boolean debug = "true".equalsIgnoreCase(System.getProperty("tprofiler.debug"));
/*
* 查找顺序:
* 1. 系统参数-Dprofile.properties=/path/profile.properties
* 2. 当前文件夹下的profile.properties
* 3. 用户文件夹~/.tprofiler/profile.properties,如:/home/manlge/.tprofiler/profile
* .properties
* 4. 默认jar包中的profile.properties
*/
String specifiedConfigFileName = System.getProperty(CONFIG_FILE_NAME);
File configFiles[] = {
specifiedConfigFileName == null ? null : new File(
specifiedConfigFileName),
new File(CONFIG_FILE_NAME),
DEFAULT_PROFILE_PATH
};
for (File file : configFiles) {
if (file != null && file.exists() && file.isFile()) {
if (debug) {
System.out.println(String.format("load configuration from \"%s\".",
file.getAbsolutePath()));
}
parseProperty(file);
return;
}
}
//加载默认配置
if (debug) {
System.out.println(String.format("load configuration from \"%s\".",
DEFAULT_PROFILE_PATH.getAbsolutePath()));
}
try {
extractDefaultProfile();
parseProperty(DEFAULT_PROFILE_PATH);
} catch (IOException e) {
throw new RuntimeException("error load config file " + DEFAULT_PROFILE_PATH,
e);
}
}
/**
* 解压默认的配置文件到~/.tprofiler/profile.properties,作为模板,以便用户编辑
* @throws IOException
*/
private void extractDefaultProfile() throws IOException {
/*
* 这里采用stream进行复制,而不是采用properties.load和save,主要原因为以下2点:
* 1. 性能,stream直接复制快,没有properties解析过程(不过文件较小,解析开销可以忽略)
* 2. properties会造成注释丢失,该文件作为模板提供给用户,包含注释信息
*/
InputStream in = new BufferedInputStream(
getClass().getClassLoader().getResourceAsStream(CONFIG_FILE_NAME));
OutputStream out = null;
try {
File profileDirectory = DEFAULT_PROFILE_PATH.getParentFile();
if (!profileDirectory.exists()) {
profileDirectory.mkdirs();
}
out = new BufferedOutputStream(new FileOutputStream(DEFAULT_PROFILE_PATH));
byte[] buffer = new byte[1024];
for (int len = -1; (len = in.read(buffer)) != -1; ) {
out.write(buffer, 0, len);
}
} finally {
in.close();
out.close();
}
}
/**
* 解析用户自定义配置文件
* @param path
*/
private void parseProperty(File path) {
Properties properties = new Properties();
try {
properties.load(new FileReader(path)); //配置文件原始内容,未进行变量替换
//变量查找上下文,采用System.properties和配置文件集合
Properties context = new Properties();
context.putAll(System.getProperties());
context.putAll(properties);
//加载配置
loadConfig(new ConfigureProperties(properties, context));
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 加载配置
* @param properties
*/
private void loadConfig(Properties properties) throws VariableNotFoundException {
String startProfTime = properties.getProperty("startProfTime");
String endProfTime = properties.getProperty("endProfTime");
String logFilePath = properties.getProperty("logFilePath");
String methodFilePath = properties.getProperty("methodFilePath");
String samplerFilePath = properties.getProperty("samplerFilePath");
String includePackageStartsWith = properties.getProperty(
"includePackageStartsWith");
String eachProfUseTime = properties.getProperty("eachProfUseTime");
String eachProfIntervalTime = properties.getProperty("eachProfIntervalTime");
String samplerIntervalTime = properties.getProperty("samplerIntervalTime");
String excludePackageStartsWith = properties.getProperty(
"excludePackageStartsWith");
String needNanoTime = properties.getProperty("needNanoTime");
String ignoreGetSetMethod = properties.getProperty("ignoreGetSetMethod");
String excludeClassLoader = properties.getProperty("excludeClassLoader");
String debugMode = properties.getProperty("debugMode");
String port = properties.getProperty("port");
setPort(port == null ? 50000 : Integer.valueOf(port));
setDebugMode(
"true".equalsIgnoreCase(debugMode == null ? null : debugMode.trim()));
setExcludeClassLoader(excludeClassLoader);
setExcludePackageStartsWith(excludePackageStartsWith);
setEndProfTime(endProfTime);
setIncludePackageStartsWith(includePackageStartsWith);
setLogFilePath(logFilePath);
setMethodFilePath(methodFilePath);
setSamplerFilePath(samplerFilePath);
setStartProfTime(startProfTime);
setNeedNanoTime("true".equals(needNanoTime));
setIgnoreGetSetMethod("true".equals(ignoreGetSetMethod));
if (eachProfUseTime == null) {
setEachProfUseTime(5);
} else {
setEachProfUseTime(Integer.valueOf(eachProfUseTime.trim()));
}
if (eachProfIntervalTime == null) {
setEachProfIntervalTime(50);
} else {
setEachProfIntervalTime(Integer.valueOf(eachProfIntervalTime.trim()));
}
if (samplerIntervalTime == null) {
setSamplerIntervalTime(10);
} else {
setSamplerIntervalTime(Integer.valueOf(samplerIntervalTime.trim()));
}
}
/**
* @return
*/
public String getStartProfTime() {
return startProfTime;
}
/**
* @param startProfTime
*/
public void setStartProfTime(String startProfTime) {
this.startProfTime = startProfTime;
}
/**
* @return
*/
public String getEndProfTime() {
return endProfTime;
}
/**
* @param endProfTime
*/
public void setEndProfTime(String endProfTime) {
this.endProfTime = endProfTime;
}
/**
* @return
*/
public String getLogFilePath() {
return logFilePath;
}
/**
* @param logFilePath
*/
public void setLogFilePath(String logFilePath) {
this.logFilePath = logFilePath;
}
/**
* @return the methodFilePath
*/
public String getMethodFilePath() {
return methodFilePath;
}
/**
* @param methodFilePath
* the methodFilePath to set
*/
public void setMethodFilePath(String methodFilePath) {
this.methodFilePath = methodFilePath;
}
/**
* @return
*/
public String getIncludePackageStartsWith() {
return includePackageStartsWith;
}
/**
* @param includePackageStartsWith
*/
public void setIncludePackageStartsWith(String includePackageStartsWith) {
this.includePackageStartsWith = includePackageStartsWith;
}
/**
* @return
*/
public int getEachProfUseTime() {
return eachProfUseTime;
}
/**
* @param eachProfUseTime
*/
public void setEachProfUseTime(int eachProfUseTime) {
this.eachProfUseTime = eachProfUseTime;
}
/**
* @return
*/
public int getEachProfIntervalTime() {
return eachProfIntervalTime;
}
/**
* @param eachProfIntervalTime
*/
public void setEachProfIntervalTime(int eachProfIntervalTime) {
this.eachProfIntervalTime = eachProfIntervalTime;
}
/**
* @return
*/
public String getExcludePackageStartsWith() {
return excludePackageStartsWith;
}
/**
* @param excludePackageStartsWith
*/
public void setExcludePackageStartsWith(String excludePackageStartsWith) {
this.excludePackageStartsWith = excludePackageStartsWith;
}
/**
* @return
*/
public boolean isNeedNanoTime() {
return needNanoTime;
}
/**
* @param needNanoTime
*/
public void setNeedNanoTime(boolean needNanoTime) {
this.needNanoTime = needNanoTime;
}
/**
* @return
*/
public boolean isIgnoreGetSetMethod() {
return ignoreGetSetMethod;
}
/**
* @param ignoreGetSetMethod
*/
public void setIgnoreGetSetMethod(boolean ignoreGetSetMethod) {
this.ignoreGetSetMethod = ignoreGetSetMethod;
}
/**
* @return the samplerFilePath
*/
public String getSamplerFilePath() {
return samplerFilePath;
}
/**
* @param samplerFilePath
* the samplerFilePath to set
*/
public void setSamplerFilePath(String samplerFilePath) {
this.samplerFilePath = samplerFilePath;
}
/**
* @return the samplerIntervalTime
*/
public int getSamplerIntervalTime() {
return samplerIntervalTime;
}
/**
* @param samplerIntervalTime
* the samplerIntervalTime to set
*/
public void setSamplerIntervalTime(int samplerIntervalTime) {
this.samplerIntervalTime = samplerIntervalTime;
}
/**
* @return the excludeClassLoader
*/
public String getExcludeClassLoader() {
return excludeClassLoader;
}
/**
* @param excludeClassLoader the excludeClassLoader to set
*/
public void setExcludeClassLoader(String excludeClassLoader) {
this.excludeClassLoader = excludeClassLoader;
}
/**
* @return the debugMode
*/
public boolean isDebugMode() {
return debugMode;
}
/**
* @param debugMode the debugMode to set
*/
public void setDebugMode(boolean debugMode) {
this.debugMode = debugMode;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
}
| gpl-2.0 |
doombubbles/metastonething | game/src/main/java/net/demilich/metastone/game/events/AttributeGainedEvent.java | 730 | package net.demilich.metastone.game.events;
import net.demilich.metastone.game.Attribute;
import net.demilich.metastone.game.GameContext;
import net.demilich.metastone.game.entities.Entity;
public class AttributeGainedEvent extends GameEvent {
private final Entity target;
private final Attribute attribute;
public AttributeGainedEvent(GameContext context, Entity target, Attribute attribute) {
super(context, target.getOwner(), -1);
this.target = target;
this.attribute = attribute;
}
@Override
public Entity getEventTarget() {
return target;
}
public Attribute getEventAttribute() {
return attribute;
}
@Override
public GameEventType getEventType() {
return GameEventType.ATTRIBUTE_GAINED;
}
}
| gpl-2.0 |
guanghaofan/MyTSP | 2.1.1.2/CPGTSP/src/com/BinResultConsumer.java | 22629 | package com;
/***************************************************************************
* (c) Copyright 2003 NPTest, Inc. *
* This computer program includes Confidential, Proprietary Information *
* and is a trade secret of NPTest. All use, disclosure, and/or *
* reproduction is prohibited unless authorized in writing by an officer *
* of NPTest. All Rights Reserved. *
***************************************************************************/
/**
* @file BinResultConsumer.java
* Contains all classes related binning data (soft, hard) handling management.
*/
import java.util.Iterator;
import java.util.Vector;
import managers.CapAreaManager;
import org.omg.CORBA.ORBPackage.InvalidName;
import org.omg.PortableServer.POA;
import org.omg.PortableServer.POAManagerPackage.AdapterInactive;
import org.omg.CORBA.ORB;
import Sapphire.CAP.CapArea;
import Sapphire.CAP.CommonAccessPort;
import Sapphire.CAP.ResultManager;
import SapphireTsp.CoreTsp;
import SapphireTsp.TspRuntimeException;
/**
* @class BinResultConsumer
* This class also provide basic methods to get bin results.
* Acitivate anad deactivate methods are dedicated to the registration and
* unregistration to flow:device information of the result consumer.
* This class extends the CORBA POA server dedicated to result consumers.
*/
public class BinResultConsumer extends Sapphire.CAP.ResultConsumerPOA
{
/**
* @name Private Members
*/
//@{
/// Internal class storage of the received sites.
protected boolean _receivedSites[] = null;
/// Handle to the CORBA activated object
protected byte[] _id = null;
/// Internal class storage of the hard bin information
public String _hardBinId[] = null;
/// Internal class storage of the soft bin information
public String _softBinId[] = null;
/// Internal class storage of the hard bin name information
public String _hardBinName[] = null;
/// Internal class storage of the soft bin name information
public String _softBinName[] = null;
public String _softBinDesc[] = null;
public String _hardBinDesc[] = null;
/// Internal class storage of the unit id information
public String _unitId[] = null;
protected static Vector simSiteVector = new Vector();
/// Internal class storage of the PASS/FAIL result information
protected int _binResult[] = null;
// 14225 ResultHelper used to expand compactData into the normal ResultElement
ResultHelper _resultHelper = null;
protected boolean simulationMode;
protected int simulationSiteCnt;
protected boolean debugFlag = false;
String[] TSPAction={null,null};
ResultManager rmMgr = null;
POA portableObjectAdapter = null;
CapArea tpMgr = null;
//@}
//---------------------------------------------------------------------------
/**
* Initialize the result consumer.
* - Clean hard and soft bin storage
* - Executed Site Mask is stored.
* - Received Site Mask is cleared.
*
* @exception TspRuntimeException thrown when Runtime or Corba error
*/
//---------------------------------------------------------------------------
public BinResultConsumer(boolean simMode,int simSiteNum) throws TspRuntimeException
{
try {
// Allocate the binning arrays
int nSites;
simulationMode = simMode;
if (!simMode)
{
CapAreaManager capAreaManager = CapAreaManager.instance();
tpMgr = capAreaManager.testProgram();
CapArea loadedSiteMask = tpMgr.getObject("LoadedSiteMask");
nSites = loadedSiteMask.getL("Size");
loadedSiteMask.cleanUp();
}
else {
nSites = simSiteNum;
simulationSiteCnt = simSiteNum;
}
_hardBinId = new String[nSites];
_softBinId = new String[nSites];
_hardBinName = new String[nSites];
_softBinName = new String[nSites];
_softBinDesc= new String[nSites];
_hardBinDesc= new String[nSites];
_unitId = new String[nSites];
_binResult = new int[nSites];
_resultHelper = new ResultHelper();
// Store received Site boolean marker
_receivedSites = new boolean[nSites];
if (!simMode)
activate();
}
catch (Sapphire.lib.error.Fatal f) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(f.msg);
System.err.println(f.where);
System.err.println(f.getMessage());
f.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (Sapphire.lib.error.Basic e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
}
/*
* Needs to be run prior to recieveing new data.
*/
public void clean() throws TspRuntimeException
{
try {
int nSites;
if (simulationMode) {
nSites = simulationSiteCnt;
}
else {
CapArea loadedSiteMask = tpMgr.getObject("LoadedSiteMask");
nSites = loadedSiteMask.getL("Size");
loadedSiteMask.cleanUp();
}
_hardBinId = new String[nSites];
_softBinId = new String[nSites];
_hardBinName = new String[nSites];
_softBinName = new String[nSites];
_softBinDesc= new String[nSites];
_hardBinDesc= new String[nSites];
_unitId = new String[nSites];
_binResult = new int[nSites];
_resultHelper = new ResultHelper();
// Store received Site boolean marker
_receivedSites = new boolean[nSites];
}
catch (Sapphire.lib.error.Fatal f) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(f.msg);
System.err.println(f.where);
System.err.println(f.getMessage());
f.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (Sapphire.lib.error.Basic e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
}
//---------------------------------------------------------------------------
/**
* Activate (register) the result consumer.
*
* @exception TspRuntimeException thrown when Runtime or Corba error
*/
//---------------------------------------------------------------------------
public void activate() throws TspRuntimeException
{
try {
// Activate the Result Consumer
CapAreaManager capAreaManager = CapAreaManager.instance();
CommonAccessPort cap = (CommonAccessPort) capAreaManager.capInterface();;
ORB orb = org.omg.CORBA.ORB.init(new String[0], null);
org.omg.CORBA.Object obj = orb.resolve_initial_references("RootPOA");
// create POA <equivalent to narrow() but typecast is used here>
portableObjectAdapter = (POA) obj;
_id = portableObjectAdapter.activate_object(this);
org.omg.PortableServer.POAManager poaMgr = portableObjectAdapter.the_POAManager();
poaMgr.activate();
// Subscribe Result Consumer to flow.Device information
rmMgr = cap.getResultManager();
//*NL* get the handle of resultManager from runtime instance
// *NL* pass the servant_locator of servant BinResultConsumer
rmMgr.subscribe("FlowResult:NODE:DEVICE:flow.Device", _this(), "*", "*", true);
rmMgr.subscribe("TestResult:Test", _this(), "ReadFuncFuse", "*", true);
}
catch (AdapterInactive e)
{
System.err.println("POA is inactive. This is a CORBA communication related issue.");
throw new TspRuntimeException("Internal DataPackage Setup Error.");
}
catch (org.omg.PortableServer.POAPackage.ServantAlreadyActive e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (org.omg.PortableServer.POAPackage.WrongPolicy e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (Sapphire.lib.error.Basic e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (Sapphire.lib.error.Fatal e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (InvalidName e){
CoreTsp.out("A CORBA exception occurred induced by the TSP.");
throw new TspRuntimeException(e);
}
}
//---------------------------------------------------------------------------
/**
* Deactivate (unregister) the result consumer.
*
* @exception TspRuntimeException thrown when Runtime or Corba error
*/
//---------------------------------------------------------------------------
public void deactivate() throws TspRuntimeException
{
try {
//rMgr.unsubscribe("*:flow.Device", _this(), "*", "*"); //1415
rmMgr.unsubscribe("FlowResult:NODE:DEVICE:flow.Device", _this(), "*", "*");
rmMgr.unsubscribe("TestResult:Test", _this(), "ReadFuncFuse", "*");
// Deactivate the Result Consumer
portableObjectAdapter.deactivate_object(_id);
}
catch (org.omg.PortableServer.POAPackage.ObjectNotActive e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (org.omg.PortableServer.POAPackage.WrongPolicy e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (Sapphire.lib.error.Basic e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
catch (Sapphire.lib.error.Fatal e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
throw new TspRuntimeException("Result Error");
}
}
//---------------------------------------------------------------------------
/**
* Get the Hard Bin Id
*/
//---------------------------------------------------------------------------
public String[] hardBinId()
{
return _hardBinId;
}
//---------------------------------------------------------------------------
/**
* Get the Hard Bin Name
*/
//---------------------------------------------------------------------------
public String[] hardBinName()
{
return _hardBinName;
}
//---------------------------------------------------------------------------
/**
* Get the Hard BinDesc
*/
//---------------------------------------------------------------------------
public String[] hardBinDesc()
{
return _hardBinDesc;
}
//---------------------------------------------------------------------------
/**
* Get the Soft Bin Id
*/
//---------------------------------------------------------------------------
public String[] softBinId()
{
return _softBinId;
}
//---------------------------------------------------------------------------
/**
* Get the Soft Bin Name
*/
//---------------------------------------------------------------------------
public String[] softBinName()
{
return _softBinName;
}
//---------------------------------------------------------------------------
/**
* Get the Soft Bin Desc
*/
//---------------------------------------------------------------------------
public String[] softBinDesc()
{
return _softBinDesc;
}
//---------------------------------------------------------------------------
/**
* Get the Unit Id
*/
//---------------------------------------------------------------------------
public String[] unitId()
{
return _unitId;
}
//---------------------------------------------------------------------------
/**
* Get the PASS/FAIL result
*/
//---------------------------------------------------------------------------
public int[] binResult()
{
return _binResult;
}
public static void markSimulatedExecutedSite(int site)
{
if(simSiteVector != null)
{
simSiteVector.add(new Integer(site));
} else {
CoreTsp.out("Nothing Executed");
}
}
//---------------------------------------------------------------------------
/**
* Get the Done flag (true if all sites received)
*/
//---------------------------------------------------------------------------
public boolean isDone()
{
boolean areIdentical = true;
boolean executedSites[];
// Get executed Site array marker
if (simulationMode)
{
executedSites = new boolean[simulationSiteCnt];
for (int i = 0; i<simulationSiteCnt;i++)
executedSites[i] = false;
Iterator itr = simSiteVector.iterator();
while(itr.hasNext())
executedSites[((Integer)itr.next()).intValue()] = true;
}
else {
try {
Sapphire.CAP.CapArea loadedSiteMask = tpMgr.getObject("LoadedSiteMask");
int nSites = loadedSiteMask.getL("Size");
loadedSiteMask.cleanUp();
executedSites = new boolean[nSites];
Sapphire.CAP.CapArea siteMask = tpMgr.getObject("ExecutedSiteMask");
Sapphire.CAP.CapArea siteMaskItr = null;
siteMaskItr = siteMask.getArea("Iterator");
while (siteMaskItr.hasNext()) {
int site = siteMaskItr.getL("Next");
executedSites[site] = true;
}
siteMaskItr.cleanUp();
siteMask.cleanUp();
}
catch (Sapphire.lib.error.Basic e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
return false;
}
catch (Sapphire.lib.error.Fatal e) {
// Print the exception, the stack and rethrow as TspRuntimeException
System.err.println(e.msg);
System.err.println(e.where);
System.err.println(e.getMessage());
e.printStackTrace(System.err);
return false;
}
}
// Compare executed sites and received sites
for (int i = 0; i < _receivedSites.length; i++) {
if (executedSites[i] != _receivedSites[i]) {
areIdentical = false;
}
}
return areIdentical;
}
//---------------------------------------------------------------------------
/**
* Implement the handleResult() to be called by updateResult()
*/
//---------------------------------------------------------------------------
public void handleResult(Sapphire.CAP.ResultData resultData)
{
for (int idx = 0; idx < resultData.site.length; ++idx) {
int iSite = resultData.site[idx];
if (resultData.element.elements == null) {
continue;
}
Sapphire.CAP.ResultElement elmts[] = resultData.element.elements;
for (int i = 0; i < elmts.length; i++) {
Sapphire.CAP.ResultElement elmt = elmts[i];
// Hard Bin Id stored into 'HardBinId' tag
if (elmt.name.equals("HardBinId"))
_hardBinId[iSite] = elmt.value.extract_string();
else if (elmt.name.equals("HardBinName"))
_hardBinName[iSite] = elmt.value.extract_string();
else if (elmt.name.equals("SoftBinId"))
_softBinId[iSite] = elmt.value.extract_string();
else if (elmt.name.equals("SoftBinName"))
_softBinName[iSite] = elmt.value.extract_string();
else if (elmt.name.equals("SoftBinDesc"))
_softBinDesc[iSite] = elmt.value.extract_string();
else if (elmt.name.equals("HardBinDesc"))
_hardBinDesc[iSite] = elmt.value.extract_string();
else if (elmt.name.equals("DeviceDescription"))
_unitId[iSite] = elmt.value.extract_string();
else if (elmt.name.equals("TestDecision"))
if (elmt.value.extract_string().equals("Pass"))
_binResult[iSite] = 1;
else
_binResult[iSite] = 0;
}
// Mark the received site
_receivedSites[iSite] = true;
}
}
/* //added function to get unit ID using PUSH method
public void retrieveUnitId (Sapphire.CAP.ResultData resultData){
//System.out.print("resultData object" + resultData);
//CoreTsp.out("resultData object" + resultData);
if(_IsSerialNumberObject(resultData) == true){
for (int idx = 0; idx < resultData.site.length; ++idx){
if (resultData.element.elements == null){
continue;
}
int iSite = resultData.site[idx];
if(_receivedSites[iSite] == false){
Sapphire.CAP.ResultElement elmts[] = resultData.element.elements;
for (int i = 0; i < elmts.length; i++){
Sapphire.CAP.ResultElement elmt = elmts[i];
String FieldName = elmt.name;
if(_isSerialNumberField(FieldName) == true){
//added to retrieve unit id
//System.out.println("Element Val" + elmt.value.extract_string());
//CoreTsp.out("Element Val" + elmt.value.extract_string());
_unitId[iSite] = elmt.value.extract_string();
//Mark the received site
_receivedSites[iSite] = true;
break;
}
}
}
}
}
}
*/
private boolean _IsSerialNumberObject(Sapphire.CAP.ResultData resultData){
if (resultData.element != null){
String Name = resultData.element.name;
if(Name.equals("FuseRecord"))
return true;
else if(Name.equals("JTAG_FUNCFUSE"))
return true;
else if(Name.equals("JTAG_FUNCFUSE_SH_F"))
return true;
else if(Name.equals("JTAG_FUNCFUSE_SH_E"))
return true;
else if(Name.equals("JTAG_FUNCFUSE_JH_E"))
return true;
}
return false;
}
public boolean _isSerialNumberField (String FieldName){
String [] SerialNumberFieldNames = {
"FuseBitValues",
"DieFuseBitValues",
"SerialNum",
"FuseBits",
"funcfuse",
"redundfuse",
"RedundFuse",
"RedundFuseCore1",
"RedundFuseCore1_ProgFuseBits",
"ReadRedundFuseCore0",
"ProgramRRDFuseCore0",
"RedundFuse_VerifyBits",
"RedundFuseCore1_VerifyBits",
"FuncFuse",
"FuncFuse_VerifyBits",
"funcfuse_VerifyBits",
"fusereg_ProgFuseBits",
"funcfuse_ProgFuseBits",
"redundfuse_ProgFuseBits",
"RMW_ProgFuseBits",
"RMW_VerifyBits"
};
boolean RetValue = false;
for (int idx = 0; idx < SerialNumberFieldNames.length; ++idx){
if(SerialNumberFieldNames[idx].equals(FieldName)){
RetValue = true;
break;
}
}
return RetValue;
}
/* Implement the pure virtual updateResult() call back method
*/
//---------------------------------------------------------------------------
public void updateResult(Sapphire.CAP.ResultData result)
{
// Extract element: Only interested in POP_ELEMENT
// Skip PUSH ELEMENT
// Skip POP_TO_ELEMENT
// Skip ADD_ELEMENT
if (result.elementContext == Sapphire.CAP.ResultContext.POP_ELEMENT
||
result.elementContext == Sapphire.CAP.ResultContext.POP_TO_ELEMENT
) {
if (result.compactData != null && result.compactData.length() > 0) {
Sapphire.CAP.ResultData resultData = new Sapphire.CAP.ResultData();
resultData.type = result.type;
resultData.elementContext = result.elementContext;
resultData.flowContext = result.flowContext;
resultData.site = result.site;
resultData.element = new Sapphire.CAP.ResultElement();
try {
_resultHelper.reset();
while (_resultHelper.expandElement(result.compactData,resultData.element)) {
handleResult(resultData);
}
} catch (TspRuntimeException e) {
CoreTsp.out("BinResultConsumer::" + e.getMessage());
e.printStackTrace();
}
} else {
handleResult(result);
}
}
/* //added to retrive Unit Id
if (result.elementContext == Sapphire.CAP.ResultContext.ADD_ELEMENT){
if (result.compactData != null && result.compactData.length() > 0) {
Sapphire.CAP.ResultData resultData = new Sapphire.CAP.ResultData();
resultData.type = result.type;
resultData.elementContext = result.elementContext;
resultData.flowContext = result.flowContext;
resultData.site = result.site;
resultData.element = new Sapphire.CAP.ResultElement();
try {
_resultHelper.reset();
while (_resultHelper.expandElement(result.compactData,resultData.element)) {
retrieveUnitId(resultData);
}
} catch (TspRuntimeException e) {
CoreTsp.out("BinResultConsumer::" + e.getMessage());
e.printStackTrace();
}
} else{
retrieveUnitId(result);
}
}*/
}
//---------------------------------------------------------------------------
/**
* Implement the pure virtual quit() call back method
*/
//---------------------------------------------------------------------------
public void quit (boolean shutdown)
{
}
/**
* Emulates the functionality of the loadsitemask, which we cannot use
* in simulation mode. Therefore, this method should only be called
* while in simulation mode.
*/
public static void setSiteExecuted(int site){
simSiteVector.add(new Integer(site));
}
} | gpl-2.0 |
dlitz/resin | modules/resin/src/com/caucho/ejb/session/StatefulComponent.java | 2418 | /*
* Copyright (c) 1998-2011 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Scott Ferguson
*/
package com.caucho.ejb.session;
import com.caucho.config.inject.InjectManager;
import com.caucho.config.xml.XmlConfigContext;
import java.lang.annotation.*;
import java.util.Set;
import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.AnnotatedType;
import javax.enterprise.inject.spi.InjectionPoint;
import javax.enterprise.inject.spi.InjectionTarget;
/**
* Component for session beans
*/
public class StatefulComponent<X> implements InjectionTarget<X> {
private final StatefulProvider _provider;
private final Class _beanClass;
public StatefulComponent(StatefulProvider provider,
Class beanClass)
{
_provider = provider;
_beanClass = beanClass;
}
/**
* Creates a new instance of the component
*/
public X produce(CreationalContext<X> env)
{
return (X) _provider.__caucho_createNew(this, env);
}
/**
* Inject the bean.
*/
public void inject(X instance, CreationalContext<X> ctx)
{
}
/**
* PostConstruct initialization
*/
public void postConstruct(X instance)
{
}
/**
* Call pre-destroy
*/
public void dispose(X instance)
{
}
/**
* Call destroy
*/
public void preDestroy(X instance)
{
}
/**
* Returns the injection points.
*/
public Set<InjectionPoint> getInjectionPoints()
{
return null;
}
}
| gpl-2.0 |
m-31/qedeq | QedeqKernelBo/src/org/qedeq/kernel/bo/service/basis/ModuleServiceExecutor.java | 1198 | /* This file is part of the project "Hilbert II" - http://www.qedeq.org
*
* Copyright 2000-2014, Michael Meyling <mime@qedeq.org>.
*
* "Hilbert II" 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.
*/
package org.qedeq.kernel.bo.service.basis;
import org.qedeq.kernel.bo.module.InternalModuleServiceCall;
import org.qedeq.kernel.se.visitor.InterruptException;
/**
* Represents a service execution.
*
* @author Michael Meyling
*/
public interface ModuleServiceExecutor {
/**
* Execute service.
*
* @param call Parameters for service call and current execution status.
* @throws InterruptException User canceled call.
*/
public void executeService(InternalModuleServiceCall call) throws InterruptException;
}
| gpl-2.0 |
sadybr/UtilFrame | UtilFrame/src/sady/utilframe/bdControl/FullDBObject.java | 1296 | package sady.utilframe.bdControl;
import java.util.List;
import java.util.Set;
import sady.utilframe.bdControl.configuration.ColumnConfiguration;
import sady.utilframe.bdControl.configuration.FKConfiguration;
import sady.utilframe.bdControl.configuration.TableConfiguration;
public abstract class FullDBObject extends DBObject {
@Override
public List<String> getColumnNames() {
return super.getColumnNames();
}
@Override
public ColumnConfiguration getConfiguration(String columnName) {
return super.getConfiguration(columnName);
}
@Override
public List<List<FKConfiguration>> getFKs() {
return super.getFKs();
}
@Override
public List<List<FKConfiguration>> getReverseFKs() {
return super.getReverseFKs();
}
@Override
public TableConfiguration getTableConfiguration() {
return super.getTableConfiguration();
}
@Override
public Set<String> getUpdatedValues() {
return super.getUpdatedValues();
}
@Override
public boolean hasChanged() {
return super.hasChanged();
}
@Override
public FKConfiguration getFKConfiguration(String columnName) {
return super.getFKConfiguration(columnName);
}
@Override
public boolean isFK(String columnName) {
return super.isFK(columnName);
}
@Override
public List<String> getPKs() {
return super.getPKs();
}
}
| gpl-2.0 |
soniyj/basement | src/Java/maven/demo/src/main/java/com/example/Greeting2.java | 660 | package com.example;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class Greeting2 {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
@RequestMapping("/greeting2")
public MyGret greeting(@RequestParam(value="name", defaultValue="World") String name) {
return new MyGret(counter.incrementAndGet(),
String.format(template, name));
}
} | gpl-2.0 |
hchapman/libpulse-android | src/main/java/com/harrcharr/pulse/JNIUtil.java | 102 | package com.harrcharr.pulse;
class JNIUtil {
public static native void deleteGlobalRef(long ref);
}
| gpl-2.0 |
rafaelkalan/metastone | src/main/java/net/demilich/metastone/game/actions/ActionType.java | 161 | package net.demilich.metastone.game.actions;
public enum ActionType {
SYSTEM, END_TURN, PHYSICAL_ATTACK, SPELL, SUMMON, HERO_POWER, BATTLECRY, EQUIP_WEAPON,
}
| gpl-2.0 |
openthinclient/openthinclient-manager | console-web/webapp/src/main/java/org/openthinclient/web/ui/LoginUI.java | 5939 | package org.openthinclient.web.ui;
import static org.openthinclient.web.i18n.ConsoleWebMessages.UI_LOGIN_LOGIN;
import static org.openthinclient.web.i18n.ConsoleWebMessages.UI_LOGIN_PASSWORD;
import static org.openthinclient.web.i18n.ConsoleWebMessages.UI_LOGIN_REMEMBERME;
import static org.openthinclient.web.i18n.ConsoleWebMessages.UI_LOGIN_USERNAME;
import static org.openthinclient.web.i18n.ConsoleWebMessages.UI_LOGIN_WELCOME;
import ch.qos.cal10n.IMessageConveyor;
import ch.qos.cal10n.MessageConveyor;
import com.vaadin.annotations.Theme;
import com.vaadin.event.ShortcutAction.KeyCode;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.Responsive;
import com.vaadin.server.VaadinRequest;
import com.vaadin.spring.annotation.SpringUI;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.PasswordField;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.ValoTheme;
import org.openthinclient.i18n.LocaleUtil;
import org.openthinclient.web.i18n.ConsoleWebMessages;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.CommunicationException;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.vaadin.spring.security.shared.VaadinSharedSecurity;
/**
* LoginUI
*/
@SpringUI(path = "/login")
@Theme("openthinclient")
public class LoginUI extends UI {
private static final Logger LOGGER = LoggerFactory.getLogger(LoginUI.class);
@Autowired
VaadinSharedSecurity vaadinSecurity;
private IMessageConveyor mc;
private CheckBox rememberMe;
@Override
protected void init(VaadinRequest request) {
setLocale(LocaleUtil.getLocaleForMessages(ConsoleWebMessages.class, UI.getCurrent().getLocale()));
mc = new MessageConveyor(UI.getCurrent().getLocale());
Component loginForm = buildLoginForm();
VerticalLayout rootLayout = new VerticalLayout(loginForm);
rootLayout.setSizeFull();
rootLayout.setComponentAlignment(loginForm, Alignment.MIDDLE_CENTER);
setContent(rootLayout);
setSizeFull();
}
private Component buildLoginForm() {
final VerticalLayout loginPanel = new VerticalLayout();
loginPanel.setSizeUndefined();
Responsive.makeResponsive(loginPanel);
loginPanel.addStyleName("login-panel");
loginPanel.addComponent(buildLabels());
Label loginFailed = new Label();
loginFailed.setStyleName("login-failed");
loginFailed.setVisible(false);
loginPanel.addComponents(loginFailed);
HorizontalLayout fields = new HorizontalLayout();
fields.setSpacing(true);
fields.addStyleName("fields");
final TextField username = new TextField(mc.getMessage(UI_LOGIN_USERNAME));
username.setIcon(FontAwesome.USER);
username.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);
final PasswordField password = new PasswordField(mc.getMessage(UI_LOGIN_PASSWORD));
password.setIcon(FontAwesome.LOCK);
password.addStyleName(ValoTheme.TEXTFIELD_INLINE_ICON);
final Button signin = new Button(mc.getMessage(UI_LOGIN_LOGIN));
signin.addStyleName(ValoTheme.BUTTON_PRIMARY);
signin.setClickShortcut(KeyCode.ENTER);
signin.focus();
signin.addClickListener(event -> {
final IMessageConveyor mc = new MessageConveyor(UI.getCurrent().getLocale());
try {
final Authentication authentication = vaadinSecurity.login(username.getValue(), password.getValue(), rememberMe.getValue());
LOGGER.debug("Received UserLoginRequestedEvent for ", authentication.getPrincipal());
} catch (AuthenticationException | AccessDeniedException ex) {
loginFailed.getParent().addStyleName("failed");
if (ex.getCause() instanceof CommunicationException) {
loginFailed.setValue(mc.getMessage(ConsoleWebMessages.UI_DASHBOARDUI_LOGIN_COMMUNICATION_EXCEPTION));
} else {
loginFailed.setValue(mc.getMessage(ConsoleWebMessages.UI_DASHBOARDUI_LOGIN_FAILED));
}
loginFailed.setVisible(true);
} catch (Exception ex) {
loginFailed.getParent().getParent().addStyleName("error");
loginFailed.setValue(mc.getMessage(ConsoleWebMessages.UI_DASHBOARDUI_LOGIN_UNEXPECTED_ERROR));
loginFailed.setVisible(true);
LOGGER.error("Unexpected error while logging in", ex);
}
});
fields.addComponents(username, password, signin);
fields.setComponentAlignment(signin, Alignment.BOTTOM_LEFT);
loginPanel.addComponent(fields);
loginPanel.addComponent(rememberMe = new CheckBox(mc.getMessage(UI_LOGIN_REMEMBERME), false));
return loginPanel;
}
private Component buildLabels() {
CssLayout labels = new CssLayout();
labels.addStyleName("labels");
Label welcome = new Label(mc.getMessage(UI_LOGIN_WELCOME));
welcome.setSizeUndefined();
welcome.addStyleName(ValoTheme.LABEL_H4);
welcome.addStyleName(ValoTheme.LABEL_COLORED);
labels.addComponent(welcome);
Label title = new Label("openthinclient.org");
title.setSizeUndefined();
title.addStyleName(ValoTheme.LABEL_H3);
title.addStyleName(ValoTheme.LABEL_LIGHT);
labels.addComponent(title);
return labels;
}
}
| gpl-2.0 |
BarrySW19/CalculonX | src/test/java/barrysw19/calculon/analyzer/KingSafetyScorerTest.java | 1728 | /**
* Calculon - A Java chess-engine.
*
* Copyright (C) 2008-2009 Barry Smith
*
* 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 barrysw19.calculon.analyzer;
import org.junit.Test;
import javax.imageio.ImageIO;
import java.util.Arrays;
public class KingSafetyScorerTest extends AbstractAnalyserTest {
public KingSafetyScorerTest() {
super(new KingSafetyScorer());
}
@Test
public void testStart() {
assertScore(0, "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w - - 0 1");
}
@Test
public void testCastled() {
assertScore(250, "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQ1RK1 w - - 0 1");
}
@Test
public void testPawnGone() {
System.out.println(Arrays.toString(ImageIO.getReaderMIMETypes()));
assertScore(-70, "rnbq1rk1/1ppppppp/8/8/8/8/PPPPPP1P/RNBQ1RK1 w - - 0 1");
}
@Test
public void testFiancettoed() {
assertScore(-30, "rnbq1rk1/pppppppp/8/8/8/8/PPPPPPBP/RNBQ1RK1 w - - 0 1");
}
@Test
public void testFiancettoedNoBishop() {
assertScore(210, "6k1/1q6/8/8/8/Q7/5PPP/6K1 w - - 0 1");
assertScore(180, "6k1/1q6/8/8/8/Q5P1/5PBP/6K1 w - - 0 1");
assertScore(140, "6k1/1q6/8/8/8/Q5P1/5P1P/6K1 w - - 0 1");
}
}
| gpl-2.0 |
FunkyNoodles/ProjectCirkt | app/src/main/java/io/github/funkynoodles/projectcirkt/FindFragment.java | 3641 | package io.github.funkynoodles.projectcirkt;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
/**
* Created by Louis on 9/14/2015.
* contains contents for "Find" tab
*/
public class FindFragment extends Fragment {
//public ArrayList<String> listViewArray = new ArrayList<String>();
NearByClasses nbc = new NearByClasses();
public static FindFragment newInstance(){
FindFragment fragment = new FindFragment();
return fragment;
}
private HandleXML obj;
Button findBtn;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_find, container, false);
Spinner spinner = (Spinner) myFragmentView.findViewById(R.id.timeSpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(),
R.array.timeArray, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
findBtn = (Button)myFragmentView.findViewById(R.id.findButton);
findBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v){
obj = new HandleXML("http://courses.illinois.edu/cisapp/explorer/schedule/2015/fall/CS/225/35917.xml");
obj.fetchXML();
Intent intent = new Intent(v.getContext(),NearByClasses.class);
startActivity(intent);
getActivity().overridePendingTransition(R.animator.page_enter_animation, R.animator.page_exit_animation);
while(obj.parsingComplete);
NearByClasses.listViewArrayList.clear();
NearByClasses.listViewArrayList.add(obj.getCourseName() + ", " + obj.getSubjectName());
NearByClasses.listViewArrayList.add(obj.getSubjectID() + " " + obj.getCourseID());
NearByClasses.listViewArrayList.add(obj.getDescription());
NearByClasses.listViewArrayList.add(obj.getSectionNumber());
NearByClasses.listViewArrayList.add(obj.getSectionNotes());
NearByClasses.listViewArrayList.add(obj.getStatusCode());
NearByClasses.listViewArrayList.add(obj.getStartDate());
NearByClasses.listViewArrayList.add(obj.getEndDate());
NearByClasses.listViewArrayList.add(obj.getMeetingType());
NearByClasses.listViewArrayList.add(obj.getMeetingStart());
NearByClasses.listViewArrayList.add(obj.getMeetingEnd());
NearByClasses.listViewArrayList.add(obj.getDaysOfTheWeek());
NearByClasses.listViewArrayList.add(obj.getBuildingName() + " " + obj.getRoomNumber());
for(int loop1=0;loop1<obj.getInstructors().size();loop1++){
NearByClasses.listViewArrayList.add(obj.getInstructors().get(loop1));
}
//getActivity().finish();
//getActivity().overridePendingTransition(R.animator.page_exit_animation, R.animator.page_enter_animation);
}
});
return myFragmentView;
}
/**
* Called when Find button is pressed
*/
public void findClasses(View view){
}
} | gpl-2.0 |
pitosalas/blogbridge | src/com/salas/bb/views/themes/LAFTheme.java | 4729 | // BlogBridge -- RSS feed reader, manager, and web based service
// Copyright (C) 2002-2006 by R. Pito Salas
//
// 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
//
// Contact: R. Pito Salas
// mailto:pitosalas@users.sourceforge.net
// More information: about BlogBridge
// http://www.blogbridge.com
// http://sourceforge.net/projects/blogbridge
//
// $Id: LAFTheme.java,v 1.13 2008/02/28 15:59:52 spyromus Exp $
//
package com.salas.bb.views.themes;
import javax.swing.*;
import java.awt.*;
/**
* Theme which is completely based on current LAF.
*/
public class LAFTheme extends AbstractTheme
{
private static final String NAME = "LAF";
private static final String TITLE = "Look And Feel";
private static final JLabel LABEL = new JLabel();
private static final JList LIST = new JList();
/**
* Creates default LAF theme.
*/
public LAFTheme()
{
super(NAME, TITLE);
}
/**
* Returns color defined by the theme.
*
* @param key the key.
*
* @return color or <code>NULL</code> if color isn't defined by this theme.
*/
public Color getColor(ThemeKey.Color key)
{
Color color = null;
if ((ThemeKey.Color.ARTICLE_DATE_SEL_FG == key) ||
(ThemeKey.Color.ARTICLE_DATE_UNSEL_FG == key) ||
(ThemeKey.Color.ARTICLE_TEXT_SEL_FG == key) ||
(ThemeKey.Color.ARTICLE_TEXT_UNSEL_FG == key) ||
(ThemeKey.Color.ARTICLE_TITLE_SEL_FG == key) ||
(ThemeKey.Color.ARTICLE_TITLE_UNSEL_FG == key) ||
(ThemeKey.Color.ARTICLEGROUP_FG == key))
{
color = UIManager.getColor("Label.foreground");
} else if (ThemeKey.Color.ARTICLELIST_FEEDNAME_FG == key)
{
color = UIManager.getColor("SimpleInternalFrame.activeTitleForeground");
if (color == null) color = UIManager.getColor("InternalFrame.activeTitleForeground");
if (color == null) color = UIManager.getColor("Label.foreground");
} else if ((ThemeKey.Color.ARTICLE_SEL_BG == key) ||
(ThemeKey.Color.FEEDSLIST_SEL_BG == key))
{
color = LIST.getSelectionBackground();
} else if ((ThemeKey.Color.ARTICLE_UNSEL_BG == key) ||
(ThemeKey.Color.ARTICLEGROUP_BG == key) ||
(ThemeKey.Color.ARTICLELIST_BG == key) ||
(ThemeKey.Color.FEEDSLIST_BG == key) ||
(ThemeKey.Color.FEEDSLIST_ALT_BG == key))
{
color = LIST.getBackground();
} else if ((ThemeKey.Color.BLOGLINK_DISC_BG == key) ||
(ThemeKey.Color.BLOGLINK_UNDISC_BG == key))
{
// TODO change this to more appropriate value
color = LIST.getSelectionBackground();
} else if (ThemeKey.Color.FEEDSLIST_FG == key)
{
color = LIST.getForeground();
} else if (ThemeKey.Color.FEEDSLIST_SEL_FG == key)
{
color = LIST.getSelectionForeground();
}
return color;
}
/**
* Returns font defined by the theme.
*
* @param key the key.
*
* @return font or <code>NULL</code> if font isn't defined by this theme.
*/
public Font getFont(ThemeKey.Font key)
{
Font font = null;
if ((ThemeKey.Font.ARTICLE_TEXT == key) ||
(ThemeKey.Font.ARTICLE_TITLE == key) ||
(ThemeKey.Font.ARTICLE_DATE == key) ||
(ThemeKey.Font.ARTICLEGROUP == key) ||
(ThemeKey.Font.ARTICLELIST_FEEDNAME == key) ||
(ThemeKey.Font.MAIN == key))
{
font = LABEL.getFont();
}
return font;
}
/**
* Returns the delta to be applied to the size of the main font to get the font for the given
* key.
*
* @param key the key.
*
* @return the delta.
*/
public int getFontSizeDelta(ThemeKey.Font key)
{
return 0;
}
}
| gpl-2.0 |
ia-toki/judgels-gabriel-commons | src/main/java/org/iatoki/judgels/gabriel/blackbox/sandboxes/FakeSandboxesInteractor.java | 2878 | package org.iatoki.judgels.gabriel.blackbox.sandboxes;
import org.iatoki.judgels.gabriel.blackbox.Sandbox;
import org.iatoki.judgels.gabriel.blackbox.SandboxExecutionResult;
import org.iatoki.judgels.gabriel.blackbox.SandboxesInteractor;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public final class FakeSandboxesInteractor implements SandboxesInteractor {
@Override
public SandboxExecutionResult[] executeInteraction(Sandbox sandbox1, List<String> command1, Sandbox sandbox2, List<String> command2) {
ProcessBuilder pb1 = sandbox1.getProcessBuilder(command1);
ProcessBuilder pb2 = sandbox2.getProcessBuilder(command2);
Process p1;
Process p2;
try {
p1 = pb1.start();
p2 = pb2.start();
} catch (IOException e) {
return new SandboxExecutionResult[]{
SandboxExecutionResult.internalError(e.getMessage()),
SandboxExecutionResult.internalError(e.getMessage())
};
}
InputStream p1InputStream = p1.getInputStream();
OutputStream p1OutputStream = p1.getOutputStream();
InputStream p2InputStream = p2.getInputStream();
OutputStream p2OutputStream = p2.getOutputStream();
ExecutorService executor = Executors.newFixedThreadPool(2);
executor.submit(new UnidirectionalPipe(p1InputStream, p2OutputStream));
executor.submit(new UnidirectionalPipe(p2InputStream, p1OutputStream));
int exitCode1 = 0;
int exitCode2 = 0;
try {
exitCode2 = p2.waitFor();
exitCode1 = p1.waitFor();
} catch (InterruptedException e) {
return new SandboxExecutionResult[]{
SandboxExecutionResult.internalError(e.getMessage()),
SandboxExecutionResult.internalError(e.getMessage())
};
}
return new SandboxExecutionResult[]{
sandbox1.getResult(exitCode1),
sandbox2.getResult(exitCode2)
};
}
}
class UnidirectionalPipe implements Runnable {
private final InputStream in;
private final OutputStream out;
public UnidirectionalPipe(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
}
@Override
public void run() {
try {
while (true) {
byte[] buffer = new byte[4096];
int len = in.read(buffer);
if (len == -1) {
break;
}
out.write(buffer, 0, len);
out.flush();
}
in.close();
out.close();
} catch (IOException e) {
}
}
} | gpl-2.0 |
dominikl/bioformats | components/formats-api/src/loci/formats/meta/ModuloAnnotation.java | 3845 | /*
* #%L
* BSD implementations of Bio-Formats readers and writers
* %%
* Copyright (C) 2005 - 2015 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package loci.formats.meta;
import loci.common.xml.XMLTools;
import loci.formats.Modulo;
import loci.formats.ome.OMEXMLMetadata;
import ome.xml.model.XMLAnnotation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class ModuloAnnotation extends XMLAnnotation {
public static final String MODULO_NS;
static {
MODULO_NS = "openmicroscopy.org/omero/dimension/modulo";
}
private Modulo modulo;
public void setModulo(OMEXMLMetadata meta, Modulo m) {
modulo = m;
setNamespace(MODULO_NS);
Document doc = XMLTools.createDocument();
Element r = makeModuloElement(doc);
setValue(XMLTools.dumpXML(null, doc, r, false));
}
protected Element makeModuloElement(Document document) {
Element mtop = document.createElement("Modulo");
mtop.setAttribute("namespace", "http://www.openmicroscopy.org/Schemas/Additions/2011-09");
// TODO: the above should likely NOT be hard-coded
Element m = document.createElement("ModuloAlong" + modulo.parentDimension);
mtop.appendChild(m);
String type = modulo.type;
String typeDescription = modulo.typeDescription;
if (type != null) {
type = type.toLowerCase();
}
// Handle CZI files for the moment.
// TODO: see http://trac.openmicroscopy.org.uk/ome/ticket/11720
if (type.equals("rotation")) {
type = "angle";
}
if (type == null || (!type.equals("angle") && !type.equals("phase") &&
!type.equals("tile") && !type.equals("lifetime") &&
!type.equals("lambda")))
{
if (typeDescription == null) {
typeDescription = type;
}
type = "other";
}
m.setAttribute("Type", type);
m.setAttribute("TypeDescription", typeDescription);
if (modulo.unit != null) {
m.setAttribute("Unit", modulo.unit);
}
if (modulo.end > modulo.start) {
m.setAttribute("Start", String.valueOf(modulo.start));
m.setAttribute("Step", String.valueOf(modulo.step));
m.setAttribute("End", String.valueOf(modulo.end));
}
if (modulo.labels != null) {
for (String label : modulo.labels) {
Element labelNode = document.createElement("Label");
labelNode.setTextContent(label);
m.appendChild(labelNode);
}
}
return mtop;
}
}
| gpl-2.0 |