repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
NCIP/cagrid-core | caGrid/projects/globalModelExchange/domain/src/org/cagrid/gme/domain/XMLSchemaNamespace.java | 2272 | /**
*============================================================================
* Copyright The Ohio State University Research Foundation, The University of Chicago -
* Argonne National Laboratory, Emory University, SemanticBits LLC, and
* Ekagra Software Technologies Ltd.
*
* Distributed under the OSI-approved BSD 3-Clause License.
* See http://ncip.github.com/cagrid-core/LICENSE.txt for details.
*============================================================================
**/
package org.cagrid.gme.domain;
import java.net.URI;
import java.net.URISyntaxException;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import org.hibernate.annotations.Type;
/**
* This generally is just a wrapper for a URI, set in the context of being a
* targetNamespace for an XML schema.
*/
@Embeddable
public class XMLSchemaNamespace {
@Column(nullable = false, unique = true)
@Type(type = "org.cagrid.gme.persistence.hibernate.types.URIUserType")
private URI uri;
// Needed for Castor to work
public XMLSchemaNamespace() {
}
public XMLSchemaNamespace(String uri) throws URISyntaxException {
this.uri = new URI(uri);
}
public XMLSchemaNamespace(URI uri) {
this.uri = uri;
}
public URI getURI() {
return this.uri;
}
public void setURI(URI uri) {
this.uri = uri;
}
@Override
public String toString() {
return (this.uri == null) ? "null" : this.uri.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.uri == null) ? 0 : this.uri.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final XMLSchemaNamespace other = (XMLSchemaNamespace) obj;
if (this.uri == null) {
if (other.uri != null) {
return false;
}
} else if (!this.uri.equals(other.uri)) {
return false;
}
return true;
}
}
| bsd-3-clause |
jayjaybillings/fern | src/edu.utk.phys.fern/edu/utk/phys/fern/ShowIsotopes.java | 4272 | package edu.utk.phys.fern;
// -------------------------------------------------------------------------------------------------------------
// Class ShowIsotopes to lay out contour plotting frame for ElementMaker
// by creating an instance of ContourFrame
// -------------------------------------------------------------------------------------------------------------
import java.awt.Color;
import java.awt.Menu;
import java.awt.MenuBar;
import java.awt.MenuItem;
import java.awt.MenuShortcut;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
public class ShowIsotopes {
static Color isoBC = Color.black; //MyColors.gray235; // Background color
// ContourFrame instance declared static in order to allow
// instances of MyFileDialogue class to communicate with
// the instance gp of ContourPad through a ContourFrame
// method (PSfile). See the MyFileDialogue class, and the
// static declaration of ContourPad gp = new ContourPad()
static ContourFrame cd;
// ----------------------------------------------------------------
// Public constructor
// ----------------------------------------------------------------
public ShowIsotopes() {
cd = new ContourFrame();
// Create a customized main frame and display it
cd.setSize(800,600);
cd.setTitle(" Isotopic Abundances");
cd.setBackground(isoBC);
cd.setLocation(200,200);
// Create a menu bar and add menu to it
MenuBar cdmb = new MenuBar();
cd.setMenuBar(cdmb);
Menu cdMenu = new Menu("File");
cdmb.add(cdMenu);
Menu helpMenu = new Menu("Help");
cdmb.add(helpMenu);
// Create menu items with keyboard shortcuts
MenuItem s,m,l,p,h,q;
cdMenu.add(s=new MenuItem("Save as Postscript",
new MenuShortcut(KeyEvent.VK_S)));
cdMenu.add(m=new MenuItem("Save Movie Frames",
new MenuShortcut(KeyEvent.VK_M)));
cdMenu.add(l=new MenuItem("Load", new MenuShortcut(KeyEvent.VK_L)));
cdMenu.add(p=new MenuItem("Print", new MenuShortcut(KeyEvent.VK_P)));
cdMenu.addSeparator(); // Menu separator
cdMenu.add(q=new MenuItem("Quit", new MenuShortcut(KeyEvent.VK_Q)));
helpMenu.add(h=new MenuItem("Instructions",
new MenuShortcut(KeyEvent.VK_H)));
// Create and register action listeners for menu items
s.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
ContourFileDialogue fd =
new ContourFileDialogue(100,130,400,110,Color.black,
MyColors.gray204,"Choose File Name",
"Choose a postscript file name:");
fd.setResizable(false);
fd.hT.setText("nz.ps");
fd.show();
}
});
m.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
cd.gp.saveFrames();}
});
l.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){System.exit(0);}
});
p.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
cd.printThisFrame(20,20,false);}
});
h.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){
if(cd.helpWindowOpen) {
cd.hf.toFront();
} else {
cd.hf = new MyHelpFrame();
cd.hf.setSize(300,400);
cd.hf.setLocation(100,100);
cd.hf.setResizable(false);
cd.hf.setTitle(" Help");
cd.hf.show();
cd.helpWindowOpen = true;
}
}
});
q.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e){System.exit(0);}
});
cd.show();
}
} /* End class ShowIsotopes */
| bsd-3-clause |
exponent/exponent | android/versioned-abis/expoview-abi41_0_0/src/main/java/abi41_0_0/expo/modules/firebase/core/FirebaseCoreInterface.java | 162 | package abi41_0_0.expo.modules.firebase.core;
import com.google.firebase.FirebaseApp;
public interface FirebaseCoreInterface {
FirebaseApp getDefaultApp();
}
| bsd-3-clause |
Ervacon/webflow | samples/PhoneBook/WEB-INF/source/com/ervacon/springframework/samples/phonebook/domain/PhoneBookQuery.java | 540 | package com.ervacon.springframework.samples.phonebook.domain;
import java.io.Serializable;
public class PhoneBookQuery implements Serializable {
private String firstName;
private String lastName;
public PhoneBookQuery() {
this.firstName="";
this.lastName="";
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName=firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName=lastName;
}
}
| bsd-3-clause |
mikiobraun/jblas | src/main/java/org/jblas/ranges/package-info.java | 1790 | // --- BEGIN LICENSE BLOCK ---
/*
* Copyright (c) 2009, Mikio L. Braun
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
*
* * Neither the name of the Technische Universitaet Berlin nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
// --- END LICENSE BLOCK ---
/**
* Provide ways to specify indices ranges.
*/
package org.jblas.ranges;
| bsd-3-clause |
jolicloud/exponent | android/app/src/main/java/abi11_0_0/host/exp/exponent/modules/api/components/maps/AirMapCircleManager.java | 2574 | package abi11_0_0.host.exp.exponent.modules.api.components.maps;
import android.content.Context;
import android.graphics.Color;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.WindowManager;
import abi11_0_0.com.facebook.react.bridge.ReactApplicationContext;
import abi11_0_0.com.facebook.react.bridge.ReadableMap;
import abi11_0_0.com.facebook.react.uimanager.ThemedReactContext;
import abi11_0_0.com.facebook.react.uimanager.ViewGroupManager;
import abi11_0_0.com.facebook.react.uimanager.annotations.ReactProp;
import com.google.android.gms.maps.model.LatLng;
public class AirMapCircleManager extends ViewGroupManager<AirMapCircle> {
private final DisplayMetrics metrics;
public AirMapCircleManager(ReactApplicationContext reactContext) {
super();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
metrics = new DisplayMetrics();
((WindowManager) reactContext.getSystemService(Context.WINDOW_SERVICE))
.getDefaultDisplay()
.getRealMetrics(metrics);
} else {
metrics = reactContext.getResources().getDisplayMetrics();
}
}
@Override
public String getName() {
return "AIRMapCircle";
}
@Override
public AirMapCircle createViewInstance(ThemedReactContext context) {
return new AirMapCircle(context);
}
@ReactProp(name = "center")
public void setCenter(AirMapCircle view, ReadableMap center) {
view.setCenter(new LatLng(center.getDouble("latitude"), center.getDouble("longitude")));
}
@ReactProp(name = "radius", defaultDouble = 0)
public void setRadius(AirMapCircle view, double radius) {
view.setRadius(radius);
}
@ReactProp(name = "strokeWidth", defaultFloat = 1f)
public void setStrokeWidth(AirMapCircle view, float widthInPoints) {
float widthInScreenPx = metrics.density * widthInPoints; // done for parity with iOS
view.setStrokeWidth(widthInScreenPx);
}
@ReactProp(name = "fillColor", defaultInt = Color.RED, customType = "Color")
public void setFillColor(AirMapCircle view, int color) {
view.setFillColor(color);
}
@ReactProp(name = "strokeColor", defaultInt = Color.RED, customType = "Color")
public void setStrokeColor(AirMapCircle view, int color) {
view.setStrokeColor(color);
}
@ReactProp(name = "zIndex", defaultFloat = 1.0f)
public void setZIndex(AirMapCircle view, float zIndex) {
view.setZIndex(zIndex);
}
}
| bsd-3-clause |
vivo-project/Vitro | api/src/main/java/edu/cornell/mannlib/vitro/webapp/dao/jena/VitroModelSource.java | 4359 | /* $This file is distributed under the terms of the license in LICENSE$ */
package edu.cornell.mannlib.vitro.webapp.dao.jena;
import javax.servlet.ServletContext;
import org.apache.commons.lang3.StringUtils;
import org.apache.jena.rdf.model.Model;
import org.apache.jena.rdf.model.ModelReader;
import org.apache.jena.rdf.model.ModelSource;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelAccess;
import edu.cornell.mannlib.vitro.webapp.modelaccess.ModelNames;
/**
* ModelSource that will handle specially named Vitro models such
* as display and t-box. Any other models will be retrieved from
* the inner ModelSource.
*
* None of these models will be retrieved
* from the attributes of a ServletRequest.
*/
public class VitroModelSource implements ModelSource {
private ModelSource innerSource;
private ServletContext context;
/**
* Each of these values identifies a model in the system.
*/
public enum ModelName {
/** Name for default assertion model. */
ABOX,
/** Name of default t-box for default assertion model. */
TBOX,
/** Name for default display model related to ABOX and TBOX. */
DISPLAY,
/** Name for t-box for DISPLAY. */
DISPLAY_TBOX,
/** Name for display model related to DISPLAY and DISPLAY_TBOX. */
DISPLAY_DISPLAY,
/** Name for user accounts model. */
USER_ACCOUNTS
//may need a way to specify unions of these models and unions of URI models
}
public VitroModelSource(ModelSource innerSource, ServletContext context){
this.innerSource = innerSource;
this.context = context;
}
@Override
public Model getModel(String arg0) {
ModelName pn = getModelName( arg0 );
if( pn != null ){
return getNamedModel(pn);
}else{
return innerSource.getModel(arg0);
}
}
@Override
public Model getModel(String arg0, ModelReader arg1) {
ModelName pn = getModelName( arg0 );
if( pn != null ){
return getNamedModel(pn);
}else{
return innerSource.getModel(arg0,arg1);
}
}
@Override
public Model createDefaultModel() {
return innerSource.createDefaultModel();
}
@Override
public Model createFreshModel() {
return innerSource.createFreshModel();
}
@Override
public Model openModel(String arg0) {
ModelName pn = getModelName( arg0 );
if( pn != null ){
return getNamedModel( pn );
}else{
return innerSource.openModel(arg0);
}
}
@Override
public Model openModelIfPresent(String arg0) {
ModelName pn = getModelName( arg0 );
if( pn != null ){
return getNamedModel( pn );
}else{
return innerSource.openModelIfPresent(arg0);
}
}
/**
* This should not return null for any value of pmn in
* the enum PrivilegedModelName.
*/
private Model getNamedModel( ModelName pmn ){
switch( pmn ){
case ABOX:
return ModelAccess.on(context).getOntModel();
case TBOX:
return (Model) context.getAttribute("tboxmodel???");
case DISPLAY:
return ModelAccess.on(context).getOntModel(ModelNames.DISPLAY);
case DISPLAY_TBOX:
return ModelAccess.on(context).getOntModel(ModelNames.DISPLAY_TBOX);
case DISPLAY_DISPLAY:
return ModelAccess.on(context).getOntModel(ModelNames.DISPLAY_DISPLAY);
case USER_ACCOUNTS:
throw new IllegalArgumentException("getNamedModel() Does not yet handle USER_ACCOUNTS");
default:
throw new IllegalArgumentException("getNamedModel() should handle all values for enum PrivilegedModelName");
}
}
/**
* Returns null if the string is not a ModelName.
*/
public static ModelName getModelName( String string ){
if( StringUtils.isEmpty(string))
return null;
try{
return ModelName.valueOf( string.trim().toUpperCase());
}catch(IllegalArgumentException ex){
//Did not find value in enum ModelName for the string, no problem.
return null;
}
}
}
| bsd-3-clause |
juli1/smaccm-improvements | fm-workbench/agree/com.rockwellcollins.atc.agree/src-gen/com/rockwellcollins/atc/agree/agree/impl/GetPropertyExprImpl.java | 6540 | /**
*/
package com.rockwellcollins.atc.agree.agree.impl;
import com.rockwellcollins.atc.agree.agree.AgreePackage;
import com.rockwellcollins.atc.agree.agree.Expr;
import com.rockwellcollins.atc.agree.agree.GetPropertyExpr;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.osate.aadl2.NamedElement;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Get Property Expr</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link com.rockwellcollins.atc.agree.agree.impl.GetPropertyExprImpl#getComponent <em>Component</em>}</li>
* <li>{@link com.rockwellcollins.atc.agree.agree.impl.GetPropertyExprImpl#getProp <em>Prop</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class GetPropertyExprImpl extends ExprImpl implements GetPropertyExpr
{
/**
* The cached value of the '{@link #getComponent() <em>Component</em>}' containment reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getComponent()
* @generated
* @ordered
*/
protected Expr component;
/**
* The cached value of the '{@link #getProp() <em>Prop</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getProp()
* @generated
* @ordered
*/
protected NamedElement prop;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected GetPropertyExprImpl()
{
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass()
{
return AgreePackage.Literals.GET_PROPERTY_EXPR;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public Expr getComponent()
{
return component;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NotificationChain basicSetComponent(Expr newComponent, NotificationChain msgs)
{
Expr oldComponent = component;
component = newComponent;
if (eNotificationRequired())
{
ENotificationImpl notification = new ENotificationImpl(this, Notification.SET, AgreePackage.GET_PROPERTY_EXPR__COMPONENT, oldComponent, newComponent);
if (msgs == null) msgs = notification; else msgs.add(notification);
}
return msgs;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setComponent(Expr newComponent)
{
if (newComponent != component)
{
NotificationChain msgs = null;
if (component != null)
msgs = ((InternalEObject)component).eInverseRemove(this, EOPPOSITE_FEATURE_BASE - AgreePackage.GET_PROPERTY_EXPR__COMPONENT, null, msgs);
if (newComponent != null)
msgs = ((InternalEObject)newComponent).eInverseAdd(this, EOPPOSITE_FEATURE_BASE - AgreePackage.GET_PROPERTY_EXPR__COMPONENT, null, msgs);
msgs = basicSetComponent(newComponent, msgs);
if (msgs != null) msgs.dispatch();
}
else if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AgreePackage.GET_PROPERTY_EXPR__COMPONENT, newComponent, newComponent));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NamedElement getProp()
{
if (prop != null && ((EObject)prop).eIsProxy())
{
InternalEObject oldProp = (InternalEObject)prop;
prop = (NamedElement)eResolveProxy(oldProp);
if (prop != oldProp)
{
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.RESOLVE, AgreePackage.GET_PROPERTY_EXPR__PROP, oldProp, prop));
}
}
return prop;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public NamedElement basicGetProp()
{
return prop;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setProp(NamedElement newProp)
{
NamedElement oldProp = prop;
prop = newProp;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, AgreePackage.GET_PROPERTY_EXPR__PROP, oldProp, prop));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs)
{
switch (featureID)
{
case AgreePackage.GET_PROPERTY_EXPR__COMPONENT:
return basicSetComponent(null, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType)
{
switch (featureID)
{
case AgreePackage.GET_PROPERTY_EXPR__COMPONENT:
return getComponent();
case AgreePackage.GET_PROPERTY_EXPR__PROP:
if (resolve) return getProp();
return basicGetProp();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eSet(int featureID, Object newValue)
{
switch (featureID)
{
case AgreePackage.GET_PROPERTY_EXPR__COMPONENT:
setComponent((Expr)newValue);
return;
case AgreePackage.GET_PROPERTY_EXPR__PROP:
setProp((NamedElement)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID)
{
switch (featureID)
{
case AgreePackage.GET_PROPERTY_EXPR__COMPONENT:
setComponent((Expr)null);
return;
case AgreePackage.GET_PROPERTY_EXPR__PROP:
setProp((NamedElement)null);
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID)
{
switch (featureID)
{
case AgreePackage.GET_PROPERTY_EXPR__COMPONENT:
return component != null;
case AgreePackage.GET_PROPERTY_EXPR__PROP:
return prop != null;
}
return super.eIsSet(featureID);
}
} //GetPropertyExprImpl
| bsd-3-clause |
jabouzi/NiceCompass | app/src/main/java/com/digitallizard/nicecompass/GPSManager.java | 4012 | /*******************************************************************************
* NiceCompass
* Released under the BSD License. See README or LICENSE.
* Copyright (c) 2011, Digital Lizard (Oscar Key, Thomas Boby)
* All rights reserved.
******************************************************************************/
package com.digitallizard.nicecompass;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
public class GPSManager {
public static int STATUS_NO_GPS = 0; // the device does not have gps
public static int STATUS_GPS_DISABLED = 1; // the gps has been disabled by the system
public static int STATUS_GPS_STOPPED = 2; // the gps is not currently active, call startGps()
public static int STATUS_GPS_NO_FIX = 3;
public static int STATUS_GPS_FIX = 4;
private static long MIN_UPDATE_TIME_MILLIS = 10l * 1000l; // 10 seconds
private static float MIN_UPDATE_DISTANCE_METERS = 1f; // 1 meter
private LocationManager locationManager;
private LocationListener locationListener;
private Location locationCache;
private int status;
private synchronized void updateStatus(int newStatus) {
status = newStatus;
}
private synchronized void updateLocationCache(Location newLocation) {
locationCache = newLocation;
}
private synchronized Location getLocationCache() {
return locationCache;
}
public synchronized int getStatus() {
return status;
}
public double getAltitude() {
return getLocationCache().getAltitude();
}
public void stopGPS() {
// stop receiving updates
locationManager.removeUpdates(locationListener);
// update the status
updateStatus(STATUS_GPS_STOPPED);
}
public boolean startGPS() {
// check if the device has gps
if(locationManager.getProvider(LocationManager.GPS_PROVIDER) == null) {
// no gps, set the status and then bail
updateStatus(STATUS_NO_GPS);
return false; // we could not enable gps
}
// check if the gps is enabled
if(!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
// the provider is disabled, update the status and then bail
updateStatus(STATUS_GPS_DISABLED);
return false; // we could not enable the gps
}
// add a listener to receive updates from the gps
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_UPDATE_TIME_MILLIS, MIN_UPDATE_DISTANCE_METERS,
locationListener);
return true; // we didn't have any problems, probably
}
public GPSManager(Context context) {
// initialize variables
locationManager = (LocationManager)context.getSystemService(Context.LOCATION_SERVICE);
// define a listener that listens for location updates
locationListener = new LocationListener() {
public void onStatusChanged(String provider, int status, Bundle extras) {
// we don't need to do anything, status updates generated by this are handled elsewhere
}
public void onProviderEnabled(String provider) {
// only listen to stuff about gps
if(provider == LocationManager.GPS_PROVIDER){
// if the status currently says that the gps is disabled, change it to stopped
if(getStatus() == STATUS_GPS_DISABLED) {
updateStatus(STATUS_GPS_STOPPED);
}
}
}
public void onProviderDisabled(String provider) {
// only listen to stuff about gps
if(provider == LocationManager.GPS_PROVIDER){
// stop the gps, probably unneeded
stopGPS();
// update the status
updateStatus(STATUS_GPS_DISABLED);
}
}
public void onLocationChanged(Location location) {
// test if the fix is useful
if(location.hasAltitude()) {
// store the new location
updateLocationCache(location);
// update the status, we have a fix
updateStatus(STATUS_GPS_FIX);
} else {
// the gps is still trying to get a fix (or so we will pretend, we need altitude)
updateStatus(STATUS_GPS_NO_FIX);
}
}
};
}
}
| bsd-3-clause |
synergynet/synergynet3 | synergynet3-parent/synergynet3-appsystem-web/src/main/java/synergynet3/web/appsystem/client/service/SynergyNetAppSystemService.java | 2756 | package synergynet3.web.appsystem.client.service;
import java.util.ArrayList;
import java.util.List;
import synergynet3.web.shared.ClassRoom;
import synergynet3.web.shared.Student;
import synergynet3.web.shared.messages.PerformActionMessage;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
@RemoteServiceRelativePath("SynergyNetAppSystemService")
public interface SynergyNetAppSystemService extends RemoteService {
public void devicesShouldOpenApplication(String className, List<String> devices);
//Student control functions
public void sendStudentToTable(String ID, String deviceSelected);
public void removeStudentFromTable(String ID, String table);
public void modifyStudent(Student student);
public void createStudent(Student student);
public void removeStudent(String ID);
public ArrayList<Student> getStudentsFromClass(String classSelected);
public void changeStudentClass(String ID, String newClass);
public void removeStudentsOfClass(String name);
//Database control functions
public void startDatabase();
public void stopDatabase();
//Class selection functions
public ArrayList<ClassRoom> getCurrentClasses();
public void addClassRoom(ClassRoom classroom);
public void removeClassRoom(ClassRoom classroom);
//Media control functions
public void setNetworkFlick(PerformActionMessage message, String[] deviceToSendTo);
public void reloadServerContents(PerformActionMessage message, String[] deviceToSendTo);
public void reloadRemovableDriveContents(PerformActionMessage message, String[] deviceToSendTo);
public void bringStudentsToTop(PerformActionMessage message, String[] deviceToSendTo);
public void takeScreenshot(PerformActionMessage message, String[] deviceToSendTo);
public void removeAdditionalContent(PerformActionMessage message, String[] deviceToSendTo);
public void toggleFreeze(PerformActionMessage message, String[] deviceToSendTo);
//Projector control functions
public void clearProjectorContents(PerformActionMessage message, String[] deviceToSendTo);
public void align(PerformActionMessage message, String[] deviceToSendTo);
public void sendScreenshotsToProjector(String[] projectorsToSendTo, String[] tablesToSendTo);
public void sendContentsToProjector(String[] projectorsToSendTo, String[] tablesToSendTo);
public void sendProjectedContentsToTable(String[] tablesToSendTo, String[] projectorsToSendTo);
public static class Util {
private static SynergyNetAppSystemServiceAsync instance;
public static SynergyNetAppSystemServiceAsync get(){
if (instance == null) {
instance = GWT.create(SynergyNetAppSystemService.class);
}
return instance;
}
}
} | bsd-3-clause |
BaseXdb/basex | basex-core/src/main/java/org/basex/query/func/user/UserUpdateInfo.java | 1794 | package org.basex.query.func.user;
import static org.basex.query.QueryError.*;
import org.basex.core.users.*;
import org.basex.query.*;
import org.basex.query.up.primitives.*;
import org.basex.query.value.item.*;
import org.basex.query.value.node.*;
import org.basex.query.value.seq.*;
import org.basex.util.*;
/**
* Function implementation.
*
* @author BaseX Team 2005-22, BSD License
* @author Christian Gruen
*/
public final class UserUpdateInfo extends UserFn {
@Override
public Item item(final QueryContext qc, final InputInfo ii) throws QueryException {
final ANode node = toElem(exprs[0], qc);
if(!T_INFO.matches(node)) throw ELM_X_X.get(info, Q_INFO.prefixId(), node);
final User user = exprs.length > 1 ? toUser(1, qc) : null;
qc.updates().add(new UpdateInfo(node.materialize(qc, true), user, qc, info), qc);
return Empty.VALUE;
}
/** Update primitive. */
private static final class UpdateInfo extends UserUpdate {
/** Node to be updated. */
private final ANode node;
/**
* Constructor.
* @param user user ({@code null} if operation is global)
* @param node info element
* @param qc query context
* @param info input info
*/
private UpdateInfo(final ANode node, final User user, final QueryContext qc,
final InputInfo info) {
super(UpdateType.USERINFO, user, qc, info);
this.node = node;
}
@Override
public void merge(final Update update) throws QueryException {
if(user != null) super.merge(update);
else throw USER_INFO_X.get(info, operation());
}
@Override
public void apply() {
if(user != null) user.info(node);
else users.info(node);
}
@Override
public String operation() {
return "updated";
}
}
}
| bsd-3-clause |
KingBowser/hatter-source-code | hostsmanager/src/me/hatter/tools/hostsmanager/hosts/Hosts.java | 2022 | package me.hatter.tools.hostsmanager.hosts;
import java.util.ArrayList;
import java.util.List;
public class Hosts {
private List<Group> groups = new ArrayList<Group>();
public List<Group> getGroups() {
return groups;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
public static Hosts parse(List<String> lines) {
Hosts hosts = new Hosts();
List<Line> ll = parseLines(lines);
Group group = new Group();
for (Line l : ll) {
if (l.isGroupStart()) {
if (!group.getLines().isEmpty()) {
hosts.getGroups().add(group);
group = new Group();
}
group.setGroup(l.getGroup());
group.getLines().add(l);
} else {
group.getLines().add(l);
if (l.isGroupEnd()) {
hosts.getGroups().add(group);
group = new Group();
}
}
}
if (!group.getLines().isEmpty()) {
hosts.getGroups().add(group);
}
return hosts;
}
public List<String> toLines() {
List<String> lines = new ArrayList<String>();
for (Group g : getGroups()) {
if (g.getGroup() == null) {
for (Line l : g.getLines()) {
lines.add(l.getLine());
}
} else {
lines.add(Line.GROUP_START + " " + g.getGroup());
for (Line l : g.getLines()) {
if (!l.isGroup()) {
lines.add(l.getLine());
}
}
lines.add(Line.GROUP_END);
}
}
return lines;
}
private static List<Line> parseLines(List<String> lines) {
List<Line> result = new ArrayList<Line>();
for (String l : lines) {
result.add(Line.parse(l));
}
return result;
}
}
| bsd-3-clause |
NCIP/cagrid | cagrid/Software/core/integration-tests/projects/dataTests/src/org/cagrid/data/test/upgrades/from1pt4/UpgradeFrom1pt4Tests.java | 4833 | package org.cagrid.data.test.upgrades.from1pt4;
import gov.nih.nci.cagrid.testing.system.deployment.ServiceContainer;
import gov.nih.nci.cagrid.testing.system.deployment.ServiceContainerFactory;
import gov.nih.nci.cagrid.testing.system.deployment.ServiceContainerType;
import gov.nih.nci.cagrid.testing.system.deployment.steps.DeployServiceStep;
import gov.nih.nci.cagrid.testing.system.deployment.steps.DestroyContainerStep;
import gov.nih.nci.cagrid.testing.system.deployment.steps.StartContainerStep;
import gov.nih.nci.cagrid.testing.system.deployment.steps.StopContainerStep;
import gov.nih.nci.cagrid.testing.system.deployment.steps.UnpackContainerStep;
import gov.nih.nci.cagrid.testing.system.haste.Step;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.Vector;
import junit.framework.TestResult;
import junit.framework.TestSuite;
import junit.textui.TestRunner;
import org.cagrid.data.test.creation.DataTestCaseInfo;
import org.cagrid.data.test.creation.DeleteOldServiceStep;
import org.cagrid.data.test.system.BaseSystemTest;
import org.cagrid.data.test.system.ResyncAndBuildStep;
import org.cagrid.data.test.system.VerifyOperationsStep;
import org.cagrid.data.test.upgrades.UnpackOldServiceStep;
import org.cagrid.data.test.upgrades.UpgradeIntroduceServiceStep;
import org.cagrid.data.test.upgrades.UpgradeTestConstants;
/**
* UpgradeFrom1pt4Tests
* Tests to upgrade a data service from 1.4 to current
*/
public class UpgradeFrom1pt4Tests extends BaseSystemTest {
public static final String SERVICE_ZIP_NAME = "BasicDataService_1-4.zip";
public static final String SERVICE_DIR_NAME = "BasicDataService_1-4";
public static final String SERVICE_NAME = "BasicDataService";
public static final String SERVICE_PACKAGE = "org.cagrid.test.data.basic14";
public static final String SERVICE_NAMESPACE = "http://basic14.data.test.cagrid.org/BasicDataService";
private DataTestCaseInfo testServiceInfo = null;
private ServiceContainer container = null;
public String getDescription() {
return "Tests upgrade of a data service from version 1.4 to " + UpgradeTestConstants.getCurrentDataVersion();
}
public String getName() {
return "Data Service 1_4 to "
+ UpgradeTestConstants.getCurrentDataVersion().replace(".", "_")
+ " Upgrade Tests";
}
public boolean storySetUp() {
this.testServiceInfo = new DataTestCaseInfo() {
public String getServiceDirName() {
return SERVICE_DIR_NAME;
}
public String getName() {
return SERVICE_NAME;
}
public String getNamespace() {
return SERVICE_NAMESPACE;
}
public String getPackageName() {
return SERVICE_PACKAGE;
}
};
try {
this.container = ServiceContainerFactory.createContainer(ServiceContainerType.TOMCAT_CONTAINER);
} catch (IOException ex) {
ex.printStackTrace();
fail("Error creating service container: " + ex.getMessage());
}
return true;
}
protected Vector<?> steps() {
Vector<Step> steps = new Vector<Step>();
// steps to unpack and upgrade the old service
steps.add(new DeleteOldServiceStep(testServiceInfo));
steps.add(new UnpackOldServiceStep(SERVICE_ZIP_NAME));
steps.add(new UpgradeIntroduceServiceStep(testServiceInfo.getDir()));
steps.add(new ResyncAndBuildStep(testServiceInfo, getIntroduceBaseDir()));
// deploy the service, check out the CQL 2 related operations and metadata
steps.add(new UnpackContainerStep(container));
List<String> args = Arrays.asList(new String[] {
"-Dno.deployment.validation=true", "-Dperform.index.service.registration=false"});
steps.add(new DeployServiceStep(container, testServiceInfo.getDir(), args));
steps.add(new StartContainerStep(container));
steps.add(new VerifyOperationsStep(container, testServiceInfo.getName(),
false, false, false));
return steps;
}
protected void storyTearDown() throws Throwable {
if (container.isStarted()) {
Step stopStep = new StopContainerStep(container);
stopStep.runStep();
}
if (container.isUnpacked()) {
Step deleteStep = new DestroyContainerStep(container);
deleteStep.runStep();
}
Step destroyStep = new DeleteOldServiceStep(testServiceInfo);
destroyStep.runStep();
}
public static void main(String[] args) {
TestRunner runner = new TestRunner();
TestResult result = runner.doRun(new TestSuite(UpgradeFrom1pt4Tests.class));
System.exit(result.errorCount() + result.failureCount());
}
}
| bsd-3-clause |
Just-D/chromium-1 | android_webview/java/src/org/chromium/android_webview/AwResource.java | 1821 | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package org.chromium.android_webview;
import android.content.res.Resources;
import android.util.SparseArray;
import org.chromium.base.annotations.CalledByNative;
import org.chromium.base.annotations.JNINamespace;
import java.lang.ref.SoftReference;
/**
* A class that defines a set of resource IDs and functionality to resolve
* those IDs to concrete resources.
*/
@JNINamespace("android_webview::AwResource")
public class AwResource {
// The following resource ID's must be initialized by the embedder.
// Array resource ID for the configuration of platform specific key-systems.
private static int sStringArrayConfigKeySystemUUIDMapping;
// The embedder should inject a Resources object that will be used
// to resolve Resource IDs into the actual resources.
private static Resources sResources;
// Loading some resources is expensive, so cache the results.
private static SparseArray<SoftReference<String>> sResourceCache;
public static void setResources(Resources resources) {
sResources = resources;
sResourceCache = new SparseArray<SoftReference<String>>();
}
public static void setErrorPageResources(int loaderror, int nodomain) {
// TODO(mnaganov): Remove after getting rid of all usages.
}
public static void setConfigKeySystemUuidMapping(int config) {
sStringArrayConfigKeySystemUUIDMapping = config;
}
@CalledByNative
private static String[] getConfigKeySystemUuidMapping() {
// No need to cache, since this should be called only once.
return sResources.getStringArray(sStringArrayConfigKeySystemUUIDMapping);
}
}
| bsd-3-clause |
DataBiosphere/jade-data-repo | src/main/java/bio/terra/service/filedata/google/gcs/GcsBufferedReader.java | 582 | package bio.terra.service.filedata.google.gcs;
import com.google.cloud.storage.Storage;
import java.io.BufferedReader;
import java.nio.channels.Channels;
import java.nio.charset.StandardCharsets;
/** Given a gs path and a storage object, return a buffered reader for the blob */
public class GcsBufferedReader extends BufferedReader {
public GcsBufferedReader(Storage storage, String projectId, String gspath) {
super(
Channels.newReader(
GcsPdao.getBlobFromGsPath(storage, gspath, projectId).reader(),
StandardCharsets.UTF_8.name()));
}
}
| bsd-3-clause |
AvatarBlueray/k9-mail-5.002-spam-filter-edition | src/com/fsck/k9/fragment/MessageListFragment.java | 129151 | package com.fsck.k9.fragment;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.Future;
import android.app.Activity;
import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.app.DialogFragment;
import android.app.LoaderManager;
import android.app.LoaderManager.LoaderCallbacks;
import android.content.CursorLoader;
import android.content.Loader;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.CursorAdapter;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.format.DateUtils;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.util.TypedValue;
import android.view.ActionMode;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.QuickContactBadge;
import android.widget.TextView;
import android.widget.Toast;
import com.fsck.k9.Account;
import com.fsck.k9.Account.SortType;
import com.fsck.k9.FontSizes;
import com.fsck.k9.K9;
import com.fsck.k9.Preferences;
import com.fsck.k9.R;
import com.fsck.k9.activity.ActivityListener;
import com.fsck.k9.activity.ChooseFolder;
import com.fsck.k9.activity.FolderInfoHolder;
import com.fsck.k9.activity.MessageReference;
import com.fsck.k9.activity.misc.ContactPictureLoader;
import com.fsck.k9.cache.EmailProviderCache;
import com.fsck.k9.controller.MessagingController;
import com.fsck.k9.fragment.ConfirmationDialogFragment.ConfirmationDialogFragmentListener;
import com.fsck.k9.helper.ContactPicture;
import com.fsck.k9.helper.MergeCursorWithUniqueId;
import com.fsck.k9.helper.MessageHelper;
import com.fsck.k9.helper.StringUtils;
import com.fsck.k9.helper.Utility;
import com.fsck.k9.mail.Address;
import com.fsck.k9.mail.Flag;
import com.fsck.k9.mail.Folder;
import com.fsck.k9.mail.Message;
import com.fsck.k9.mail.MessagingException;
import com.fsck.k9.mail.store.LocalStore;
import com.fsck.k9.mail.store.LocalStore.LocalFolder;
import com.fsck.k9.provider.EmailProvider;
import com.fsck.k9.provider.EmailProvider.MessageColumns;
import com.fsck.k9.provider.EmailProvider.SpecialColumns;
import com.fsck.k9.provider.EmailProvider.ThreadColumns;
import com.fsck.k9.search.ConditionsTreeNode;
import com.fsck.k9.search.LocalSearch;
import com.fsck.k9.search.SearchSpecification;
import com.fsck.k9.search.SearchSpecification.SearchCondition;
import com.fsck.k9.search.SearchSpecification.Searchfield;
import com.fsck.k9.search.SqlQueryBuilder;
import com.fsck.k9.spam_filter.NoteEdit;
import com.fsck.k9.spam_filter.NotesDbAdapter;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
public class MessageListFragment extends Fragment implements OnItemClickListener,
ConfirmationDialogFragmentListener, LoaderCallbacks<Cursor> {
private static final String[] THREADED_PROJECTION = {
MessageColumns.ID,
MessageColumns.UID,
MessageColumns.INTERNAL_DATE,
MessageColumns.SUBJECT,
MessageColumns.DATE,
MessageColumns.SENDER_LIST,
MessageColumns.TO_LIST,
MessageColumns.CC_LIST,
MessageColumns.READ,
MessageColumns.FLAGGED,
MessageColumns.ANSWERED,
MessageColumns.FORWARDED,
MessageColumns.ATTACHMENT_COUNT,
MessageColumns.FOLDER_ID,
MessageColumns.PREVIEW,
ThreadColumns.ROOT,
SpecialColumns.ACCOUNT_UUID,
SpecialColumns.FOLDER_NAME,
SpecialColumns.THREAD_COUNT,
};
private static final int ID_COLUMN = 0;
private static final int UID_COLUMN = 1;
private static final int INTERNAL_DATE_COLUMN = 2;
private static final int SUBJECT_COLUMN = 3;
private static final int DATE_COLUMN = 4;
private static final int SENDER_LIST_COLUMN = 5;
private static final int TO_LIST_COLUMN = 6;
private static final int CC_LIST_COLUMN = 7;
private static final int READ_COLUMN = 8;
private static final int FLAGGED_COLUMN = 9;
private static final int ANSWERED_COLUMN = 10;
private static final int FORWARDED_COLUMN = 11;
private static final int ATTACHMENT_COUNT_COLUMN = 12;
private static final int FOLDER_ID_COLUMN = 13;
private static final int PREVIEW_COLUMN = 14;
private static final int THREAD_ROOT_COLUMN = 15;
private static final int ACCOUNT_UUID_COLUMN = 16;
private static final int FOLDER_NAME_COLUMN = 17;
private static final int THREAD_COUNT_COLUMN = 18;
private static final String[] PROJECTION = Arrays.copyOf(THREADED_PROJECTION,
THREAD_COUNT_COLUMN);
public static MessageListFragment newInstance(LocalSearch search, boolean isThreadDisplay, boolean threadedList) {
MessageListFragment fragment = new MessageListFragment();
Bundle args = new Bundle();
args.putParcelable(ARG_SEARCH, search);
args.putBoolean(ARG_IS_THREAD_DISPLAY, isThreadDisplay);
args.putBoolean(ARG_THREADED_LIST, threadedList);
fragment.setArguments(args);
return fragment;
}
/**
* Reverses the result of a {@link Comparator}.
*
* @param <T>
*/
public static class ReverseComparator<T> implements Comparator<T> {
private Comparator<T> mDelegate;
/**
* @param delegate
* Never {@code null}.
*/
public ReverseComparator(final Comparator<T> delegate) {
mDelegate = delegate;
}
@Override
public int compare(final T object1, final T object2) {
// arg1 & 2 are mixed up, this is done on purpose
return mDelegate.compare(object2, object1);
}
}
/**
* Chains comparator to find a non-0 result.
*
* @param <T>
*/
public static class ComparatorChain<T> implements Comparator<T> {
private List<Comparator<T>> mChain;
/**
* @param chain
* Comparator chain. Never {@code null}.
*/
public ComparatorChain(final List<Comparator<T>> chain) {
mChain = chain;
}
@Override
public int compare(T object1, T object2) {
int result = 0;
for (final Comparator<T> comparator : mChain) {
result = comparator.compare(object1, object2);
if (result != 0) {
break;
}
}
return result;
}
}
public static class ReverseIdComparator implements Comparator<Cursor> {
private int mIdColumn = -1;
@Override
public int compare(Cursor cursor1, Cursor cursor2) {
if (mIdColumn == -1) {
mIdColumn = cursor1.getColumnIndex("_id");
}
long o1Id = cursor1.getLong(mIdColumn);
long o2Id = cursor2.getLong(mIdColumn);
return (o1Id > o2Id) ? -1 : 1;
}
}
public static class AttachmentComparator implements Comparator<Cursor> {
@Override
public int compare(Cursor cursor1, Cursor cursor2) {
int o1HasAttachment = (cursor1.getInt(ATTACHMENT_COUNT_COLUMN) > 0) ? 0 : 1;
int o2HasAttachment = (cursor2.getInt(ATTACHMENT_COUNT_COLUMN) > 0) ? 0 : 1;
return o1HasAttachment - o2HasAttachment;
}
}
public static class FlaggedComparator implements Comparator<Cursor> {
@Override
public int compare(Cursor cursor1, Cursor cursor2) {
int o1IsFlagged = (cursor1.getInt(FLAGGED_COLUMN) == 1) ? 0 : 1;
int o2IsFlagged = (cursor2.getInt(FLAGGED_COLUMN) == 1) ? 0 : 1;
return o1IsFlagged - o2IsFlagged;
}
}
public static class UnreadComparator implements Comparator<Cursor> {
@Override
public int compare(Cursor cursor1, Cursor cursor2) {
int o1IsUnread = cursor1.getInt(READ_COLUMN);
int o2IsUnread = cursor2.getInt(READ_COLUMN);
return o1IsUnread - o2IsUnread;
}
}
public static class DateComparator implements Comparator<Cursor> {
@Override
public int compare(Cursor cursor1, Cursor cursor2) {
long o1Date = cursor1.getLong(DATE_COLUMN);
long o2Date = cursor2.getLong(DATE_COLUMN);
if (o1Date < o2Date) {
return -1;
} else if (o1Date == o2Date) {
return 0;
} else {
return 1;
}
}
}
public static class ArrivalComparator implements Comparator<Cursor> {
@Override
public int compare(Cursor cursor1, Cursor cursor2) {
long o1Date = cursor1.getLong(INTERNAL_DATE_COLUMN);
long o2Date = cursor2.getLong(INTERNAL_DATE_COLUMN);
if (o1Date == o2Date) {
return 0;
} else if (o1Date < o2Date) {
return -1;
} else {
return 1;
}
}
}
public static class SubjectComparator implements Comparator<Cursor> {
@Override
public int compare(Cursor cursor1, Cursor cursor2) {
String subject1 = cursor1.getString(SUBJECT_COLUMN);
String subject2 = cursor2.getString(SUBJECT_COLUMN);
if (subject1 == null) {
return (subject2 == null) ? 0 : -1;
} else if (subject2 == null) {
return 1;
}
return subject1.compareToIgnoreCase(subject2);
}
}
public static class SenderComparator implements Comparator<Cursor> {
@Override
public int compare(Cursor cursor1, Cursor cursor2) {
String sender1 = getSenderAddressFromCursor(cursor1);
String sender2 = getSenderAddressFromCursor(cursor2);
if (sender1 == null && sender2 == null) {
return 0;
} else if (sender1 == null) {
return 1;
} else if (sender2 == null) {
return -1;
} else {
return sender1.compareToIgnoreCase(sender2);
}
}
}
private static final int ACTIVITY_CHOOSE_FOLDER_MOVE = 1;
private static final int ACTIVITY_CHOOSE_FOLDER_COPY = 2;
private static final String ARG_SEARCH = "searchObject";
private static final String ARG_THREADED_LIST = "threadedList";
private static final String ARG_IS_THREAD_DISPLAY = "isThreadedDisplay";
private static final String STATE_SELECTED_MESSAGES = "selectedMessages";
private static final String STATE_ACTIVE_MESSAGE = "activeMessage";
private static final String STATE_REMOTE_SEARCH_PERFORMED = "remoteSearchPerformed";
private static final String STATE_MESSAGE_LIST = "listState";
/**
* Maps a {@link SortType} to a {@link Comparator} implementation.
*/
private static final Map<SortType, Comparator<Cursor>> SORT_COMPARATORS;
static {
// fill the mapping at class time loading
final Map<SortType, Comparator<Cursor>> map =
new EnumMap<SortType, Comparator<Cursor>>(SortType.class);
map.put(SortType.SORT_ATTACHMENT, new AttachmentComparator());
map.put(SortType.SORT_DATE, new DateComparator());
map.put(SortType.SORT_ARRIVAL, new ArrivalComparator());
map.put(SortType.SORT_FLAGGED, new FlaggedComparator());
map.put(SortType.SORT_SUBJECT, new SubjectComparator());
map.put(SortType.SORT_SENDER, new SenderComparator());
map.put(SortType.SORT_UNREAD, new UnreadComparator());
// make it immutable to prevent accidental alteration (content is immutable already)
SORT_COMPARATORS = Collections.unmodifiableMap(map);
}
private ListView mListView;
private PullToRefreshListView mPullToRefreshView;
private Parcelable mSavedListState;
private int mPreviewLines = 0;
private MessageListAdapter mAdapter;
private View mFooterView;
private FolderInfoHolder mCurrentFolder;
private LayoutInflater mInflater;
private MessagingController mController;
private Account mAccount;
private String[] mAccountUuids;
private int mUnreadMessageCount = 0;
private Cursor[] mCursors;
private boolean[] mCursorValid;
private int mUniqueIdColumn;
/**
* Stores the name of the folder that we want to open as soon as possible after load.
*/
private String mFolderName;
private boolean mRemoteSearchPerformed = false;
private Future<?> mRemoteSearchFuture = null;
public List<Message> mExtraSearchResults;
private String mTitle;
private LocalSearch mSearch = null;
private boolean mSingleAccountMode;
private boolean mSingleFolderMode;
private boolean mAllAccounts;
private MessageListHandler mHandler = new MessageListHandler(this);
private SortType mSortType = SortType.SORT_DATE;
private boolean mSortAscending = true;
private boolean mSortDateAscending = false;
private boolean mSenderAboveSubject = false;
private boolean mCheckboxes = true;
private boolean mStars = true;
private int mSelectedCount = 0;
private Set<Long> mSelected = new HashSet<Long>();
private FontSizes mFontSizes = K9.getFontSizes();
private ActionMode mActionMode;
private Boolean mHasConnectivity;
/**
* Relevant messages for the current context when we have to remember the chosen messages
* between user interactions (e.g. selecting a folder for move operation).
*/
private List<Message> mActiveMessages;
/* package visibility for faster inner class access */
MessageHelper mMessageHelper;
private ActionModeCallback mActionModeCallback = new ActionModeCallback();
private MessageListFragmentListener mFragmentListener;
private boolean mThreadedList;
private boolean mIsThreadDisplay;
private Context mContext;
private final ActivityListener mListener = new MessageListActivityListener();
private Preferences mPreferences;
private boolean mLoaderJustInitialized;
private MessageReference mActiveMessage;
/**
* {@code true} after {@link #onCreate(Bundle)} was executed. Used in {@link #updateTitle()} to
* make sure we don't access member variables before initialization is complete.
*/
private boolean mInitialized = false;
private ContactPictureLoader mContactsPictureLoader;
private LocalBroadcastManager mLocalBroadcastManager;
private BroadcastReceiver mCacheBroadcastReceiver;
private IntentFilter mCacheIntentFilter;
/**
* Stores the unique ID of the message the context menu was opened for.
*
* We have to save this because the message list might change between the time the menu was
* opened and when the user clicks on a menu item. When this happens the 'adapter position' that
* is accessible via the {@code ContextMenu} object might correspond to another list item and we
* would end up using/modifying the wrong message.
*
* The value of this field is {@code 0} when no context menu is currently open.
*/
private long mContextMenuUniqueId = 0;
/**
* This class is used to run operations that modify UI elements in the UI thread.
*
* <p>We are using convenience methods that add a {@link android.os.Message} instance or a
* {@link Runnable} to the message queue.</p>
*
* <p><strong>Note:</strong> If you add a method to this class make sure you don't accidentally
* perform the operation in the calling thread.</p>
*/
static class MessageListHandler extends Handler {
private static final int ACTION_FOLDER_LOADING = 1;
private static final int ACTION_REFRESH_TITLE = 2;
private static final int ACTION_PROGRESS = 3;
private static final int ACTION_REMOTE_SEARCH_FINISHED = 4;
private static final int ACTION_GO_BACK = 5;
private static final int ACTION_RESTORE_LIST_POSITION = 6;
private static final int ACTION_OPEN_MESSAGE = 7;
private WeakReference<MessageListFragment> mFragment;
public MessageListHandler(MessageListFragment fragment) {
mFragment = new WeakReference<MessageListFragment>(fragment);
}
public void folderLoading(String folder, boolean loading) {
android.os.Message msg = android.os.Message.obtain(this, ACTION_FOLDER_LOADING,
(loading) ? 1 : 0, 0, folder);
sendMessage(msg);
}
public void refreshTitle() {
android.os.Message msg = android.os.Message.obtain(this, ACTION_REFRESH_TITLE);
sendMessage(msg);
}
public void progress(final boolean progress) {
android.os.Message msg = android.os.Message.obtain(this, ACTION_PROGRESS,
(progress) ? 1 : 0, 0);
sendMessage(msg);
}
public void remoteSearchFinished() {
android.os.Message msg = android.os.Message.obtain(this, ACTION_REMOTE_SEARCH_FINISHED);
sendMessage(msg);
}
public void updateFooter(final String message) {
post(new Runnable() {
@Override
public void run() {
MessageListFragment fragment = mFragment.get();
if (fragment != null) {
fragment.updateFooter(message);
}
}
});
}
public void goBack() {
android.os.Message msg = android.os.Message.obtain(this, ACTION_GO_BACK);
sendMessage(msg);
}
public void restoreListPosition() {
MessageListFragment fragment = mFragment.get();
if (fragment != null) {
android.os.Message msg = android.os.Message.obtain(this, ACTION_RESTORE_LIST_POSITION,
fragment.mSavedListState);
fragment.mSavedListState = null;
sendMessage(msg);
}
}
public void openMessage(MessageReference messageReference) {
android.os.Message msg = android.os.Message.obtain(this, ACTION_OPEN_MESSAGE,
messageReference);
sendMessage(msg);
}
@Override
public void handleMessage(android.os.Message msg) {
MessageListFragment fragment = mFragment.get();
if (fragment == null) {
return;
}
// The following messages don't need an attached activity.
switch (msg.what) {
case ACTION_REMOTE_SEARCH_FINISHED: {
fragment.remoteSearchFinished();
return;
}
}
// Discard messages if the fragment isn't attached to an activity anymore.
Activity activity = fragment.getActivity();
if (activity == null) {
return;
}
switch (msg.what) {
case ACTION_FOLDER_LOADING: {
String folder = (String) msg.obj;
boolean loading = (msg.arg1 == 1);
fragment.folderLoading(folder, loading);
break;
}
case ACTION_REFRESH_TITLE: {
fragment.updateTitle();
break;
}
case ACTION_PROGRESS: {
boolean progress = (msg.arg1 == 1);
fragment.progress(progress);
break;
}
case ACTION_GO_BACK: {
fragment.mFragmentListener.goBack();
break;
}
case ACTION_RESTORE_LIST_POSITION: {
fragment.mListView.onRestoreInstanceState((Parcelable) msg.obj);
break;
}
case ACTION_OPEN_MESSAGE: {
MessageReference messageReference = (MessageReference) msg.obj;
fragment.mFragmentListener.openMessage(messageReference);
break;
}
}
}
}
/**
* @return The comparator to use to display messages in an ordered
* fashion. Never {@code null}.
*/
protected Comparator<Cursor> getComparator() {
final List<Comparator<Cursor>> chain =
new ArrayList<Comparator<Cursor>>(3 /* we add 3 comparators at most */);
// Add the specified comparator
final Comparator<Cursor> comparator = SORT_COMPARATORS.get(mSortType);
if (mSortAscending) {
chain.add(comparator);
} else {
chain.add(new ReverseComparator<Cursor>(comparator));
}
// Add the date comparator if not already specified
if (mSortType != SortType.SORT_DATE && mSortType != SortType.SORT_ARRIVAL) {
final Comparator<Cursor> dateComparator = SORT_COMPARATORS.get(SortType.SORT_DATE);
if (mSortDateAscending) {
chain.add(dateComparator);
} else {
chain.add(new ReverseComparator<Cursor>(dateComparator));
}
}
// Add the id comparator
chain.add(new ReverseIdComparator());
// Build the comparator chain
return new ComparatorChain<Cursor>(chain);
}
private void folderLoading(String folder, boolean loading) {
if (mCurrentFolder != null && mCurrentFolder.name.equals(folder)) {
mCurrentFolder.loading = loading;
}
updateFooterView();
}
public void updateTitle() {
if (!mInitialized) {
return;
}
setWindowTitle();
if (!mSearch.isManualSearch()) {
setWindowProgress();
}
}
private void setWindowProgress() {
int level = Window.PROGRESS_END;
if (mCurrentFolder != null && mCurrentFolder.loading && mListener.getFolderTotal() > 0) {
int divisor = mListener.getFolderTotal();
if (divisor != 0) {
level = (Window.PROGRESS_END / divisor) * (mListener.getFolderCompleted()) ;
if (level > Window.PROGRESS_END) {
level = Window.PROGRESS_END;
}
}
}
mFragmentListener.setMessageListProgress(level);
}
private void setWindowTitle() {
// regular folder content display
if (!isManualSearch() && mSingleFolderMode) {
Activity activity = getActivity();
String displayName = FolderInfoHolder.getDisplayName(activity, mAccount,
mFolderName);
mFragmentListener.setMessageListTitle(displayName);
String operation = mListener.getOperation(activity);
if (operation.length() < 1) {
mFragmentListener.setMessageListSubTitle(mAccount.getEmail());
} else {
mFragmentListener.setMessageListSubTitle(operation);
}
} else {
// query result display. This may be for a search folder as opposed to a user-initiated search.
if (mTitle != null) {
// This was a search folder; the search folder has overridden our title.
mFragmentListener.setMessageListTitle(mTitle);
} else {
// This is a search result; set it to the default search result line.
mFragmentListener.setMessageListTitle(getString(R.string.search_results));
}
mFragmentListener.setMessageListSubTitle(null);
}
// set unread count
if (mUnreadMessageCount <= 0) {
mFragmentListener.setUnreadCount(0);
} else {
if (!mSingleFolderMode && mTitle == null) {
// The unread message count is easily confused
// with total number of messages in the search result, so let's hide it.
mFragmentListener.setUnreadCount(0);
} else {
mFragmentListener.setUnreadCount(mUnreadMessageCount);
}
}
}
private void progress(final boolean progress) {
mFragmentListener.enableActionBarProgress(progress);
if (mPullToRefreshView != null && !progress) {
mPullToRefreshView.onRefreshComplete();
}
}
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (view == mFooterView) {
if (mCurrentFolder != null && !mSearch.isManualSearch()) {
mController.loadMoreMessages(mAccount, mFolderName, null);
} else if (mCurrentFolder != null && isRemoteSearch() &&
mExtraSearchResults != null && mExtraSearchResults.size() > 0) {
int numResults = mExtraSearchResults.size();
int limit = mAccount.getRemoteSearchNumResults();
List<Message> toProcess = mExtraSearchResults;
if (limit > 0 && numResults > limit) {
toProcess = toProcess.subList(0, limit);
mExtraSearchResults = mExtraSearchResults.subList(limit,
mExtraSearchResults.size());
} else {
mExtraSearchResults = null;
updateFooter("");
}
mController.loadSearchResults(mAccount, mCurrentFolder.name, toProcess, mListener);
}
return;
}
Cursor cursor = (Cursor) parent.getItemAtPosition(position);
if (cursor == null) {
return;
}
if (mSelectedCount > 0) {
toggleMessageSelect(position);
} else {
if (mThreadedList && cursor.getInt(THREAD_COUNT_COLUMN) > 1) {
Account account = getAccountFromCursor(cursor);
long folderId = cursor.getLong(FOLDER_ID_COLUMN);
String folderName = getFolderNameById(account, folderId);
// If threading is enabled and this item represents a thread, display the thread contents.
long rootId = cursor.getLong(THREAD_ROOT_COLUMN);
mFragmentListener.showThread(account, folderName, rootId);
} else {
// This item represents a message; just display the message.
openMessageAtPosition(listViewToAdapterPosition(position));
}
}
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mContext = activity.getApplicationContext();
try {
mFragmentListener = (MessageListFragmentListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.getClass() +
" must implement MessageListFragmentListener");
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Context appContext = getActivity().getApplicationContext();
mPreferences = Preferences.getPreferences(appContext);
mController = MessagingController.getInstance(getActivity().getApplication());
mPreviewLines = K9.messageListPreviewLines();
mCheckboxes = K9.messageListCheckboxes();
mStars = K9.messageListStars();
if (K9.showContactPicture()) {
mContactsPictureLoader = ContactPicture.getContactPictureLoader(getActivity());
}
restoreInstanceState(savedInstanceState);
decodeArguments();
createCacheBroadcastReceiver(appContext);
mInitialized = true;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mInflater = inflater;
View view = inflater.inflate(R.layout.message_list_fragment, container, false);
initializePullToRefresh(inflater, view);
initializeLayout();
mListView.setVerticalFadingEdgeEnabled(false);
return view;
}
@Override
public void onDestroyView() {
mSavedListState = mListView.onSaveInstanceState();
super.onDestroyView();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mMessageHelper = MessageHelper.getInstance(getActivity());
initializeMessageList();
// This needs to be done before initializing the cursor loader below
initializeSortSettings();
mLoaderJustInitialized = true;
LoaderManager loaderManager = getLoaderManager();
int len = mAccountUuids.length;
mCursors = new Cursor[len];
mCursorValid = new boolean[len];
for (int i = 0; i < len; i++) {
loaderManager.initLoader(i, null, this);
mCursorValid[i] = false;
}
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
saveSelectedMessages(outState);
saveListState(outState);
outState.putBoolean(STATE_REMOTE_SEARCH_PERFORMED, mRemoteSearchPerformed);
outState.putParcelable(STATE_ACTIVE_MESSAGE, mActiveMessage);
}
/**
* Restore the state of a previous {@link MessageListFragment} instance.
*
* @see #onSaveInstanceState(Bundle)
*/
private void restoreInstanceState(Bundle savedInstanceState) {
if (savedInstanceState == null) {
return;
}
restoreSelectedMessages(savedInstanceState);
mRemoteSearchPerformed = savedInstanceState.getBoolean(STATE_REMOTE_SEARCH_PERFORMED);
mSavedListState = savedInstanceState.getParcelable(STATE_MESSAGE_LIST);
mActiveMessage = savedInstanceState.getParcelable(STATE_ACTIVE_MESSAGE);
}
/**
* Write the unique IDs of selected messages to a {@link Bundle}.
*/
private void saveSelectedMessages(Bundle outState) {
long[] selected = new long[mSelected.size()];
int i = 0;
for (Long id : mSelected) {
selected[i++] = id;
}
outState.putLongArray(STATE_SELECTED_MESSAGES, selected);
}
/**
* Restore selected messages from a {@link Bundle}.
*/
private void restoreSelectedMessages(Bundle savedInstanceState) {
long[] selected = savedInstanceState.getLongArray(STATE_SELECTED_MESSAGES);
for (long id : selected) {
mSelected.add(Long.valueOf(id));
}
}
private void saveListState(Bundle outState) {
if (mSavedListState != null) {
// The previously saved state was never restored, so just use that.
outState.putParcelable(STATE_MESSAGE_LIST, mSavedListState);
} else if (mListView != null) {
outState.putParcelable(STATE_MESSAGE_LIST, mListView.onSaveInstanceState());
}
}
private void initializeSortSettings() {
if (mSingleAccountMode) {
mSortType = mAccount.getSortType();
mSortAscending = mAccount.isSortAscending(mSortType);
mSortDateAscending = mAccount.isSortAscending(SortType.SORT_DATE);
} else {
mSortType = K9.getSortType();
mSortAscending = K9.isSortAscending(mSortType);
mSortDateAscending = K9.isSortAscending(SortType.SORT_DATE);
}
}
private void decodeArguments() {
Bundle args = getArguments();
mThreadedList = args.getBoolean(ARG_THREADED_LIST, false);
mIsThreadDisplay = args.getBoolean(ARG_IS_THREAD_DISPLAY, false);
mSearch = args.getParcelable(ARG_SEARCH);
mTitle = mSearch.getName();
String[] accountUuids = mSearch.getAccountUuids();
mSingleAccountMode = false;
if (accountUuids.length == 1 && !mSearch.searchAllAccounts()) {
mSingleAccountMode = true;
mAccount = mPreferences.getAccount(accountUuids[0]);
}
mSingleFolderMode = false;
if (mSingleAccountMode && (mSearch.getFolderNames().size() == 1)) {
mSingleFolderMode = true;
mFolderName = mSearch.getFolderNames().get(0);
mCurrentFolder = getFolder(mFolderName, mAccount);
}
mAllAccounts = false;
if (mSingleAccountMode) {
mAccountUuids = new String[] { mAccount.getUuid() };
} else {
if (accountUuids.length == 1 &&
accountUuids[0].equals(SearchSpecification.ALL_ACCOUNTS)) {
mAllAccounts = true;
Account[] accounts = mPreferences.getAccounts();
mAccountUuids = new String[accounts.length];
for (int i = 0, len = accounts.length; i < len; i++) {
mAccountUuids[i] = accounts[i].getUuid();
}
if (mAccountUuids.length == 1) {
mSingleAccountMode = true;
mAccount = accounts[0];
}
} else {
mAccountUuids = accountUuids;
}
}
}
private void initializeMessageList() {
mAdapter = new MessageListAdapter();
if (mFolderName != null) {
mCurrentFolder = getFolder(mFolderName, mAccount);
}
if (mSingleFolderMode) {
mListView.addFooterView(getFooterView(mListView));
updateFooterView();
}
mListView.setAdapter(mAdapter);
}
private void createCacheBroadcastReceiver(Context appContext) {
mLocalBroadcastManager = LocalBroadcastManager.getInstance(appContext);
mCacheBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mAdapter.notifyDataSetChanged();
}
};
mCacheIntentFilter = new IntentFilter(EmailProviderCache.ACTION_CACHE_UPDATED);
}
private FolderInfoHolder getFolder(String folder, Account account) {
LocalFolder localFolder = null;
try {
LocalStore localStore = account.getLocalStore();
localFolder = localStore.getFolder(folder);
return new FolderInfoHolder(mContext, localFolder, account);
} catch (Exception e) {
Log.e(K9.LOG_TAG, "getFolder(" + folder + ") goes boom: ", e);
return null;
} finally {
if (localFolder != null) {
localFolder.close();
}
}
}
private String getFolderNameById(Account account, long folderId) {
try {
Folder folder = getFolderById(account, folderId);
if (folder != null) {
return folder.getName();
}
} catch (Exception e) {
Log.e(K9.LOG_TAG, "getFolderNameById() failed.", e);
}
return null;
}
private Folder getFolderById(Account account, long folderId) {
try {
LocalStore localStore = account.getLocalStore();
LocalFolder localFolder = localStore.getFolderById(folderId);
localFolder.open(Folder.OPEN_MODE_RO);
return localFolder;
} catch (Exception e) {
Log.e(K9.LOG_TAG, "getFolderNameById() failed.", e);
return null;
}
}
@Override
public void onPause() {
super.onPause();
mLocalBroadcastManager.unregisterReceiver(mCacheBroadcastReceiver);
mListener.onPause(getActivity());
mController.removeListener(mListener);
}
/**
* On resume we refresh messages for the folder that is currently open.
* This guarantees that things like unread message count and read status
* are updated.
*/
@Override
public void onResume() {
super.onResume();
Context appContext = getActivity().getApplicationContext();
mSenderAboveSubject = K9.messageListSenderAboveSubject();
if (!mLoaderJustInitialized) {
restartLoader();
} else {
mLoaderJustInitialized = false;
}
// Check if we have connectivity. Cache the value.
if (mHasConnectivity == null) {
mHasConnectivity = Utility.hasConnectivity(getActivity().getApplication());
}
mLocalBroadcastManager.registerReceiver(mCacheBroadcastReceiver, mCacheIntentFilter);
mListener.onResume(getActivity());
mController.addListener(mListener);
//Cancel pending new mail notifications when we open an account
Account[] accountsWithNotification;
Account account = mAccount;
if (account != null) {
accountsWithNotification = new Account[] { account };
} else {
accountsWithNotification = mPreferences.getAccounts();
}
for (Account accountWithNotification : accountsWithNotification) {
mController.notifyAccountCancel(appContext, accountWithNotification);
}
if (mAccount != null && mFolderName != null && !mSearch.isManualSearch()) {
mController.getFolderUnreadMessageCount(mAccount, mFolderName, mListener);
}
updateTitle();
}
private void restartLoader() {
if (mCursorValid == null) {
return;
}
// Refresh the message list
LoaderManager loaderManager = getLoaderManager();
for (int i = 0; i < mAccountUuids.length; i++) {
loaderManager.restartLoader(i, null, this);
mCursorValid[i] = false;
}
}
private void initializePullToRefresh(LayoutInflater inflater, View layout) {
mPullToRefreshView = (PullToRefreshListView) layout.findViewById(R.id.message_list);
// Set empty view
View loadingView = inflater.inflate(R.layout.message_list_loading, null);
mPullToRefreshView.setEmptyView(loadingView);
if (isRemoteSearchAllowed()) {
// "Pull to search server"
mPullToRefreshView.setOnRefreshListener(
new PullToRefreshBase.OnRefreshListener<ListView>() {
@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
mPullToRefreshView.onRefreshComplete();
onRemoteSearchRequested();
}
});
ILoadingLayout proxy = mPullToRefreshView.getLoadingLayoutProxy();
proxy.setPullLabel(getString(
R.string.pull_to_refresh_remote_search_from_local_search_pull));
proxy.setReleaseLabel(getString(
R.string.pull_to_refresh_remote_search_from_local_search_release));
} else if (isCheckMailSupported()) {
// "Pull to refresh"
mPullToRefreshView.setOnRefreshListener(
new PullToRefreshBase.OnRefreshListener<ListView>() {
@Override
public void onRefresh(PullToRefreshBase<ListView> refreshView) {
checkMail();
}
});
}
// Disable pull-to-refresh until the message list has been loaded
setPullToRefreshEnabled(false);
}
/**
* Enable or disable pull-to-refresh.
*
* @param enable
* {@code true} to enable. {@code false} to disable.
*/
private void setPullToRefreshEnabled(boolean enable) {
mPullToRefreshView.setMode((enable) ?
PullToRefreshBase.Mode.PULL_FROM_START : PullToRefreshBase.Mode.DISABLED);
}
private void initializeLayout() {
mListView = mPullToRefreshView.getRefreshableView();
mListView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
mListView.setLongClickable(true);
mListView.setFastScrollEnabled(true);
mListView.setScrollingCacheEnabled(false);
mListView.setOnItemClickListener(this);
registerForContextMenu(mListView);
}
public void onCompose() {
if (!mSingleAccountMode) {
/*
* If we have a query string, we don't have an account to let
* compose start the default action.
*/
mFragmentListener.onCompose(null);
} else {
mFragmentListener.onCompose(mAccount);
}
}
public void onReply(Message message) {
mFragmentListener.onReply(message);
}
public void onReplyAll(Message message) {
mFragmentListener.onReplyAll(message);
}
public void onForward(Message message) {
mFragmentListener.onForward(message);
}
public void onResendMessage(Message message) {
mFragmentListener.onResendMessage(message);
}
public void changeSort(SortType sortType) {
Boolean sortAscending = (mSortType == sortType) ? !mSortAscending : null;
changeSort(sortType, sortAscending);
}
/**
* User has requested a remote search. Setup the bundle and start the intent.
*/
public void onRemoteSearchRequested() {
String searchAccount;
String searchFolder;
searchAccount = mAccount.getUuid();
searchFolder = mCurrentFolder.name;
String queryString = mSearch.getRemoteSearchArguments();
mRemoteSearchPerformed = true;
mRemoteSearchFuture = mController.searchRemoteMessages(searchAccount, searchFolder,
queryString, null, null, mListener);
setPullToRefreshEnabled(false);
mFragmentListener.remoteSearchStarted();
}
/**
* Change the sort type and sort order used for the message list.
*
* @param sortType
* Specifies which field to use for sorting the message list.
* @param sortAscending
* Specifies the sort order. If this argument is {@code null} the default search order
* for the sort type is used.
*/
// FIXME: Don't save the changes in the UI thread
private void changeSort(SortType sortType, Boolean sortAscending) {
mSortType = sortType;
Account account = mAccount;
if (account != null) {
account.setSortType(mSortType);
if (sortAscending == null) {
mSortAscending = account.isSortAscending(mSortType);
} else {
mSortAscending = sortAscending;
}
account.setSortAscending(mSortType, mSortAscending);
mSortDateAscending = account.isSortAscending(SortType.SORT_DATE);
account.save(mPreferences);
} else {
K9.setSortType(mSortType);
if (sortAscending == null) {
mSortAscending = K9.isSortAscending(mSortType);
} else {
mSortAscending = sortAscending;
}
K9.setSortAscending(mSortType, mSortAscending);
mSortDateAscending = K9.isSortAscending(SortType.SORT_DATE);
Editor editor = mPreferences.getPreferences().edit();
K9.save(editor);
editor.commit();
}
reSort();
}
private void reSort() {
int toastString = mSortType.getToast(mSortAscending);
Toast toast = Toast.makeText(getActivity(), toastString, Toast.LENGTH_SHORT);
toast.show();
LoaderManager loaderManager = getLoaderManager();
for (int i = 0, len = mAccountUuids.length; i < len; i++) {
loaderManager.restartLoader(i, null, this);
}
}
public void onCycleSort() {
SortType[] sorts = SortType.values();
int curIndex = 0;
for (int i = 0; i < sorts.length; i++) {
if (sorts[i] == mSortType) {
curIndex = i;
break;
}
}
curIndex++;
if (curIndex == sorts.length) {
curIndex = 0;
}
changeSort(sorts[curIndex]);
}
private void onDelete(Message message) {
onDelete(Collections.singletonList(message));
}
private void onDelete(List<Message> messages) {
if (K9.confirmDelete()) {
// remember the message selection for #onCreateDialog(int)
mActiveMessages = messages;
showDialog(R.id.dialog_confirm_delete);
} else {
onDeleteConfirmed(messages);
}
}
private void onDeleteConfirmed(List<Message> messages) {
if (mThreadedList) {
mController.deleteThreads(messages);
} else {
mController.deleteMessages(messages, null);
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}
switch (requestCode) {
case ACTIVITY_CHOOSE_FOLDER_MOVE:
case ACTIVITY_CHOOSE_FOLDER_COPY: {
if (data == null) {
return;
}
final String destFolderName = data.getStringExtra(ChooseFolder.EXTRA_NEW_FOLDER);
final List<Message> messages = mActiveMessages;
if (destFolderName != null) {
mActiveMessages = null; // don't need it any more
if (messages.size() > 0) {
Account account = messages.get(0).getFolder().getAccount();
account.setLastSelectedFolderName(destFolderName);
}
switch (requestCode) {
case ACTIVITY_CHOOSE_FOLDER_MOVE:
move(messages, destFolderName);
break;
case ACTIVITY_CHOOSE_FOLDER_COPY:
copy(messages, destFolderName);
break;
}
}
break;
}
}
}
public void onExpunge() {
if (mCurrentFolder != null) {
onExpunge(mAccount, mCurrentFolder.name);
}
}
private void onExpunge(final Account account, String folderName) {
mController.expunge(account, folderName, null);
}
private void showDialog(int dialogId) {
DialogFragment fragment;
switch (dialogId) {
case R.id.dialog_confirm_spam: {
String title = getString(R.string.dialog_confirm_spam_title);
int selectionSize = mActiveMessages.size();
String message = getResources().getQuantityString(
R.plurals.dialog_confirm_spam_message, selectionSize,
Integer.valueOf(selectionSize));
String confirmText = getString(R.string.dialog_confirm_spam_confirm_button);
String cancelText = getString(R.string.dialog_confirm_spam_cancel_button);
fragment = ConfirmationDialogFragment.newInstance(dialogId, title, message,
confirmText, cancelText);
break;
}
case R.id.dialog_confirm_delete: {
String title = getString(R.string.dialog_confirm_delete_title);
int selectionSize = mActiveMessages.size();
String message = getResources().getQuantityString(
R.plurals.dialog_confirm_delete_messages, selectionSize,
Integer.valueOf(selectionSize));
String confirmText = getString(R.string.dialog_confirm_delete_confirm_button);
String cancelText = getString(R.string.dialog_confirm_delete_cancel_button);
fragment = ConfirmationDialogFragment.newInstance(dialogId, title, message,
confirmText, cancelText);
break;
}
default: {
throw new RuntimeException("Called showDialog(int) with unknown dialog id.");
}
}
fragment.setTargetFragment(this, dialogId);
fragment.show(getFragmentManager(), getDialogTag(dialogId));
}
private String getDialogTag(int dialogId) {
return "dialog-" + dialogId;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int itemId = item.getItemId();
switch (itemId) {
case R.id.set_sort_date: {
changeSort(SortType.SORT_DATE);
return true;
}
case R.id.set_sort_arrival: {
changeSort(SortType.SORT_ARRIVAL);
return true;
}
case R.id.set_sort_subject: {
changeSort(SortType.SORT_SUBJECT);
return true;
}
case R.id.set_sort_sender: {
changeSort(SortType.SORT_SENDER);
return true;
}
case R.id.set_sort_flag: {
changeSort(SortType.SORT_FLAGGED);
return true;
}
case R.id.set_sort_unread: {
changeSort(SortType.SORT_UNREAD);
return true;
}
case R.id.set_sort_attach: {
changeSort(SortType.SORT_ATTACHMENT);
return true;
}
case R.id.select_all: {
selectAll();
return true;
}
}
if (!mSingleAccountMode) {
// None of the options after this point are "safe" for search results
//TODO: This is not true for "unread" and "starred" searches in regular folders
return false;
}
switch (itemId) {
case R.id.send_messages: {
onSendPendingMessages();
return true;
}
case R.id.expunge: {
if (mCurrentFolder != null) {
onExpunge(mAccount, mCurrentFolder.name);
}
return true;
}
default: {
return super.onOptionsItemSelected(item);
}
}
}
public void onSendPendingMessages() {
mController.sendPendingMessages(mAccount, null);
}
@Override
public boolean onContextItemSelected(android.view.MenuItem item) {
if (mContextMenuUniqueId == 0) {
return false;
}
int adapterPosition = getPositionForUniqueId(mContextMenuUniqueId);
if (adapterPosition == AdapterView.INVALID_POSITION) {
return false;
}
switch (item.getItemId()) {
case R.id.deselect:
case R.id.select: {
toggleMessageSelectWithAdapterPosition(adapterPosition);
break;
}
case R.id.reply: {
Message message = getMessageAtPosition(adapterPosition);
onReply(message);
break;
}
case R.id.configure_spam_filter_from_source: {
Message message = getMessageAtPosition(adapterPosition);
String subj = message.getSubject();
Address[] address = message.getFrom();
Address adr_t = null;
for (Address adr:address){
adr_t = adr;
}
String from = "";
if ( adr_t != null ) {
from = adr_t.getAddress();
}
Intent i = new Intent(mContext, NoteEdit.class);
i.putExtra(NotesDbAdapter.KEY_SUBJ, subj);
i.putExtra(NotesDbAdapter.KEY_FROM, from);
startActivityForResult(i, 1);
break;
}
case R.id.to_spam_from_this_domain: {
Message message = getMessageAtPosition(adapterPosition);
Address[] address = message.getFrom();
Address adr_t = null;
for (Address adr:address){
adr_t = adr;
}
String from = "";
if ( adr_t != null ) {
from = ".*@"+adr_t.getAddress().split("@")[1];
}
Intent i = new Intent(mContext, NoteEdit.class);
i.putExtra(NotesDbAdapter.KEY_SUBJ, "");
i.putExtra(NotesDbAdapter.KEY_FROM, from);
i.putExtra(NotesDbAdapter.KEY_DEL, true);
startActivityForResult(i, 1);
break;
}
case R.id.reply_all: {
Message message = getMessageAtPosition(adapterPosition);
onReplyAll(message);
break;
}
case R.id.forward: {
Message message = getMessageAtPosition(adapterPosition);
onForward(message);
break;
}
case R.id.send_again: {
Message message = getMessageAtPosition(adapterPosition);
onResendMessage(message);
mSelectedCount = 0;
break;
}
case R.id.same_sender: {
Cursor cursor = (Cursor) mAdapter.getItem(adapterPosition);
String senderAddress = getSenderAddressFromCursor(cursor);
if (senderAddress != null) {
mFragmentListener.showMoreFromSameSender(senderAddress);
}
break;
}
case R.id.delete: {
Message message = getMessageAtPosition(adapterPosition);
onDelete(message);
break;
}
case R.id.mark_as_read: {
setFlag(adapterPosition, Flag.SEEN, true);
break;
}
case R.id.mark_as_unread: {
setFlag(adapterPosition, Flag.SEEN, false);
break;
}
case R.id.flag: {
setFlag(adapterPosition, Flag.FLAGGED, true);
break;
}
case R.id.unflag: {
setFlag(adapterPosition, Flag.FLAGGED, false);
break;
}
// only if the account supports this
case R.id.archive: {
Message message = getMessageAtPosition(adapterPosition);
onArchive(message);
break;
}
case R.id.spam: {
Message message = getMessageAtPosition(adapterPosition);
onSpam(message);
break;
}
case R.id.move: {
Message message = getMessageAtPosition(adapterPosition);
onMove(message);
break;
}
case R.id.copy: {
Message message = getMessageAtPosition(adapterPosition);
onCopy(message);
break;
}
}
mContextMenuUniqueId = 0;
return true;
}
private static String getSenderAddressFromCursor(Cursor cursor) {
String fromList = cursor.getString(SENDER_LIST_COLUMN);
Address[] fromAddrs = Address.unpack(fromList);
return (fromAddrs.length > 0) ? fromAddrs[0].getAddress() : null;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
Cursor cursor = (Cursor) mListView.getItemAtPosition(info.position);
if (cursor == null) {
return;
}
getActivity().getMenuInflater().inflate(R.menu.message_list_item_context, menu);
mContextMenuUniqueId = cursor.getLong(mUniqueIdColumn);
Account account = getAccountFromCursor(cursor);
String subject = cursor.getString(SUBJECT_COLUMN);
boolean read = (cursor.getInt(READ_COLUMN) == 1);
boolean flagged = (cursor.getInt(FLAGGED_COLUMN) == 1);
menu.setHeaderTitle(subject);
if( mSelected.contains(mContextMenuUniqueId)) {
menu.findItem(R.id.select).setVisible(false);
} else {
menu.findItem(R.id.deselect).setVisible(false);
}
if (read) {
menu.findItem(R.id.mark_as_read).setVisible(false);
} else {
menu.findItem(R.id.mark_as_unread).setVisible(false);
}
if (flagged) {
menu.findItem(R.id.flag).setVisible(false);
} else {
menu.findItem(R.id.unflag).setVisible(false);
}
if (!mController.isCopyCapable(account)) {
menu.findItem(R.id.copy).setVisible(false);
}
if (!mController.isMoveCapable(account)) {
menu.findItem(R.id.move).setVisible(false);
menu.findItem(R.id.archive).setVisible(false);
menu.findItem(R.id.spam).setVisible(false);
}
if (!account.hasArchiveFolder()) {
menu.findItem(R.id.archive).setVisible(false);
}
if (!account.hasSpamFolder()) {
menu.findItem(R.id.spam).setVisible(false);
}
}
public void onSwipeRightToLeft(final MotionEvent e1, final MotionEvent e2) {
// Handle right-to-left as an un-select
handleSwipe(e1, false);
}
public void onSwipeLeftToRight(final MotionEvent e1, final MotionEvent e2) {
// Handle left-to-right as a select.
handleSwipe(e1, true);
}
/**
* Handle a select or unselect swipe event.
*
* @param downMotion
* Event that started the swipe
* @param selected
* {@code true} if this was an attempt to select (i.e. left to right).
*/
private void handleSwipe(final MotionEvent downMotion, final boolean selected) {
int x = (int) downMotion.getRawX();
int y = (int) downMotion.getRawY();
Rect headerRect = new Rect();
mListView.getGlobalVisibleRect(headerRect);
// Only handle swipes in the visible area of the message list
if (headerRect.contains(x, y)) {
int[] listPosition = new int[2];
mListView.getLocationOnScreen(listPosition);
int listX = x - listPosition[0];
int listY = y - listPosition[1];
int listViewPosition = mListView.pointToPosition(listX, listY);
toggleMessageSelect(listViewPosition);
}
}
private int listViewToAdapterPosition(int position) {
if (position > 0 && position <= mAdapter.getCount()) {
return position - 1;
}
return AdapterView.INVALID_POSITION;
}
private int adapterToListViewPosition(int position) {
if (position >= 0 && position < mAdapter.getCount()) {
return position + 1;
}
return AdapterView.INVALID_POSITION;
}
class MessageListActivityListener extends ActivityListener {
@Override
public void remoteSearchFailed(Account acct, String folder, final String err) {
mHandler.post(new Runnable() {
@Override
public void run() {
Activity activity = getActivity();
if (activity != null) {
Toast.makeText(activity, R.string.remote_search_error,
Toast.LENGTH_LONG).show();
}
}
});
}
@Override
public void remoteSearchStarted(Account acct, String folder) {
mHandler.progress(true);
mHandler.updateFooter(mContext.getString(R.string.remote_search_sending_query));
}
@Override
public void enableProgressIndicator(boolean enable) {
mHandler.progress(enable);
}
@Override
public void remoteSearchFinished(Account acct, String folder, int numResults, List<Message> extraResults) {
mHandler.progress(false);
mHandler.remoteSearchFinished();
mExtraSearchResults = extraResults;
if (extraResults != null && extraResults.size() > 0) {
mHandler.updateFooter(String.format(mContext.getString(R.string.load_more_messages_fmt), acct.getRemoteSearchNumResults()));
} else {
mHandler.updateFooter("");
}
mFragmentListener.setMessageListProgress(Window.PROGRESS_END);
}
@Override
public void remoteSearchServerQueryComplete(Account account, String folderName, int numResults) {
mHandler.progress(true);
if (account != null && account.getRemoteSearchNumResults() != 0 && numResults > account.getRemoteSearchNumResults()) {
mHandler.updateFooter(mContext.getString(R.string.remote_search_downloading_limited,
account.getRemoteSearchNumResults(), numResults));
} else {
mHandler.updateFooter(mContext.getString(R.string.remote_search_downloading, numResults));
}
mFragmentListener.setMessageListProgress(Window.PROGRESS_START);
}
@Override
public void informUserOfStatus() {
mHandler.refreshTitle();
}
@Override
public void synchronizeMailboxStarted(Account account, String folder) {
if (updateForMe(account, folder)) {
mHandler.progress(true);
mHandler.folderLoading(folder, true);
}
super.synchronizeMailboxStarted(account, folder);
}
@Override
public void synchronizeMailboxFinished(Account account, String folder,
int totalMessagesInMailbox, int numNewMessages) {
if (updateForMe(account, folder)) {
mHandler.progress(false);
mHandler.folderLoading(folder, false);
}
super.synchronizeMailboxFinished(account, folder, totalMessagesInMailbox, numNewMessages);
}
@Override
public void synchronizeMailboxFailed(Account account, String folder, String message) {
if (updateForMe(account, folder)) {
mHandler.progress(false);
mHandler.folderLoading(folder, false);
}
super.synchronizeMailboxFailed(account, folder, message);
}
@Override
public void folderStatusChanged(Account account, String folder, int unreadMessageCount) {
if (isSingleAccountMode() && isSingleFolderMode() && mAccount.equals(account) &&
mFolderName.equals(folder)) {
mUnreadMessageCount = unreadMessageCount;
}
super.folderStatusChanged(account, folder, unreadMessageCount);
}
private boolean updateForMe(Account account, String folder) {
if (account == null || folder == null) {
return false;
}
if (!Utility.arrayContains(mAccountUuids, account.getUuid())) {
return false;
}
List<String> folderNames = mSearch.getFolderNames();
return (folderNames.size() == 0 || folderNames.contains(folder));
}
}
class MessageListAdapter extends CursorAdapter {
private Drawable mAttachmentIcon;
private Drawable mForwardedIcon;
private Drawable mAnsweredIcon;
private Drawable mForwardedAnsweredIcon;
MessageListAdapter() {
super(getActivity(), null, 0);
mAttachmentIcon = getResources().getDrawable(R.drawable.ic_email_attachment_small);
mAnsweredIcon = getResources().getDrawable(R.drawable.ic_email_answered_small);
mForwardedIcon = getResources().getDrawable(R.drawable.ic_email_forwarded_small);
mForwardedAnsweredIcon = getResources().getDrawable(R.drawable.ic_email_forwarded_answered_small);
}
private String recipientSigil(boolean toMe, boolean ccMe) {
if (toMe) {
return getString(R.string.messagelist_sent_to_me_sigil);
} else if (ccMe) {
return getString(R.string.messagelist_sent_cc_me_sigil);
} else {
return "";
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.message_list_item, parent, false);
view.setId(R.layout.message_list_item);
MessageViewHolder holder = new MessageViewHolder();
holder.date = (TextView) view.findViewById(R.id.date);
holder.chip = view.findViewById(R.id.chip);
if (mPreviewLines == 0 && mContactsPictureLoader == null) {
view.findViewById(R.id.preview).setVisibility(View.GONE);
holder.preview = (TextView) view.findViewById(R.id.sender_compact);
holder.flagged = (CheckBox) view.findViewById(R.id.flagged_center_right);
view.findViewById(R.id.flagged_bottom_right).setVisibility(View.GONE);
} else {
view.findViewById(R.id.sender_compact).setVisibility(View.GONE);
holder.preview = (TextView) view.findViewById(R.id.preview);
holder.flagged = (CheckBox) view.findViewById(R.id.flagged_bottom_right);
view.findViewById(R.id.flagged_center_right).setVisibility(View.GONE);
}
QuickContactBadge contactBadge =
(QuickContactBadge) view.findViewById(R.id.contact_badge);
if (mContactsPictureLoader != null) {
holder.contactBadge = contactBadge;
} else {
contactBadge.setVisibility(View.GONE);
}
if (mSenderAboveSubject) {
holder.from = (TextView) view.findViewById(R.id.subject);
mFontSizes.setViewTextSize(holder.from, mFontSizes.getMessageListSender());
} else {
holder.subject = (TextView) view.findViewById(R.id.subject);
mFontSizes.setViewTextSize(holder.subject, mFontSizes.getMessageListSubject());
}
mFontSizes.setViewTextSize(holder.date, mFontSizes.getMessageListDate());
// 1 preview line is needed even if it is set to 0, because subject is part of the same text view
holder.preview.setLines(Math.max(mPreviewLines,1));
mFontSizes.setViewTextSize(holder.preview, mFontSizes.getMessageListPreview());
holder.threadCount = (TextView) view.findViewById(R.id.thread_count);
mFontSizes.setViewTextSize(holder.threadCount, mFontSizes.getMessageListSubject()); // thread count is next to subject
view.findViewById(R.id.selected_checkbox_wrapper).setVisibility((mCheckboxes) ? View.VISIBLE : View.GONE);
holder.flagged.setVisibility(mStars ? View.VISIBLE : View.GONE);
holder.flagged.setOnClickListener(holder);
holder.selected = (CheckBox) view.findViewById(R.id.selected_checkbox);
holder.selected.setOnClickListener(holder);
view.setTag(holder);
return view;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
Account account = getAccountFromCursor(cursor);
String fromList = cursor.getString(SENDER_LIST_COLUMN);
String toList = cursor.getString(TO_LIST_COLUMN);
String ccList = cursor.getString(CC_LIST_COLUMN);
Address[] fromAddrs = Address.unpack(fromList);
Address[] toAddrs = Address.unpack(toList);
Address[] ccAddrs = Address.unpack(ccList);
boolean fromMe = mMessageHelper.toMe(account, fromAddrs);
boolean toMe = mMessageHelper.toMe(account, toAddrs);
boolean ccMe = mMessageHelper.toMe(account, ccAddrs);
CharSequence displayName = mMessageHelper.getDisplayName(account, fromAddrs, toAddrs);
CharSequence displayDate = DateUtils.getRelativeTimeSpanString(context, cursor.getLong(DATE_COLUMN));
Address counterpartyAddress = null;
if (fromMe) {
if (toAddrs.length > 0) {
counterpartyAddress = toAddrs[0];
} else if (ccAddrs.length > 0) {
counterpartyAddress = ccAddrs[0];
}
} else if (fromAddrs.length > 0) {
counterpartyAddress = fromAddrs[0];
}
int threadCount = (mThreadedList) ? cursor.getInt(THREAD_COUNT_COLUMN) : 0;
String subject = cursor.getString(SUBJECT_COLUMN);
if (StringUtils.isNullOrEmpty(subject)) {
subject = getString(R.string.general_no_subject);
} else if (threadCount > 1) {
// If this is a thread, strip the RE/FW from the subject. "Be like Outlook."
subject = Utility.stripSubject(subject);
}
boolean read = (cursor.getInt(READ_COLUMN) == 1);
boolean flagged = (cursor.getInt(FLAGGED_COLUMN) == 1);
boolean answered = (cursor.getInt(ANSWERED_COLUMN) == 1);
boolean forwarded = (cursor.getInt(FORWARDED_COLUMN) == 1);
boolean hasAttachments = (cursor.getInt(ATTACHMENT_COUNT_COLUMN) > 0);
MessageViewHolder holder = (MessageViewHolder) view.getTag();
int maybeBoldTypeface = (read) ? Typeface.NORMAL : Typeface.BOLD;
long uniqueId = cursor.getLong(mUniqueIdColumn);
boolean selected = mSelected.contains(uniqueId);
holder.chip.setBackgroundColor(account.getChipColor());
if (mCheckboxes) {
holder.selected.setChecked(selected);
}
if (mStars) {
holder.flagged.setChecked(flagged);
}
holder.position = cursor.getPosition();
if (holder.contactBadge != null) {
if (counterpartyAddress != null) {
holder.contactBadge.assignContactFromEmail(counterpartyAddress.getAddress(), true);
/*
* At least in Android 2.2 a different background + padding is used when no
* email address is available. ListView reuses the views but QuickContactBadge
* doesn't reset the padding, so we do it ourselves.
*/
holder.contactBadge.setPadding(0, 0, 0, 0);
mContactsPictureLoader.loadContactPicture(counterpartyAddress, holder.contactBadge);
} else {
holder.contactBadge.assignContactUri(null);
holder.contactBadge.setImageResource(R.drawable.ic_contact_picture);
}
}
// Background color
if (selected || K9.useBackgroundAsUnreadIndicator()) {
int res;
if (selected) {
res = R.attr.messageListSelectedBackgroundColor;
} else if (read) {
res = R.attr.messageListReadItemBackgroundColor;
} else {
res = R.attr.messageListUnreadItemBackgroundColor;
}
TypedValue outValue = new TypedValue();
getActivity().getTheme().resolveAttribute(res, outValue, true);
view.setBackgroundColor(outValue.data);
} else {
view.setBackgroundColor(Color.TRANSPARENT);
}
if (mActiveMessage != null) {
String uid = cursor.getString(UID_COLUMN);
String folderName = cursor.getString(FOLDER_NAME_COLUMN);
if (account.getUuid().equals(mActiveMessage.accountUuid) &&
folderName.equals(mActiveMessage.folderName) &&
uid.equals(mActiveMessage.uid)) {
int res = R.attr.messageListActiveItemBackgroundColor;
TypedValue outValue = new TypedValue();
getActivity().getTheme().resolveAttribute(res, outValue, true);
view.setBackgroundColor(outValue.data);
}
}
// Thread count
if (threadCount > 1) {
holder.threadCount.setText(Integer.toString(threadCount));
holder.threadCount.setVisibility(View.VISIBLE);
} else {
holder.threadCount.setVisibility(View.GONE);
}
CharSequence beforePreviewText = (mSenderAboveSubject) ? subject : displayName;
String sigil = recipientSigil(toMe, ccMe);
SpannableStringBuilder messageStringBuilder = new SpannableStringBuilder(sigil)
.append(beforePreviewText);
if (mPreviewLines > 0) {
String preview = cursor.getString(PREVIEW_COLUMN);
if (preview != null) {
messageStringBuilder.append(" ").append(preview);
}
}
holder.preview.setText(messageStringBuilder, TextView.BufferType.SPANNABLE);
Spannable str = (Spannable)holder.preview.getText();
// Create a span section for the sender, and assign the correct font size and weight
int fontSize = (mSenderAboveSubject) ?
mFontSizes.getMessageListSubject():
mFontSizes.getMessageListSender();
AbsoluteSizeSpan span = new AbsoluteSizeSpan(fontSize, true);
str.setSpan(span, 0, beforePreviewText.length() + sigil.length(),
Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
//TODO: make this part of the theme
int color = (K9.getK9Theme() == K9.Theme.LIGHT) ?
Color.rgb(105, 105, 105) :
Color.rgb(160, 160, 160);
// Set span (color) for preview message
str.setSpan(new ForegroundColorSpan(color), beforePreviewText.length() + sigil.length(),
str.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Drawable statusHolder = null;
if (forwarded && answered) {
statusHolder = mForwardedAnsweredIcon;
} else if (answered) {
statusHolder = mAnsweredIcon;
} else if (forwarded) {
statusHolder = mForwardedIcon;
}
if (holder.from != null ) {
holder.from.setTypeface(null, maybeBoldTypeface);
if (mSenderAboveSubject) {
holder.from.setCompoundDrawablesWithIntrinsicBounds(
statusHolder, // left
null, // top
hasAttachments ? mAttachmentIcon : null, // right
null); // bottom
holder.from.setText(displayName);
} else {
holder.from.setText(new SpannableStringBuilder(sigil).append(displayName));
}
}
if (holder.subject != null ) {
if (!mSenderAboveSubject) {
holder.subject.setCompoundDrawablesWithIntrinsicBounds(
statusHolder, // left
null, // top
hasAttachments ? mAttachmentIcon : null, // right
null); // bottom
}
holder.subject.setTypeface(null, maybeBoldTypeface);
holder.subject.setText(subject);
}
holder.date.setText(displayDate);
}
}
class MessageViewHolder implements View.OnClickListener {
public TextView subject;
public TextView preview;
public TextView from;
public TextView time;
public TextView date;
public View chip;
public TextView threadCount;
public CheckBox flagged;
public CheckBox selected;
public int position = -1;
public QuickContactBadge contactBadge;
@Override
public void onClick(View view) {
if (position != -1) {
switch (view.getId()) {
case R.id.selected_checkbox:
toggleMessageSelectWithAdapterPosition(position);
break;
case R.id.flagged_bottom_right:
case R.id.flagged_center_right:
toggleMessageFlagWithAdapterPosition(position);
break;
}
}
}
}
private View getFooterView(ViewGroup parent) {
if (mFooterView == null) {
mFooterView = mInflater.inflate(R.layout.message_list_item_footer, parent, false);
mFooterView.setId(R.layout.message_list_item_footer);
FooterViewHolder holder = new FooterViewHolder();
holder.main = (TextView) mFooterView.findViewById(R.id.main_text);
mFooterView.setTag(holder);
}
return mFooterView;
}
private void updateFooterView() {
if (!mSearch.isManualSearch() && mCurrentFolder != null && mAccount != null) {
if (mCurrentFolder.loading) {
updateFooter(mContext.getString(R.string.status_loading_more));
} else {
String message;
if (!mCurrentFolder.lastCheckFailed) {
if (mAccount.getDisplayCount() == 0) {
message = mContext.getString(R.string.message_list_load_more_messages_action);
} else {
message = String.format(mContext.getString(R.string.load_more_messages_fmt), mAccount.getDisplayCount());
}
} else {
message = mContext.getString(R.string.status_loading_more_failed);
}
updateFooter(message);
}
} else {
updateFooter(null);
}
}
public void updateFooter(final String text) {
if (mFooterView == null) {
return;
}
FooterViewHolder holder = (FooterViewHolder) mFooterView.getTag();
if (text != null) {
holder.main.setText(text);
}
if (holder.main.getText().length() > 0) {
holder.main.setVisibility(View.VISIBLE);
} else {
holder.main.setVisibility(View.GONE);
}
}
static class FooterViewHolder {
public TextView main;
}
/**
* Set selection state for all messages.
*
* @param selected
* If {@code true} all messages get selected. Otherwise, all messages get deselected and
* action mode is finished.
*/
private void setSelectionState(boolean selected) {
if (selected) {
if (mAdapter.getCount() == 0) {
// Nothing to do if there are no messages
return;
}
mSelectedCount = 0;
for (int i = 0, end = mAdapter.getCount(); i < end; i++) {
Cursor cursor = (Cursor) mAdapter.getItem(i);
long uniqueId = cursor.getLong(mUniqueIdColumn);
mSelected.add(uniqueId);
if (mThreadedList) {
int threadCount = cursor.getInt(THREAD_COUNT_COLUMN);
mSelectedCount += (threadCount > 1) ? threadCount : 1;
} else {
mSelectedCount++;
}
}
if (mActionMode == null) {
mActionMode = getActivity().startActionMode(mActionModeCallback);
}
computeBatchDirection();
updateActionModeTitle();
computeSelectAllVisibility();
} else {
mSelected.clear();
mSelectedCount = 0;
if (mActionMode != null) {
mActionMode.finish();
mActionMode = null;
}
}
mAdapter.notifyDataSetChanged();
}
private void toggleMessageSelect(int listViewPosition) {
int adapterPosition = listViewToAdapterPosition(listViewPosition);
if (adapterPosition == AdapterView.INVALID_POSITION) {
return;
}
toggleMessageSelectWithAdapterPosition(adapterPosition);
}
private void toggleMessageFlagWithAdapterPosition(int adapterPosition) {
Cursor cursor = (Cursor) mAdapter.getItem(adapterPosition);
boolean flagged = (cursor.getInt(FLAGGED_COLUMN) == 1);
setFlag(adapterPosition,Flag.FLAGGED, !flagged);
}
private void toggleMessageSelectWithAdapterPosition(int adapterPosition) {
Cursor cursor = (Cursor) mAdapter.getItem(adapterPosition);
long uniqueId = cursor.getLong(mUniqueIdColumn);
boolean selected = mSelected.contains(uniqueId);
if (!selected) {
mSelected.add(uniqueId);
} else {
mSelected.remove(uniqueId);
}
int selectedCountDelta = 1;
if (mThreadedList) {
int threadCount = cursor.getInt(THREAD_COUNT_COLUMN);
if (threadCount > 1) {
selectedCountDelta = threadCount;
}
}
if (mActionMode != null) {
if (mSelectedCount == selectedCountDelta && selected) {
mActionMode.finish();
mActionMode = null;
return;
}
} else {
mActionMode = getActivity().startActionMode(mActionModeCallback);
}
if (selected) {
mSelectedCount -= selectedCountDelta;
} else {
mSelectedCount += selectedCountDelta;
}
computeBatchDirection();
updateActionModeTitle();
// make sure the onPrepareActionMode is called
mActionMode.invalidate();
computeSelectAllVisibility();
mAdapter.notifyDataSetChanged();
}
private void updateActionModeTitle() {
mActionMode.setTitle(String.format(getString(R.string.actionbar_selected), mSelectedCount));
}
private void computeSelectAllVisibility() {
mActionModeCallback.showSelectAll(mSelected.size() != mAdapter.getCount());
}
private void computeBatchDirection() {
boolean isBatchFlag = false;
boolean isBatchRead = false;
for (int i = 0, end = mAdapter.getCount(); i < end; i++) {
Cursor cursor = (Cursor) mAdapter.getItem(i);
long uniqueId = cursor.getLong(mUniqueIdColumn);
if (mSelected.contains(uniqueId)) {
boolean read = (cursor.getInt(READ_COLUMN) == 1);
boolean flagged = (cursor.getInt(FLAGGED_COLUMN) == 1);
if (!flagged) {
isBatchFlag = true;
}
if (!read) {
isBatchRead = true;
}
if (isBatchFlag && isBatchRead) {
break;
}
}
}
mActionModeCallback.showMarkAsRead(isBatchRead);
mActionModeCallback.showFlag(isBatchFlag);
}
private void setFlag(int adapterPosition, final Flag flag, final boolean newState) {
if (adapterPosition == AdapterView.INVALID_POSITION) {
return;
}
Cursor cursor = (Cursor) mAdapter.getItem(adapterPosition);
Account account = mPreferences.getAccount(cursor.getString(ACCOUNT_UUID_COLUMN));
if (mThreadedList && cursor.getInt(THREAD_COUNT_COLUMN) > 1) {
long threadRootId = cursor.getLong(THREAD_ROOT_COLUMN);
mController.setFlagForThreads(account,
Collections.singletonList(Long.valueOf(threadRootId)), flag, newState);
} else {
long id = cursor.getLong(ID_COLUMN);
mController.setFlag(account, Collections.singletonList(Long.valueOf(id)), flag,
newState);
}
computeBatchDirection();
}
private void setFlagForSelected(final Flag flag, final boolean newState) {
if (mSelected.size() == 0) {
return;
}
Map<Account, List<Long>> messageMap = new HashMap<Account, List<Long>>();
Map<Account, List<Long>> threadMap = new HashMap<Account, List<Long>>();
Set<Account> accounts = new HashSet<Account>();
for (int position = 0, end = mAdapter.getCount(); position < end; position++) {
Cursor cursor = (Cursor) mAdapter.getItem(position);
long uniqueId = cursor.getLong(mUniqueIdColumn);
if (mSelected.contains(uniqueId)) {
String uuid = cursor.getString(ACCOUNT_UUID_COLUMN);
Account account = mPreferences.getAccount(uuid);
accounts.add(account);
if (mThreadedList && cursor.getInt(THREAD_COUNT_COLUMN) > 1) {
List<Long> threadRootIdList = threadMap.get(account);
if (threadRootIdList == null) {
threadRootIdList = new ArrayList<Long>();
threadMap.put(account, threadRootIdList);
}
threadRootIdList.add(cursor.getLong(THREAD_ROOT_COLUMN));
} else {
List<Long> messageIdList = messageMap.get(account);
if (messageIdList == null) {
messageIdList = new ArrayList<Long>();
messageMap.put(account, messageIdList);
}
messageIdList.add(cursor.getLong(ID_COLUMN));
}
}
}
for (Account account : accounts) {
List<Long> messageIds = messageMap.get(account);
List<Long> threadRootIds = threadMap.get(account);
if (messageIds != null) {
mController.setFlag(account, messageIds, flag, newState);
}
if (threadRootIds != null) {
mController.setFlagForThreads(account, threadRootIds, flag, newState);
}
}
computeBatchDirection();
}
private void onMove(Message message) {
onMove(Collections.singletonList(message));
}
/**
* Display the message move activity.
*
* @param messages
* Never {@code null}.
*/
private void onMove(List<Message> messages) {
if (!checkCopyOrMovePossible(messages, FolderOperation.MOVE)) {
return;
}
final Folder folder;
if (mIsThreadDisplay) {
folder = messages.get(0).getFolder();
} else if (mSingleFolderMode) {
folder = mCurrentFolder.folder;
} else {
folder = null;
}
Account account = messages.get(0).getFolder().getAccount();
displayFolderChoice(ACTIVITY_CHOOSE_FOLDER_MOVE, account, folder, messages);
}
private void onCopy(Message message) {
onCopy(Collections.singletonList(message));
}
/**
* Display the message copy activity.
*
* @param messages
* Never {@code null}.
*/
private void onCopy(List<Message> messages) {
if (!checkCopyOrMovePossible(messages, FolderOperation.COPY)) {
return;
}
final Folder folder;
if (mIsThreadDisplay) {
folder = messages.get(0).getFolder();
} else if (mSingleFolderMode) {
folder = mCurrentFolder.folder;
} else {
folder = null;
}
displayFolderChoice(ACTIVITY_CHOOSE_FOLDER_COPY, mAccount, folder, messages);
}
/**
* Helper method to manage the invocation of {@link #startActivityForResult(Intent, int)} for a
* folder operation ({@link ChooseFolder} activity), while saving a list of associated messages.
*
* @param requestCode
* If {@code >= 0}, this code will be returned in {@code onActivityResult()} when the
* activity exits.
* @param folder
* The source folder. Never {@code null}.
* @param messages
* Messages to be affected by the folder operation. Never {@code null}.
*
* @see #startActivityForResult(Intent, int)
*/
private void displayFolderChoice(int requestCode, Account account, Folder folder,
List<Message> messages) {
Intent intent = new Intent(getActivity(), ChooseFolder.class);
intent.putExtra(ChooseFolder.EXTRA_ACCOUNT, account.getUuid());
intent.putExtra(ChooseFolder.EXTRA_SEL_FOLDER, account.getLastSelectedFolderName());
if (folder == null) {
intent.putExtra(ChooseFolder.EXTRA_SHOW_CURRENT, "yes");
} else {
intent.putExtra(ChooseFolder.EXTRA_CUR_FOLDER, folder.getName());
}
// remember the selected messages for #onActivityResult
mActiveMessages = messages;
startActivityForResult(intent, requestCode);
}
private void onArchive(final Message message) {
onArchive(Collections.singletonList(message));
}
private void onArchive(final List<Message> messages) {
Map<Account, List<Message>> messagesByAccount = groupMessagesByAccount(messages);
for (Entry<Account, List<Message>> entry : messagesByAccount.entrySet()) {
Account account = entry.getKey();
String archiveFolder = account.getArchiveFolderName();
if (!K9.FOLDER_NONE.equals(archiveFolder)) {
move(entry.getValue(), archiveFolder);
}
}
}
private Map<Account, List<Message>> groupMessagesByAccount(final List<Message> messages) {
Map<Account, List<Message>> messagesByAccount = new HashMap<Account, List<Message>>();
for (Message message : messages) {
Account account = message.getFolder().getAccount();
List<Message> msgList = messagesByAccount.get(account);
if (msgList == null) {
msgList = new ArrayList<Message>();
messagesByAccount.put(account, msgList);
}
msgList.add(message);
}
return messagesByAccount;
}
private void onSpam(Message message) {
onSpam(Collections.singletonList(message));
}
/**
* Move messages to the spam folder.
*
* @param messages
* The messages to move to the spam folder. Never {@code null}.
*/
private void onSpam(List<Message> messages) {
if (K9.confirmSpam()) {
// remember the message selection for #onCreateDialog(int)
mActiveMessages = messages;
showDialog(R.id.dialog_confirm_spam);
} else {
onSpamConfirmed(messages);
}
}
private void onSpamConfirmed(List<Message> messages) {
Map<Account, List<Message>> messagesByAccount = groupMessagesByAccount(messages);
for (Entry<Account, List<Message>> entry : messagesByAccount.entrySet()) {
Account account = entry.getKey();
String spamFolder = account.getSpamFolderName();
if (!K9.FOLDER_NONE.equals(spamFolder)) {
move(entry.getValue(), spamFolder);
}
}
}
private static enum FolderOperation {
COPY, MOVE
}
/**
* Display a Toast message if any message isn't synchronized
*
* @param messages
* The messages to copy or move. Never {@code null}.
* @param operation
* The type of operation to perform. Never {@code null}.
*
* @return {@code true}, if operation is possible.
*/
private boolean checkCopyOrMovePossible(final List<Message> messages,
final FolderOperation operation) {
if (messages.size() == 0) {
return false;
}
boolean first = true;
for (final Message message : messages) {
if (first) {
first = false;
// account check
final Account account = message.getFolder().getAccount();
if ((operation == FolderOperation.MOVE && !mController.isMoveCapable(account)) ||
(operation == FolderOperation.COPY && !mController.isCopyCapable(account))) {
return false;
}
}
// message check
if ((operation == FolderOperation.MOVE && !mController.isMoveCapable(message)) ||
(operation == FolderOperation.COPY && !mController.isCopyCapable(message))) {
final Toast toast = Toast.makeText(getActivity(), R.string.move_copy_cannot_copy_unsynced_message,
Toast.LENGTH_LONG);
toast.show();
return false;
}
}
return true;
}
/**
* Copy the specified messages to the specified folder.
*
* @param messages
* List of messages to copy. Never {@code null}.
* @param destination
* The name of the destination folder. Never {@code null}.
*/
private void copy(List<Message> messages, final String destination) {
copyOrMove(messages, destination, FolderOperation.COPY);
}
/**
* Move the specified messages to the specified folder.
*
* @param messages
* The list of messages to move. Never {@code null}.
* @param destination
* The name of the destination folder. Never {@code null}.
*/
private void move(List<Message> messages, final String destination) {
copyOrMove(messages, destination, FolderOperation.MOVE);
}
/**
* The underlying implementation for {@link #copy(List, String)} and
* {@link #move(List, String)}. This method was added mainly because those 2
* methods share common behavior.
*
* @param messages
* The list of messages to copy or move. Never {@code null}.
* @param destination
* The name of the destination folder. Never {@code null} or {@link K9#FOLDER_NONE}.
* @param operation
* Specifies what operation to perform. Never {@code null}.
*/
private void copyOrMove(List<Message> messages, final String destination,
final FolderOperation operation) {
Map<String, List<Message>> folderMap = new HashMap<String, List<Message>>();
for (Message message : messages) {
if ((operation == FolderOperation.MOVE && !mController.isMoveCapable(message)) ||
(operation == FolderOperation.COPY && !mController.isCopyCapable(message))) {
Toast.makeText(getActivity(), R.string.move_copy_cannot_copy_unsynced_message,
Toast.LENGTH_LONG).show();
// XXX return meaningful error value?
// message isn't synchronized
return;
}
String folderName = message.getFolder().getName();
if (folderName.equals(destination)) {
// Skip messages already in the destination folder
continue;
}
List<Message> outMessages = folderMap.get(folderName);
if (outMessages == null) {
outMessages = new ArrayList<Message>();
folderMap.put(folderName, outMessages);
}
outMessages.add(message);
}
for (Map.Entry<String, List<Message>> entry : folderMap.entrySet()) {
String folderName = entry.getKey();
List<Message> outMessages = entry.getValue();
Account account = outMessages.get(0).getFolder().getAccount();
if (operation == FolderOperation.MOVE) {
if (mThreadedList) {
mController.moveMessagesInThread(account, folderName, outMessages, destination);
} else {
mController.moveMessages(account, folderName, outMessages, destination, null);
}
} else {
if (mThreadedList) {
mController.copyMessagesInThread(account, folderName, outMessages, destination);
} else {
mController.copyMessages(account, folderName, outMessages, destination, null);
}
}
}
}
class ActionModeCallback implements ActionMode.Callback {
private MenuItem mSelectAll;
private MenuItem mMarkAsRead;
private MenuItem mMarkAsUnread;
private MenuItem mFlag;
private MenuItem mUnflag;
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
mSelectAll = menu.findItem(R.id.select_all);
mMarkAsRead = menu.findItem(R.id.mark_as_read);
mMarkAsUnread = menu.findItem(R.id.mark_as_unread);
mFlag = menu.findItem(R.id.flag);
mUnflag = menu.findItem(R.id.unflag);
// we don't support cross account actions atm
if (!mSingleAccountMode) {
// show all
menu.findItem(R.id.move).setVisible(true);
menu.findItem(R.id.archive).setVisible(true);
menu.findItem(R.id.spam).setVisible(true);
menu.findItem(R.id.copy).setVisible(true);
Set<String> accountUuids = getAccountUuidsForSelected();
for (String accountUuid : accountUuids) {
Account account = mPreferences.getAccount(accountUuid);
if (account != null) {
setContextCapabilities(account, menu);
}
}
}
return true;
}
/**
* Get the set of account UUIDs for the selected messages.
*/
private Set<String> getAccountUuidsForSelected() {
int maxAccounts = mAccountUuids.length;
Set<String> accountUuids = new HashSet<String>(maxAccounts);
for (int position = 0, end = mAdapter.getCount(); position < end; position++) {
Cursor cursor = (Cursor) mAdapter.getItem(position);
long uniqueId = cursor.getLong(mUniqueIdColumn);
if (mSelected.contains(uniqueId)) {
String accountUuid = cursor.getString(ACCOUNT_UUID_COLUMN);
accountUuids.add(accountUuid);
if (accountUuids.size() == mAccountUuids.length) {
break;
}
}
}
return accountUuids;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
mSelectAll = null;
mMarkAsRead = null;
mMarkAsUnread = null;
mFlag = null;
mUnflag = null;
setSelectionState(false);
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.message_list_context, menu);
// check capabilities
setContextCapabilities(mAccount, menu);
return true;
}
/**
* Disables menu options not supported by the account type or current "search view".
*
* @param account
* The account to query for its capabilities.
* @param menu
* The menu to adapt.
*/
private void setContextCapabilities(Account account, Menu menu) {
if (!mSingleAccountMode) {
// We don't support cross-account copy/move operations right now
menu.findItem(R.id.move).setVisible(false);
menu.findItem(R.id.copy).setVisible(false);
//TODO: we could support the archive and spam operations if all selected messages
// belong to non-POP3 accounts
menu.findItem(R.id.archive).setVisible(false);
menu.findItem(R.id.spam).setVisible(false);
} else {
// hide unsupported
if (!mController.isCopyCapable(account)) {
menu.findItem(R.id.copy).setVisible(false);
}
if (!mController.isMoveCapable(account)) {
menu.findItem(R.id.move).setVisible(false);
menu.findItem(R.id.archive).setVisible(false);
menu.findItem(R.id.spam).setVisible(false);
}
if (!account.hasArchiveFolder()) {
menu.findItem(R.id.archive).setVisible(false);
}
if (!account.hasSpamFolder()) {
menu.findItem(R.id.spam).setVisible(false);
}
}
}
public void showSelectAll(boolean show) {
if (mActionMode != null) {
mSelectAll.setVisible(show);
}
}
public void showMarkAsRead(boolean show) {
if (mActionMode != null) {
mMarkAsRead.setVisible(show);
mMarkAsUnread.setVisible(!show);
}
}
public void showFlag(boolean show) {
if (mActionMode != null) {
mFlag.setVisible(show);
mUnflag.setVisible(!show);
}
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
/*
* In the following we assume that we can't move or copy
* mails to the same folder. Also that spam isn't available if we are
* in the spam folder,same for archive.
*
* This is the case currently so safe assumption.
*/
switch (item.getItemId()) {
case R.id.delete: {
List<Message> messages = getCheckedMessages();
onDelete(messages);
mSelectedCount = 0;
break;
}
case R.id.mark_as_read: {
setFlagForSelected(Flag.SEEN, true);
break;
}
case R.id.mark_as_unread: {
setFlagForSelected(Flag.SEEN, false);
break;
}
case R.id.flag: {
setFlagForSelected(Flag.FLAGGED, true);
break;
}
case R.id.unflag: {
setFlagForSelected(Flag.FLAGGED, false);
break;
}
case R.id.select_all: {
selectAll();
break;
}
// only if the account supports this
case R.id.archive: {
List<Message> messages = getCheckedMessages();
onArchive(messages);
mSelectedCount = 0;
break;
}
case R.id.spam: {
List<Message> messages = getCheckedMessages();
onSpam(messages);
mSelectedCount = 0;
break;
}
case R.id.move: {
List<Message> messages = getCheckedMessages();
onMove(messages);
mSelectedCount = 0;
break;
}
case R.id.copy: {
List<Message> messages = getCheckedMessages();
onCopy(messages);
mSelectedCount = 0;
break;
}
}
if (mSelectedCount == 0) {
mActionMode.finish();
}
return true;
}
}
@Override
public void doPositiveClick(int dialogId) {
switch (dialogId) {
case R.id.dialog_confirm_spam: {
onSpamConfirmed(mActiveMessages);
// No further need for this reference
mActiveMessages = null;
break;
}
case R.id.dialog_confirm_delete: {
onDeleteConfirmed(mActiveMessages);
mActiveMessage = null;
break;
}
}
}
@Override
public void doNegativeClick(int dialogId) {
switch (dialogId) {
case R.id.dialog_confirm_spam:
case R.id.dialog_confirm_delete: {
// No further need for this reference
mActiveMessages = null;
break;
}
}
}
@Override
public void dialogCancelled(int dialogId) {
doNegativeClick(dialogId);
}
public void checkMail() {
if (isSingleAccountMode() && isSingleFolderMode()) {
mController.synchronizeMailbox(mAccount, mFolderName, mListener, null);
mController.sendPendingMessages(mAccount, mListener);
} else if (mAllAccounts) {
mController.checkMail(mContext, null, true, true, mListener);
} else {
for (String accountUuid : mAccountUuids) {
Account account = mPreferences.getAccount(accountUuid);
mController.checkMail(mContext, account, true, true, mListener);
}
}
}
/**
* We need to do some special clean up when leaving a remote search result screen. If no
* remote search is in progress, this method does nothing special.
*/
@Override
public void onStop() {
// If we represent a remote search, then kill that before going back.
if (isRemoteSearch() && mRemoteSearchFuture != null) {
try {
Log.i(K9.LOG_TAG, "Remote search in progress, attempting to abort...");
// Canceling the future stops any message fetches in progress.
final boolean cancelSuccess = mRemoteSearchFuture.cancel(true); // mayInterruptIfRunning = true
if (!cancelSuccess) {
Log.e(K9.LOG_TAG, "Could not cancel remote search future.");
}
// Closing the folder will kill off the connection if we're mid-search.
final Account searchAccount = mAccount;
final Folder remoteFolder = mCurrentFolder.folder;
remoteFolder.close();
// Send a remoteSearchFinished() message for good measure.
mListener.remoteSearchFinished(searchAccount, mCurrentFolder.name, 0, null);
} catch (Exception e) {
// Since the user is going back, log and squash any exceptions.
Log.e(K9.LOG_TAG, "Could not abort remote search before going back", e);
}
}
super.onStop();
}
public ArrayList<MessageReference> getMessageReferences() {
ArrayList<MessageReference> messageRefs = new ArrayList<MessageReference>();
for (int i = 0, len = mAdapter.getCount(); i < len; i++) {
Cursor cursor = (Cursor) mAdapter.getItem(i);
MessageReference ref = new MessageReference();
ref.accountUuid = cursor.getString(ACCOUNT_UUID_COLUMN);
ref.folderName = cursor.getString(FOLDER_NAME_COLUMN);
ref.uid = cursor.getString(UID_COLUMN);
messageRefs.add(ref);
}
return messageRefs;
}
public void selectAll() {
setSelectionState(true);
}
public void onMoveUp() {
int currentPosition = mListView.getSelectedItemPosition();
if (currentPosition == AdapterView.INVALID_POSITION || mListView.isInTouchMode()) {
currentPosition = mListView.getFirstVisiblePosition();
}
if (currentPosition > 0) {
mListView.setSelection(currentPosition - 1);
}
}
public void onMoveDown() {
int currentPosition = mListView.getSelectedItemPosition();
if (currentPosition == AdapterView.INVALID_POSITION || mListView.isInTouchMode()) {
currentPosition = mListView.getFirstVisiblePosition();
}
if (currentPosition < mListView.getCount()) {
mListView.setSelection(currentPosition + 1);
}
}
public boolean openPrevious(MessageReference messageReference) {
int position = getPosition(messageReference);
if (position <= 0) {
return false;
}
openMessageAtPosition(position - 1);
return true;
}
public boolean openNext(MessageReference messageReference) {
int position = getPosition(messageReference);
if (position < 0 || position == mAdapter.getCount() - 1) {
return false;
}
openMessageAtPosition(position + 1);
return true;
}
public boolean isFirst(MessageReference messageReference) {
return mAdapter.isEmpty() || messageReference.equals(getReferenceForPosition(0));
}
public boolean isLast(MessageReference messageReference) {
return mAdapter.isEmpty() || messageReference.equals(getReferenceForPosition(mAdapter.getCount() - 1));
}
private MessageReference getReferenceForPosition(int position) {
Cursor cursor = (Cursor) mAdapter.getItem(position);
MessageReference ref = new MessageReference();
ref.accountUuid = cursor.getString(ACCOUNT_UUID_COLUMN);
ref.folderName = cursor.getString(FOLDER_NAME_COLUMN);
ref.uid = cursor.getString(UID_COLUMN);
return ref;
}
private void openMessageAtPosition(int position) {
// Scroll message into view if necessary
int listViewPosition = adapterToListViewPosition(position);
if (listViewPosition != AdapterView.INVALID_POSITION &&
(listViewPosition < mListView.getFirstVisiblePosition() ||
listViewPosition > mListView.getLastVisiblePosition())) {
mListView.setSelection(listViewPosition);
}
MessageReference ref = getReferenceForPosition(position);
// For some reason the mListView.setSelection() above won't do anything when we call
// onOpenMessage() (and consequently mAdapter.notifyDataSetChanged()) right away. So we
// defer the call using MessageListHandler.
mHandler.openMessage(ref);
}
private int getPosition(MessageReference messageReference) {
for (int i = 0, len = mAdapter.getCount(); i < len; i++) {
Cursor cursor = (Cursor) mAdapter.getItem(i);
String accountUuid = cursor.getString(ACCOUNT_UUID_COLUMN);
String folderName = cursor.getString(FOLDER_NAME_COLUMN);
String uid = cursor.getString(UID_COLUMN);
if (accountUuid.equals(messageReference.accountUuid) &&
folderName.equals(messageReference.folderName) &&
uid.equals(messageReference.uid)) {
return i;
}
}
return -1;
}
public interface MessageListFragmentListener {
void enableActionBarProgress(boolean enable);
void setMessageListProgress(int level);
void showThread(Account account, String folderName, long rootId);
void showMoreFromSameSender(String senderAddress);
void onResendMessage(Message message);
void onForward(Message message);
void onReply(Message message);
void onReplyAll(Message message);
void openMessage(MessageReference messageReference);
void setMessageListTitle(String title);
void setMessageListSubTitle(String subTitle);
void setUnreadCount(int unread);
void onCompose(Account account);
boolean startSearch(Account account, String folderName);
void remoteSearchStarted();
void goBack();
void updateMenu();
}
public void onReverseSort() {
changeSort(mSortType);
}
private Message getSelectedMessage() {
int listViewPosition = mListView.getSelectedItemPosition();
int adapterPosition = listViewToAdapterPosition(listViewPosition);
return getMessageAtPosition(adapterPosition);
}
private int getAdapterPositionForSelectedMessage() {
int listViewPosition = mListView.getSelectedItemPosition();
return listViewToAdapterPosition(listViewPosition);
}
private int getPositionForUniqueId(long uniqueId) {
for (int position = 0, end = mAdapter.getCount(); position < end; position++) {
Cursor cursor = (Cursor) mAdapter.getItem(position);
if (cursor.getLong(mUniqueIdColumn) == uniqueId) {
return position;
}
}
return AdapterView.INVALID_POSITION;
}
private Message getMessageAtPosition(int adapterPosition) {
if (adapterPosition == AdapterView.INVALID_POSITION) {
return null;
}
Cursor cursor = (Cursor) mAdapter.getItem(adapterPosition);
String uid = cursor.getString(UID_COLUMN);
Account account = getAccountFromCursor(cursor);
long folderId = cursor.getLong(FOLDER_ID_COLUMN);
Folder folder = getFolderById(account, folderId);
try {
return folder.getMessage(uid);
} catch (MessagingException e) {
Log.e(K9.LOG_TAG, "Something went wrong while fetching a message", e);
}
return null;
}
private List<Message> getCheckedMessages() {
List<Message> messages = new ArrayList<Message>(mSelected.size());
for (int position = 0, end = mAdapter.getCount(); position < end; position++) {
Cursor cursor = (Cursor) mAdapter.getItem(position);
long uniqueId = cursor.getLong(mUniqueIdColumn);
if (mSelected.contains(uniqueId)) {
Message message = getMessageAtPosition(position);
if (message != null) {
messages.add(message);
}
}
}
return messages;
}
public void onDelete() {
Message message = getSelectedMessage();
if (message != null) {
onDelete(Collections.singletonList(message));
}
}
public void toggleMessageSelect() {
toggleMessageSelect(mListView.getSelectedItemPosition());
}
public void onToggleFlagged() {
onToggleFlag(Flag.FLAGGED, FLAGGED_COLUMN);
}
public void onToggleRead() {
onToggleFlag(Flag.SEEN, READ_COLUMN);
}
private void onToggleFlag(Flag flag, int flagColumn) {
int adapterPosition = getAdapterPositionForSelectedMessage();
if (adapterPosition == ListView.INVALID_POSITION) {
return;
}
Cursor cursor = (Cursor) mAdapter.getItem(adapterPosition);
boolean flagState = (cursor.getInt(flagColumn) == 1);
setFlag(adapterPosition, flag, !flagState);
}
public void onMove() {
Message message = getSelectedMessage();
if (message != null) {
onMove(message);
}
}
public void onArchive() {
Message message = getSelectedMessage();
if (message != null) {
onArchive(message);
}
}
public void onCopy() {
Message message = getSelectedMessage();
if (message != null) {
onCopy(message);
}
}
public boolean isOutbox() {
return (mFolderName != null && mFolderName.equals(mAccount.getOutboxFolderName()));
}
public boolean isErrorFolder() {
return K9.ERROR_FOLDER_NAME.equals(mFolderName);
}
public boolean isRemoteFolder() {
if (mSearch.isManualSearch() || isOutbox() || isErrorFolder()) {
return false;
}
if (!mController.isMoveCapable(mAccount)) {
// For POP3 accounts only the Inbox is a remote folder.
return (mFolderName != null && mFolderName.equals(mAccount.getInboxFolderName()));
}
return true;
}
public boolean isManualSearch() {
return mSearch.isManualSearch();
}
public boolean isAccountExpungeCapable() {
try {
return (mAccount != null && mAccount.getRemoteStore().isExpungeCapable());
} catch (Exception e) {
return false;
}
}
public void onRemoteSearch() {
// Remote search is useless without the network.
if (mHasConnectivity) {
onRemoteSearchRequested();
} else {
Toast.makeText(getActivity(), getText(R.string.remote_search_unavailable_no_network),
Toast.LENGTH_SHORT).show();
}
}
public boolean isRemoteSearch() {
return mRemoteSearchPerformed;
}
public boolean isRemoteSearchAllowed() {
if (!mSearch.isManualSearch() || mRemoteSearchPerformed || !mSingleFolderMode) {
return false;
}
boolean allowRemoteSearch = false;
final Account searchAccount = mAccount;
if (searchAccount != null) {
allowRemoteSearch = searchAccount.allowRemoteSearch();
}
return allowRemoteSearch;
}
public boolean onSearchRequested() {
String folderName = (mCurrentFolder != null) ? mCurrentFolder.name : null;
return mFragmentListener.startSearch(mAccount, folderName);
}
@Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
String accountUuid = mAccountUuids[id];
Account account = mPreferences.getAccount(accountUuid);
String threadId = getThreadId(mSearch);
Uri uri;
String[] projection;
boolean needConditions;
if (threadId != null) {
uri = Uri.withAppendedPath(EmailProvider.CONTENT_URI, "account/" + accountUuid + "/thread/" + threadId);
projection = PROJECTION;
needConditions = false;
} else if (mThreadedList) {
uri = Uri.withAppendedPath(EmailProvider.CONTENT_URI, "account/" + accountUuid + "/messages/threaded");
projection = THREADED_PROJECTION;
needConditions = true;
} else {
uri = Uri.withAppendedPath(EmailProvider.CONTENT_URI, "account/" + accountUuid + "/messages");
projection = PROJECTION;
needConditions = true;
}
StringBuilder query = new StringBuilder();
List<String> queryArgs = new ArrayList<String>();
if (needConditions) {
boolean selectActive = mActiveMessage != null && mActiveMessage.accountUuid.equals(accountUuid);
if (selectActive) {
query.append("(" + MessageColumns.UID + " = ? AND " + SpecialColumns.FOLDER_NAME + " = ?) OR (");
queryArgs.add(mActiveMessage.uid);
queryArgs.add(mActiveMessage.folderName);
}
SqlQueryBuilder.buildWhereClause(account, mSearch.getConditions(), query, queryArgs);
if (selectActive) {
query.append(')');
}
}
String selection = query.toString();
String[] selectionArgs = queryArgs.toArray(new String[0]);
String sortOrder = buildSortOrder();
return new CursorLoader(getActivity(), uri, projection, selection, selectionArgs,
sortOrder);
}
private String getThreadId(LocalSearch search) {
for (ConditionsTreeNode node : search.getLeafSet()) {
SearchCondition condition = node.mCondition;
if (condition.field == Searchfield.THREAD_ID) {
return condition.value;
}
}
return null;
}
private String buildSortOrder() {
String sortColumn = MessageColumns.ID;
switch (mSortType) {
case SORT_ARRIVAL: {
sortColumn = MessageColumns.INTERNAL_DATE;
break;
}
case SORT_ATTACHMENT: {
sortColumn = "(" + MessageColumns.ATTACHMENT_COUNT + " < 1)";
break;
}
case SORT_FLAGGED: {
sortColumn = "(" + MessageColumns.FLAGGED + " != 1)";
break;
}
case SORT_SENDER: {
//FIXME
sortColumn = MessageColumns.SENDER_LIST;
break;
}
case SORT_SUBJECT: {
sortColumn = MessageColumns.SUBJECT + " COLLATE NOCASE";
break;
}
case SORT_UNREAD: {
sortColumn = MessageColumns.READ;
break;
}
case SORT_DATE:
default: {
sortColumn = MessageColumns.DATE;
}
}
String sortDirection = (mSortAscending) ? " ASC" : " DESC";
String secondarySort;
if (mSortType == SortType.SORT_DATE || mSortType == SortType.SORT_ARRIVAL) {
secondarySort = "";
} else {
secondarySort = MessageColumns.DATE + ((mSortDateAscending) ? " ASC, " : " DESC, ");
}
String sortOrder = sortColumn + sortDirection + ", " + secondarySort +
MessageColumns.ID + " DESC";
return sortOrder;
}
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
if (mIsThreadDisplay && data.getCount() == 0) {
mHandler.goBack();
return;
}
// Remove the "Loading..." view
mPullToRefreshView.setEmptyView(null);
setPullToRefreshEnabled(isPullToRefreshAllowed());
final int loaderId = loader.getId();
mCursors[loaderId] = data;
mCursorValid[loaderId] = true;
Cursor cursor;
if (mCursors.length > 1) {
cursor = new MergeCursorWithUniqueId(mCursors, getComparator());
mUniqueIdColumn = cursor.getColumnIndex("_id");
} else {
cursor = data;
mUniqueIdColumn = ID_COLUMN;
}
if (mIsThreadDisplay) {
if (cursor.moveToFirst()) {
mTitle = cursor.getString(SUBJECT_COLUMN);
if (!StringUtils.isNullOrEmpty(mTitle)) {
mTitle = Utility.stripSubject(mTitle);
}
if (StringUtils.isNullOrEmpty(mTitle)) {
mTitle = getString(R.string.general_no_subject);
}
updateTitle();
} else {
//TODO: empty thread view -> return to full message list
}
}
cleanupSelected(cursor);
updateContextMenu(cursor);
mAdapter.swapCursor(cursor);
resetActionMode();
computeBatchDirection();
if (isLoadFinished()) {
if (mSavedListState != null) {
mHandler.restoreListPosition();
}
mFragmentListener.updateMenu();
}
}
public boolean isLoadFinished() {
if (mCursorValid == null) {
return false;
}
for (boolean cursorValid : mCursorValid) {
if (!cursorValid) {
return false;
}
}
return true;
}
/**
* Close the context menu when the message it was opened for is no longer in the message list.
*/
private void updateContextMenu(Cursor cursor) {
if (mContextMenuUniqueId == 0) {
return;
}
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
long uniqueId = cursor.getLong(mUniqueIdColumn);
if (uniqueId == mContextMenuUniqueId) {
return;
}
}
mContextMenuUniqueId = 0;
Activity activity = getActivity();
if (activity != null) {
activity.closeContextMenu();
}
}
private void cleanupSelected(Cursor cursor) {
if (mSelected.size() == 0) {
return;
}
Set<Long> selected = new HashSet<Long>();
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
long uniqueId = cursor.getLong(mUniqueIdColumn);
if (mSelected.contains(uniqueId)) {
selected.add(uniqueId);
}
}
mSelected = selected;
}
/**
* Starts or finishes the action mode when necessary.
*/
private void resetActionMode() {
if (mSelected.size() == 0) {
if (mActionMode != null) {
mActionMode.finish();
}
return;
}
if (mActionMode == null) {
mActionMode = getActivity().startActionMode(mActionModeCallback);
}
recalculateSelectionCount();
updateActionModeTitle();
}
/**
* Recalculates the selection count.
*
* <p>
* For non-threaded lists this is simply the number of visibly selected messages. If threaded
* view is enabled this method counts the number of messages in the selected threads.
* </p>
*/
private void recalculateSelectionCount() {
if (!mThreadedList) {
mSelectedCount = mSelected.size();
return;
}
mSelectedCount = 0;
for (int i = 0, end = mAdapter.getCount(); i < end; i++) {
Cursor cursor = (Cursor) mAdapter.getItem(i);
long uniqueId = cursor.getLong(mUniqueIdColumn);
if (mSelected.contains(uniqueId)) {
int threadCount = cursor.getInt(THREAD_COUNT_COLUMN);
mSelectedCount += (threadCount > 1) ? threadCount : 1;
}
}
}
@Override
public void onLoaderReset(Loader<Cursor> loader) {
mSelected.clear();
mAdapter.swapCursor(null);
}
private Account getAccountFromCursor(Cursor cursor) {
String accountUuid = cursor.getString(ACCOUNT_UUID_COLUMN);
return mPreferences.getAccount(accountUuid);
}
private void remoteSearchFinished() {
mRemoteSearchFuture = null;
}
/**
* Mark a message as 'active'.
*
* <p>
* The active message is the one currently displayed in the message view portion of the split
* view.
* </p>
*
* @param messageReference
* {@code null} to not mark any message as being 'active'.
*/
public void setActiveMessage(MessageReference messageReference) {
mActiveMessage = messageReference;
// Reload message list with modified query that always includes the active message
if (isAdded()) {
restartLoader();
}
// Redraw list immediately
if (mAdapter != null) {
mAdapter.notifyDataSetChanged();
}
}
public boolean isSingleAccountMode() {
return mSingleAccountMode;
}
public boolean isSingleFolderMode() {
return mSingleFolderMode;
}
public boolean isInitialized() {
return mInitialized;
}
public boolean isMarkAllAsReadSupported() {
return (isSingleAccountMode() && isSingleFolderMode());
}
public void markAllAsRead() {
if (isMarkAllAsReadSupported()) {
mController.markAllMessagesRead(mAccount, mFolderName);
}
}
public boolean isCheckMailSupported() {
return (mAllAccounts || !isSingleAccountMode() || !isSingleFolderMode() ||
isRemoteFolder());
}
private boolean isCheckMailAllowed() {
return (!isManualSearch() && isCheckMailSupported());
}
private boolean isPullToRefreshAllowed() {
return (isRemoteSearchAllowed() || isCheckMailAllowed());
}
}
| bsd-3-clause |
narphorium/freebase-power-tools | src/main/java/com/narphorium/freebase/util/BatchCreateTool.java | 378 | package com.narphorium.freebase.util;
public class BatchCreateTool extends AbstractFreebaseTool {
public BatchCreateTool() {
super("freebase-create");
}
public void run() {
// TODO
}
/**
* @param args
*/
public static void main(String[] args) {
BatchCreateTool tool = new BatchCreateTool();
tool.config(args);
tool.run();
}
}
| bsd-3-clause |
herveyw/azure-sdk-for-java | azure-mgmt-compute/src/main/java/com/microsoft/azure/management/compute/ApiErrorBase.java | 1757 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.compute;
/**
* Api error base.
*/
public class ApiErrorBase {
/**
* the error code.
*/
private String code;
/**
* the target of the particular error.
*/
private String target;
/**
* the error message.
*/
private String message;
/**
* Get the code value.
*
* @return the code value
*/
public String code() {
return this.code;
}
/**
* Set the code value.
*
* @param code the code value to set
* @return the ApiErrorBase object itself.
*/
public ApiErrorBase withCode(String code) {
this.code = code;
return this;
}
/**
* Get the target value.
*
* @return the target value
*/
public String target() {
return this.target;
}
/**
* Set the target value.
*
* @param target the target value to set
* @return the ApiErrorBase object itself.
*/
public ApiErrorBase withTarget(String target) {
this.target = target;
return this;
}
/**
* Get the message value.
*
* @return the message value
*/
public String message() {
return this.message;
}
/**
* Set the message value.
*
* @param message the message value to set
* @return the ApiErrorBase object itself.
*/
public ApiErrorBase withMessage(String message) {
this.message = message;
return this;
}
}
| mit |
spotify/robolectric | shadows/framework/src/main/java/org/robolectric/shadows/ShadowInputDevice.java | 756 | package org.robolectric.shadows;
import android.view.InputDevice;
import org.robolectric.annotation.Implementation;
import org.robolectric.annotation.Implements;
import org.robolectric.shadow.api.Shadow;
@Implements(InputDevice.class)
public class ShadowInputDevice {
private String deviceName;
public static InputDevice makeInputDeviceNamed(String deviceName) {
InputDevice inputDevice = Shadow.newInstanceOf(InputDevice.class);
ShadowInputDevice shadowInputDevice = Shadow.extract(inputDevice);
shadowInputDevice.setDeviceName(deviceName);
return inputDevice;
}
@Implementation
protected String getName() {
return deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
}
| mit |
kashike/SpongeCommon | src/main/java/org/spongepowered/common/mixin/core/ban/MixinUserListBans.java | 3574 | /*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.common.mixin.core.ban;
import net.minecraft.server.management.UserList;
import net.minecraft.server.management.UserListBans;
import net.minecraft.server.management.UserListEntry;
import org.spongepowered.api.Sponge;
import org.spongepowered.api.profile.GameProfile;
import org.spongepowered.api.service.ban.BanService;
import org.spongepowered.api.util.ban.Ban;
import org.spongepowered.asm.mixin.Mixin;
import org.spongepowered.asm.mixin.Overwrite;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
@Mixin(UserListBans.class)
public abstract class MixinUserListBans extends UserList {
public MixinUserListBans(File saveFile) {
super(saveFile);
}
@Override
public boolean hasEntry(Object object) {
return Sponge.getServiceManager().provideUnchecked(BanService.class).isBanned((GameProfile) object);
}
@Override
public UserListEntry getEntry(Object object) {
return (UserListEntry) Sponge.getServiceManager().provideUnchecked(BanService.class).getBanFor((GameProfile) object).orElse(null);
}
@Overwrite
@Override
public String[] getKeys() {
List<String> names = new ArrayList<>();
for (Ban.Profile ban: Sponge.getServiceManager().provideUnchecked(BanService.class).getProfileBans()) {
names.add(ban.getProfile().getName());
}
return names.toArray(new String[names.size()]);
}
@Override
public void addEntry(UserListEntry entry) {
Sponge.getServiceManager().provideUnchecked(BanService.class).addBan((Ban) entry);
}
@Override
public boolean isEmpty() {
return Sponge.getServiceManager().provideUnchecked(BanService.class).getProfileBans().isEmpty();
}
@Override
public void removeEntry(Object object) {
Sponge.getServiceManager().provideUnchecked(BanService.class).pardon((GameProfile) object);
}
@Overwrite
public com.mojang.authlib.GameProfile isUsernameBanned(String username) {
for (Ban.Profile ban: Sponge.getServiceManager().provideUnchecked(BanService.class).getProfileBans()) {
if (ban.getProfile().getName().equals(username)) {
return (com.mojang.authlib.GameProfile) ban.getProfile();
}
}
return null;
}
}
| mit |
zaoying/EChartsAnnotation | src/cn/edu/gdut/zaoying/Option/series/effectScatter/SymbolOffsetArray.java | 321 | package cn.edu.gdut.zaoying.Option.series.effectScatter;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface SymbolOffsetArray {
} | mit |
tosseto/online-whatif | src/main/java/au/org/aurin/wif/controller/demand/DemandConfigController.java | 9929 | package au.org.aurin.wif.controller.demand;
import static au.org.aurin.wif.io.RestAPIConstants.HEADER_USER_ID_KEY;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import au.org.aurin.wif.controller.OWIURLs;
import au.org.aurin.wif.exception.config.ParsingException;
import au.org.aurin.wif.exception.config.WifInvalidConfigException;
import au.org.aurin.wif.exception.validate.IncompleteDemandConfigException;
import au.org.aurin.wif.exception.validate.WifInvalidInputException;
import au.org.aurin.wif.model.demand.DemandConfig;
import au.org.aurin.wif.svc.suitability.DemandConfigService;
/**
* The Class DemandConfigController.
*/
@Controller
@RequestMapping(OWIURLs.PROJECT_SVC_URI)
public class DemandConfigController {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory
.getLogger(DemandConfigController.class);
/** The demand config service. */
@Resource
private DemandConfigService demandConfigService;
/**
* Sets the demand config service.
*
* @param demandConfigService
* the new demand config service
*/
public void setDemandConfigService(
final DemandConfigService demandConfigService) {
this.demandConfigService = demandConfigService;
}
/**
* Creates the demand config.
*
* @param roleId
* the role id
* @param projectId
* the project id
* @param demandConfig
* the demand config
* @param response
* the response
* @return the demand config
* @throws WifInvalidInputException
* the wif invalid input exception
* @throws BindException
* the bind exception
* @throws WifInvalidConfigException
* the wif invalid config exception
* @throws ParsingException
* the parsing exception
* @throws IncompleteDemandConfigException
* the incomplete demand config exception
*/
@RequestMapping(method = RequestMethod.POST, value = "/{projectId}/demand/setup", consumes = "application/json", produces = "application/json")
@ResponseStatus(HttpStatus.CREATED)
public @ResponseBody
DemandConfig createDemandConfig(
@RequestHeader(HEADER_USER_ID_KEY) final String roleId,
@PathVariable("projectId") final String projectId,
@RequestBody final DemandConfig demandConfig,
final HttpServletResponse response)
throws IncompleteDemandConfigException, WifInvalidInputException,
WifInvalidConfigException, ParsingException {
LOGGER.info("*******>> createDemandConfig request for project id ={}",
projectId);
final String msg = "createDemandConfig failed: {}";
try {
return demandConfigService.createDemandConfig(demandConfig, projectId);
} catch (final WifInvalidInputException e) {
LOGGER.error(msg, e.getMessage());
throw new WifInvalidInputException(msg, e);
} catch (final WifInvalidConfigException e) {
LOGGER.error(msg, e.getMessage());
throw new WifInvalidConfigException(msg, e);
} catch (final ParsingException e) {
LOGGER.error(msg, e.getMessage());
throw new ParsingException(msg, e);
} catch (final IncompleteDemandConfigException e) {
LOGGER.error(msg, e.getMessage());
throw new IncompleteDemandConfigException(msg, e);
}
}
/**
* Gets the demand config.
*
* @param roleId
* the role id
* @param projectId
* the project id
* @return the demand config
* @throws WifInvalidInputException
* the wif invalid input exception
* @throws WifInvalidConfigException
* the wif invalid config exception
* @throws ParsingException
* the parsing exception
*/
@RequestMapping(method = RequestMethod.GET, value = "/{projectId}/demand/setup", produces = "application/json")
@ResponseStatus(HttpStatus.OK)
public @ResponseBody
DemandConfig getDemandConfig(
@RequestHeader(HEADER_USER_ID_KEY) final String roleId,
@PathVariable("projectId") final String projectId)
throws WifInvalidInputException, WifInvalidConfigException,
ParsingException {
LOGGER.info("*******>> getDemandConfig request for project id ={}",
projectId);
final String msg = "getDemandConfig failed: {}";
try {
return demandConfigService.getDemandConfig(projectId);
} catch (final WifInvalidInputException e) {
LOGGER.error(msg, e.getMessage());
throw new WifInvalidInputException(msg, e);
} catch (final WifInvalidConfigException e) {
LOGGER.error(msg, e.getMessage());
throw new WifInvalidConfigException(msg, e);
} catch (final ParsingException e) {
LOGGER.error(msg, e.getMessage());
throw new ParsingException(msg, e);
}
}
/**
* Update demand config.
*
* @param roleId
* the role id
* @param projectId
* the project id
* @param demandConfig
* the demand config
* @throws WifInvalidInputException
* the wif invalid input exception
* @throws BindException
* the bind exception
* @throws WifInvalidConfigException
* the wif invalid config exception
* @throws ParsingException
* @throws IncompleteDemandConfigException
*/
@RequestMapping(method = RequestMethod.PUT, value = "/{projectId}/demand/setup", consumes = "application/json", produces = "application/json")
@ResponseStatus(HttpStatus.OK)
// was NO_CONTENT
public @ResponseBody
String updateDemandConfig(
// instead of public void
@RequestHeader(HEADER_USER_ID_KEY) final String roleId,
@PathVariable("projectId") final String projectId,
@RequestBody final DemandConfig demandConfig)
throws WifInvalidInputException, BindException,
WifInvalidConfigException, ParsingException,
IncompleteDemandConfigException {
LOGGER
.info(
"*******>> updateDemandConfig/deleting the old one and creating a new demandConfig request for project id ={}",
projectId);
final String msg = "updateDemandConfig failed: {}";
try {
demandConfigService.updateDemandConfig(demandConfig, projectId);
// //very new return revision
return "{\"_rev\" :\"" + demandConfig.getRevision() + "\"}";
} catch (final WifInvalidInputException e) {
LOGGER.error(msg, e.getMessage());
throw new WifInvalidInputException(msg, e);
} catch (final WifInvalidConfigException e) {
LOGGER.error(msg, e.getMessage());
throw new WifInvalidConfigException(msg, e);
}
}
/**
* Delete demand config.
*
* @param roleId
* the role id
* @param projectId
* the project id
* @throws WifInvalidInputException
* the wif invalid input exception
* @throws WifInvalidConfigException
* the wif invalid config exception
*/
@RequestMapping(method = RequestMethod.DELETE, value = "/{projectId}/demand/setup")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void deleteDemandConfig(
@RequestHeader(HEADER_USER_ID_KEY) final String roleId,
@PathVariable("projectId") final String projectId)
throws WifInvalidInputException, WifInvalidConfigException {
LOGGER.info("*******>> deleteDemandConfig request for project id ={}",
projectId);
final String msg = "deleteDemandConfig failed: {}";
try {
demandConfigService.deleteDemandConfig(projectId);
} catch (final WifInvalidInputException e) {
LOGGER.error(msg, e.getMessage());
throw new WifInvalidInputException(msg, e);
} catch (final WifInvalidConfigException e) {
LOGGER.error(msg, e.getMessage());
throw new WifInvalidConfigException(msg, e);
}
}
/**
* ali Gets the demand config report.
*
* @param roleId
* the role id
* @param projectId
* the project id
* @return the demand config
* @throws WifInvalidInputException
* the wif invalid input exception
* @throws WifInvalidConfigException
* the wif invalid config exception
* @throws ParsingException
* the parsing exception
*/
@RequestMapping(method = RequestMethod.GET, value = "/{projectId}/demand/setup/report", produces = "application/json")
@ResponseStatus(HttpStatus.OK)
public @ResponseBody
DemandConfig getDemandConfigReport(
@RequestHeader(HEADER_USER_ID_KEY) final String roleId,
@PathVariable("projectId") final String projectId)
throws WifInvalidInputException, WifInvalidConfigException,
ParsingException {
LOGGER.info("*******>> getDemandConfigReport request for project id ={}",
projectId);
final String msg = "getDemandConfigReport failed: {}";
try {
return demandConfigService.getDemandConfig(projectId);
} catch (final WifInvalidInputException e) {
LOGGER.error(msg, e.getMessage());
throw new WifInvalidInputException(msg, e);
} catch (final WifInvalidConfigException e) {
LOGGER.error(msg, e.getMessage());
throw new WifInvalidConfigException(msg, e);
} catch (final ParsingException e) {
LOGGER.error(msg, e.getMessage());
throw new ParsingException(msg, e);
}
}
}
| mit |
mepcotterell/SuggestionEngine | src/inputOutputMatch/LeafMediation.java | 27288 | package inputOutputMatch;
//import java.lang.reflect.Array;
import util.NodeType;
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.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.xpath.XPath;
//import ontologySimilarity.WBzard;
//import ontologySimilarity.WBzard.Match;
import parser.LeafDmParser;
import parser.MsIODGparser;
import parser.ParseWSDL;
import parser.JdomParser;
import parser.SawsdlParser;
import util.IODG;
import util.WebServiceOpr;
import util.WebServiceOprScore_type;
import org.semanticweb.owlapi.model.*;
/**
* Currently not used / supported.
*
* @author Rui Wang
*/
public class LeafMediation {
//
// /**doc/literal
// * get the bottom element name of input of given operation
// * @param fileName
// * @param opName
// * @return
// */
// private List<String> getOpInBottomEleNameList(String fileName, String opName){
// //all bottom level elements name list
// //for the (input--->message--->parts--->)element--->sub elements,
// //if not complex type, no sub element, then add itself
// List<String> partsEleNameList=null;
// ParseWSDL wsdlparser=new ParseWSDL();
// try{
// partsEleNameList=wsdlparser.getOpInMsElemName(fileName, opName);
// }catch(Exception e){
// e.printStackTrace();
// }
// List<String> bottomElemList=new ArrayList<String>();
// for(int i=0;i<partsEleNameList.size();i++){
// List<String> tempSubelemL=JdomParser.getSubelemList(fileName, partsEleNameList.get(i));
// if(tempSubelemL!=null){
// bottomElemList.addAll(tempSubelemL);
// }
// else bottomElemList.add(partsEleNameList.get(i));
// }
//
// return bottomElemList;
// }
//
// /**doc/literal
// * get the bottom element node list of input of given operation
// *
// * @param fileName
// * @param opName
// * @return
// */
// public List<Element> getOpInBottomEleNodeList(String fileName, String opName){
// //all bottom level elements name list
// //for the (input--->message--->parts--->)element--->sub elements,
// //if not complex type, no sub element, then add itself
// List<String> partsEleNameList=null;
// ParseWSDL wsdlparser=new ParseWSDL();
// try{
// partsEleNameList=wsdlparser.getOpInMsElemName(fileName, opName);
// }catch(Exception e){
// e.printStackTrace();
// }
// List<Element> bottomElemList=new ArrayList<Element>();
// if (partsEleNameList==null){
// SawsdlParser sp =new SawsdlParser();
// Element msElem = sp.getOutMsElem(fileName, opName);
// bottomElemList.add(msElem);
// }else{
// for(int i=0;i<partsEleNameList.size();i++){
// List<Element> tempSubelemL=JdomParser.getSubelemNodeList(fileName, partsEleNameList.get(i));
// if(tempSubelemL!=null){
// bottomElemList.addAll(tempSubelemL);
// }
// else System.out.println("Mediation.java--getOpInBottomEleNodeList warning:no element name="+partsEleNameList.get(i));
// }
// }
// return bottomElemList;
// }
//
///**
// * get the bottom element name of output of given operation
// * @param fileName
// * @param opName
// * @return
// */
//private List<String> getOpOutBottomEleNameList(String fileName, String opName){
// //all bottom level elements name list
// //for the (output--->message--->parts--->)element--->sub elements,
// //if not complex type, no sub element, then add itself
// List<String> partsEleNameList=null;
// ParseWSDL wsdlparser=new ParseWSDL();
// try{
// partsEleNameList=wsdlparser.getOpOutMsElemName(fileName, opName);
// }catch(Exception e){
// e.printStackTrace();
// }
// List<String> bottomElemList=new ArrayList<String>();
// for(int i=0;i<partsEleNameList.size();i++){
// List<String> tempSubelemL=JdomParser.getSubelemList(fileName, partsEleNameList.get(i));
//
// if(tempSubelemL!=null){
// bottomElemList.addAll(tempSubelemL);
// }
// else bottomElemList.add(partsEleNameList.get(i));
// }
//
// return bottomElemList;
// }
//
///**
// * get the bottom element node list of output of given operation
// * @param fileName
// * @param opName
// * @return
// */
//public List<Element> getOpOutBottomEleNodeList(String fileName, String opName){
// //all bottom level elements name list
// //for the (output--->message--->parts--->)element--->sub elements,
// //if not complex type, no sub element, then add itself
// List<String> partsEleNameList=null;
// ParseWSDL wsdlparser=new ParseWSDL();
// try{
// partsEleNameList=wsdlparser.getOpOutMsElemName(fileName, opName);
// }catch(Exception e){
// e.printStackTrace();
// }
// List<Element> bottomElemList=new ArrayList<Element>();
// if (partsEleNameList==null){
// SawsdlParser sp =new SawsdlParser();
// Element msElem = sp.getOutMsElem(fileName, opName);
// bottomElemList.add(msElem);
// }else{
// for(int i=0;i<partsEleNameList.size();i++){
// List<Element> tempSubelemL=JdomParser.getSubelemNodeList(fileName, partsEleNameList.get(i));
//
// if(tempSubelemL!=null){
// bottomElemList.addAll(tempSubelemL);
// }
// else System.out.println("Mediation.java--getOpOutBottomEleNodeList warning:no element name="+partsEleNameList.get(i));
// }
// }
// return bottomElemList;
// }
//
///**no
// * get input bottom element-Xpath map of given operation in given wsdl file
// * @param fileName
// * @param opName
// * @return
// */
//private Map<String, String> getOpInBottomEleNameXpathMap(String fileName, String opName){
// //all bottom level elements name list
// //for the (input--->message--->parts--->)element--->sub elements,
// //if not complex type, no sub element, then add itself
// List<String> partsEleNameList=null;
// ParseWSDL wsdlparser=new ParseWSDL();
// try{
// partsEleNameList=wsdlparser.getOpInMsElemName(fileName, opName);
//}catch(Exception e){
// e.printStackTrace();
//}
//
//Map<String, String> bottomElemXpathMap=new HashMap<String, String>();
//for(int i=0;i<partsEleNameList.size();i++){
// Map<String, String> tempSubelemXpathMap=JdomParser.getSubelemXpathMap(fileName, partsEleNameList.get(i));
//
//if(tempSubelemXpathMap!=null){
// bottomElemXpathMap.putAll(tempSubelemXpathMap);
//}
//else bottomElemXpathMap.put(partsEleNameList.get(i),"/");
//}
//
//return bottomElemXpathMap;
//}
//
///**
// * get input bottom elementNOde-Xpath map of given operation in given wsdl file
// * @param fileName
// * @param opName
// * @return
// */
//public Map<Element, String> getOpInBottomEleNodeXpathMap(String fileName, String opName){
// //all bottom level elements name list
// //for the (input--->message--->parts--->)element--->sub elements,
// //if not complex type, no sub element, then add itself
// List<String> partsEleNameList=null;
// ParseWSDL wsdlparser=new ParseWSDL();
// try{
// partsEleNameList=wsdlparser.getOpInMsElemName(fileName, opName);
//}catch(Exception e){
// e.printStackTrace();
//}
//
//Map<Element, String> bottomElemXpathMap=new HashMap<Element, String>();
//for(int i=0;i<partsEleNameList.size();i++){
// Map<Element, String> tempSubelemXpathMap=JdomParser.getSubelemNodeXpathMap(fileName, partsEleNameList.get(i));
//
//if(tempSubelemXpathMap!=null){
// bottomElemXpathMap.putAll(tempSubelemXpathMap);
//}
//else System.out.println("Mediation.java--getOpInBottomEleNodeXpathMap warning:no element name="+partsEleNameList.get(i));
//
//}
//
//return bottomElemXpathMap;
//}
//
//
///**
// * get output bottom element-Xpath map of given operation in given wsdl file
// * @param fileName
// * @param opName
// * @return
// */
//private Map<String, String> getOpOutBottomEleNameXpathMap(String fileName, String opName){
////all bottom level elements name list
////for the (output--->message--->parts--->)element--->sub elements,
////if not complex type, no sub element, then add itself
// List<String> partsEleNameList=null;
// ParseWSDL wsdlparser=new ParseWSDL();
// try{
// partsEleNameList=wsdlparser.getOpOutMsElemName(fileName, opName);
//}catch(Exception e){
// e.printStackTrace();
//}
//
//Map<String, String> bottomElemXpathMap=new HashMap<String, String>();
//for(int i=0;i<partsEleNameList.size();i++){
// Map<String, String> tempSubelemXpathMap=JdomParser.getSubelemXpathMap(fileName, partsEleNameList.get(i));
//
//if(tempSubelemXpathMap!=null){
// bottomElemXpathMap.putAll(tempSubelemXpathMap);
//}
//else bottomElemXpathMap.put(partsEleNameList.get(i),"/");
//}
//
//return bottomElemXpathMap;
//}
//
///**
// * get output bottom elementNode-Xpath map of given operation in given wsdl file
// * @param fileName
// * @param opName
// * @return
// */
//public Map<Element, String> getOpOutBottomEleNodeXpathMap(String fileName, String opName){
////all bottom level elements name list
////for the (output--->message--->parts--->)element--->sub elements,
////if not complex type, no sub element, then add itself
// List<String> partsEleNameList=null;
// ParseWSDL wsdlparser=new ParseWSDL();
// try{
// partsEleNameList=wsdlparser.getOpOutMsElemName(fileName, opName);
//}catch(Exception e){
// e.printStackTrace();
//}
//
//Map<Element, String> bottomElemXpathMap=new HashMap<Element, String>();
//for(int i=0;i<partsEleNameList.size();i++){
// Map<Element, String> tempSubelemXpathMap=JdomParser.getSubelemNodeXpathMap(fileName, partsEleNameList.get(i));
//
//if(tempSubelemXpathMap!=null){
// bottomElemXpathMap.putAll(tempSubelemXpathMap);
//}
//else System.out.println("Mediation.java--getOpOutBottomEleNodeXpathMap warning:no element name="+partsEleNameList.get(i));
//}
//
//return bottomElemXpathMap;
//}
//
// /**
// * given file name, element name, retrive back its modelReference concept
// * if not exist, return null;
// * @param fileName
// * @param eleName
// * @return
// */
// public static String getElementConcept(String fileName, String eleName){
// Element schemaEle=JdomParser.getSchemaElem(fileName);
// String preXsdNs=schemaEle.getNamespacePrefix();
// String concept=null;
// //System.out.println("prefix--"+preXsdNs);
// try{
// XPath xpath=XPath.newInstance("//"+preXsdNs+":schema/descendant::"+preXsdNs+":element[@name=\""+eleName+"\"]");
// //XPath xpath=XPath.newInstance("//xsd:schema/descendant::xsd:element[@name=\"symbol\"]");
// Element elem=(Element)(xpath.selectSingleNode(schemaEle));
// if (elem!=null){
// String temp=elem.getAttributeValue("modelReference", JdomParser.sawsdlNS);
// //System.out.println(elem.getAttributeValue("name"));
// //System.out.println(temp);
// if(temp!=null){
// concept = temp.split("#")[1];
// //System.out.println("schema11---"+elem.getAttributeValue("modelReference", sawsdlNS));
// //System.out.println("schema---"+schemaEle.getChild("element", xsdNS).getChild("complexType", xsdNS).getChild("sequence", xsdNS).getChild("element", xsdNS).getAttributeValue("modelReference", sawsdlNS));
// }
// }
// }catch(JDOMException e){
// e.printStackTrace();
// }
//
// return concept;
// }
//
// /**yes
// * get the concept annotation of the given element node
// * @param node
// * @return
// */
// public String getNodeConcept(Element node){
// String concept=null;
// if (node!=null){
// String temp=node.getAttributeValue("modelReference", JdomParser.sawsdlNS);
// //System.out.println(elem.getAttributeValue("name"));
// //System.out.println(temp);
// if(temp!=null){
// concept = temp.split("#")[1];
// //System.out.println("schema11---"+elem.getAttributeValue("modelReference", sawsdlNS));
// //System.out.println("schema---"+schemaEle.getChild("element", xsdNS).getChild("complexType", xsdNS).getChild("sequence", xsdNS).getChild("element", xsdNS).getAttributeValue("modelReference", sawsdlNS));
// }
// else System.out.println("Mediation.java--getNodeConcept:no annotation in the node="+node.getAttributeValue("name"));
// }
// else System.out.println("Mediation.java--getNodeConcept: empty node");
// return concept;
// }
//
// /**no
// * operation-->input--->message--->parts--->element--->sub elements-->annotation concepts
// * if not complex type (no sub element), then find annotation of element itself
// * if no annotation of the element, then <element, null>
// *
// * @param fileName
// * @param opName
// * @return Map<element,concept>
// */
// private Map<String, String> getInputBottomEleConceptMap(String fileName, String opName){
// List<String> inBottomEleList=new ArrayList<String>();
//// ParseWSDL wsdlparser=new ParseWSDL();
// inBottomEleList=getOpInBottomEleNameList(fileName, opName);
//
// Map<String, String> eleConceptMap=getBottomEleConceptMap(fileName,inBottomEleList);
// return eleConceptMap;
// }
//
//
// /**no
// * given list of element name of all parts
// * element--->sub elements-->annotation concepts
// * if not complex type (no sub element), then find annotation of element itself
// * if no annotation of the element, then <element, null>
// *
// * @param fileName
// * @param partsEleNameList
// * @return Map<element,concept>
// */
// private Map<String, String> getBottomEleConceptMap(String fileName, List<String> bottomElemList){
//
// Map<String, String> bottomEleConceptMap=new HashMap<String, String>();
//
// for(int i=0;i<bottomElemList.size();i++){
// String concept=getElementConcept(fileName,bottomElemList.get(i));
// if(concept==null){
// System.out.println("Mediation.java:the element--"+bottomElemList.get(i)+" has no annotation");
//
// }
// bottomEleConceptMap.put(bottomElemList.get(i),concept);
// }
// return bottomEleConceptMap;
// }
//
// /**
// * operation-->output--->message--->parts--->element--->sub elements-->annotation concepts
// * if not complex type (no sub element), then find annotation of element itself
// *
// * @param fileName
// * @param opName
// * @return Map<element,concept>
// */
// private Map<String, String> getOutputBottomEleConceptMap(String fileName, String opName){
// List<String> outBottomEleList=null;
//// ParseWSDL wsdlparser=new ParseWSDL();
//
// outBottomEleList=getOpOutBottomEleNameList(fileName, opName);
//
// Map<String, String> eleConceptMap=getBottomEleConceptMap(fileName,outBottomEleList);
//
//
// return eleConceptMap;
// }
//
//
//
// /**no
// * given annotated two sawsdl files
// * find the input output elements of fileA which matche input elements of fileB
// * return matched elements map<fileBinputElement, matchedfileAoutputElement>
// *
// * @param ontoFilename
// * @param fileA
// * @param opA
// * @param fileB
// * @param opB
// * @return
// */
// private Map<String, String> getMatchedOp1outputToOp2inputMap(String ontoFilename,String fileA, String opA, String fileB, String opB){
// Map<String, String> outputMap=getOutputBottomEleConceptMap(fileA, opA);
// //System.out.println(outputMap);
// Map<String, String> inputMap=getInputBottomEleConceptMap(fileB, opB);
// //System.out.println(inputMap);
//
// Object[] arrayA=outputMap.keySet().toArray();
// Object[] arrayB=inputMap.keySet().toArray();
//
// Map<String, String> matchedEleMap=new HashMap<String, String>();
//
//
// for(int i=0;i<arrayB.length;i++){
// String tempInconcept=inputMap.get(arrayB[i]);
// //System.out.println(i+" input "+arrayB[i]+" annotation="+tempInconcept);
// if(tempInconcept==null){
//
// continue;
// }
// //System.out.println("#fileA output="+arrayA.length);
// for(int j=0;j<arrayA.length;j++){
// String tempOutconcept=outputMap.get(arrayA[j].toString());
// //System.out.println(j+" output "+arrayA[j]+" annotation="+tempOutconcept);
// if(tempOutconcept==null){
// continue;
// }
// WBzard ontology=new WBzard(ontoFilename);
// if(tempOutconcept.equalsIgnoreCase(tempInconcept)){
// //System.out.println("matched concepts--"+tempOutconcept+"=="+tempInconcept);
// matchedEleMap.put(arrayB[i].toString(), arrayA[j].toString());
// //System.out.println(matchedEleMap);
// continue;
// }
// Match tempResult=ontology.compare2concepts(tempOutconcept, tempInconcept);
// //System.out.println(arrayB[i].toString()+" vs "+arrayA[j].toString()+"="+tempResult);
// if(tempResult==null){
//
// continue;
// }
// if(tempResult.equals(Match.SAMECLASS)||tempResult.equals(Match.EQUIVALENTCLASS)){
// matchedEleMap.put(arrayB[i].toString(), arrayA[j].toString());
// }
// }
//
// }
//
// //System.out.println(matchedEleMap);
// return matchedEleMap;
// }
//
// /**
// * get the matched xpath map<inputXpathOffileB, outputXpathOffileA>
// * if no match then <fileBinputXpath, null>
// *
// * @param ontoFilename
// * @param fileA
// * @param opA
// * @param fileB
// * @param opB
// * @return
// */
// public Map<String, String> matchedInputOutputXpathMap(String ontoFilename,String fileA, String opA, String fileB, String opB){
//
// //input of file B
// Map<Element, String> inputNodeXpathMap=this.getOpInBottomEleNodeXpathMap(fileB, opB);
// //output of file A
// Map<Element, String> outputNodeXpathMap=this.getOpOutBottomEleNodeXpathMap(fileA, opA);
// //result xpath map<inputXpathOfA, outputXpathOfB>
// Map<String, String> matchedXpathMap=new HashMap<String, String>();
// //input/output element nodes array
// Element[] inputNodes=inputNodeXpathMap.keySet().toArray(new Element[0]);
// Element[] outputNodes=outputNodeXpathMap.keySet().toArray(new Element[0]);
//
// WBzard ontology=new WBzard(ontoFilename);
//
// //match process
// for(int i=0;i<inputNodes.length;i++){
// Element tempInputEle=inputNodes[i];
// String tempInputXpath=inputNodeXpathMap.get(tempInputEle);
// //if no match then <inputXpath, null>
// matchedXpathMap.put(tempInputXpath, null);
// String tempInputConcept=this.getNodeConcept(tempInputEle);
// if(tempInputConcept==null){
//
// continue;
// }
// for(int j=0;j<outputNodes.length;j++){
// Element tempOutputEle=outputNodes[j];
// String tempOutputConcept=this.getNodeConcept(tempOutputEle);
// if(tempOutputConcept==null){
// continue;
// }
// String tempOutputXpath=outputNodeXpathMap.get(tempOutputEle);
// if(tempOutputConcept.equalsIgnoreCase(tempInputConcept)){
// matchedXpathMap.put(tempInputXpath, tempOutputXpath);
// continue;
// }
// Match tempResult=ontology.compare2concepts(tempOutputConcept, tempInputConcept);
// if(tempResult==null){
// continue;
// }
// if(tempResult.equals(Match.SAMECLASS)||tempResult.equals(Match.EQUIVALENTCLASS)||tempResult.equals(Match.SUPERCLASS)){
// matchedXpathMap.put(tempInputXpath, tempOutputXpath);
// }
// }
//
// }
// return matchedXpathMap;
// }
//
// /**no
// * given annotated two sawsdl files
// * find the input output elements of fileA which matche input elements of fileB
// * return matched elements xpath map<fileBinputElementXpath, matchedfileAoutputElementXpath>
// *
// * @param ontoFilename
// * @param fileA
// * @param opA
// * @param fileB
// * @param opB
// * @return
// */
// private Map<String, String> getMatchedXpathMap(String ontoFilename,String fileA, String opA, String fileB, String opB){
// Map<String, String> matchedEleMap=this.getMatchedOp1outputToOp2inputMap(ontoFilename, fileA, opA, fileB, opB);
// Map<String, String> outputEleXpathMap=this.getOpOutBottomEleNameXpathMap(fileA, opA);
// Map<String, String> inputEleXpathMap=this.getOpInBottomEleNameXpathMap(fileB, opB);
// Map<String, String> matchedXpathMap=new HashMap<String, String>();
// Iterator<String> itMatch=matchedEleMap.keySet().iterator();
// //System.out.println(matchedEleMap);
// //System.out.println(outputEleXpathMap);
// //System.out.println(inputEleXpathMap);
// while(itMatch.hasNext()){
// String tempInName=itMatch.next();
// String tempOutName=matchedEleMap.get(tempInName);
// String tempOutXpath=outputEleXpathMap.get(tempOutName);
// String tempInXpath=inputEleXpathMap.get(tempInName);
// matchedXpathMap.put(tempInXpath,tempOutXpath);
// //System.out.println(tempOutName+"--"+tempInName);
// //System.out.println(tempOutXpath+"--"+tempInXpath);
// }
// return matchedXpathMap;
// }
//
// /**
// * given annotated two sawsdl files
// * find the missed input elements of fileB which has no matched elements to input of fileA
// * return list of missed input element names of fileB
// *
// * @param ontoFilename
// * @param fileA
// * @param opA
// * @param fileB
// * @param opB
// * @return
// */
// public List<String> getMissedEleList(String ontoFilename,String fileA, String opA, String fileB, String opB){
// List<String> missedEleList=new ArrayList<String>();
// //ParseWSDL wsdlparser=new ParseWSDL();
// List<String> inBottomEleList=getOpInBottomEleNameList(fileB, opB);
// missedEleList.addAll(inBottomEleList);
//
// Map<String, String> matchedEleMap=getMatchedOp1outputToOp2inputMap(ontoFilename,fileA,opA, fileB, opB);
// missedEleList.removeAll(matchedEleMap.keySet());
//
// return missedEleList;
// }
//
// /**
// * given annotated two sawsdl files
// * find the missed input elements of fileB which has no matched elements to input of fileA
// * return the missed element-xpath map
// * @param ontoFilename
// * @param fileA
// * @param opA
// * @param fileB
// * @param opB
// * @return
// */
// public Map<String, String> getMissedEleXpathMap(String ontoFilename,String fileA, String opA, String fileB, String opB){
// List<String> missedEleList=this.getMissedEleList(ontoFilename, fileA, opA, fileB, opB);
// Map<String, String> inputEleXpathMap=this.getOpInBottomEleNameXpathMap(fileB, opB);
// Map<String, String> missedEleXpathMap=new HashMap<String, String>();
// for(int i=0;i<missedEleList.size();i++){
// String tempMissedEle=missedEleList.get(i);
// missedEleXpathMap.put(tempMissedEle, inputEleXpathMap.get(tempMissedEle));
// }
// return missedEleXpathMap;
// }
//
//
// /**given workflow operation, and candidate operation
// * compare the output of the last operation in the workflow with the input of the candidate operation
// * return a map[node&scoreOfinput, node&scoreOfoutput]
// * to reuse the WebServiceOprScore_type, node is presented as a list(path) with one node
// * @param workflowOPs
// * @param candidateOP
// * @param owlFileName
// * @return
// */
// public Map<WebServiceOprScore_type, WebServiceOprScore_type> dm(List<WebServiceOpr> workflowOPs, WebServiceOpr candidateOP, String owlURI){
// if(workflowOPs == null || candidateOP == null){
// System.out.println("LeafMediation.dm: warning: given empty workflow or candidiate operation");
// return null;
// }
//
// WebServiceOpr lastOp = workflowOPs.get(workflowOPs.size()-1);
//// List<Element> lastopNodeList= this.getOpOutBottomEleNodeList(lastOp.getWsdlName(), lastOp.getOpName());
//// List<Element> candidateNodeList = this.getOpInBottomEleNodeList(candidateOP.getWsdlName(), candidateOP.getOpName());
//
// LeafDmParser ldp = new LeafDmParser();
// List<Element> lastopNodeList= ldp.getOutBottomElemList(lastOp.getWsDescriptionDoc(), lastOp.getOperationName());
// List<Element> candidateNodeList = ldp.getInBottomElemList(candidateOP.getWsDescriptionDoc(), candidateOP.getOperationName());
// if (lastopNodeList==null ||lastopNodeList.isEmpty() ||candidateNodeList==null|| candidateNodeList.isEmpty()){
// System.out.println("LeafMediation.dm: warning: given operation has no input or output");
// return null;
// }
//
// Map<WebServiceOprScore_type, WebServiceOprScore_type> inMatchMap = new HashMap<WebServiceOprScore_type, WebServiceOprScore_type>();
// PathRank pk = new PathRank();
// for (Element inNode: candidateNodeList){
// List<WebServiceOprScore_type> outList = new ArrayList<WebServiceOprScore_type>();
// for(Element outNode:lastopNodeList){
// double s = pk.compare2node(outNode, inNode, owlURI, NodeType.LEAF_NODE);
// //a singlton path with only one node, to reuse the WebServiceOprScore_type
// List<Element> nodePath = new ArrayList<Element>();
// nodePath.add(outNode);
// WebServiceOprScore_type outNodeScore = new WebServiceOprScore_type(lastOp.getWsDescriptionDoc(), lastOp.getOperationName(),nodePath, false);
// outNodeScore.setScore(s);
// outList.add(outNodeScore);
// }
// WebServiceOprScore_type match = Collections.max(outList);
// //a singlton path with only one node, to reuse the WebServiceOprScore_type
// List<Element> inNodePath = new ArrayList<Element>();
// inNodePath.add(inNode);
// WebServiceOprScore_type inNodeScore = new WebServiceOprScore_type(candidateOP.getWsDescriptionDoc(), candidateOP.getOperationName(),inNodePath, true);
// inNodeScore.setScore(match.getScore());
// inMatchMap.put(inNodeScore, match);
// }
// return inMatchMap;
//
// }
//
// public LeafMediation() {
//
// }
//
// /**
// * @param args
// */
// public static void main(String[] args) {
// LeafMediation test=new LeafMediation();
// /*Map temp=test.getOutputBottomEleConceptMap("CompanyInfo.wsdl", "getInfo");
// Map tempIn=test.getInputBottomEleConceptMap("CompanyInfo.wsdl", "getInfo");
// System.out.println("input bottom element="+tempIn);
// System.out.println("output bottom element="+temp);*/
// /*
// Map matchedEleMap=test.getMatchedOp1outputToOp2inputMap("LSDIS_Finance.owl", "CompanyInfo.wsdl", "getInfo", "stockquote.wsdl", "GetQuote");
// List missedEle=test.getMissedEleList("LSDIS_Finance.owl", "CompanyInfo.wsdl", "getInfo", "stockquote.wsdl", "GetQuote");
// System.out.println("matched elements: "+matchedEleMap);
// System.out.println("missed input elements="+missedEle);*/
//
// //Map matchedXpathMap=test.getMatchedXpathMap("LSDIS_Finance.owl", "CompanyInfo.wsdl", "getInfo", "stockquote.wsdl", "GetQuote");
// //Map missedEleXpathMap=test.getMissedEleXpathMap("LSDIS_Finance.owl", "CompanyInfo.wsdl", "getInfo", "stockquote.wsdl", "GetQuote");
// /*Map matchedXpathMap=test.getMatchedXpathMap("so.owl", "NewWuBlast.wsdl","wuBlast", "NewGeneByLocation.wsdl", "invoke");
// Map missedEleXpathMap=test.getMissedEleXpathMap("so.owl", "NewWuBlast.wsdl","wuBlast", "NewGeneByLocation.wsdl", "invoke");
// System.out.println("matched element fileBInputxpath--fileAOutputxpath: "+matchedXpathMap);
// System.out.println("missed input elements--xpath="+missedEleXpathMap);
// */
//// Map<String, String> matchXpathMap=test.matchedInputOutputXpathMap("owl/obi.owl", "wsdl/8/WSWuBlast.wsdl","runWUBlast", "wsdl/8/WSWuBlast.wsdl", "getIds");
//// System.out.println("matched element fileBInputxpath--fileAOutputxpath: " + matchXpathMap);
//
//
//
// }
}
| mit |
JeffRisberg/BING01 | proxies/com/microsoft/bingads/reporting/ArrayOfDestinationUrlPerformanceReportColumn.java | 2557 |
package com.microsoft.bingads.reporting;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ArrayOfDestinationUrlPerformanceReportColumn complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="ArrayOfDestinationUrlPerformanceReportColumn">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="DestinationUrlPerformanceReportColumn" type="{https://bingads.microsoft.com/Reporting/v9}DestinationUrlPerformanceReportColumn" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "ArrayOfDestinationUrlPerformanceReportColumn", propOrder = {
"destinationUrlPerformanceReportColumns"
})
public class ArrayOfDestinationUrlPerformanceReportColumn {
@XmlElement(name = "DestinationUrlPerformanceReportColumn")
@XmlSchemaType(name = "string")
protected List<DestinationUrlPerformanceReportColumn> destinationUrlPerformanceReportColumns;
/**
* Gets the value of the destinationUrlPerformanceReportColumns property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the destinationUrlPerformanceReportColumns property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDestinationUrlPerformanceReportColumns().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DestinationUrlPerformanceReportColumn }
*
*
*/
public List<DestinationUrlPerformanceReportColumn> getDestinationUrlPerformanceReportColumns() {
if (destinationUrlPerformanceReportColumns == null) {
destinationUrlPerformanceReportColumns = new ArrayList<DestinationUrlPerformanceReportColumn>();
}
return this.destinationUrlPerformanceReportColumns;
}
}
| mit |
tlaplus/tlaplus | tlatools/org.lamport.tlatools/src/tlc2/model/MCState.java | 13061 | package tlc2.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import tla2sany.st.Location;
import tlc2.tool.TLCState;
import tlc2.tool.TLCStateInfo;
import tlc2.value.IValue;
import tlc2.value.impl.RecordValue;
import tlc2.value.impl.Value;
import util.TLAConstants;
import util.UniqueString;
/**
* Encapsulates information about a TLC state.
*/
public class MCState {
private static final String BACK_TO_STATE = " " + TLAConstants.BACK_TO_STATE;
/**
* The variables captured by this state.
*/
private final MCVariable[] variables;
/**
* The name of the next-state-relation taken to arrive in this state.
*/
private final String name;
/**
* The state label; takes form of <$name $location>
*/
private final String label;
/**
* The location of the next-state-relation, a parsed representation of (for example):
* line 7, col 9 to line 11, col 23 of module Alias
*/
private final Location location;
/**
* Whether this state was reached by stuttering.
* Found in behaviors witnessing a liveness property violation.
*/
private final boolean isStuttering;
/**
* Whether this state returns to a previous state in the behavior.
* Found in behaviors witnessing a liveness property violation.
*/
private final boolean isBackToState;
/**
* The depth of this state in the behavior, counting from 1.
*/
private final int stateNumber;
private RecordValue record;
/**
* Parses a state from the standard TLC command line output format, for example:
*
* 3: <Next line 7, col 9 to line 11, col 23 of module Alias>
* /\ x = 3
* /\ y = FALSE
*
* @param stateInputString The unparsed state in TLC command line output format.
* @return A parsed {@link MCState} instance.
*/
public static MCState parseState(final String stateInputString) {
// state number
final int index = stateInputString.indexOf(TLAConstants.COLON);
// multi line
int index2 = stateInputString.indexOf(TLAConstants.CR, index);
if (index2 == -1) {
index2 = stateInputString.length();
}
final int stateNumber = Integer.parseInt(stateInputString.substring(0, index).trim());
final String label = stateInputString.substring((index + 1), index2);
final boolean isStuttering = (label.indexOf(TLAConstants.STUTTERING) == 0);
final boolean isBackToState = (label.indexOf(BACK_TO_STATE) == 0);
MCVariable[] vars = null;
final String name;
final Location location;
if (!isBackToState && !isStuttering) {
// string from which the variables can be parsed
final String variableInputString = stateInputString.substring(index2 + 1);
vars = parseVariables(variableInputString);
// The format of states in the output of depth-first (iterative deepening)
// obviously differs from BFS (why use one implementation when we can have 2 and
// more). Thus, take care of states that lack a label.
final String sublabel;
if (label.length() > 2) {
sublabel = label.substring(2, (label.length() - 1));
final int lineIndex = sublabel.indexOf(TLAConstants.LINE);
if (lineIndex != -1) {
name = sublabel.substring(0, (lineIndex - 1));
location = Location.parseLocation(sublabel.substring(lineIndex));
} else {
name = sublabel;
location = null;
}
} else {
name = null;
location = null;
}
} else {
name = null;
location = null;
}
return new MCState(vars, name, label, location, isStuttering, isBackToState, stateNumber);
}
/**
* @param vars variables in this state.
* @param stateName the name for this state
* @param stateLabel the display label, usually including line location and module
* @param moduleLocation the name of this module whose checking this state is from
* @param stuttering whether this is a stuttering state or not
* @param backToState whether this is a back to state or not
* @param ordinal number of the state in the trace
*/
public MCState(
final MCVariable[] vars,
final String stateName,
final String stateLabel,
final Location moduleLocation,
final boolean stuttering,
final boolean backToState,
final int ordinal) {
variables = vars;
name = stateName;
label = stateLabel;
location = moduleLocation;
isStuttering = stuttering;
isBackToState = backToState;
stateNumber = ordinal;
}
/**
* Initializes a new instance of this class.
* @param other The state from which to copy values.
* @param isStuttering Whether to mark this state as stuttering.
* @param isBackToState Whether to mark this state as the end of a lasso.
*/
public MCState(final MCState other, boolean isStuttering, boolean isBackToState) {
this.variables = other.variables;
this.name = other.name;
this.label = other.label;
this.location = other.location;
this.stateNumber = other.stateNumber;
this.isStuttering = isStuttering;
this.isBackToState = isBackToState;
}
public MCState(TLCStateInfo tlcState) {
this.name = "";
this.label = "";
this.location = null;
this.isStuttering = false;
this.isBackToState = false;
this.stateNumber = (int)tlcState.stateNumber;
Map<UniqueString, IValue> variableMap = tlcState.getOriginalState().getVals();
List<MCVariable> variableList = new ArrayList<MCVariable>();
for (UniqueString key : variableMap.keySet()) {
IValue value = variableMap.get(key);
// value is null if the successor state is not completely specified by the
// next-state relation. See e.g. IncompleteNextTest.java
MCVariable variable = new MCVariable(key.toString(), value);
variableList.add(variable);
}
this.variables = variableList.toArray(new MCVariable[variableList.size()]);
this.record = new RecordValue(tlcState.getOriginalState());
}
public MCVariable[] getVariables() {
return this.variables;
}
public String getLabel() {
return this.label;
}
public String getName() {
return this.name;
}
public boolean isStuttering() {
return this.isStuttering;
}
public boolean isBackToState() {
return this.isBackToState;
}
public int getStateNumber() {
return this.stateNumber;
}
public Location getLocation() {
return this.location;
}
public String asRecord(final boolean includeHeader) {
final StringBuilder result = new StringBuilder();
result.append(TLAConstants.L_SQUARE_BRACKET);
result.append(TLAConstants.CR);
if (includeHeader) {
result.append(TLAConstants.SPACE);
result.append(TLAConstants.TraceExplore.ACTION);
result.append(TLAConstants.RECORD_ARROW);
result.append(TLAConstants.L_SQUARE_BRACKET);
result.append(TLAConstants.CR);
result.append(TLAConstants.SPACE).append(TLAConstants.SPACE).append(TLAConstants.SPACE);
result.append("position");
result.append(TLAConstants.RECORD_ARROW);
result.append(getStateNumber());
result.append(TLAConstants.COMMA).append(TLAConstants.CR);
result.append(TLAConstants.SPACE).append(TLAConstants.SPACE).append(TLAConstants.SPACE);
result.append("name");
result.append(TLAConstants.RECORD_ARROW);
result.append(TLAConstants.QUOTE);
result.append(name);
result.append(TLAConstants.QUOTE);
result.append(TLAConstants.COMMA).append(TLAConstants.CR);
result.append(TLAConstants.SPACE).append(TLAConstants.SPACE).append(TLAConstants.SPACE);
result.append("location");
result.append(TLAConstants.RECORD_ARROW);
result.append(TLAConstants.QUOTE);
result.append(location);
result.append(TLAConstants.QUOTE);
result.append(TLAConstants.CR);
result.append(TLAConstants.SPACE).append(TLAConstants.R_SQUARE_BRACKET);
if (variables.length != 0) {
// only append comma for additional records iff there are any variables to
// append.
result.append(TLAConstants.COMMA).append(TLAConstants.CR);
}
}
for (int i = 0; i < variables.length; i++) {
final MCVariable variable = variables[i];
if (variable.isTraceExplorerExpression()) {
result.append(variable.getSingleLineDisplayName());
} else {
result.append(variable.getName());
}
result.append(TLAConstants.RECORD_ARROW);
result.append(variable.getValueAsString());
if (i < (variables.length - 1)) {
result.append(TLAConstants.COMMA).append(TLAConstants.CR);
}
}
result.append(TLAConstants.CR).append(TLAConstants.R_SQUARE_BRACKET);
return result.toString();
}
public String asSimpleRecord() {
final StringBuilder buf = new StringBuilder();
buf.append(TLAConstants.L_SQUARE_BRACKET);
for (int i = 0; i < variables.length; i++) {
final MCVariable var = variables[i];
buf.append(var.getName());
buf.append(TLAConstants.RECORD_ARROW);
buf.append(var.getValueAsString());
if (i < variables.length - 1) {
buf.append(TLAConstants.COMMA);
}
}
buf.append(TLAConstants.R_SQUARE_BRACKET);
return buf.toString();
}
/**
* The returns a conjunction list of variables.
*
* For variables representing trace explorer expressions, if {@code includeTraceExpressions} is true,
* the returned string has:
*
* /\ expr = value
*
* where expr is the single line form of the trace explorer expression as shown in the Name column of
* the trace viewer.
*
* For all other variables, this method attempts to display them as TLC does.
*
* @param includeTraceExpressions whether trace expressions should be included.
* @param indent if non-null, this will be prepended to each line
* @return
*/
public String getConjunctiveDescription(final boolean includeTraceExpressions, final String indent) {
return getConjunctiveDescription(includeTraceExpressions, indent, false);
}
/**
* The returns a conjunction list of variables.
*
* For variables representing trace explorer expressions, if {@code includeTraceExpressions} is true,
* the returned string has:
*
* /\ expr = value
*
* where expr is the single line form of the trace explorer expression as shown in the Name column of
* the trace viewer.
*
* For all other variables, this method attempts to display them as TLC does.
*
* @param includeTraceExpressions whether trace expressions should be included.
* @param indent if non-null, this will be prepended to each line
* @param ansiMarkup if true, the String will include ANSI markup for trace expressions; this is currently ignored
* if includeTraceExpressions is false
* @return
*/
public String getConjunctiveDescription(final boolean includeTraceExpressions, final String indent,
final boolean ansiMarkup) {
final StringBuilder result = new StringBuilder();
for (int i = 0; i < variables.length; i++) {
final MCVariable var = variables[i];
if (var.isTraceExplorerExpression() && !includeTraceExpressions) {
continue;
}
if (indent != null) {
result.append(indent);
}
result.append("/\\ ");
if (var.isTraceExplorerExpression()) {
if (ansiMarkup) {
result.append(TLAConstants.ANSI.BOLD_CODE);
}
result.append(var.getSingleLineDisplayName());
} else {
result.append(var.getName());
}
result.append(" = ").append(var.getValueAsString());
if (var.isTraceExplorerExpression() && ansiMarkup) {
result.append(TLAConstants.ANSI.RESET_CODE);
}
result.append('\n');
}
return result.toString();
}
private static MCVariable[] parseVariables(final String variableInputString) {
String[] lines = variableInputString.split(TLAConstants.CR);
ArrayList<MCVariable> vars = new ArrayList<>();
int index;
// buffer for accumulating the state variable
String[] stateVarString = null;
// iterate line-wise
for (int j = 0; j < lines.length; j++) {
// find the index of the first /\ in the line
index = lines[j].indexOf(TLAConstants.TLA_AND);
// adding the current line to the previous lines
if (index != -1) {
// there was something in the buffer for the state variable
// found an empty line, which means that this is the end of the current state
if (stateVarString != null) {
final MCVariable var = new MCVariable(stateVarString[0], stateVarString[1]);
vars.add(var);
}
stateVarString = lines[j].substring(index + TLAConstants.TLA_AND.length() + 1).split(TLAConstants.EQ);
} else {
// no index
if (stateVarString != null) {
// either an empty line
stateVarString[1] += TLAConstants.CR;
stateVarString[1] += lines[j];
} else {
// the state has one variable only
stateVarString = lines[j].split(TLAConstants.EQ);
}
}
}
// write the last one
if (stateVarString != null) {
final MCVariable var = new MCVariable(stateVarString[0], stateVarString[1]);
vars.add(var);
}
return (MCVariable[]) vars.toArray(new MCVariable[vars.size()]);
}
public Value getRecord() {
return record;
}
}
| mit |
Microsoft/ApplicationInsights-Android | applicationinsights-android/src/androidTest/java/com/microsoft/applicationinsights/library/ChannelQueueTest.java | 3428 | package com.microsoft.applicationinsights.library;
import android.test.InstrumentationTestCase;
import com.microsoft.applicationinsights.library.config.IQueueConfig;
import junit.framework.Assert;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Mockito.after;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.mockito.internal.verification.VerificationModeFactory.times;
public class ChannelQueueTest extends InstrumentationTestCase {
private PublicChannelQueue sut;
private IQueueConfig mockConfig;
private PublicPersistence mockPersistence;
public void setUp() throws Exception {
super.setUp();
System.setProperty("dexmaker.dexcache", getInstrumentation().getTargetContext().getCacheDir().getPath());
mockConfig = mock(IQueueConfig.class);
sut = new PublicChannelQueue(mockConfig);
mockPersistence = mock(PublicPersistence.class);
sut.setPersistence(mockPersistence);
}
public void testInitialisationWorks() {
Assert.assertNotNull(sut.config);
Assert.assertNotNull(sut.timer);
Assert.assertNotNull(sut.list);
Assert.assertEquals(0, sut.list.size());
Assert.assertFalse(sut.isCrashing);
}
public void testItemGetsEnqueued() {
// Setup
when(mockConfig.getMaxBatchIntervalMs()).thenReturn(10000);
when(mockConfig.getMaxBatchCount()).thenReturn(3);
// Test
sut.enqueue("");
sut.enqueue("");
// Verify
Assert.assertEquals(2, sut.list.size());
}
public void testQueueFlushedIfMaxBatchCountReached() {
// Setup
when(mockConfig.getMaxBatchIntervalMs()).thenReturn(10000);
when(mockConfig.getMaxBatchCount()).thenReturn(3);
// Test
sut.enqueue("");
sut.enqueue("");
// Verify
Assert.assertEquals(2, sut.list.size());
verify(mockPersistence, never()).persist(any(String[].class), anyBoolean());
sut.enqueue("");
Assert.assertEquals(0, sut.list.size());
verify(mockPersistence, times(1)).persist(any(String[].class), anyBoolean());
}
public void testQueueFlushedAfterBatchIntervalReached() {
// Setup
when(mockConfig.getMaxBatchIntervalMs()).thenReturn(200);
when(mockConfig.getMaxBatchCount()).thenReturn(3);
// Test
sut.enqueue("");
// Verify
Assert.assertEquals(1, sut.list.size());
verify(mockPersistence, never()).persist(any(String[].class), anyBoolean());
verify(mockPersistence, after(250).times(1)).persist(any(String[].class), anyBoolean());
Assert.assertEquals(0, sut.list.size());
}
public void testFlushingQueueWorks() {
//Setup
when(mockConfig.getMaxBatchIntervalMs()).thenReturn(200);
when(mockConfig.getMaxBatchCount()).thenReturn(3);
sut.enqueue("");
Assert.assertEquals(1, sut.list.size());
verify(mockPersistence, never()).persist(any(String[].class), anyBoolean());
// Test
sut.flush();
// Verify
Assert.assertEquals(0, sut.list.size());
verify(mockPersistence, times(1)).persist(any(String[].class), anyBoolean());
}
}
| mit |
G43riko/Java | GLib/src/glib/data/good/oneDirLinkedList/Node.java | 494 | package glib.data.good.oneDirLinkedList;
public class Node<S extends Comparable<S>> {
private S value;
private Node<S> next;
public Node(S value) {
this.value = value;
}
@Override
public String toString() {
return "[ " + value +" ]\n" + (next != null ? next : "");
}
public Node<S> getNext() {
return next;
}
public void setNext(Node<S> next) {
this.next = next;
}
public S getValue() {
return value;
}
public void setValue(S value) {
this.value = value;
}
}
| mit |
UIKit0/vocobox | dev/java/vocobox-api/src/main/java/org/vocobox/events/SoundEventStatistics.java | 2717 | package org.vocobox.events;
import java.util.Arrays;
import java.util.Collection;
import org.jzy3d.maths.Statistics;
public class SoundEventStatistics {
public static float[] LEVELS = { 0.00f, 0.25f, 0, 50f, 0.75f, 1.00f };
public float[] values;
public float[] levels;
public float[] quantiles;
public float min;
public float q25;
public float q50;
public float q75;
public float max;
public SoundEventStatistics(Collection<SoundEvent> events) {
compute(events);
}
public void compute(Collection<SoundEvent> events) {
values = SoundEvent.toArray(events);
levels = LEVELS;
quantiles = quantile(values, levels);
min = Statistics.min(values);// quantiles[0];
q25 = quantiles[1];
q50 = quantiles[2];
q75 = quantiles[3];
max = Statistics.max(values);// quantiles[4];
}
public static float[] quantile(float[] values, float[] levels, boolean interpolated) {
if (values.length == 0)
return new float[0];
float[] quantiles = new float[levels.length];
float[] sorted = new float[values.length];
System.arraycopy(values, 0, sorted, 0, values.length);
Arrays.sort(sorted);
float quantileIdx;
float quantileIdxCeil;
float quantileIdxFloor;
for (int i = 0; i < levels.length; i++) {
if (levels[i] > 100 || levels[i] < 0)
throw new IllegalArgumentException("input level " + levels[i] + " is out of bounds [0;100].");
quantileIdx = (sorted.length - 1) * levels[i] / 100;
if (quantileIdx == (int) quantileIdx) // exactly find the quantile
quantiles[i] = sorted[(int) quantileIdx];
else {
quantileIdxCeil = (float) Math.ceil(quantileIdx);
quantileIdxFloor = (float) Math.floor(quantileIdx);
if (interpolated) { // generate an interpolated quantile
quantiles[i] = sorted[(int) quantileIdxFloor] * (quantileIdxCeil - quantileIdx) + sorted[(int) quantileIdxCeil] * (quantileIdx - quantileIdxFloor);
} else { // return the quantile corresponding to the closest
// value
if (quantileIdx - quantileIdxFloor < quantileIdxCeil - quantileIdx)
quantiles[i] = sorted[(int) quantileIdxFloor];
else
quantiles[i] = sorted[(int) quantileIdxCeil];
}
}
}
return quantiles;
}
public static float[] quantile(float[] values, float[] levels) {
return quantile(values, levels, true);
}
}
| mit |
hpe-idol/find | webapp/core/src/main/java/com/hp/autonomy/frontend/find/core/savedsearches/UserEntity.java | 1814 | /*
* Copyright 2016 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.hp.autonomy.frontend.find.core.savedsearches;
import com.hp.autonomy.frontend.find.core.savedsearches.query.SavedQuery;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Single entity that defines multiple types of user for our various implementations.
*
* We cannot use inheritance in this case because it would mean we would have to employ the
* {@link org.hibernate.annotations.Any} annotation on the user entity of {@link SavedSearch}.
*
* This annotation requires you to define in place all the possible concrete types the field could
* take at runtime. This in turn would mean we have to define implementation-specific children of
* {@link SavedSearch}, but then we would lose the centralisation of {@link SavedQuery} and other search types.
*/
@Entity
@Table(name = UserEntity.Table.NAME)
@Data
@Builder(toBuilder = true)
@EqualsAndHashCode(exclude = "username")
@NoArgsConstructor
@AllArgsConstructor
public class UserEntity {
@Id
@Column(name = Table.Column.USER_ID)
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
private String username;
public interface Table {
String NAME = "users";
@SuppressWarnings("InnerClassTooDeeplyNested")
interface Column {
String USER_ID = "user_id";
}
}
}
| mit |
butla/jsonrpc4j | src/main/java/com/googlecode/jsonrpc4j/JsonRpcClientException.java | 1847 | /*
The MIT License (MIT)
Copyright (c) 2014 jsonrpc4j
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package com.googlecode.jsonrpc4j;
import com.fasterxml.jackson.databind.JsonNode;
/**
* Unchecked Exception thrown by a JSON-RPC client when
* an error occurs.
*/
@SuppressWarnings("serial")
public class JsonRpcClientException
extends RuntimeException {
private int code;
private JsonNode data;
/**
* Creates the exception.
* @param code the code from the server
* @param message the message from the server
* @param data the data from the server
*/
public JsonRpcClientException(int code, String message, JsonNode data) {
super(message);
this.code = code;
this.data = data;
}
/**
* @return the code
*/
public int getCode() {
return code;
}
/**
* @return the data
*/
public JsonNode getData() {
return data;
}
}
| mit |
ArcticWarriors/snobot-2017 | RobotCode/snobot2016/src/com/snobot2016/smartdashboard/DefenseInFront.java | 2445 | package com.snobot2016.smartdashboard;
import com.snobot2016.Properties2016;
import com.snobot2016.SmartDashBoardNames;
import edu.wpi.first.wpilibj.smartdashboard.SendableChooser;
import edu.wpi.first.wpilibj.smartdashboard.SmartDashboard;
import edu.wpi.first.wpilibj.tables.ITableListener;
/**
* @author Andrew/Alec
*/
public class DefenseInFront
{
/**
* This is the sendable chooser that the class makes.
*/
private SendableChooser mDefenseInFront;
/**
* This enum lists all of the defenses and other options for things to do
* before crossing the Outer Works in autonomous. All of these are sent as a
* sendableChooser to the smart dashboard; the selected is used in
* AutonFactory.
*/
public enum Defenses
{
LOW_BAR, PORTCULLIS, CHIVAL_DE_FRISE, MOAT, RAMPARTS, DRAWBRIDGE, SALLY_PORT, ROCK_WALL, ROUGH_TERRAIN, DO_NOTHING;
}
/**
* In the constructor, we new up the chooser and add all of the enum
* options.
*/
public DefenseInFront()
{
mDefenseInFront = new SendableChooser();
mDefenseInFront.addDefault("Low Bar", Defenses.LOW_BAR);
mDefenseInFront.addObject("Portcullis", Defenses.PORTCULLIS);
mDefenseInFront.addObject("Chival de Frise", Defenses.CHIVAL_DE_FRISE);
mDefenseInFront.addObject("Moat", Defenses.MOAT);
mDefenseInFront.addObject("Ramparts", Defenses.RAMPARTS);
mDefenseInFront.addObject("Drawbridge", Defenses.DRAWBRIDGE);
mDefenseInFront.addObject("Sally Port", Defenses.SALLY_PORT);
mDefenseInFront.addObject("Rock Wall", Defenses.ROCK_WALL);
mDefenseInFront.addObject("Rough Terrain", Defenses.ROUGH_TERRAIN);
mDefenseInFront.addObject("Do Nothing", Defenses.DO_NOTHING);
}
/**
* This method can be called to put the defenses sendable chooser onto the
* dashboard.
*/
public void putOnDash()
{
SmartDashboard.putData(SmartDashBoardNames.sDEFENSE_SENDER_NAME, mDefenseInFront);
}
/**
* This method is used to get the selected output (defaulting to Low Bar).
*/
public String getDefensePath()
{
return Properties2016.sAUTON_DEFENSE_DIRECTORY.getValue() + "/" + mDefenseInFront.getSelected().toString() + ".txt";
}
public void addChangeListener(ITableListener aListener)
{
mDefenseInFront.getTable().addTableListener(aListener);
}
}
| mit |
auth0/auth0-api-java | src/main/java/com/auth0/json/mgmt/organizations/Roles.java | 906 | package com.auth0.json.mgmt.organizations;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import java.util.List;
/**
* Represents the request body when adding or deleting roles from a member of an organization.
* @see com.auth0.client.mgmt.OrganizationsEntity
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class Roles {
@JsonProperty("roles")
private List<String> roles;
/**
* Create a new instance.
*
* @param roles the list of Role IDs to associate with the member.
*/
public Roles(List<String> roles) {
this.roles = roles;
}
/**
* @return the list of Role IDs associated with the member.
*/
public List<String> getRoles() {
return roles;
}
}
| mit |
lambadaframework/lambadaframework | wagon/src/test/java/org/lambadaframework/wagon/AbstractWagonTest.java | 26050 | /*
* Copyright 2010-2014 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.lambadaframework.wagon;
import org.apache.maven.wagon.ConnectionException;
import org.apache.maven.wagon.ResourceDoesNotExistException;
import org.apache.maven.wagon.TransferFailedException;
import org.apache.maven.wagon.Wagon;
import org.apache.maven.wagon.authentication.AuthenticationException;
import org.apache.maven.wagon.authentication.AuthenticationInfo;
import org.apache.maven.wagon.authorization.AuthorizationException;
import org.apache.maven.wagon.events.SessionListener;
import org.apache.maven.wagon.events.TransferEvent;
import org.apache.maven.wagon.events.TransferListener;
import org.apache.maven.wagon.proxy.ProxyInfo;
import org.apache.maven.wagon.proxy.ProxyInfoProvider;
import org.apache.maven.wagon.repository.Repository;
import org.apache.maven.wagon.resource.Resource;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.*;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Matchers.isNull;
import static org.mockito.Mockito.*;
public final class AbstractWagonTest {
private final SessionListenerSupport sessionListenerSupport = mock(SessionListenerSupport.class);
private final SessionListener sessionListener = mock(SessionListener.class);
private final TransferListenerSupport transferListenerSupport = mock(TransferListenerSupport.class);
private final TransferListener transferListener = mock(TransferListener.class);
private final Repository repository = mock(Repository.class);
private final AuthenticationInfo authenticationInfo = mock(AuthenticationInfo.class);
private final ProxyInfoProvider proxyInfoProvider = mock(ProxyInfoProvider.class);
private final ProxyInfo proxyInfo = mock(ProxyInfo.class);
private final StubWagon wagon = spy(new StubWagon(true, this.sessionListenerSupport, this.transferListenerSupport));
@Test
public void addSessionListener() {
this.wagon.addSessionListener(this.sessionListener);
verify(this.sessionListenerSupport).addSessionListener(this.sessionListener);
}
@Test
public void hasSessionListener() {
this.wagon.hasSessionListener(this.sessionListener);
verify(this.sessionListenerSupport).hasSessionListener(this.sessionListener);
}
@Test
public void removeSessionListener() {
this.wagon.removeSessionListener(this.sessionListener);
verify(this.sessionListenerSupport).removeSessionListener(this.sessionListener);
}
@Test
public void addTransferListener() {
this.wagon.addTransferListener(this.transferListener);
verify(this.transferListenerSupport).addTransferListener(this.transferListener);
}
@Test
public void hasTransferListener() {
this.wagon.hasTransferListener(this.transferListener);
verify(this.transferListenerSupport).hasTransferListener(this.transferListener);
}
@Test
public void removeTransferListener() {
this.wagon.removeTransferListener(this.transferListener);
verify(this.transferListenerSupport).removeTransferListener(this.transferListener);
}
@Test
public void interactive() {
this.wagon.setInteractive(true);
assertTrue(this.wagon.isInteractive());
}
@Test
public void connectRepository() throws ConnectionException, AuthenticationException {
this.wagon.connect(this.repository);
assertEquals(this.repository, this.wagon.getRepository());
verify(this.sessionListenerSupport).fireSessionOpening();
verify(this.wagon).connectToRepository(this.repository, null, null);
verify(this.sessionListenerSupport).fireSessionLoggedIn();
verify(this.sessionListenerSupport).fireSessionOpened();
}
@Test
public void connectRepositoryProxyInfo() throws ConnectionException, AuthenticationException {
this.wagon.connect(this.repository, this.proxyInfo);
assertEquals(this.repository, this.wagon.getRepository());
verify(this.sessionListenerSupport).fireSessionOpening();
verify(this.wagon).connectToRepository(eq(this.repository), (AuthenticationInfo) isNull(),
any(NullProtectingProxyInfoProvider.class));
verify(this.sessionListenerSupport).fireSessionLoggedIn();
verify(this.sessionListenerSupport).fireSessionOpened();
}
@Test
public void connectRepositoryAuthenticationInfo() throws ConnectionException, AuthenticationException {
this.wagon.connect(this.repository, this.authenticationInfo);
assertEquals(this.repository, this.wagon.getRepository());
verify(this.sessionListenerSupport).fireSessionOpening();
verify(this.wagon).connectToRepository(this.repository, this.authenticationInfo, null);
verify(this.sessionListenerSupport).fireSessionLoggedIn();
verify(this.sessionListenerSupport).fireSessionOpened();
}
@Test
public void connectRepositoryProxyInfoProvider() throws ConnectionException, AuthenticationException {
this.wagon.connect(this.repository, this.proxyInfoProvider);
assertEquals(this.repository, this.wagon.getRepository());
verify(this.sessionListenerSupport).fireSessionOpening();
verify(this.wagon).connectToRepository(this.repository, null, this.proxyInfoProvider);
verify(this.sessionListenerSupport).fireSessionLoggedIn();
verify(this.sessionListenerSupport).fireSessionOpened();
}
@Test
public void connectRepositoryAuthenticationProxyInfo() throws ConnectionException, AuthenticationException {
this.wagon.connect(this.repository, this.authenticationInfo, this.proxyInfo);
assertEquals(this.repository, this.wagon.getRepository());
verify(this.sessionListenerSupport).fireSessionOpening();
verify(this.wagon).connectToRepository(eq(this.repository), eq(this.authenticationInfo),
any(NullProtectingProxyInfoProvider.class));
verify(this.sessionListenerSupport).fireSessionLoggedIn();
verify(this.sessionListenerSupport).fireSessionOpened();
}
@Test
public void connectRepositoryAuthenticationInfoProxyInfoProvider() throws ConnectionException,
AuthenticationException {
this.wagon.connect(this.repository, this.authenticationInfo, this.proxyInfoProvider);
assertEquals(this.repository, this.wagon.getRepository());
verify(this.sessionListenerSupport).fireSessionOpening();
verify(this.wagon).connectToRepository(this.repository, this.authenticationInfo, this.proxyInfoProvider);
verify(this.sessionListenerSupport).fireSessionLoggedIn();
verify(this.sessionListenerSupport).fireSessionOpened();
}
@Test
public void connectConnectionException() throws ConnectionException, AuthenticationException {
doThrow(new ConnectionException("")).when(this.wagon).connectToRepository(this.repository,
this.authenticationInfo, this.proxyInfoProvider);
try {
this.wagon.connect(this.repository, this.authenticationInfo, this.proxyInfoProvider);
fail();
} catch (ConnectionException e) {
assertEquals(this.repository, this.wagon.getRepository());
verify(this.sessionListenerSupport).fireSessionOpening();
verify(this.sessionListenerSupport).fireSessionConnectionRefused();
}
}
@Test
public void connectAuthenticationException() throws ConnectionException, AuthenticationException {
doThrow(new AuthenticationException("")).when(this.wagon).connectToRepository(this.repository,
this.authenticationInfo, this.proxyInfoProvider);
try {
this.wagon.connect(this.repository, this.authenticationInfo, this.proxyInfoProvider);
fail();
} catch (AuthenticationException e) {
assertEquals(this.repository, this.wagon.getRepository());
verify(this.sessionListenerSupport).fireSessionOpening();
verify(this.sessionListenerSupport).fireSessionConnectionRefused();
}
}
@Test
public void disconnect() throws ConnectionException {
this.wagon.disconnect();
verify(this.sessionListenerSupport).fireSessionDisconnecting();
verify(this.wagon).disconnectFromRepository();
verify(this.sessionListenerSupport).fireSessionLoggedOff();
verify(this.sessionListenerSupport).fireSessionDisconnected();
}
@Test
public void disconnectConnectionException() throws ConnectionException {
doThrow(new ConnectionException("")).when(this.wagon).disconnectFromRepository();
try {
this.wagon.disconnect();
fail();
} catch (ConnectionException e) {
verify(this.sessionListenerSupport).fireSessionDisconnecting();
verify(this.sessionListenerSupport).fireSessionConnectionRefused();
}
}
@Test
public void get() throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
this.wagon.get("foo", new File("bar"));
verify(this.transferListenerSupport).fireTransferInitiated(new Resource("foo"), TransferEvent.REQUEST_GET);
verify(this.transferListenerSupport).fireTransferStarted(new Resource("foo"), TransferEvent.REQUEST_GET);
verify(this.wagon).getResource(eq("foo"), eq(new File("bar")), any(TransferProgress.class));
verify(this.transferListenerSupport).fireTransferCompleted(new Resource("foo"), TransferEvent.REQUEST_GET);
}
@Test
public void getTransferFailedException() throws ResourceDoesNotExistException, AuthorizationException,
TransferFailedException {
TransferFailedException exception = new TransferFailedException("");
doThrow(exception).when(this.wagon).getResource(eq("foo"), eq(new File("bar")), any(TransferProgress.class));
try {
this.wagon.get("foo", new File("bar"));
fail();
} catch (TransferFailedException e) {
verify(this.transferListenerSupport).fireTransferInitiated(new Resource("foo"), TransferEvent.REQUEST_GET);
verify(this.transferListenerSupport).fireTransferStarted(new Resource("foo"), TransferEvent.REQUEST_GET);
verify(this.transferListenerSupport).fireTransferError(new Resource("foo"), TransferEvent.REQUEST_GET,
exception);
}
}
@Test
public void getResourceDoesNotExistException() throws TransferFailedException, ResourceDoesNotExistException,
AuthorizationException {
ResourceDoesNotExistException exception = new ResourceDoesNotExistException("");
doThrow(exception).when(this.wagon).getResource(eq("foo"), eq(new File("bar")), any(TransferProgress.class));
try {
this.wagon.get("foo", new File("bar"));
fail();
} catch (ResourceDoesNotExistException e) {
verify(this.transferListenerSupport).fireTransferInitiated(new Resource("foo"), TransferEvent.REQUEST_GET);
verify(this.transferListenerSupport).fireTransferStarted(new Resource("foo"), TransferEvent.REQUEST_GET);
verify(this.transferListenerSupport).fireTransferError(new Resource("foo"), TransferEvent.REQUEST_GET,
exception);
}
}
@Test
public void getAuthorizationException() throws TransferFailedException, ResourceDoesNotExistException,
AuthorizationException {
AuthorizationException exception = new AuthorizationException("");
doThrow(exception).when(this.wagon).getResource(eq("foo"), eq(new File("bar")), any(TransferProgress.class));
try {
this.wagon.get("foo", new File("bar"));
fail();
} catch (AuthorizationException e) {
verify(this.transferListenerSupport).fireTransferInitiated(new Resource("foo"), TransferEvent.REQUEST_GET);
verify(this.transferListenerSupport).fireTransferStarted(new Resource("foo"), TransferEvent.REQUEST_GET);
verify(this.transferListenerSupport).fireTransferError(new Resource("foo"), TransferEvent.REQUEST_GET,
exception);
}
}
@Test
public void getFileList() throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
when(this.wagon.listDirectory("foo")).thenReturn(Arrays.<String>asList());
assertEquals(Arrays.<String>asList(), this.wagon.getFileList("foo"));
}
@Test
public void getFileListTransferFailedException() throws TransferFailedException, ResourceDoesNotExistException,
AuthorizationException {
TransferFailedException exception = new TransferFailedException("");
when(this.wagon.listDirectory("foo")).thenThrow(exception);
try {
this.wagon.getFileList("foo");
fail();
} catch (TransferFailedException e) {
verify(this.transferListenerSupport).fireTransferError(new Resource("foo"), TransferEvent.REQUEST_GET,
exception);
}
}
@Test
public void getFileResourceDoesNotExistException() throws TransferFailedException, ResourceDoesNotExistException,
AuthorizationException {
ResourceDoesNotExistException exception = new ResourceDoesNotExistException("");
when(this.wagon.listDirectory("foo")).thenThrow(exception);
try {
this.wagon.getFileList("foo");
fail();
} catch (ResourceDoesNotExistException e) {
verify(this.transferListenerSupport).fireTransferError(new Resource("foo"), TransferEvent.REQUEST_GET,
exception);
}
}
@Test
public void getFileListAuthorizationException() throws TransferFailedException, ResourceDoesNotExistException,
AuthorizationException {
AuthorizationException exception = new AuthorizationException("");
when(this.wagon.listDirectory("foo")).thenThrow(exception);
try {
this.wagon.getFileList("foo");
fail();
} catch (AuthorizationException e) {
verify(this.transferListenerSupport).fireTransferError(new Resource("foo"), TransferEvent.REQUEST_GET,
exception);
}
}
@Test
public void getIfNewerOlder() throws TransferFailedException, ResourceDoesNotExistException,
AuthorizationException {
when(this.wagon.isRemoteResourceNewer("foo", 0)).thenReturn(false);
assertFalse(this.wagon.getIfNewer("foo", new File("bar"), 0));
}
@Test
public void getIfNewerNewer() throws TransferFailedException, ResourceDoesNotExistException,
AuthorizationException {
when(this.wagon.isRemoteResourceNewer("foo", 0)).thenReturn(true);
assertTrue(this.wagon.getIfNewer("foo", new File("bar"), 0));
verify(this.wagon).getResource(eq("foo"), eq(new File("bar")), any(TransferProgress.class));
}
@Test
public void getIfNewerTransferFailedException() throws TransferFailedException, ResourceDoesNotExistException,
AuthorizationException {
TransferFailedException exception = new TransferFailedException("");
when(this.wagon.isRemoteResourceNewer("foo", 0)).thenThrow(exception);
try {
this.wagon.getIfNewer("foo", new File("bar"), 0);
fail();
} catch (TransferFailedException e) {
verify(this.transferListenerSupport).fireTransferError(new Resource("foo"), TransferEvent.REQUEST_GET,
exception);
}
}
@Test
public void getIfNewerResourceDoesNotExistException() throws TransferFailedException, ResourceDoesNotExistException,
AuthorizationException {
ResourceDoesNotExistException exception = new ResourceDoesNotExistException("");
when(this.wagon.isRemoteResourceNewer("foo", 0)).thenThrow(exception);
try {
this.wagon.getIfNewer("foo", new File("bar"), 0);
fail();
} catch (ResourceDoesNotExistException e) {
verify(this.transferListenerSupport).fireTransferError(new Resource("foo"), TransferEvent.REQUEST_GET,
exception);
}
}
@Test
public void getIfNewerAuthorizationException() throws TransferFailedException, ResourceDoesNotExistException,
AuthorizationException {
AuthorizationException exception = new AuthorizationException("");
when(this.wagon.isRemoteResourceNewer("foo", 0)).thenThrow(exception);
try {
this.wagon.getIfNewer("foo", new File("bar"), 0);
fail();
} catch (AuthorizationException e) {
verify(this.transferListenerSupport).fireTransferError(new Resource("foo"), TransferEvent.REQUEST_GET,
exception);
}
}
@Test
public void openConnection() {
this.wagon.openConnection();
}
@Test
public void put() throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
this.wagon.put(new File("foo"), "bar");
verify(this.transferListenerSupport).fireTransferInitiated(new Resource("bar"), TransferEvent.REQUEST_PUT);
verify(this.transferListenerSupport).fireTransferStarted(new Resource("bar"), TransferEvent.REQUEST_PUT);
verify(this.wagon).putResource(eq(new File("foo")), eq("bar"), any(TransferProgress.class));
verify(this.transferListenerSupport).fireTransferCompleted(new Resource("bar"), TransferEvent.REQUEST_PUT);
}
@Test
public void putTransferFailedException() throws TransferFailedException, ResourceDoesNotExistException,
AuthorizationException {
TransferFailedException exception = new TransferFailedException("");
doThrow(exception).when(this.wagon).putResource(eq(new File("foo")), eq("bar"), any(TransferProgress.class));
try {
this.wagon.put(new File("foo"), "bar");
fail();
} catch (TransferFailedException e) {
verify(this.transferListenerSupport).fireTransferInitiated(new Resource("bar"), TransferEvent.REQUEST_PUT);
verify(this.transferListenerSupport).fireTransferStarted(new Resource("bar"), TransferEvent.REQUEST_PUT);
verify(this.transferListenerSupport).fireTransferError(new Resource("bar"), TransferEvent.REQUEST_PUT,
exception);
}
}
@Test
public void putResourceDoesNotExistException() throws TransferFailedException, ResourceDoesNotExistException,
AuthorizationException {
ResourceDoesNotExistException exception = new ResourceDoesNotExistException("");
doThrow(exception).when(this.wagon).putResource(eq(new File("foo")), eq("bar"), any(TransferProgress.class));
try {
this.wagon.put(new File("foo"), "bar");
fail();
} catch (ResourceDoesNotExistException e) {
verify(this.transferListenerSupport).fireTransferInitiated(new Resource("bar"), TransferEvent.REQUEST_PUT);
verify(this.transferListenerSupport).fireTransferStarted(new Resource("bar"), TransferEvent.REQUEST_PUT);
verify(this.transferListenerSupport).fireTransferError(new Resource("bar"), TransferEvent.REQUEST_PUT,
exception);
}
}
@Test
public void putAuthorizationException() throws TransferFailedException, ResourceDoesNotExistException,
AuthorizationException {
AuthorizationException exception = new AuthorizationException("");
doThrow(exception).when(this.wagon).putResource(eq(new File("foo")), eq("bar"), any(TransferProgress.class));
try {
this.wagon.put(new File("foo"), "bar");
fail();
} catch (AuthorizationException e) {
verify(this.transferListenerSupport).fireTransferInitiated(new Resource("bar"), TransferEvent.REQUEST_PUT);
verify(this.transferListenerSupport).fireTransferStarted(new Resource("bar"), TransferEvent.REQUEST_PUT);
verify(this.transferListenerSupport).fireTransferError(new Resource("bar"), TransferEvent.REQUEST_PUT,
exception);
}
}
@Test
public void putDirectory() throws IOException, TransferFailedException, ResourceDoesNotExistException,
AuthorizationException {
File directory = new File("target/test");
directory.mkdirs();
File file = new File(directory, "test.txt");
file.createNewFile();
this.wagon.putDirectory(directory, "foo");
verify(this.transferListenerSupport).fireTransferInitiated(new Resource("foo/test.txt"),
TransferEvent.REQUEST_PUT);
verify(this.transferListenerSupport).fireTransferStarted(new Resource("foo/test.txt"),
TransferEvent.REQUEST_PUT);
verify(this.wagon).putResource(eq(new File("target/test/test.txt")), eq("foo/test.txt"),
any(TransferProgress.class));
verify(this.transferListenerSupport).fireTransferCompleted(new Resource("foo/test.txt"),
TransferEvent.REQUEST_PUT);
}
@Test
public void resourceExists() throws TransferFailedException, AuthorizationException {
this.wagon.resourceExists("foo");
verify(this.wagon).doesRemoteResourceExist("foo");
}
@Test
public void resourceExistsAuthorizationException() throws TransferFailedException, AuthorizationException {
AuthorizationException exception = new AuthorizationException("");
when(this.wagon.doesRemoteResourceExist("foo")).thenThrow(exception);
try {
this.wagon.resourceExists("foo");
fail();
} catch (AuthorizationException e) {
verify(this.transferListenerSupport).fireTransferError(new Resource("foo"), TransferEvent.REQUEST_GET,
exception);
}
}
@Test
public void resourceExistsTransferFailedException() throws TransferFailedException, AuthorizationException {
TransferFailedException exception = new TransferFailedException("");
when(this.wagon.doesRemoteResourceExist("foo")).thenThrow(exception);
try {
this.wagon.resourceExists("foo");
fail();
} catch (TransferFailedException e) {
verify(this.transferListenerSupport).fireTransferError(new Resource("foo"), TransferEvent.REQUEST_GET,
exception);
}
}
@Test
public void supportsDirectoryCopy() {
assertTrue(this.wagon.supportsDirectoryCopy());
}
@Test
public void readTimeOut() {
assertEquals(Wagon.DEFAULT_READ_TIMEOUT, this.wagon.getReadTimeout());
this.wagon.setReadTimeout(Integer.MAX_VALUE);
assertEquals(Integer.MAX_VALUE, this.wagon.getReadTimeout());
}
@Test
public void timeOut() {
assertEquals(Wagon.DEFAULT_CONNECTION_TIMEOUT, this.wagon.getTimeout());
this.wagon.setTimeout(Integer.MAX_VALUE);
assertEquals(Integer.MAX_VALUE, this.wagon.getTimeout());
}
@SuppressWarnings("unused")
@Test
public void simpleConstructor() {
new StubWagon(true);
}
private static class StubWagon extends AbstractWagon {
protected StubWagon(boolean supportsDirectoryCopy) {
super(supportsDirectoryCopy);
}
protected StubWagon(boolean supportsDirectoryCopy, SessionListenerSupport sessionListenerSupport,
TransferListenerSupport transferListenerSupport) {
super(supportsDirectoryCopy, sessionListenerSupport, transferListenerSupport);
}
@Override
protected void connectToRepository(Repository source, AuthenticationInfo authenticationInfo,
ProxyInfoProvider proxyInfo) throws ConnectionException,
AuthenticationException {
}
@Override
protected boolean doesRemoteResourceExist(String resourceName) throws TransferFailedException,
AuthorizationException {
return false;
}
@Override
protected void disconnectFromRepository() throws ConnectionException {
}
@Override
protected void getResource(String resourceName, File destination, TransferProgress progress)
throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
}
@Override
protected boolean isRemoteResourceNewer(String resourceName, long timestamp) throws TransferFailedException,
ResourceDoesNotExistException, AuthorizationException {
return false;
}
@Override
protected List<String> listDirectory(String directory) throws TransferFailedException,
ResourceDoesNotExistException, AuthorizationException {
return null;
}
@Override
protected void putResource(File source, String destination, TransferProgress progress)
throws TransferFailedException, ResourceDoesNotExistException, AuthorizationException {
}
}
}
| mit |
Deadrik/jMapGen | src/pythagoras/f/IDimension.java | 492 | //
// Pythagoras - a collection of geometry classes
// http://github.com/samskivert/pythagoras
package pythagoras.f;
/**
* Provides read-only access to a {@link Dimension}.
*/
public interface IDimension extends Cloneable
{
/**
* Returns the magnitude in the x-dimension.
*/
float width ();
/**
* Returns the magnitude in the y-dimension.
*/
float height ();
/**
* Returns a mutable copy of this dimension.
*/
Dimension clone ();
}
| mit |
breakinblocks/BBTweaks | src/main/java/com/breakinblocks/bbtweaks/items/ItemBreakBitEnderium.java | 207 | package com.breakinblocks.bbtweaks.items;
public class ItemBreakBitEnderium extends ItemBase {
public ItemBreakBitEnderium() {
super("breakbitenderium", "breakbitenderium");
setMaxStackSize(64);
}
}
| mit |
GoHD/java-angularjs-architecture | api/app-model/src/main/java/com/github/app/model/dao/UsuarioDao.java | 924 | package com.github.app.model.dao;
import java.util.Optional;
import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.RequestScoped;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
import com.github.app.model.entity.Usuario;
import com.github.app.model.entity.Usuario.NamedQueries;
@ApplicationScoped
public class UsuarioDao extends DaoGenerico<Usuario, Long> {
@Override
protected Class<Usuario> getPersistentClass() {
return Usuario.class;
}
public Optional<Usuario> buscaPorLogin(String login) {
TypedQuery<Usuario> query = em.createNamedQuery(NamedQueries.BUSCA_POR_LOGIN.name, Usuario.class);
query.setParameter("login", login);
try {
return Optional.ofNullable(query.getSingleResult());
} catch (NoResultException ex) {
return Optional.empty();
}
}
}
| mit |
juanalvarez123/payu-latam-java-payments-sdk | src/main/java/com/payu/sdk/model/request/Environment.java | 2640 | /**
* The MIT License (MIT)
*
* Copyright (c) 2016 developers-payu-latam
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.payu.sdk.model.request;
/**
* Represents the environment in the PayU SDK.
*
* @author PayU Latam
* @since 1.0.0
* @version 1.0.0, 21/08/2013
*/
public enum Environment {
/**
* Default url for payments and reports requests
*/
API_URL("https://api.payulatam.com/payments-api/",
"https://api.payulatam.com/reports-api/");
/** Payments request's url */
private String paymentsUrl;
/** Reports request's url */
private String reportsUrl;
/**
* Private constructor
*
* @param paymentsUrl
* the payments url to use
* @param reportsUrl
* the reports url to use
*/
private Environment(String paymentsUrl, String reportsUrl) {
this.paymentsUrl = paymentsUrl;
this.reportsUrl = reportsUrl;
}
/**
* Creates an environment with the given urls
*
* @param paymentsUrl
* the payments url to use
* @param reportsUrl
* the reports url to use
* @return The created environment
*/
public static Environment createEnvironment(String paymentsUrl,
String reportsUrl) {
Environment environment = Environment.API_URL;
environment.paymentsUrl = paymentsUrl;
environment.reportsUrl = reportsUrl;
return environment;
}
/**
* Returns the payments url
*
* @return the payments url
*/
public String getPaymentsUrl() {
return paymentsUrl;
}
/**
* Returns the reports url
*
* @return the reports Url
*/
public String getReportsUrl() {
return reportsUrl;
}
}
| mit |
icersummer/firstcodeandroid | jikexueyuan/HelloNote/src/com/vjia/hellonote/MyAdapter.java | 3031 | package com.vjia.hellonote;
import android.annotation.SuppressLint;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.ThumbnailUtils;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter {
private Context context;
private Cursor cursor;
private LinearLayout layout;
public MyAdapter(Context context, Cursor cursor) {
this.context = context;
this.cursor = cursor;
}
@Override
public int getCount() {
return cursor.getCount();
}
@Override
public Object getItem(int position) {
return cursor.getPosition();
}
@Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(context);
layout = (LinearLayout) inflater.inflate(R.layout.cell, null);
TextView contenttv = (TextView) layout.findViewById(R.id.list_content);
TextView timetv = (TextView) layout.findViewById(R.id.list_time);
ImageView imgiv = (ImageView) layout.findViewById(R.id.list_img);
ImageView videoiv = (ImageView) layout.findViewById(R.id.list_video);
cursor.moveToPosition(position);
String content = cursor.getString(cursor.getColumnIndex("content"));
String time = cursor.getString(cursor.getColumnIndex("time"));
String url = cursor.getString(cursor.getColumnIndex("path"));
String urlvideo = cursor.getString(cursor.getColumnIndex("video"));
contenttv.setText(content);
timetv.setText(time);
videoiv.setImageBitmap(getVideoThumbnail(urlvideo, 200, 200,
MediaStore.Images.Thumbnails.MICRO_KIND));
imgiv.setImageBitmap(getImageThumbnail(url, 200, 200));
return layout;
}
public Bitmap getImageThumbnail(String uri, int width, int height) {
Bitmap bitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
bitmap = BitmapFactory.decodeFile(uri, options);
options.inJustDecodeBounds = false;
int beWidth = options.outWidth / width;
int beHeight = options.outHeight / height;
int be = 1;
if (beWidth < beHeight) {
be = beWidth;
} else {
be = beHeight;
}
if (be <= 0) {
be = 1;
}
options.inSampleSize = be;
bitmap = BitmapFactory.decodeFile(uri, options);
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
return bitmap;
}
private Bitmap getVideoThumbnail(String uri, int width, int height, int kind) {
Bitmap bitmap = null;
bitmap = ThumbnailUtils.createVideoThumbnail(uri, kind);
bitmap = ThumbnailUtils.extractThumbnail(bitmap, width, height,
ThumbnailUtils.OPTIONS_RECYCLE_INPUT);
return bitmap;
}
}
| mit |
navalev/azure-sdk-for-java | sdk/mariadb/mgmt-v2018_06_01/src/main/java/com/microsoft/azure/management/mariadb/v2018_06_01/implementation/OperationListResultImpl.java | 964 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.mariadb.v2018_06_01.implementation;
import com.microsoft.azure.management.mariadb.v2018_06_01.OperationListResult;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import java.util.List;
class OperationListResultImpl extends WrapperImpl<OperationListResultInner> implements OperationListResult {
private final MariaDBManager manager;
OperationListResultImpl(OperationListResultInner inner, MariaDBManager manager) {
super(inner);
this.manager = manager;
}
@Override
public MariaDBManager manager() {
return this.manager;
}
@Override
public List<OperationInner> value() {
return this.inner().value();
}
}
| mit |
ShotaOd/Carbon | carbon-web/src/main/java/org/carbon/web/core/request/TypeSafeRequestMapper.java | 228 | package org.carbon.web.core.request;
import javax.servlet.http.HttpServletRequest;
/**
* @author Shota Oda 2016/10/12.
*/
public interface TypeSafeRequestMapper {
<T> T map(HttpServletRequest request, Class<T> mapTo);
}
| mit |
kucharzyk/spring-angular2-starter | shardis-auth/src/main/java/com/shardis/auth/controllers/rest/AuthRestController.java | 417 | package com.shardis.auth.controllers.rest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.security.Principal;
/**
* Created by Tomasz Kucharzyk
*/
@RestController
@RequestMapping("/")
public class AuthRestController {
@RequestMapping("/user")
public Principal user(Principal user) {
return user;
}
}
| mit |
herveyw/azure-sdk-for-java | azure-mgmt-website/src/main/java/com/microsoft/azure/management/website/ProvisioningState.java | 1585 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.website;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonValue;
/**
* Defines values for ProvisioningState.
*/
public enum ProvisioningState {
/** Enum value Succeeded. */
SUCCEEDED("Succeeded"),
/** Enum value Failed. */
FAILED("Failed"),
/** Enum value Canceled. */
CANCELED("Canceled"),
/** Enum value InProgress. */
IN_PROGRESS("InProgress"),
/** Enum value Deleting. */
DELETING("Deleting");
/** The actual serialized value for a ProvisioningState instance. */
private String value;
ProvisioningState(String value) {
this.value = value;
}
/**
* Parses a serialized value to a ProvisioningState instance.
*
* @param value the serialized value to parse.
* @return the parsed ProvisioningState object, or null if unable to parse.
*/
@JsonCreator
public static ProvisioningState fromString(String value) {
ProvisioningState[] items = ProvisioningState.values();
for (ProvisioningState item : items) {
if (item.toString().equalsIgnoreCase(value)) {
return item;
}
}
return null;
}
@JsonValue
@Override
public String toString() {
return this.value;
}
}
| mit |
vboctor/ews-java-api | src/main/java/microsoft/exchange/webservices/data/ClientCertificateCredentials.java | 1807 | /**************************************************************************
* copyright file="ClientCertificateCredentials.java" company="Microsoft"
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* Defines the ClientCertificateCredentials.java.
**************************************************************************/
package microsoft.exchange.webservices.data;
import javax.net.ssl.TrustManager;
/**
* ClientCertificateCredentials wraps an instance of X509CertificateCollection used for client certification-based authentication.
*/
public class ClientCertificateCredentials extends ExchangeCredentials {
/**
* Collection of client certificates.
*/
private TrustManager clientCertificates;
/**
* Initializes a new instance of the ClientCertificateCredentials class.
* @param clientCertificates The clientCertificates
* @throws Exception
*/
public ClientCertificateCredentials(TrustManager clientCertificates) throws Exception
{
EwsUtilities.validateParam(clientCertificates, "clientCertificates");
this.clientCertificates = clientCertificates;
}
/**
* This method is called to apply credentials to a service request before the request is made.
* @param request The request.
*/
@Override
protected void prepareWebRequest(HttpWebRequest request)
{
// TODO need to check
//request.ClientCertificates = this.clientCertificates;
try {
request.setClientCertificates(this.clientCertificates);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Gets the client certificates collection.
* @return clientCertificates
*/
public TrustManager getClientCertificates()
{
return this.clientCertificates;
}
}
| mit |
davidholiday/smoosh | src/test/java/com/projectvalis/reverse_rabin/FurlSteps.java | 9646 | package com.projectvalis.reverse_rabin;
import org.jbehave.core.annotations.BeforeScenario;
import org.jbehave.core.annotations.Given;
import org.jbehave.core.annotations.Named;
import org.jbehave.core.annotations.Then;
import org.jbehave.core.annotations.When;
import org.jbehave.core.steps.Steps;
import org.junit.Assert;
import org.rabinfingerprint.polynomial.Polynomial;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.projectvalis.util.ByteManipulation;
import com.projectvalis.util.TestHelper;
import com.projectvalis.util.rabin.RabinFingerprintLong_SmooshMod;
public class FurlSteps extends Steps {
static Logger LOGGER = LoggerFactory.getLogger(FurlSteps.class);
private byte[] generatedByteARR;
private byte[] fingerprintHeadsARR;
private Polynomial rabinPolynomial;
private RabinFingerprintLong_SmooshMod fingerprinter;
@BeforeScenario
public void setup() {
rabinPolynomial = Polynomial.createIrreducible(53);
fingerprinter = new RabinFingerprintLong_SmooshMod(rabinPolynomial);
LOGGER.info("GENERATED POLYNOMIAL IS: " +
rabinPolynomial.toHexString());
}
@Given("a push table updated for furl")
public void updatePushTable() {
for (int i = 0; i < 256; i ++) {
long oldPoly = fingerprinter.getPushTable()[i];
long newPoly = ByteManipulation.replaceTailByte(oldPoly, (byte)i);
LOGGER.trace("oldPoly is: " + String.format("%X", oldPoly));
LOGGER.trace("newPoly is: " + String.format("%X", newPoly) + "\n");
fingerprinter.getPushTable()[i] = newPoly;
}
}
@Then("the low order byte of each element matches that element's index value")
public void checkUpdatedPushTableIndexes() {
for (int i = 0; i < 256; i++) {
long poly = fingerprinter.getPushTable()[i];
byte lowOrderByteActual = (byte) ByteManipulation.getTailByte(poly);
LOGGER.trace("lowOrderByteActual and expected-value are: " + lowOrderByteActual + " " + (byte)i);
Assert.assertTrue("low order byte doesn't match element index!", lowOrderByteActual == (byte)i);
}
}
@Given("an array of $numBytesI bytes")
public void createByteArray(@Named("numBytesI") int numBytesI) {
generatedByteARR = TestHelper.createByteArray(numBytesI);
}
@When("the byte array is fingerprinted with heads saved")
public void fingerprintByteArraySaveHeads() {
fingerprintHeadsARR = fingerprinter.pushAndSaveHeads(generatedByteARR);
}
/**
*
* for retain-bytes-list --> heads, don't forget that the lists aren't quite in sync. the first head
* in the list will be the first three bits of byte 7, then the trailing 5 bits of byte 7 with the leading
* three bits of byte 8 - then the trailing five bits of b8 with the leading three bits from b9, etc etc.
*
*
*
*
*
*
*/
@Then("you can recover the correct head list")
public void checkRecoveredHeadsList() {
long fingerprintLocalL = fingerprinter.getFingerprintLong();
LOGGER.info("fingerprint is: " + String.format("%X", fingerprintLocalL));
// replay all the heads except the first one - that's the one that'll be in play
//
byte[] computedBytesARR = new byte[generatedByteARR.length];
byte[] computedHeadBytesARR = new byte[generatedByteARR.length];
for (int i = generatedByteARR.length - 1; i > 6; i --) {
byte currentTailByte = ByteManipulation.getTailByte(fingerprintLocalL);
byte currentHeadByte = (byte)(currentTailByte ^ generatedByteARR[i]);
computedHeadBytesARR[i] = currentHeadByte;
LOGGER.info("head byte was derived from value: " + String.format("%X", generatedByteARR[i]));
LOGGER.info("computed head byte is: " + String.format("%X", currentHeadByte));
int pushTableIndexI = (currentHeadByte & 0xFF);
fingerprintLocalL = fingerprintLocalL ^ fingerprinter.getPushTable()[pushTableIndexI];
computedBytesARR[i] = ByteManipulation.getTailByte(fingerprintLocalL);
fingerprintLocalL = ByteManipulation.removeTailByte(fingerprintLocalL);
ByteManipulation.appendByteToHead(currentHeadByte, fingerprintLocalL, fingerprinter.getShiftVal());
LOGGER.info("fingerprint is now: " + String.format("%X", fingerprintLocalL));
}
LOGGER.info("");
LOGGER.info("computed heads are : " + ByteManipulation.getByteArrayAsHexString(computedHeadBytesARR));
LOGGER.info("actual heads are : " + ByteManipulation.getByteArrayAsHexString(fingerprintHeadsARR));
LOGGER.info("");
LOGGER.info("computed bytes are : " + ByteManipulation.getByteArrayAsHexString(computedBytesARR));
LOGGER.info("generated bytes are: " + ByteManipulation.getByteArrayAsHexString(generatedByteARR));
LOGGER.info("");
LOGGER.info("*** NOW UNFURLING WITH A MODIFIED (WRONG) FIRST HEAD BIT **");
byte wrongFirstHeadI = (byte) (fingerprintHeadsARR[6] + 1);
computedHeadBytesARR[6] = wrongFirstHeadI;
LOGGER.info("head byte was derived from value: " + String.format("%X", generatedByteARR[6]));
LOGGER.info("computed head byte is: " + String.format("%X", wrongFirstHeadI));
int pushTableIndexI = (wrongFirstHeadI & 0xFF);
fingerprintLocalL = fingerprintLocalL ^ fingerprinter.getPushTable()[pushTableIndexI];
computedBytesARR[6] = ByteManipulation.getTailByte(fingerprintLocalL);
fingerprintLocalL = ByteManipulation.removeTailByte(fingerprintLocalL);
ByteManipulation.appendByteToHead(wrongFirstHeadI, fingerprintLocalL, fingerprinter.getShiftVal());
LOGGER.info("fingerprint is now: " + String.format("%X", fingerprintLocalL));
LOGGER.info("");
LOGGER.info("*** UPDATING COMPUTED BYTES ARR WITH KNOWN-INCORRECT BYTE DATA AND GENERATED NEW HEADS**");
for (int k = 5; k > -1; k --) {
computedBytesARR[k] = ByteManipulation.getTailByte(fingerprintLocalL);
fingerprintLocalL = fingerprintLocalL >> 8;
}
LOGGER.info("computed bytes are : " + ByteManipulation.getByteArrayAsHexString(computedBytesARR));
fingerprinter.reset();
byte[] shouldBeWrongHeadsARR = fingerprinter.pushAndSaveHeads(computedBytesARR);
LOGGER.info("");
LOGGER.info("right heads are: " + ByteManipulation.getByteArrayAsHexString(fingerprintHeadsARR));
LOGGER.info("wrong heads are: " + ByteManipulation.getByteArrayAsHexString(shouldBeWrongHeadsARR));
LOGGER.info("");
LOGGER.info("computed bytes are : " + ByteManipulation.getByteArrayAsHexString(computedBytesARR));
LOGGER.info("generated bytes are: " + ByteManipulation.getByteArrayAsHexString(generatedByteARR));
LOGGER.info("");
/*
byte[][] allHeadsARR = new byte[8][];
for (int i = 0; i < 8; i ++) {
long fingerprintLocalTempL = fingerprintLocalL;
int wrongFirstHeadI = i;
byte currentTailByte = ByteManipulation.getTailByte(fingerprintLocalTempL);
byte currentHeadByte = (byte)(currentTailByte ^ wrongFirstHeadI);
computedHeadBytesARR[6] = currentHeadByte;
LOGGER.info("head byte was derived from value: " + String.format("%X", generatedByteARR[6]));
LOGGER.info("computed head byte is: " + String.format("%X", currentHeadByte));
int pushTableIndexI = (currentHeadByte & 0xFF);
fingerprintLocalTempL = fingerprintLocalTempL ^ fingerprinter.getPushTable()[pushTableIndexI];
computedBytesARR[6] = ByteManipulation.getTailByte(fingerprintLocalTempL);
fingerprintLocalTempL = ByteManipulation.removeTailByte(fingerprintLocalTempL);
ByteManipulation.appendByteToHead(currentHeadByte, fingerprintLocalTempL);
LOGGER.info("fingerprint is now: " + String.format("%X", fingerprintLocalTempL));
LOGGER.info("");
LOGGER.info("*** UPDATING COMPUTED BYTES ARR WITH KNOWN-INCORRECT BYTE DATA AND GENERATED NEW HEADS**");
for (int k = 5; k > -1; k --) {
computedBytesARR[k] = ByteManipulation.getTailByte(fingerprintLocalTempL);
fingerprintLocalTempL = fingerprintLocalTempL >> 8;
}
LOGGER.info("computed bytes are : " + ByteManipulation.getByteArrayAsHexString(computedBytesARR));
fingerprinter.reset();
allHeadsARR[i] = fingerprinter.pushAndSaveHeads(computedBytesARR);
}
LOGGER.info("");
LOGGER.info("right heads are: " + ByteManipulation.getByteArrayAsHexString(fingerprintHeadsARR));
LOGGER.info("all heads are: ");
for (int i = 0; i < allHeadsARR.length; i ++) {
LOGGER.info(" : " + ByteManipulation.getByteArrayAsHexString(allHeadsARR[i]));
}
LOGGER.info("");
LOGGER.info("computed bytes are : " + ByteManipulation.getByteArrayAsHexString(computedBytesARR));
LOGGER.info("generated bytes are: " + ByteManipulation.getByteArrayAsHexString(generatedByteARR));
LOGGER.info("");
*/
}
}
| mit |
webratio/typescript.java | eclipse/terminal/ts.eclipse.ide.terminal.interpreter/src/ts/eclipse/ide/terminal/interpreter/internal/CommandInterpreterProcessor.java | 2874 | /**
* Copyright (c) 2015-2017 Angelo ZERR.
* 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:
* Angelo Zerr <angelo.zerr@gmail.com> - initial API and implementation
*/
package ts.eclipse.ide.terminal.interpreter.internal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.eclipse.tm.terminal.view.core.interfaces.ITerminalServiceOutputStreamMonitorListener;
import org.eclipse.tm.terminal.view.core.interfaces.constants.ITerminalsConnectorConstants;
import ts.eclipse.ide.terminal.interpreter.ICommandInterpreter;
import ts.eclipse.ide.terminal.interpreter.ICommandInterpreterFactory;
import ts.eclipse.ide.terminal.interpreter.LineCommand;
public class CommandInterpreterProcessor extends CommandTerminalTracker
implements ITerminalServiceOutputStreamMonitorListener {
private ICommandInterpreter interpreter;
private final String encoding;
public CommandInterpreterProcessor(Map<String, Object> properties) {
this.encoding = getInitialEncoding(properties);
}
@Override
public final void onContentReadFromStream(byte[] byteBuffer, int bytesRead) {
super.parse(byteBuffer, bytesRead, encoding);
}
/**
* Returns the initial encoding when terminal is opened.
*
* @param properties
* @return the initial encoding when terminal is opened.
*/
private static String getInitialEncoding(Map<String, Object> properties) {
return (String) properties.get(ITerminalsConnectorConstants.PROP_ENCODING);
}
@Override
public void submitCommand(LineCommand lineCommand) {
super.submitCommand(lineCommand);
initializeInterpreter(lineCommand.getWorkingDir(), lineCommand.getCommand());
}
@Override
protected void executingCommand(String line, LineCommand lineCommand) {
super.executingCommand(line, lineCommand);
if (interpreter != null) {
interpreter.onTrace(line);
}
}
@Override
protected void terminateCommand(LineCommand lineCommand) {
if (interpreter != null) {
interpreter.execute(lineCommand.getNewWorkingDir());
}
interpreter = null;
// Execute here ancestor terminateCommand command which can executes an
// another command.
super.terminateCommand(lineCommand);
}
/**
* Initialize interpreter if needed.
*
* @param workingDir
*/
private void initializeInterpreter(String workingDir, String command) {
// Initialize interpreter if needed
if (interpreter == null) {
if (command != null) {
interpreter = CommandInterpreterManager.getInstance().createInterpreter(command.trim(), workingDir);
}
}
}
}
| mit |
egrohs/Politicos | site/src/main/java/org/politicos/service/mapper/UserMapper.java | 1750 | package org.politicos.service.mapper;
import org.politicos.domain.Authority;
import org.politicos.domain.User;
import org.politicos.service.dto.UserDTO;
import org.mapstruct.*;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* Mapper for the entity User and its DTO UserDTO.
*/
@Mapper(componentModel = "spring", uses = {})
public interface UserMapper {
UserDTO userToUserDTO(User user);
List<UserDTO> usersToUserDTOs(List<User> users);
@Mapping(target = "createdBy", ignore = true)
@Mapping(target = "createdDate", ignore = true)
@Mapping(target = "lastModifiedBy", ignore = true)
@Mapping(target = "lastModifiedDate", ignore = true)
@Mapping(target = "persistentTokens", ignore = true)
@Mapping(target = "id", ignore = true)
@Mapping(target = "activationKey", ignore = true)
@Mapping(target = "resetKey", ignore = true)
@Mapping(target = "resetDate", ignore = true)
@Mapping(target = "password", ignore = true)
User userDTOToUser(UserDTO userDTO);
List<User> userDTOsToUsers(List<UserDTO> userDTOs);
default User userFromId(Long id) {
if (id == null) {
return null;
}
User user = new User();
user.setId(id);
return user;
}
default Set<String> stringsFromAuthorities (Set<Authority> authorities) {
return authorities.stream().map(Authority::getName)
.collect(Collectors.toSet());
}
default Set<Authority> authoritiesFromStrings(Set<String> strings) {
return strings.stream().map(string -> {
Authority auth = new Authority();
auth.setName(string);
return auth;
}).collect(Collectors.toSet());
}
}
| mit |
auth0/auth0-api-java | src/test/java/com/auth0/json/mgmt/users/IdentityTest.java | 1143 | package com.auth0.json.mgmt.users;
import com.auth0.json.JsonTest;
import org.junit.Test;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
public class IdentityTest extends JsonTest<Identity> {
private static final String json = "{\"connection\":\"auth0\",\"user_id\":\"user|123\",\"isSocial\":true,\"provider\":\"oauth\",\"access_token\":\"aTokEn\",\"profileData\":{},\"access_token_secret\":\"s3cr3t\"}";
@Test
public void shouldDeserialize() throws Exception {
Identity identity = fromJSON(json, Identity.class);
assertThat(identity, is(notNullValue()));
assertThat(identity.getConnection(), is("auth0"));
assertThat(identity.getUserId(), is("user|123"));
assertThat(identity.isSocial(), is(true));
assertThat(identity.getProvider(), is("oauth"));
assertThat(identity.getAccessToken(), is("aTokEn"));
assertThat(identity.getProfileData(), is(notNullValue()));
assertThat(identity.getValues(), is(notNullValue()));
assertThat(identity.getValues(), hasEntry("access_token_secret", "s3cr3t"));
}
}
| mit |
MarcoAlves/Prog-Scripts | Teste/src/main/java/Mundo.java | 184 | import br.com.caelum.vraptor.Controller;
@Controller
public class Mundo {
public void boasVindas(){
System.out.println("Teste");
}
public void teste(){
}
}
| mit |
guixiaoyuan/workspace | exchange/view/photoview/scrollerproxy/ScrollerProxy.java | 1761 | /**
* ****************************************************************************
* Copyright 2011, 2012 Chris Banes.
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* *****************************************************************************
*/
package com.deeal.exchange.view.photoview.scrollerproxy;
import android.content.Context;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
public abstract class ScrollerProxy {
public static ScrollerProxy getScroller(Context context) {
if (VERSION.SDK_INT < VERSION_CODES.GINGERBREAD) {
return new PreGingerScroller(context);
} else if (VERSION.SDK_INT < VERSION_CODES.ICE_CREAM_SANDWICH) {
return new GingerScroller(context);
} else {
return new IcsScroller(context);
}
}
public abstract boolean computeScrollOffset();
public abstract void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY,
int maxY, int overX, int overY);
public abstract void forceFinished(boolean finished);
public abstract boolean isFinished();
public abstract int getCurrX();
public abstract int getCurrY();
}
| mit |
selvasingh/azure-sdk-for-java | sdk/compute/mgmt-v2019_03_01/src/main/java/com/microsoft/azure/management/compute/v2019_03_01/RollbackStatusInfo.java | 1861 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.compute.v2019_03_01;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Information about rollback on failed VM instances after a OS Upgrade
* operation.
*/
public class RollbackStatusInfo {
/**
* The number of instances which have been successfully rolled back.
*/
@JsonProperty(value = "successfullyRolledbackInstanceCount", access = JsonProperty.Access.WRITE_ONLY)
private Integer successfullyRolledbackInstanceCount;
/**
* The number of instances which failed to rollback.
*/
@JsonProperty(value = "failedRolledbackInstanceCount", access = JsonProperty.Access.WRITE_ONLY)
private Integer failedRolledbackInstanceCount;
/**
* Error details if OS rollback failed.
*/
@JsonProperty(value = "rollbackError", access = JsonProperty.Access.WRITE_ONLY)
private ApiError rollbackError;
/**
* Get the number of instances which have been successfully rolled back.
*
* @return the successfullyRolledbackInstanceCount value
*/
public Integer successfullyRolledbackInstanceCount() {
return this.successfullyRolledbackInstanceCount;
}
/**
* Get the number of instances which failed to rollback.
*
* @return the failedRolledbackInstanceCount value
*/
public Integer failedRolledbackInstanceCount() {
return this.failedRolledbackInstanceCount;
}
/**
* Get error details if OS rollback failed.
*
* @return the rollbackError value
*/
public ApiError rollbackError() {
return this.rollbackError;
}
}
| mit |
Zontzor/DT228-MobileDev | MoreLists/app/src/main/java/com/zontzor/lab5_morelists/Country.java | 2024 | package com.zontzor.lab5_morelists;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ImageView;
import android.widget.TextView;
import org.w3c.dom.Text;
/**
* Created by nanrick on 15/10/15.
*/
public class Country extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.country_layout);
// Get info passed with intent
String country = getIntent().getExtras().getString("Country");
int position = getIntent().getExtras().getInt("Position");
setupCountryView(country, position);
}
public void setupCountryView(String country, int position) {
// Set text for selected country
TextView country_text = (TextView) findViewById(R.id.text_set);
country_text.setText(country);
// Set the flag corresponding to country
ImageView country_flag = (ImageView) findViewById(R.id.flag_set);
switch (country) {
case "Ireland":
country_flag.setImageResource(R.mipmap.ireland_flag);
break;
case "Sri Lanka":
country_flag.setImageResource(R.mipmap.sri_lanka_flag);
break;
case "Saudi Arabia":
country_flag.setImageResource(R.mipmap.saudi_flag);
break;
case "China":
country_flag.setImageResource(R.mipmap.china_flag);
break;
case "Sealand":
country_flag.setImageResource(R.mipmap.sealand_flag);
break;
case "Christmas Island":
country_flag.setImageResource(R.mipmap.christmas_flag);
break;
case "DRPK":
country_flag.setImageResource(R.mipmap.drpk_flag);
break;
}
TextView position_text = (TextView) findViewById(R.id.position_set);
position_text.setText("Position: " + position);
}
}
| mit |
TheOpenCloudEngine/metaworks | metaworks-dwr/core/api/main/java/org/directwebremoting/util/Base64.java | 16777 | /*
* $Header: /home/cvs/jakarta-commons/codec/src/java/org/apache/commons/codec/binary/Base64.java,v 1.1 2003/04/25 17:50:56 tobrien Exp $
* $Revision: 1.1 $
* $Date: 2003/04/25 17:50:56 $
*
* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Jakarta Project", "Tomcat", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/
package org.directwebremoting.util;
/**
* This class provides encode/decode for RFC 2045 Base64 as
* defined by RFC 2045, N. Freed and N. Borenstein. <a
* href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>:
* Multipurpose Internet Mail Extensions (MIME) Part One: Format of
* Internet Message Bodies. Reference 1996
*
* @author Jeffrey Rodriguez
* @author <a href="dlr@apache.org">Daniel Rall</a>
* @author <a href="m.redington@ucl.ac.uk">Martin Redington</a>
* @since 1.0-dev
*
*/
@SuppressWarnings({"ALL"})
public class Base64 {
// Create constants pertaining to the chunk requirement
static final int CHUNK_SIZE = 76;
static final byte[] CHUNK_SEPARATOR = "\n".getBytes();
// Create numerical and byte constants
static final int BASELENGTH = 255;
static final int LOOKUPLENGTH = 64;
static final int TWENTYFOURBITGROUP = 24;
static final int EIGHTBIT = 8;
static final int SIXTEENBIT = 16;
static final int SIXBIT = 6;
static final int FOURBYTE = 4;
static final int SIGN = -128;
static final byte PAD = (byte) '=';
// Create arrays to hold the base64 characters and a
// lookup for base64 chars
private static byte[] base64Alphabet = new byte[BASELENGTH];
private static byte[] lookUpBase64Alphabet = new byte[LOOKUPLENGTH];
// Populating the lookup and character arrays
static {
for (int i = 0; i < BASELENGTH; i++) {
base64Alphabet[i] = (byte) -1;
}
for (int i = 'Z'; i >= 'A'; i--) {
base64Alphabet[i] = (byte) (i - 'A');
}
for (int i = 'z'; i >= 'a'; i--) {
base64Alphabet[i] = (byte) (i - 'a' + 26);
}
for (int i = '9'; i >= '0'; i--) {
base64Alphabet[i] = (byte) (i - '0' + 52);
}
base64Alphabet['+'] = 62;
base64Alphabet['/'] = 63;
for (int i = 0; i <= 25; i++) {
lookUpBase64Alphabet[i] = (byte) ('A' + i);
}
for (int i = 26, j = 0; i <= 51; i++, j++) {
lookUpBase64Alphabet[i] = (byte) ('a' + j);
}
for (int i = 52, j = 0; i <= 61; i++, j++) {
lookUpBase64Alphabet[i] = (byte) ('0' + j);
}
lookUpBase64Alphabet[62] = (byte) '+';
lookUpBase64Alphabet[63] = (byte) '/';
}
private static boolean isBase64(byte octect) {
if (octect == PAD) {
return true;
}
else if (base64Alphabet[octect] == -1) {
return false;
}
else {
return true;
}
}
public static boolean isArrayByteBase64(byte[] arrayOctect) {
arrayOctect = discardWhitespace(arrayOctect);
int length = arrayOctect.length;
if (length == 0) {
// shouldn't a 0 length array be valid base64 data?
// return false;
return true;
}
for (int i = 0; i < length; i++) {
if (!isBase64(arrayOctect[i])) {
return false;
}
}
return true;
}
public static byte[] encodeBase64(byte[] binaryData) {
return (encodeBase64(binaryData, false));
}
public static byte[] encodeBase64Chunked(byte[] binaryData) {
return (encodeBase64(binaryData, true));
}
public Object decode(Object pObject) throws IllegalArgumentException {
Object result;
if (!(pObject instanceof byte[])) {
throw new IllegalArgumentException(
"Parameter supplied to "
+ "Base64 "
+ "decode is not a byte[]");
}
else {
result = decode((byte[]) pObject);
}
return result;
}
public byte[] decode(byte[] pArray) throws IllegalArgumentException {
byte[] result;
if (!isArrayByteBase64(pArray)) {
throw new IllegalArgumentException(
"Parameter supplied to "
+ "Base64 "
+ "decode is not a valid base64 data.");
}
else {
result = decodeBase64(pArray);
}
return (result);
}
/**
* Encodes hex octects into Base64.
*
* @param binaryData Array containing binary data to encode.
* @return Base64-encoded data.
*/
public static byte[] encodeBase64(byte[] binaryData, boolean isChunked) {
int lengthDataBits = binaryData.length * EIGHTBIT;
int fewerThan24bits = lengthDataBits % TWENTYFOURBITGROUP;
int numberTriplets = lengthDataBits / TWENTYFOURBITGROUP;
byte encodedData[] = null;
int encodedDataLength = 0;
int nbrChunks = 0;
if (fewerThan24bits != 0) {
//data not divisible by 24 bit
encodedDataLength = (numberTriplets + 1) * 4;
}
else {
// 16 or 8 bit
encodedDataLength = numberTriplets * 4;
}
// If the output is to be "chunked" into 76 character sections,
// for compliance with RFC 2045 MIME, then it is important to
// allow for extra length to account for the separator(s)
if (isChunked) {
nbrChunks =
(CHUNK_SEPARATOR.length == 0
? 0
: (int) Math.ceil((float) encodedDataLength / CHUNK_SIZE));
encodedDataLength += nbrChunks * CHUNK_SEPARATOR.length;
}
encodedData = new byte[encodedDataLength];
byte k = 0, l = 0, b1 = 0, b2 = 0, b3 = 0;
int encodedIndex = 0;
int dataIndex = 0;
int i = 0;
int nextSeparatorIndex = CHUNK_SIZE;
int chunksSoFar = 0;
//log.debug("number of triplets = " + numberTriplets);
for (i = 0; i < numberTriplets; i++) {
dataIndex = i * 3;
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
b3 = binaryData[dataIndex + 2];
//log.debug("b1= " + b1 +", b2= " + b2 + ", b3= " + b3);
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 =
((b1 & SIGN) == 0)
? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2 =
((b2 & SIGN) == 0)
? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);
byte val3 =
((b3 & SIGN) == 0)
? (byte) (b3 >> 6)
: (byte) ((b3) >> 6 ^ 0xfc);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
//log.debug( "val2 = " + val2 );
//log.debug( "k4 = " + (k<<4) );
//log.debug( "vak = " + (val2 | (k<<4)) );
encodedData[encodedIndex + 1] =
lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex + 2] =
lookUpBase64Alphabet[(l << 2) | val3];
encodedData[encodedIndex + 3] = lookUpBase64Alphabet[b3 & 0x3f];
encodedIndex += 4;
// If we are chunking, let's put a chunk separator down.
if (isChunked) {
// this assumes that CHUNK_SIZE % 4 == 0
if (encodedIndex == nextSeparatorIndex) {
System.arraycopy(
CHUNK_SEPARATOR,
0,
encodedData,
encodedIndex,
CHUNK_SEPARATOR.length);
chunksSoFar++;
nextSeparatorIndex =
(CHUNK_SIZE * (chunksSoFar + 1))
+ (chunksSoFar * CHUNK_SEPARATOR.length);
encodedIndex += CHUNK_SEPARATOR.length;
}
}
}
// form integral number of 6-bit groups
dataIndex = i * 3;
if (fewerThan24bits == EIGHTBIT) {
b1 = binaryData[dataIndex];
k = (byte) (b1 & 0x03);
//log.debug("b1=" + b1);
//log.debug("b1<<2 = " + (b1>>2) );
byte val1 =
((b1 & SIGN) == 0)
? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex + 1] = lookUpBase64Alphabet[k << 4];
encodedData[encodedIndex + 2] = PAD;
encodedData[encodedIndex + 3] = PAD;
}
else if (fewerThan24bits == SIXTEENBIT) {
b1 = binaryData[dataIndex];
b2 = binaryData[dataIndex + 1];
l = (byte) (b2 & 0x0f);
k = (byte) (b1 & 0x03);
byte val1 =
((b1 & SIGN) == 0)
? (byte) (b1 >> 2)
: (byte) ((b1) >> 2 ^ 0xc0);
byte val2 =
((b2 & SIGN) == 0)
? (byte) (b2 >> 4)
: (byte) ((b2) >> 4 ^ 0xf0);
encodedData[encodedIndex] = lookUpBase64Alphabet[val1];
encodedData[encodedIndex + 1] =
lookUpBase64Alphabet[val2 | (k << 4)];
encodedData[encodedIndex + 2] = lookUpBase64Alphabet[l << 2];
encodedData[encodedIndex + 3] = PAD;
}
if (isChunked) {
// we also add a separator to the end of the final chunk.
if (chunksSoFar < nbrChunks) {
System.arraycopy(
CHUNK_SEPARATOR,
0,
encodedData,
encodedDataLength - CHUNK_SEPARATOR.length,
CHUNK_SEPARATOR.length);
}
}
return encodedData;
}
/**
* Decodes Base64 data into octects
*
* @param base64Data Byte array containing Base64 data
* @return Array containing decoded data.
*/
public static byte[] decodeBase64(byte[] base64Data) {
// RFC 2045 suggests line wrapping at (no more than) 76
// characters -- we may have embedded whitespace.
base64Data = discardWhitespace(base64Data);
// handle the edge case, so we don't have to worry about it later
if (base64Data.length == 0) {
return new byte[0];
}
int numberQuadruple = base64Data.length / FOURBYTE;
byte decodedData[] = null;
byte b1 = 0, b2 = 0, b3 = 0, b4 = 0, marker0 = 0, marker1 = 0;
// Throw away anything not in base64Data
int encodedIndex = 0;
int dataIndex = 0;
{
// this sizes the output array properly - rlw
int lastData = base64Data.length;
// ignore the '=' padding
while (base64Data[lastData - 1] == PAD) {
if (--lastData == 0) {
return new byte[0];
}
}
decodedData = new byte[lastData - numberQuadruple];
}
for (int i = 0; i < numberQuadruple; i++) {
dataIndex = i * 4;
marker0 = base64Data[dataIndex + 2];
marker1 = base64Data[dataIndex + 3];
b1 = base64Alphabet[base64Data[dataIndex]];
b2 = base64Alphabet[base64Data[dataIndex + 1]];
if (marker0 != PAD && marker1 != PAD) {
//No PAD e.g 3cQl
b3 = base64Alphabet[marker0];
b4 = base64Alphabet[marker1];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] =
(byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
decodedData[encodedIndex + 2] = (byte) (b3 << 6 | b4);
}
else if (marker0 == PAD) {
//Two PAD e.g. 3c[Pad][Pad]
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
}
else if (marker1 == PAD) {
//One PAD e.g. 3cQ[Pad]
b3 = base64Alphabet[marker0];
decodedData[encodedIndex] = (byte) (b1 << 2 | b2 >> 4);
decodedData[encodedIndex + 1] =
(byte) (((b2 & 0xf) << 4) | ((b3 >> 2) & 0xf));
}
encodedIndex += 3;
}
return decodedData;
}
/**
* Discards any whitespace from a base-64 encoded block.
*
* @param data The base-64 encoded data to discard the whitespace
* from.
* @return The data, less whitespace (see RFC 2045).
*/
static byte[] discardWhitespace(byte[] data) {
byte groomedData[] = new byte[data.length];
int bytesCopied = 0;
for (int i = 0; i < data.length; i++) {
switch (data[i]) {
case (byte) ' ' :
case (byte) '\n' :
case (byte) '\r' :
case (byte) '\t' :
break;
default:
groomedData[bytesCopied++] = data[i];
}
}
byte packedData[] = new byte[bytesCopied];
System.arraycopy(groomedData, 0, packedData, 0, bytesCopied);
return packedData;
}
// Implementation of the Encoder Interface
/**
* encode an Object
*/
public Object encode(Object pObject) throws IllegalArgumentException {
Object result;
if (!(pObject instanceof byte[])) {
throw new IllegalArgumentException(
"Parameter supplied to "
+ "Base64 "
+ "encode is not a byte[]");
}
else {
result = encode((byte[]) pObject);
}
return result;
}
public byte[] encode(byte[] pArray) throws IllegalArgumentException {
return (encodeBase64(pArray, false));
}
} | mit |
scrollback/android-wrapper | app/src/main/java/io/scrollback/app/Scrollback.java | 1026 | package io.scrollback.app;
import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
public class Scrollback extends Application implements Application.ActivityLifecycleCallbacks {
public static boolean appOpen = false;
@Override
public void onCreate() {
super.onCreate();
registerActivityLifecycleCallbacks(this);
}
@Override
public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
}
@Override
public void onActivityStarted(Activity activity) {
appOpen = true;
}
@Override
public void onActivityResumed(Activity activity) {
}
@Override
public void onActivityPaused(Activity activity) {
appOpen = false;
}
@Override
public void onActivityStopped(Activity activity) {
}
@Override
public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
}
@Override
public void onActivityDestroyed(Activity activity) {
}
}
| mit |
hkuhn42/sylvani.bots | src/org/sylvani/bot/util/Prompt.java | 1897 | /**
* Copyright (C) 2016-2017 Harald Kuhn
*
* 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.sylvani.bot.util;
import org.sylvani.bot.IActivity;
import org.sylvani.bot.ISession;
import org.sylvani.bot.connector.GenericActivity;
/**
* Utiltiy for creating activities to prompt text to the conversation
*
* TODO: intergrate with bot and session
*
* @author Harald Kuhn
*
*/
public class Prompt {
ISession session;
public Prompt(ISession session) {
this.session = session;
}
public static IActivity answer(IActivity inIActivity) {
IActivity activity = new GenericActivity();
activity.setId(inIActivity.getId() + "a");
activity.setFrom(inIActivity.getRecipient());
activity.setRecipient(inIActivity.getFrom());
return activity;
}
public static IActivity answer(String text, IActivity inIActivity) {
IActivity activity = answer(inIActivity);
activity.setText(text);
return activity;
}
public static IActivity choice(String text, String[] choices, IActivity inIActivity) {
StringBuilder textBuilder = new StringBuilder(text);
for (int i = 0; i < choices.length; i++) {
textBuilder.append("\n" + (i + 1) + "." + choices[i]);
}
IActivity activity = answer(textBuilder.toString(), inIActivity);
return activity;
}
}
| mit |
uwol/vb6parser | src/main/java/io/proleap/vb6/asg/visitor/impl/VbModuleNameAnalyzerVisitorImpl.java | 1210 | /*
* Copyright (C) 2017, Ulrich Wolffgang <ulrich.wolffgang@proleap.io>
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE file for details.
*/
package io.proleap.vb6.asg.visitor.impl;
import io.proleap.vb6.VisualBasic6BaseVisitor;
import io.proleap.vb6.VisualBasic6Parser;
import io.proleap.vb6.asg.resolver.impl.NameResolverImpl;
/**
* Determines the module name as declared in the VB_Name attribute.
*/
public class VbModuleNameAnalyzerVisitorImpl extends VisualBasic6BaseVisitor<String> {
public final String VB_NAME = "VB_Name";
@Override
protected String aggregateResult(final String aggregate, final String nextResult) {
if (nextResult != null) {
return nextResult;
}
return aggregate;
}
@Override
public String visitAttributeStmt(final VisualBasic6Parser.AttributeStmtContext ctx) {
final String name = new NameResolverImpl().determineName(ctx);
// if the module name is declared
if (VB_NAME.toLowerCase().equals(name.toLowerCase())) {
final String attributeValue = ctx.literal(0).getText().replace("\"", "");
return attributeValue;
} else {
return visitChildren(ctx);
}
}
}
| mit |
navalev/azure-sdk-for-java | sdk/cosmosdb/mgmt-v2019_08_01_preview/src/main/java/com/microsoft/azure/management/cosmosdb/v2019_08_01_preview/implementation/PartitionUsageImpl.java | 1654 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.cosmosdb.v2019_08_01_preview.implementation;
import com.microsoft.azure.management.cosmosdb.v2019_08_01_preview.PartitionUsage;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import com.microsoft.azure.management.cosmosdb.v2019_08_01_preview.MetricName;
import com.microsoft.azure.management.cosmosdb.v2019_08_01_preview.UnitType;
class PartitionUsageImpl extends WrapperImpl<PartitionUsageInner> implements PartitionUsage {
private final CosmosDBManager manager;
PartitionUsageImpl(PartitionUsageInner inner, CosmosDBManager manager) {
super(inner);
this.manager = manager;
}
@Override
public CosmosDBManager manager() {
return this.manager;
}
@Override
public Long currentValue() {
return this.inner().currentValue();
}
@Override
public Long limit() {
return this.inner().limit();
}
@Override
public MetricName name() {
return this.inner().name();
}
@Override
public String partitionId() {
return this.inner().partitionId();
}
@Override
public String partitionKeyRangeId() {
return this.inner().partitionKeyRangeId();
}
@Override
public String quotaPeriod() {
return this.inner().quotaPeriod();
}
@Override
public UnitType unit() {
return this.inner().unit();
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/mediaservices/mgmt-v2019_05_01_preview/src/main/java/com/microsoft/azure/management/mediaservices/v2019_05_01_preview/ListStreamingLocatorsResponse.java | 966 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.mediaservices.v2019_05_01_preview;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.mediaservices.v2019_05_01_preview.implementation.MediaManager;
import com.microsoft.azure.management.mediaservices.v2019_05_01_preview.implementation.ListStreamingLocatorsResponseInner;
import java.util.List;
/**
* Type representing ListStreamingLocatorsResponse.
*/
public interface ListStreamingLocatorsResponse extends HasInner<ListStreamingLocatorsResponseInner>, HasManager<MediaManager> {
/**
* @return the streamingLocators value.
*/
List<AssetStreamingLocator> streamingLocators();
}
| mit |
jrachiele/java-timeseries | math/src/main/java/com/github/signaflo/math/optim/ViolatedTheoremAssumptionsException.java | 1466 | /*
* Copyright (c) 2016 Jacob Rachiele
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of this software
* and associated documentation files (the "Software"), to deal in the Software without restriction
* including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense
* and/or sell copies of the Software, and to permit persons to whom the Software is furnished to
* do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all copies or
* substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED
* INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
* LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
* USE OR OTHER DEALINGS IN THE SOFTWARE.
*
* Contributors:
*
* Jacob Rachiele
*/
package com.github.signaflo.math.optim;
class ViolatedTheoremAssumptionsException extends RuntimeException {
ViolatedTheoremAssumptionsException(String message) {
super(message);
}
ViolatedTheoremAssumptionsException() {
super("The theorem assumptions have been violated.");
}
}
| mit |
openlegacy/lombok | test/transform/resource/after-delombok/DelegateTypesAndExcludes.java | 823 | class DelegatePlain {
private final BarImpl bar = new BarImpl();
private final FooImpl foo = new FooImpl();
private static class FooImpl implements Foo {
public void foo() {
}
public void bar(java.util.ArrayList<java.lang.String> list) {
}
}
private static class BarImpl implements Bar {
public void bar(java.util.ArrayList<java.lang.String> list) {
}
}
private static interface Foo extends Bar {
void foo();
}
private static interface Bar {
void bar(java.util.ArrayList<java.lang.String> list);
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public void bar(final java.util.ArrayList<java.lang.String> list) {
this.bar.bar(list);
}
@java.lang.SuppressWarnings("all")
@javax.annotation.Generated("lombok")
public void foo() {
this.foo.foo();
}
}
| mit |
joansmith/ontrack | ontrack-backend/src/main/java/net/ontrack/backend/dao/jdbc/GlobalAuthorizationJdbcDao.java | 2489 | package net.ontrack.backend.dao.jdbc;
import net.ontrack.backend.dao.GlobalAuthorizationDao;
import net.ontrack.backend.dao.model.TGlobalAuthorization;
import net.ontrack.backend.db.SQL;
import net.ontrack.core.model.Ack;
import net.ontrack.core.security.GlobalFunction;
import net.ontrack.dao.AbstractJdbcDao;
import net.ontrack.dao.SQLUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import javax.sql.DataSource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
@Component
public class GlobalAuthorizationJdbcDao extends AbstractJdbcDao implements GlobalAuthorizationDao {
private final RowMapper<TGlobalAuthorization> globalAuthorizationRowMapper = new RowMapper<TGlobalAuthorization>() {
@Override
public TGlobalAuthorization mapRow(ResultSet rs, int rowNum) throws SQLException {
return new TGlobalAuthorization(
rs.getInt("account"),
SQLUtils.getEnum(GlobalFunction.class, rs, "fn")
);
}
};
@Autowired
public GlobalAuthorizationJdbcDao(DataSource dataSource) {
super(dataSource);
}
@Override
public Ack set(int account, GlobalFunction fn) {
// Deletes any previous ACL
unset(account, fn);
// Inserts this one
return Ack.one(
getNamedParameterJdbcTemplate().update(
SQL.GLOBAL_AUTHORIZATION_SET,
params("account", account).addValue("fn", fn.name())
)
);
}
@Override
public Ack unset(int account, GlobalFunction fn) {
return Ack.one(
getNamedParameterJdbcTemplate().update(
SQL.GLOBAL_AUTHORIZATION_UNSET,
params("account", account).addValue("fn", fn.name())
)
);
}
@Override
public List<TGlobalAuthorization> all() {
return getJdbcTemplate().query(
SQL.GLOBAL_AUTHORIZATION_LIST,
globalAuthorizationRowMapper
);
}
@Override
public List<TGlobalAuthorization> findByAccount(int account) {
return getNamedParameterJdbcTemplate().query(
SQL.GLOBAL_AUTHORIZATION_BY_ACCOUNT,
params("account", account),
globalAuthorizationRowMapper
);
}
}
| mit |
alexpap/exareme | exareme-utils/src/test/java/madgik/exareme/utils/demo/DemoSA.java | 1203 | /**
* Copyright MaDgIK Group 2010 - 2015.
*/
package madgik.exareme.utils.sa.demo;
import madgik.exareme.utils.association.Pair;
import madgik.exareme.utils.simulatedAnnealing.SimulatedAnnealing;
import madgik.exareme.utils.simulatedAnnealing.State;
import madgik.exareme.utils.simulatedAnnealing.Temperature;
import madgik.exareme.utils.simulatedAnnealing.Transformation;
import java.rmi.RemoteException;
import java.util.Random;
class DemoSA extends SimulatedAnnealing {
private static final long serialVersionUID = 1L;
public DemoSA(int maxSteps, int stepsNotImprovedTermination, Temperature temperature) {
super(maxSteps, stepsNotImprovedTermination, temperature);
}
@Override public State getInitial() throws RemoteException {
return new DemoState();
}
@Override public Pair<Transformation, Transformation> getNeighbor(State state, Random rand)
throws RemoteException {
int from = rand.nextInt(100);
int to = rand.nextInt(100);
Transformation t1 = new DemoTransformation(from, to);
Transformation t2 = new DemoTransformation(to, from);
return new Pair<Transformation, Transformation>(t1, t2);
}
}
| mit |
willy2706/philosopherStone | src/client/app/src/main/java/com/sisteritb/philosopherstone/connection/request/SendFindRequest.java | 841 | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.sisteritb.philosopherstone.connection.request;
import java.util.LinkedHashMap;
import java.util.Map;
import org.json.simple.JSONValue;
/**
*
* @author winsxx
*/
public class SendFindRequest extends Request{
public String token;
public long item;
public SendFindRequest() {
method = "sendfind";
}
@Override
public String toString() {
Map obj = new LinkedHashMap();
obj.put("method", method);
obj.put("token", token);
obj.put("item", item);
String jsonString = JSONValue.toJSONString(obj);
return jsonString;
}
}
| mit |
kbase/workspace_deluxe | src/us/kbase/workspace/test/JsonTokenStreamOCStat.java | 1264 | package us.kbase.workspace.test;
import java.util.LinkedHashMap;
import java.util.Map;
import us.kbase.common.service.JsonTokenStream;
public class JsonTokenStreamOCStat {
private static Map<JsonTokenStream, Exception> openEvents = new LinkedHashMap<JsonTokenStream, Exception>();
public static void register() {
JsonTokenStream.setDebugOpenCloseListener(new JsonTokenStream.DebugOpenCloseListener() {
@Override
public void onStreamOpen(JsonTokenStream instance) {
if (openEvents.containsKey(instance)) {
throw new IllegalStateException(
"Stream was already open", openEvents.get(instance));
}
openEvents.put(instance, new Exception("Stream wasn't closed"));
}
@Override
public void onStreamClosed(JsonTokenStream instance) {
if (!openEvents.containsKey(instance)) {
throw new IllegalStateException("Stream wasn't open before");
}
openEvents.remove(instance);
}
});
}
public static void showStat() {
for (Exception ex : openEvents.values()) {
ex.printStackTrace();
}
final boolean notEmpty = !openEvents.isEmpty();
openEvents.clear();
if (notEmpty) {
throw new IllegalStateException(
"Some JsonTokenStream-related open-close errors occurred (see error log)");
}
}
}
| mit |
Azure/azure-sdk-for-java | sdk/search/azure-search-documents/src/test/java/com/azure/search/documents/test/environment/models/Author.java | 731 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
package com.azure.search.documents.test.environment.models;
import com.fasterxml.jackson.annotation.JsonProperty;
public class Author {
@JsonProperty(value = "FirstName")
private String firstName;
@JsonProperty(value = "LastName")
private String lastName;
public String firstName() {
return this.firstName;
}
public Author firstName(String firstName) {
this.firstName = firstName;
return this;
}
public String lastName() {
return this.lastName;
}
public Author lastName(String lastName) {
this.lastName = lastName;
return this;
}
}
| mit |
robrua/Orianna | orianna/src/main/java/com/merakianalytics/orianna/types/data/match/TournamentMatches.java | 2169 | package com.merakianalytics.orianna.types.data.match;
import com.merakianalytics.orianna.types.data.CoreData;
public class TournamentMatches extends CoreData.ListProxy<Long> {
private static final long serialVersionUID = -5740576983616480981L;
private String tournamentCode, platform;
public TournamentMatches() {
super();
}
public TournamentMatches(final int initialCapacity) {
super(initialCapacity);
}
@Override
public boolean equals(final Object obj) {
if(this == obj) {
return true;
}
if(!super.equals(obj)) {
return false;
}
if(getClass() != obj.getClass()) {
return false;
}
final TournamentMatches other = (TournamentMatches)obj;
if(platform == null) {
if(other.platform != null) {
return false;
}
} else if(!platform.equals(other.platform)) {
return false;
}
if(tournamentCode == null) {
if(other.tournamentCode != null) {
return false;
}
} else if(!tournamentCode.equals(other.tournamentCode)) {
return false;
}
return true;
}
/**
* @return the platform
*/
public String getPlatform() {
return platform;
}
/**
* @return the tournamentCode
*/
public String getTournamentCode() {
return tournamentCode;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + (platform == null ? 0 : platform.hashCode());
result = prime * result + (tournamentCode == null ? 0 : tournamentCode.hashCode());
return result;
}
/**
* @param platform
* the platform to set
*/
public void setPlatform(final String platform) {
this.platform = platform;
}
/**
* @param tournamentCode
* the tournamentCode to set
*/
public void setTournamentCode(final String tournamentCode) {
this.tournamentCode = tournamentCode;
}
}
| mit |
jdrider/rhodes | rhoconnect-client/Java/RhoConnect/src/com/rhomobile/rhoconnect/RhoConnectObjectNotify.java | 2009 | /*------------------------------------------------------------------------
* (The MIT License)
*
* Copyright (c) 2008-2011 Rhomobile, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
* http://rhomobile.com
*------------------------------------------------------------------------*/
package com.rhomobile.rhoconnect;
public class RhoConnectObjectNotify {
String[] mDeletedObjects;
String[] mUpdatedObjects;
String[] mCreatedObjects;
int[] mDeletedSrcIds;
int[] mUpdatedSrcIds;
int[] mCreatedSrcIds;
public String[] getDeletedObjects() { return mDeletedObjects; }
public String[] getUpdatedObjects() { return mUpdatedObjects; }
public String[] getCreatedObjects() { return mCreatedObjects; }
public int[] getDeletedSourceIds() { return mDeletedSrcIds; }
public int[] getUpdatedSourceIds() { return mUpdatedSrcIds; }
public int[] getCreatedSourceIds() { return mCreatedSrcIds; }
public static interface IDelegate {
public void call(RhoConnectObjectNotify notify);
}
}
| mit |
Yujia-Xiao/Leetcode | Tree/Breadth-First_Search/Convert_Sorted_List_to_Binary_Search_Tree.java | 1037 | /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public TreeNode sortedListToBST(ListNode head) {
if(head == null)return null;
if(head.next == null)return new TreeNode(head.val);
ListNode slow = head;
ListNode fast = head;
ListNode pre = null;
while(fast!=null && fast.next!=null){
pre = slow;
slow = slow.next;
fast = fast.next.next;
}
pre.next = null;
TreeNode left = sortedListToBST(head);
TreeNode right = sortedListToBST(slow.next);
TreeNode root = new TreeNode(slow.val);
root.left = left;
root.right = right;
return root;
}
} | mit |
navalev/azure-sdk-for-java | sdk/netapp/mgmt-v2017_08_15/src/main/java/com/microsoft/azure/management/netapp/v2017_08_15/implementation/SnapshotImpl.java | 4570 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.netapp.v2017_08_15.implementation;
import com.microsoft.azure.management.netapp.v2017_08_15.Snapshot;
import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl;
import rx.Observable;
import org.joda.time.DateTime;
import java.util.Map;
class SnapshotImpl extends CreatableUpdatableImpl<Snapshot, SnapshotInner, SnapshotImpl> implements Snapshot, Snapshot.Definition, Snapshot.Update {
private final NetAppManager manager;
private String resourceGroupName;
private String accountName;
private String poolName;
private String volumeName;
private String snapshotName;
SnapshotImpl(String name, NetAppManager manager) {
super(name, new SnapshotInner());
this.manager = manager;
// Set resource name
this.snapshotName = name;
//
}
SnapshotImpl(SnapshotInner inner, NetAppManager manager) {
super(inner.name(), inner);
this.manager = manager;
// Set resource name
this.snapshotName = inner.name();
// set resource ancestor and positional variables
this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups");
this.accountName = IdParsingUtils.getValueFromIdByName(inner.id(), "netAppAccounts");
this.poolName = IdParsingUtils.getValueFromIdByName(inner.id(), "capacityPools");
this.volumeName = IdParsingUtils.getValueFromIdByName(inner.id(), "volumes");
this.snapshotName = IdParsingUtils.getValueFromIdByName(inner.id(), "snapshots");
//
}
@Override
public NetAppManager manager() {
return this.manager;
}
@Override
public Observable<Snapshot> createResourceAsync() {
SnapshotsInner client = this.manager().inner().snapshots();
return client.createAsync(this.resourceGroupName, this.accountName, this.poolName, this.volumeName, this.snapshotName, this.inner())
.map(innerToFluentMap(this));
}
@Override
public Observable<Snapshot> updateResourceAsync() {
SnapshotsInner client = this.manager().inner().snapshots();
return client.createAsync(this.resourceGroupName, this.accountName, this.poolName, this.volumeName, this.snapshotName, this.inner())
.map(innerToFluentMap(this));
}
@Override
protected Observable<SnapshotInner> getInnerAsync() {
SnapshotsInner client = this.manager().inner().snapshots();
return client.getAsync(this.resourceGroupName, this.accountName, this.poolName, this.volumeName, this.snapshotName);
}
@Override
public boolean isInCreateMode() {
return this.inner().id() == null;
}
@Override
public DateTime creationDate() {
return this.inner().creationDate();
}
@Override
public String fileSystemId() {
return this.inner().fileSystemId();
}
@Override
public String id() {
return this.inner().id();
}
@Override
public String location() {
return this.inner().location();
}
@Override
public String name() {
return this.inner().name();
}
@Override
public String provisioningState() {
return this.inner().provisioningState();
}
@Override
public String snapshotId() {
return this.inner().snapshotId();
}
@Override
public Map<String, String> tags() {
return this.inner().getTags();
}
@Override
public String type() {
return this.inner().type();
}
@Override
public SnapshotImpl withExistingVolume(String resourceGroupName, String accountName, String poolName, String volumeName) {
this.resourceGroupName = resourceGroupName;
this.accountName = accountName;
this.poolName = poolName;
this.volumeName = volumeName;
return this;
}
@Override
public SnapshotImpl withFileSystemId(String fileSystemId) {
this.inner().withFileSystemId(fileSystemId);
return this;
}
@Override
public SnapshotImpl withLocation(String location) {
this.inner().withLocation(location);
return this;
}
@Override
public SnapshotImpl withTags(Map<String, String> tags) {
this.inner().withTags(tags);
return this;
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/devtestlabs/mgmt-v2018_09_15/src/main/java/com/microsoft/azure/management/devtestlabs/v2018_09_15/UserLabSchedule.java | 13232 | /**
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
*/
package com.microsoft.azure.management.devtestlabs.v2018_09_15;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.management.devtestlabs.v2018_09_15.implementation.ScheduleInner;
import com.microsoft.azure.arm.model.Indexable;
import com.microsoft.azure.arm.model.Refreshable;
import com.microsoft.azure.arm.model.Updatable;
import com.microsoft.azure.arm.model.Appliable;
import com.microsoft.azure.arm.model.Creatable;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.devtestlabs.v2018_09_15.implementation.DevTestLabsManager;
import java.util.Map;
import org.joda.time.DateTime;
/**
* Type representing UserLabSchedule.
*/
public interface UserLabSchedule extends HasInner<ScheduleInner>, Indexable, Refreshable<UserLabSchedule>, Updatable<UserLabSchedule.Update>, HasManager<DevTestLabsManager> {
/**
* @return the createdDate value.
*/
DateTime createdDate();
/**
* @return the dailyRecurrence value.
*/
DayDetails dailyRecurrence();
/**
* @return the hourlyRecurrence value.
*/
HourDetails hourlyRecurrence();
/**
* @return the id value.
*/
String id();
/**
* @return the location value.
*/
String location();
/**
* @return the name value.
*/
String name();
/**
* @return the notificationSettings value.
*/
NotificationSettings notificationSettings();
/**
* @return the provisioningState value.
*/
String provisioningState();
/**
* @return the status value.
*/
EnableStatus status();
/**
* @return the tags value.
*/
Map<String, String> tags();
/**
* @return the targetResourceId value.
*/
String targetResourceId();
/**
* @return the taskType value.
*/
String taskType();
/**
* @return the timeZoneId value.
*/
String timeZoneId();
/**
* @return the type value.
*/
String type();
/**
* @return the uniqueIdentifier value.
*/
String uniqueIdentifier();
/**
* @return the weeklyRecurrence value.
*/
WeekDetails weeklyRecurrence();
/**
* The entirety of the UserLabSchedule definition.
*/
interface Definition extends DefinitionStages.Blank, DefinitionStages.WithServicefabric, DefinitionStages.WithCreate {
}
/**
* Grouping of UserLabSchedule definition stages.
*/
interface DefinitionStages {
/**
* The first stage of a UserLabSchedule definition.
*/
interface Blank extends WithServicefabric {
}
/**
* The stage of the userlabschedule definition allowing to specify Servicefabric.
*/
interface WithServicefabric {
/**
* Specifies resourceGroupName, labName, userName, serviceFabricName.
* @param resourceGroupName The name of the resource group
* @param labName The name of the lab
* @param userName The name of the user profile
* @param serviceFabricName The name of the service fabric
* @return the next definition stage
*/
WithCreate withExistingServicefabric(String resourceGroupName, String labName, String userName, String serviceFabricName);
}
/**
* The stage of the userlabschedule definition allowing to specify DailyRecurrence.
*/
interface WithDailyRecurrence {
/**
* Specifies dailyRecurrence.
* @param dailyRecurrence If the schedule will occur once each day of the week, specify the daily recurrence
* @return the next definition stage
*/
WithCreate withDailyRecurrence(DayDetails dailyRecurrence);
}
/**
* The stage of the userlabschedule definition allowing to specify HourlyRecurrence.
*/
interface WithHourlyRecurrence {
/**
* Specifies hourlyRecurrence.
* @param hourlyRecurrence If the schedule will occur multiple times a day, specify the hourly recurrence
* @return the next definition stage
*/
WithCreate withHourlyRecurrence(HourDetails hourlyRecurrence);
}
/**
* The stage of the userlabschedule definition allowing to specify Location.
*/
interface WithLocation {
/**
* Specifies location.
* @param location The location of the resource
* @return the next definition stage
*/
WithCreate withLocation(String location);
}
/**
* The stage of the userlabschedule definition allowing to specify NotificationSettings.
*/
interface WithNotificationSettings {
/**
* Specifies notificationSettings.
* @param notificationSettings Notification settings
* @return the next definition stage
*/
WithCreate withNotificationSettings(NotificationSettings notificationSettings);
}
/**
* The stage of the userlabschedule definition allowing to specify Status.
*/
interface WithStatus {
/**
* Specifies status.
* @param status The status of the schedule (i.e. Enabled, Disabled). Possible values include: 'Enabled', 'Disabled'
* @return the next definition stage
*/
WithCreate withStatus(EnableStatus status);
}
/**
* The stage of the userlabschedule definition allowing to specify Tags.
*/
interface WithTags {
/**
* Specifies tags.
* @param tags The tags of the resource
* @return the next definition stage
*/
WithCreate withTags(Map<String, String> tags);
}
/**
* The stage of the userlabschedule definition allowing to specify TargetResourceId.
*/
interface WithTargetResourceId {
/**
* Specifies targetResourceId.
* @param targetResourceId The resource ID to which the schedule belongs
* @return the next definition stage
*/
WithCreate withTargetResourceId(String targetResourceId);
}
/**
* The stage of the userlabschedule definition allowing to specify TaskType.
*/
interface WithTaskType {
/**
* Specifies taskType.
* @param taskType The task type of the schedule (e.g. LabVmsShutdownTask, LabVmAutoStart)
* @return the next definition stage
*/
WithCreate withTaskType(String taskType);
}
/**
* The stage of the userlabschedule definition allowing to specify TimeZoneId.
*/
interface WithTimeZoneId {
/**
* Specifies timeZoneId.
* @param timeZoneId The time zone ID (e.g. Pacific Standard time)
* @return the next definition stage
*/
WithCreate withTimeZoneId(String timeZoneId);
}
/**
* The stage of the userlabschedule definition allowing to specify WeeklyRecurrence.
*/
interface WithWeeklyRecurrence {
/**
* Specifies weeklyRecurrence.
* @param weeklyRecurrence If the schedule will occur only some days of the week, specify the weekly recurrence
* @return the next definition stage
*/
WithCreate withWeeklyRecurrence(WeekDetails weeklyRecurrence);
}
/**
* The stage of the definition which contains all the minimum required inputs for
* the resource to be created (via {@link WithCreate#create()}), but also allows
* for any other optional settings to be specified.
*/
interface WithCreate extends Creatable<UserLabSchedule>, DefinitionStages.WithDailyRecurrence, DefinitionStages.WithHourlyRecurrence, DefinitionStages.WithLocation, DefinitionStages.WithNotificationSettings, DefinitionStages.WithStatus, DefinitionStages.WithTags, DefinitionStages.WithTargetResourceId, DefinitionStages.WithTaskType, DefinitionStages.WithTimeZoneId, DefinitionStages.WithWeeklyRecurrence {
}
}
/**
* The template for a UserLabSchedule update operation, containing all the settings that can be modified.
*/
interface Update extends Appliable<UserLabSchedule>, UpdateStages.WithDailyRecurrence, UpdateStages.WithHourlyRecurrence, UpdateStages.WithNotificationSettings, UpdateStages.WithStatus, UpdateStages.WithTags, UpdateStages.WithTargetResourceId, UpdateStages.WithTaskType, UpdateStages.WithTimeZoneId, UpdateStages.WithWeeklyRecurrence {
}
/**
* Grouping of UserLabSchedule update stages.
*/
interface UpdateStages {
/**
* The stage of the userlabschedule update allowing to specify DailyRecurrence.
*/
interface WithDailyRecurrence {
/**
* Specifies dailyRecurrence.
* @param dailyRecurrence If the schedule will occur once each day of the week, specify the daily recurrence
* @return the next update stage
*/
Update withDailyRecurrence(DayDetailsFragment dailyRecurrence);
}
/**
* The stage of the userlabschedule update allowing to specify HourlyRecurrence.
*/
interface WithHourlyRecurrence {
/**
* Specifies hourlyRecurrence.
* @param hourlyRecurrence If the schedule will occur multiple times a day, specify the hourly recurrence
* @return the next update stage
*/
Update withHourlyRecurrence(HourDetailsFragment hourlyRecurrence);
}
/**
* The stage of the userlabschedule update allowing to specify NotificationSettings.
*/
interface WithNotificationSettings {
/**
* Specifies notificationSettings.
* @param notificationSettings Notification settings
* @return the next update stage
*/
Update withNotificationSettings(NotificationSettingsFragment notificationSettings);
}
/**
* The stage of the userlabschedule update allowing to specify Status.
*/
interface WithStatus {
/**
* Specifies status.
* @param status The status of the schedule (i.e. Enabled, Disabled). Possible values include: 'Enabled', 'Disabled'
* @return the next update stage
*/
Update withStatus(EnableStatus status);
}
/**
* The stage of the userlabschedule update allowing to specify Tags.
*/
interface WithTags {
/**
* Specifies tags.
* @param tags The tags of the resource
* @return the next update stage
*/
Update withTags(Map<String, String> tags);
}
/**
* The stage of the userlabschedule update allowing to specify TargetResourceId.
*/
interface WithTargetResourceId {
/**
* Specifies targetResourceId.
* @param targetResourceId The resource ID to which the schedule belongs
* @return the next update stage
*/
Update withTargetResourceId(String targetResourceId);
}
/**
* The stage of the userlabschedule update allowing to specify TaskType.
*/
interface WithTaskType {
/**
* Specifies taskType.
* @param taskType The task type of the schedule (e.g. LabVmsShutdownTask, LabVmAutoStart)
* @return the next update stage
*/
Update withTaskType(String taskType);
}
/**
* The stage of the userlabschedule update allowing to specify TimeZoneId.
*/
interface WithTimeZoneId {
/**
* Specifies timeZoneId.
* @param timeZoneId The time zone ID (e.g. Pacific Standard time)
* @return the next update stage
*/
Update withTimeZoneId(String timeZoneId);
}
/**
* The stage of the userlabschedule update allowing to specify WeeklyRecurrence.
*/
interface WithWeeklyRecurrence {
/**
* Specifies weeklyRecurrence.
* @param weeklyRecurrence If the schedule will occur only some days of the week, specify the weekly recurrence
* @return the next update stage
*/
Update withWeeklyRecurrence(WeekDetailsFragment weeklyRecurrence);
}
}
}
| mit |
michaeltmarion/OOGASalad | src/author/panels/AbstractToggleButtonPanel.java | 703 | package author.panels;
/**
* This is an abstract class that is extended by WordPanel, ListPanel, NumberPanel,
* and MatrixPanel. It is extended by all classes that take some form of user typing
* in order to get a result.
*
* @author mray90
*
*/
import java.awt.AWTEvent;
import java.util.EventListener;
public abstract class AbstractToggleButtonPanel extends AbstractWizardPanel {
private static final long serialVersionUID = -2440277590050770853L;
protected EventListener myEventListener;
public AbstractToggleButtonPanel (String type, EventListener el) {
super(type);
myEventListener = el;
}
public abstract void updateSelectionState (AWTEvent e);
}
| mit |
ssdwa/android | dConnectDevicePlugin/dConnectDeviceIRKit/src/org/deviceconnect/android/deviceplugin/irkit/profile/package-info.java | 313 | /*
org.deviceconnect.android.deviceplugin.irkit.profile
Copyright (c) 2014 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
/**
* プロファイルを提供する.
* @author NTT DOCOMO, INC.
*/
package org.deviceconnect.android.deviceplugin.irkit.profile;
| mit |
gardaud/Kitsune | src/kitsune/Behavior.java | 2442 | package kitsune;
import java.awt.*;
import java.io.Serializable;
/**
*
* @author Guillaume
*/
public class Behavior implements Serializable {
public String type;
public Color color;
protected Agent parent;
protected int squareTarget; //the square target
protected int nextSquare; //the next square to go to
protected int currentSquare; //the next square to go to
protected int stepsSinceTarget;
protected boolean isExiting;
public boolean stuck;
public Behavior(){
type="none";
}
public void step(){
}
protected void stepToSquare(){
if (this.nextSquare==this.currentSquare+1){ //if the next square is to the right
this.parent.setX(this.parent.getX()+this.parent.speed);
} else if (this.nextSquare==this.currentSquare-1) { //if the next square is to the left
this.parent.setX(this.parent.getX()-this.parent.speed);
} else if (this.nextSquare==this.currentSquare-this.parent.size) { //if the next square is up
this.parent.setY(this.parent.getY()-this.parent.speed);
} else if (this.nextSquare==this.currentSquare+this.parent.size) { //if the next square is down
this.parent.setY(this.parent.getY()+this.parent.speed);
//DIAGONALS
}else if (this.nextSquare==this.currentSquare-this.parent.size-1) { //if the next square is to the up-left
this.parent.setX(this.parent.getX()-this.parent.speed/2);
this.parent.setY(this.parent.getY()-this.parent.speed/2);
} else if (this.nextSquare==this.currentSquare-this.parent.size+1) { //if the next square is up-right
this.parent.setX(this.parent.getX()+this.parent.speed/2);
this.parent.setY(this.parent.getY()-this.parent.speed/2);
} else if (this.nextSquare==this.currentSquare+this.parent.size-1) { //if the next square is down-left
this.parent.setX(this.parent.getX()-this.parent.speed/2);
this.parent.setY(this.parent.getY()+this.parent.speed/2);
} else if (this.nextSquare==this.currentSquare+this.parent.size+1) { //if the next square is down-right
this.parent.setX(this.parent.getX()+this.parent.speed/2);
this.parent.setY(this.parent.getY()+this.parent.speed/2);
}
}
protected void calculateNextSquare(){
}
public String getType(){
return this.type;
}
}
| mit |
gregwym/joos-compiler-java | testcases/a3/Je_6_ClosestMatch_Constructor_NoClosestMatch/Main.java | 750 | // TYPE_CHECKING,
// JOOS1: JOOS1_CLOSEST_MATCH_OVERLOADING,NO_MATCHING_CONSTRUCTOR_FOUND,AMBIGUOUS_OVERLOADING
// JOOS2: AMBIGUOUS_OVERLOADING
// JAVAC:UNKNOWN
/**
* Typecheck:
* - (Joos 1) Check that any method or constructor invocation resolves
* to a unique method with a type signature matching exactly the
* static types of the argument expressions.
* - (Joos 2) Check that any method or constructor invocation resolves
* to a uniquely closest matching method or constructor (15.12.2).
*/
public class Main implements Cloneable, Runnable{
public Main(Cloneable s) {}
public Main(Runnable s) {}
public void run(){}
public static int test() {
new Main(new Main(new Thread()));
return 123;
}
}
| mit |
Sam-Gram/CodeStreamer | src/main/java/codestreamer/CodeStreamerContextListener.java | 1226 | package codestreamer;
import codestreamer.model.Stream;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.sql.SQLException;
import java.util.HashMap;
/**
* Used for registering things with the servlet container. Currently, it just registers the
* database with it.
*/
@WebListener
public class CodeStreamerContextListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
// codestreamer.model.Database db = new codestreamer.model.Database();
// servletContextEvent.getServletContext().setAttribute("db", db);
HashMap<String, Stream> streams = new HashMap<>();
servletContextEvent.getServletContext().setAttribute("streams", streams);
}
@Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
// codestreamer.model.Database db = (codestreamer.model.Database) servletContextEvent.getServletContext().getAttribute("db");
// try {
// db.getConnection().close();
// } catch (SQLException e) {
// e.printStackTrace();
// }
}
}
| mit |
victorbriz/waffle | Source/JNA/waffle-tomcat6/src/main/java/waffle/apache/NegotiateAuthenticator.java | 7419 | /**
* Waffle (https://github.com/dblock/waffle)
*
* Copyright (c) 2010 - 2015 Application Security, 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:
* Application Security, Inc.
*/
package waffle.apache;
import java.io.IOException;
import java.security.Principal;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.catalina.connector.Request;
import org.apache.catalina.connector.Response;
import org.apache.catalina.deploy.LoginConfig;
import org.slf4j.LoggerFactory;
import com.google.common.io.BaseEncoding;
import com.sun.jna.platform.win32.Win32Exception;
import waffle.util.AuthorizationHeader;
import waffle.util.NtlmServletRequest;
import waffle.windows.auth.IWindowsIdentity;
import waffle.windows.auth.IWindowsSecurityContext;
/**
* An Apache Negotiate (NTLM, Kerberos) Authenticator.
*
* @author dblock[at]dblock[dot]org
*/
public class NegotiateAuthenticator extends WaffleAuthenticatorBase {
/**
* Instantiates a new negotiate authenticator.
*/
public NegotiateAuthenticator() {
super();
this.log = LoggerFactory.getLogger(NegotiateAuthenticator.class);
this.info = "waffle.apache.NegotiateAuthenticator/1.0";
this.log.debug("[waffle.apache.NegotiateAuthenticator] loaded");
}
/* (non-Javadoc)
* @see org.apache.catalina.authenticator.AuthenticatorBase#start()
*/
@Override
public void start() {
this.log.info("[waffle.apache.NegotiateAuthenticator] started");
}
/* (non-Javadoc)
* @see org.apache.catalina.authenticator.AuthenticatorBase#stop()
*/
@Override
public void stop() {
this.log.info("[waffle.apache.NegotiateAuthenticator] stopped");
}
/* (non-Javadoc)
* @see org.apache.catalina.authenticator.AuthenticatorBase#authenticate(org.apache.catalina.connector.Request, org.apache.catalina.connector.Response, org.apache.catalina.deploy.LoginConfig)
*/
@Override
public boolean authenticate(final Request request, final Response response, final LoginConfig loginConfig) {
Principal principal = request.getUserPrincipal();
final AuthorizationHeader authorizationHeader = new AuthorizationHeader(request);
final boolean ntlmPost = authorizationHeader.isNtlmType1PostAuthorizationHeader();
this.log.debug("{} {}, contentlength: {}", request.getMethod(), request.getRequestURI(),
Integer.valueOf(request.getContentLength()));
this.log.debug("authorization: {}, ntlm post: {}", authorizationHeader, Boolean.valueOf(ntlmPost));
if (principal != null && !ntlmPost) {
// user already authenticated
this.log.debug("previously authenticated user: {}", principal.getName());
return true;
}
// authenticate user
if (!authorizationHeader.isNull()) {
final String securityPackage = authorizationHeader.getSecurityPackage();
// maintain a connection-based session for NTLM tokens
final String connectionId = NtlmServletRequest.getConnectionId(request);
this.log.debug("security package: {}, connection id: {}", securityPackage, connectionId);
if (ntlmPost) {
// type 1 NTLM authentication message received
this.auth.resetSecurityToken(connectionId);
}
// log the user in using the token
IWindowsSecurityContext securityContext;
try {
final byte[] tokenBuffer = authorizationHeader.getTokenBytes();
this.log.debug("token buffer: {} byte(s)", Integer.valueOf(tokenBuffer.length));
try {
securityContext = this.auth.acceptSecurityToken(connectionId, tokenBuffer, securityPackage);
} catch (final Win32Exception e) {
this.log.warn("error logging in user: {}", e.getMessage());
this.log.trace("{}", e);
this.sendUnauthorized(response);
return false;
}
this.log.debug("continue required: {}", Boolean.valueOf(securityContext.isContinue()));
final byte[] continueTokenBytes = securityContext.getToken();
if (continueTokenBytes != null && continueTokenBytes.length > 0) {
final String continueToken = BaseEncoding.base64().encode(continueTokenBytes);
this.log.debug("continue token: {}", continueToken);
response.addHeader("WWW-Authenticate", securityPackage + " " + continueToken);
}
if (securityContext.isContinue() || ntlmPost) {
response.setHeader("Connection", "keep-alive");
response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
response.flushBuffer();
return false;
}
} catch (final IOException e) {
this.log.warn("error logging in user: {}", e.getMessage());
this.log.trace("{}", e);
this.sendUnauthorized(response);
return false;
}
// realm: fail if no realm is configured
if (this.context == null || this.context.getRealm() == null) {
this.log.warn("missing context/realm");
this.sendError(response, HttpServletResponse.SC_SERVICE_UNAVAILABLE);
return false;
}
// create and register the user principal with the session
final IWindowsIdentity windowsIdentity = securityContext.getIdentity();
// disable guest login
if (!this.allowGuestLogin && windowsIdentity.isGuest()) {
this.log.warn("guest login disabled: {}", windowsIdentity.getFqn());
this.sendUnauthorized(response);
return false;
}
try {
this.log.debug("logged in user: {} ({})", windowsIdentity.getFqn(), windowsIdentity.getSidString());
final GenericWindowsPrincipal windowsPrincipal = new GenericWindowsPrincipal(windowsIdentity,
this.context.getRealm(), this.principalFormat, this.roleFormat);
this.log.debug("roles: {}", windowsPrincipal.getRolesString());
principal = windowsPrincipal;
// create a session associated with this request if there's none
final HttpSession session = request.getSession(true);
this.log.debug("session id: {}", session == null ? "null" : session.getId());
// register the authenticated principal
this.register(request, response, principal, securityPackage, principal.getName(), null);
this.log.info("successfully logged in user: {}", principal.getName());
} finally {
windowsIdentity.dispose();
}
return true;
}
this.log.debug("authorization required");
this.sendUnauthorized(response);
return false;
}
}
| epl-1.0 |
LorenzoBettini/xtraitj | xtraitj.performance.tests/xtraitj-gen/xtraitj/example/examples/lifo/CLifo.java | 1111 | package xtraitj.example.examples.lifo;
import java.util.ArrayList;
import java.util.List;
import xtraitj.example.examples.lifo.ILifo;
import xtraitj.example.examples.lifo.TLifo;
import xtraitj.example.examples.lifo.TLifoImpl;
import xtraitj.example.examples.lifo.TNegateIsEmpty;
import xtraitj.example.examples.lifo.TNegateIsEmptyImpl;
@SuppressWarnings("all")
public class CLifo<T extends Object> implements ILifo<T>, TLifo<T>, TNegateIsEmpty {
private List<T> collection = new ArrayList<T>();
public List<T> getCollection() {
return this.collection;
}
public void setCollection(final List<T> collection) {
this.collection = collection;
}
private TLifoImpl<T> _TLifo = new TLifoImpl(this);
public void pop() {
_TLifo._pop();
}
public T top() {
return _TLifo._top();
}
public boolean isEmpty() {
return _TLifo._isEmpty();
}
public void push(final T o) {
_TLifo._push(o);
}
private TNegateIsEmptyImpl _TNegateIsEmpty = new TNegateIsEmptyImpl(this);
public boolean isNotEmpty() {
return _TNegateIsEmpty._isNotEmpty();
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.messaging.runtime/src/com/ibm/ws/sib/processor/impl/corespitrace/CoreSPIBifurcatedConsumerSession.java | 1455 | /*******************************************************************************
* Copyright (c) 2012 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.sib.processor.impl.corespitrace;
import com.ibm.websphere.ras.TraceComponent;
import com.ibm.ejs.ras.TraceNLS;
import com.ibm.ws.sib.processor.SIMPConstants;
import com.ibm.ws.sib.utils.TraceGroups;
import com.ibm.ws.sib.utils.ras.SibTr;
/**
* @author gatfora
*
* Trace class to provide filtering of all Core SPI calls
* made against the BifurcatedConsumerSession interface.
*
* Filtering can be done against
* com.ibm.ws.sib.processor.impl.trace.CoreSPIBifurcatedConsumerSession
*
*/
public class CoreSPIBifurcatedConsumerSession
{
//trace for messages
public static final TraceComponent tc =
SibTr.register(
CoreSPIBifurcatedConsumerSession.class,
TraceGroups.TRGRP_PROCESSOR,
SIMPConstants.TRACE_MESSAGE_RESOURCE_BUNDLE);
// NLS for component
public static final TraceNLS nls =
TraceNLS.getTraceNLS(SIMPConstants.TRACE_MESSAGE_RESOURCE_BUNDLE);
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.app.manager.ejb/src/com/ibm/ws/app/manager/ejb/internal/EJBDeployedAppInfoFactoryImpl.java | 1792 | /*******************************************************************************
* Copyright (c) 2012 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.app.manager.ejb.internal;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
import com.ibm.ws.app.manager.module.DeployedAppInfo;
import com.ibm.ws.app.manager.module.DeployedAppInfoFactory;
import com.ibm.ws.app.manager.module.DeployedAppServices;
import com.ibm.ws.app.manager.module.internal.ModuleHandler;
import com.ibm.wsspi.adaptable.module.UnableToAdaptException;
import com.ibm.wsspi.application.handler.ApplicationInformation;
@Component(service = DeployedAppInfoFactory.class,
property = { "service.vendor=IBM", "type:String=ejb" })
public class EJBDeployedAppInfoFactoryImpl implements DeployedAppInfoFactory {
@Reference
protected DeployedAppServices deployedAppServices;
@Reference(target = "(type=ejb)")
protected ModuleHandler ejbModuleHandler;
@Override
public DeployedAppInfo createDeployedAppInfo(ApplicationInformation<DeployedAppInfo> applicationInformation) throws UnableToAdaptException {
EJBDeployedAppInfo deployedApp = new EJBDeployedAppInfo(applicationInformation, deployedAppServices, ejbModuleHandler);
applicationInformation.setHandlerInfo(deployedApp);
return deployedApp;
}
} | epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jca_fat_enterpriseApp/test-resourceadapters/enterpriseAppRA/src/com/ibm/test/jca/loginmodra/LMLoginModule.java | 2942 | /*******************************************************************************
* Copyright (c) 2020 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.test.jca.loginmodra;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Map;
import javax.resource.spi.security.PasswordCredential;
import javax.security.auth.Subject;
import javax.security.auth.callback.Callback;
import javax.security.auth.callback.CallbackHandler;
import javax.security.auth.login.LoginException;
import javax.security.auth.spi.LoginModule;
import com.ibm.wsspi.security.auth.callback.WSManagedConnectionFactoryCallback;
import com.ibm.wsspi.security.auth.callback.WSMappingPropertiesCallback;
/**
* This login module always assigns the same user/password, which tests can check for.
*/
public class LMLoginModule implements LoginModule {
private CallbackHandler callbackHandler;
private Subject subject;
@Override
public void initialize(Subject subject, CallbackHandler callbackHandler, Map<String, ?> sharedState, Map<String, ?> options) {
this.callbackHandler = callbackHandler;
this.subject = subject;
}
@Override
public boolean login() throws LoginException {
try {
final WSManagedConnectionFactoryCallback mcfCallback = new WSManagedConnectionFactoryCallback("Target ManagedConnectionFactory: ");
WSMappingPropertiesCallback mpropsCallback = new WSMappingPropertiesCallback("Mapping Properties (HashMap): ");
callbackHandler.handle(new Callback[] { mcfCallback, mpropsCallback });
AccessController.doPrivileged(new PrivilegedAction<Void>() {
@Override
public Void run() {
PasswordCredential passwordCredential = new PasswordCredential("lmuser", "lmpwd".toCharArray());
passwordCredential.setManagedConnectionFactory(mcfCallback.getManagedConnectionFacotry());
subject.getPrivateCredentials().add(passwordCredential);
return null;
}
});
} catch (Exception x) {
throw (LoginException) new LoginException(x.getMessage()).initCause(x);
}
return true;
}
@Override
public boolean abort() throws LoginException {
return true;
}
@Override
public boolean commit() throws LoginException {
return true;
}
@Override
public boolean logout() throws LoginException {
return true;
}
}
| epl-1.0 |
ibm-messaging/mq-mqsc-editor-plugin | com.ibm.mq.explorer.ms0s.mqsceditor/src/com/ibm/mq/explorer/ms0s/mqsceditor/events/IMQSCCommandEventNotifier.java | 985 | /*******************************************************************************
* Copyright (c) 2007,2014 IBM Corporation and other Contributors.
*
* 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:
* Jeff Lowrey - Initial Contribution
*******************************************************************************/
package com.ibm.mq.explorer.ms0s.mqsceditor.events;
/**
* @author Jeff Lowrey
*/
/**
* <p>
* This defines an interface that allows document parsers to send
* MQSC Command events as they find each part of the document.
*
**/
public interface IMQSCCommandEventNotifier {
public void fireMQSCEventFound(MQSCCommandEvent eventFound);
public void addCommandEventListener (IMQSCCommandEventListener listener, boolean registerLocal);
}
| epl-1.0 |
MikeJMajor/openhab2-addons-dlinksmarthome | bundles/org.openhab.binding.somfytahoma/src/main/java/org/openhab/binding/somfytahoma/internal/handler/SomfyTahomaThermostatHandler.java | 1487 | /**
* 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.somfytahoma.internal.handler;
import static org.openhab.binding.somfytahoma.internal.SomfyTahomaBindingConstants.*;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.thing.Thing;
/**
* The {@link SomfyTahomaThermostatHandler} is responsible for handling commands,
* which are sent to one of the channels of the Somfy thermostat thing.
*
* @author Ondrej Pecta - Initial contribution
*/
@NonNullByDefault
public class SomfyTahomaThermostatHandler extends SomfyTahomaBaseThingHandler {
public SomfyTahomaThermostatHandler(Thing thing) {
super(thing);
stateNames.put(TARGET_TEMPERATURE, TARGET_TEMPERATURE_STATE);
stateNames.put(BATTERY_LEVEL, BATTERY_LEVEL_STATE);
stateNames.put(HEATING_MODE, "somfythermostat:HeatingModeState");
stateNames.put(DEROGATION_HEATING_MODE, "somfythermostat:DerogationHeatingModeState");
stateNames.put(DEROGATION_ACTIVATION, "core:DerogationActivationState");
stateNames.put(DEROGATED_TARGET_TEMPERATURE, "core:DerogatedTargetTemperatureState");
}
}
| epl-1.0 |
paulianttila/openhab2 | bundles/org.openhab.binding.velbus/src/main/java/org/openhab/binding/velbus/internal/packets/VelbusThermostatOperatingModePacket.java | 1120 | /**
* 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.velbus.internal.packets;
import org.eclipse.jdt.annotation.NonNullByDefault;
/**
* The {@link VelbusThermostatOperatingModePacket} represents a Velbus packet that can be used to
* set the operating mode (heating/cooling) of the given Velbus thermostat module.
*
* @author Cedric Boon - Initial contribution
*/
@NonNullByDefault
public class VelbusThermostatOperatingModePacket extends VelbusPacket {
private byte commandByte;
public VelbusThermostatOperatingModePacket(byte address, byte commandByte) {
super(address, PRIO_LOW);
this.commandByte = commandByte;
}
@Override
protected byte[] getDataBytes() {
return new byte[] { commandByte, 0x00 };
}
}
| epl-1.0 |
inocybe/odl-bgpcep | rsvp/impl/src/main/java/org/opendaylight/protocol/rsvp/parser/impl/te/SecondaryRecordRouteObjectParser.java | 2240 | /*
* Copyright (c) 2015 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.rsvp.parser.impl.te;
import com.google.common.base.Preconditions;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import org.opendaylight.protocol.rsvp.parser.spi.RROSubobjectRegistry;
import org.opendaylight.protocol.rsvp.parser.spi.RSVPParsingException;
import org.opendaylight.protocol.rsvp.parser.spi.subobjects.RROSubobjectListParser;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.RsvpTeObject;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.secondary.record.route.object.SecondaryRecordRouteObject;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.rsvp.rev150820.secondary.record.route.object.SecondaryRecordRouteObjectBuilder;
public final class SecondaryRecordRouteObjectParser extends RROSubobjectListParser {
public static final short CLASS_NUM = 201;
public static final short CTYPE = 1;
public SecondaryRecordRouteObjectParser(RROSubobjectRegistry subobjReg) {
super(subobjReg);
}
@Override
protected RsvpTeObject localParseObject(final ByteBuf byteBuf) throws RSVPParsingException {
final SecondaryRecordRouteObjectBuilder srro = new SecondaryRecordRouteObjectBuilder();
return srro.setSubobjectContainer(parseList(byteBuf)).build();
}
@Override
public void localSerializeObject(final RsvpTeObject teLspObject, final ByteBuf output) {
Preconditions.checkArgument(teLspObject instanceof SecondaryRecordRouteObject, "RecordRouteObject is mandatory.");
final SecondaryRecordRouteObject srro = (SecondaryRecordRouteObject) teLspObject;
final ByteBuf bufferAux = Unpooled.buffer();
serializeList(srro.getSubobjectContainer(), bufferAux);
serializeAttributeHeader(bufferAux.readableBytes(), CLASS_NUM, CTYPE, output);
output.writeBytes(bufferAux);
}
}
| epl-1.0 |
sebmarchand/openhab2-addons | addons/binding/org.openhab.binding.jeelink/src/main/java/org/openhab/binding/jeelink/internal/JeeLinkHandler.java | 5519 | /**
* Copyright (c) 2010-2018 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.jeelink.internal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import org.eclipse.smarthome.core.thing.Bridge;
import org.eclipse.smarthome.core.thing.ChannelUID;
import org.eclipse.smarthome.core.thing.ThingStatus;
import org.eclipse.smarthome.core.thing.ThingStatusDetail;
import org.eclipse.smarthome.core.thing.binding.BaseBridgeHandler;
import org.eclipse.smarthome.core.thing.binding.BridgeHandler;
import org.eclipse.smarthome.core.types.Command;
import org.openhab.binding.jeelink.internal.config.JeeLinkConfig;
import org.openhab.binding.jeelink.internal.connection.AbstractJeeLinkConnection;
import org.openhab.binding.jeelink.internal.connection.ConnectionListener;
import org.openhab.binding.jeelink.internal.connection.JeeLinkConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Handler for a JeeLink USB Receiver thing.
*
* @author Volker Bier - Initial contribution
*/
public class JeeLinkHandler extends BaseBridgeHandler implements BridgeHandler, ConnectionListener {
private final Logger logger = LoggerFactory.getLogger(JeeLinkHandler.class);
private JeeLinkConnection connection;
private Map<String, JeeLinkReadingConverter> converters = new HashMap<>();
private Map<JeeLinkReadingConverter, List<ReadingHandler>> convSensorMap = new HashMap<>();
private AtomicBoolean connectionInitialized = new AtomicBoolean(false);
private ScheduledFuture<?> connectJob;
public JeeLinkHandler(Bridge bridge) {
super(bridge);
}
@Override
public void initialize() {
JeeLinkConfig cfg = getConfig().as(JeeLinkConfig.class);
try {
for (JeeLinkReadingConverter c : SensorDefinition.createConverters(this)) {
converters.put(c.getSketchName(), c);
}
connection = AbstractJeeLinkConnection.createFor(cfg, scheduler, this);
connection.openConnection();
} catch (java.net.ConnectException e) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.CONFIGURATION_ERROR, e.getMessage());
}
}
@Override
public void connectionOpened() {
updateStatus(ThingStatus.ONLINE);
}
@Override
public void connectionAborted(String cause) {
updateStatus(ThingStatus.OFFLINE, ThingStatusDetail.COMMUNICATION_ERROR, cause);
connectJob = scheduler.schedule(() -> {
connection.openConnection();
}, 10, TimeUnit.SECONDS);
logger.debug("Connection to port {} aborted ({}). Reconnect scheduled.", connection.getPort(), cause);
connectionInitialized.set(false);
}
public void addReadingHandler(ReadingHandler h) {
synchronized (convSensorMap) {
JeeLinkReadingConverter c = converters.get(h.getSketchName());
List<ReadingHandler> handlers = convSensorMap.get(c);
if (handlers == null) {
handlers = new ArrayList<>();
convSensorMap.put(c, handlers);
}
if (!handlers.contains(h)) {
handlers.add(h);
}
}
}
public void removeReadingHandler(ReadingHandler h) {
synchronized (convSensorMap) {
JeeLinkReadingConverter c = converters.get(h.getSketchName());
List<ReadingHandler> handlers = convSensorMap.get(c);
if (handlers != null) {
handlers.remove(h);
if (handlers.isEmpty()) {
convSensorMap.remove(c);
}
}
}
}
@Override
public void handleCommand(ChannelUID channelUid, Command command) {
}
@Override
public void handleInput(String input) {
synchronized (convSensorMap) {
for (JeeLinkReadingConverter c : convSensorMap.keySet()) {
Reading r = c.createReading(input);
if (r != null) {
if (!connectionInitialized.getAndSet(true)) {
JeeLinkConfig cfg = getConfig().as(JeeLinkConfig.class);
String initCommands = cfg.initCommands;
if (initCommands != null && !initCommands.trim().isEmpty()) {
logger.debug("Sending init commands for port {}: {}", connection.getPort(), initCommands);
connection.sendInitCommands(initCommands);
}
}
for (ReadingHandler h : convSensorMap.get(c)) {
h.handleReading(r);
}
}
}
}
}
@Override
public void dispose() {
if (connectJob != null) {
connectJob.cancel(true);
connectJob = null;
}
if (connection != null) {
connection.closeConnection();
}
connectionInitialized.set(false);
SensorDefinition.disposeConverters(this);
super.dispose();
}
}
| epl-1.0 |
akurtakov/Pydev | plugins/org.python.pydev/src_navigator/org/python/pydev/navigator/actions/PyDeleteResourceAction.java | 4217 | /**
* Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package org.python.pydev.navigator.actions;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.ISelectionProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.actions.DeleteResourceAction;
import org.python.pydev.ast.codecompletion.revisited.PythonPathHelper;
/**
* Overriden org.eclipse.ui.actions.DeleteResourceAction
*
* with the following changes:
* - isEnabled overriden to compute the changes accordingly
* - in the run we update the selection correctly (by calling isEnabled), because this was not synched correctly in the
* eclipse version (because there could be a delay there).
*
* @author Fabio
*/
public class PyDeleteResourceAction extends DeleteResourceAction {
private ISelectionProvider provider;
private List<IResource> selected;
private List<IFolder> remFolders;
public PyDeleteResourceAction(Shell shell, ISelectionProvider selectionProvider) {
super(shell);
this.provider = selectionProvider;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jface.action.Action#isEnabled()
*/
@Override
public boolean isEnabled() {
fillSelection();
return selected != null && selected.size() > 0;
}
private boolean fillSelection() {
selected = new ArrayList<IResource>();
ISelection selection = provider.getSelection();
if (!selection.isEmpty()) {
IStructuredSelection sSelection = (IStructuredSelection) selection;
if (sSelection.size() >= 1) {
Iterator iterator = sSelection.iterator();
while (iterator.hasNext()) {
Object element = iterator.next();
if (element instanceof IAdaptable) {
IAdaptable adaptable = (IAdaptable) element;
IResource resource = (IResource) adaptable.getAdapter(IResource.class);
if (resource != null) {
selected.add(resource);
continue;
}
}
// one of the elements did not satisfy the condition
selected = null;
return false;
}
}
}
return true;
}
/**
* Update the PYTHONPATH of projects that have had source folders removed from them by
* removing the folders' paths from it.
*/
private void updatePyPath() {
// Quit if no source folder was deleted.
if (remFolders.size() == 0 || remFolders.get(0).exists()) {
return;
}
PythonPathHelper.updatePyPath(remFolders.toArray(new IResource[0]), null,
PythonPathHelper.OPERATION_DELETE);
}
@Override
protected List<IResource> getSelectedResources() {
return selected;
}
@Override
public IStructuredSelection getStructuredSelection() {
return new StructuredSelection(selected);
}
/*
* (non-Javadoc) Method declared on IAction.
*/
@Override
public void run() {
if (!fillSelection()) { //will also update the list of resources (main change from the DeleteResourceAction)
return;
}
Helpers.checkValidateState();
remFolders = new ArrayList<IFolder>();
for (IResource folder : selected) {
if (folder instanceof IFolder) {
remFolders.add((IFolder) folder);
}
}
super.run();
updatePyPath();
remFolders.clear();
}
} | epl-1.0 |
CodeOffloading/JikesRVM-CCO | jikesrvm-3.1.3/MMTk/harness/src/org/mmtk/harness/lang/runtime/AllocationSite.java | 2474 | /*
* This file is part of the Jikes RVM project (http://jikesrvm.org).
*
* This file is licensed to You under the Eclipse Public License (EPL);
* You may not use this file except in compliance with the License. You
* may obtain a copy of the License at
*
* http://www.opensource.org/licenses/eclipse-1.0.php
*
* See the COPYRIGHT.txt file distributed with this work for information
* regarding copyright ownership.
*/
package org.mmtk.harness.lang.runtime;
import java.util.ArrayList;
import org.mmtk.harness.lang.parser.Token;
/**
* Information about allocation sites in a script. Used when debugging to
* identify objects.
*/
public class AllocationSite {
/**
* The global collection of allocation sites.
*/
private static final ArrayList<AllocationSite> sites = new ArrayList<AllocationSite>();
/**
* Retrieve an allocation site by ID.
* @param id Allocation site ID
* @return The corresponding site
*/
public static AllocationSite getSite(int id) {
return sites.get(id);
}
/**
* A pre-created allocation site for internal object allocation
*/
public static final AllocationSite INTERNAL_SITE = new AllocationSite(0,0);
/**
* The ID of the internal site
*/
public static final int INTERNAL_SITE_ID = INTERNAL_SITE.getId();
/**
* @param id A potential allocation site
* @return {@code true} if id is a valid site id
*/
public static boolean isValid(int id) {
synchronized (sites) {
return id >= 0 && id < sites.size();
}
}
private final int id;
private final int column;
private final int line;
/**
* Create an allocation site for a given source code line/column.
* @param line Source code line
* @param column Source code column
*/
public AllocationSite(int line, int column) {
synchronized (sites) {
this.id = sites.size();
sites.add(this);
}
this.line = line;
this.column = column;
}
/**
* An anonymous allocation site
*/
public AllocationSite() {
this(0,0);
}
/**
* An allocation site for a given script token.
* @param token A parser token
*/
public AllocationSite(Token token) {
this(token.beginLine,token.beginColumn);
}
@Override
public String toString() {
return String.format("%d:%d", line, column);
}
public int getId() {
return id;
}
public int getColumn() {
return column;
}
public int getLine() {
return line;
}
}
| epl-1.0 |
kgibm/open-liberty | dev/com.ibm.ws.app.manager.springboot/src/com/ibm/ws/app/manager/springboot/internal/SpringBootRuntimeContainer.java | 7911 | /*******************************************************************************
* Copyright (c) 2018, 2020 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.app.manager.springboot.internal;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.ConfigurationPolicy;
import org.osgi.service.component.annotations.Reference;
import com.ibm.websphere.csi.J2EEName;
import com.ibm.websphere.ras.Tr;
import com.ibm.websphere.ras.TraceComponent;
import com.ibm.ws.app.manager.springboot.container.ApplicationError;
import com.ibm.ws.container.service.app.deploy.extended.ExtendedApplicationInfo;
import com.ibm.ws.container.service.app.deploy.extended.ExtendedModuleInfo;
import com.ibm.ws.container.service.app.deploy.extended.ModuleRuntimeContainer;
import com.ibm.ws.container.service.metadata.MetaDataException;
import com.ibm.ws.container.service.state.StateChangeException;
import com.ibm.ws.kernel.LibertyProcess;
import com.ibm.ws.runtime.metadata.ApplicationMetaData;
import com.ibm.ws.runtime.metadata.ComponentMetaData;
import com.ibm.ws.runtime.metadata.MetaDataImpl;
import com.ibm.ws.runtime.metadata.ModuleMetaData;
import com.ibm.ws.threading.FutureMonitor;
@Component(configurationPolicy = ConfigurationPolicy.IGNORE, property = { "service.vendor=IBM", "type:String=spring" })
public class SpringBootRuntimeContainer implements ModuleRuntimeContainer {
private static final TraceComponent tc = Tr.register(SpringBootRuntimeContainer.class);
static class SpringModuleMetaData extends MetaDataImpl implements ModuleMetaData {
private final SpringBootModuleInfo moduleInfo;
/**
* @param slotCnt
*/
public SpringModuleMetaData(SpringBootModuleInfo moduleInfo) {
super(0);
this.moduleInfo = moduleInfo;
}
@Override
public String getName() {
return moduleInfo.getName();
}
@Override
public ApplicationMetaData getApplicationMetaData() {
return ((ExtendedApplicationInfo) moduleInfo.getApplicationInfo()).getMetaData();
}
@Override
public ComponentMetaData[] getComponentMetaDatas() {
return null;
}
@Override
public J2EEName getJ2EEName() {
return ((ExtendedApplicationInfo) moduleInfo.getApplicationInfo()).getMetaData().getJ2EEName();
}
}
@Reference
private ExecutorService executor;
@Reference
private FutureMonitor futureMonitor;
@Reference
private LibertyProcess libertyProcess;
@Override
public ModuleMetaData createModuleMetaData(ExtendedModuleInfo moduleInfo) throws MetaDataException {
return new SpringModuleMetaData((SpringBootModuleInfo) moduleInfo);
}
@Override
public Future<Boolean> startModule(ExtendedModuleInfo moduleInfo) throws StateChangeException {
SpringBootModuleInfo springBootModuleInfo = (SpringBootModuleInfo) moduleInfo;
Future<Boolean> result = futureMonitor.createFuture(Boolean.class);
invokeSpringMain(result, springBootModuleInfo);
return result;
}
private void invokeSpringMain(Future<Boolean> mainInvokeResult, SpringBootModuleInfo springBootModuleInfo) {
final SpringBootApplicationImpl springBootApplication = springBootModuleInfo.getSpringBootApplication();
final Method main;
ClassLoader newTccl = springBootModuleInfo.getThreadContextClassLoader();
ClassLoader previousTccl = AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> Thread.currentThread().getContextClassLoader());
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
Thread.currentThread().setContextClassLoader(newTccl);
return null;
});
try {
springBootApplication.registerSpringConfigFactory();
Class<?> springApplicationClass = springBootModuleInfo.getClassLoader().loadClass(springBootApplication.getSpringBootManifest().getSpringStartClass());
main = springApplicationClass.getMethod("main", String[].class);
// TODO not sure Spring Boot supports non-private main methods
main.setAccessible(true);
} catch (ClassNotFoundException | NoSuchMethodException e) {
futureMonitor.setResult(mainInvokeResult, e);
return;
} finally {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
Thread.currentThread().setContextClassLoader(previousTccl);
return null;
});
}
// Execute the main method asynchronously.
// The mainInvokeResult is tracked to monitor completion
executor.execute(() -> {
ClassLoader execPreviousTccl = AccessController.doPrivileged((PrivilegedAction<ClassLoader>) () -> Thread.currentThread().getContextClassLoader());
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
Thread.currentThread().setContextClassLoader(newTccl);
return null;
});
try {
// get the application args to pass from the springBootApplication
String[] appArgs = libertyProcess.getArgs();
if (appArgs.length == 0) {
appArgs = springBootApplication.getAppArgs().toArray(new String[0]);
}
main.invoke(null, new Object[] { appArgs });
springBootApplication.getApplicationReadyLatch().countDown();
futureMonitor.setResult(mainInvokeResult, true);
} catch (InvocationTargetException e) {
Throwable target = e.getTargetException();
String msgKey = null;
if (target instanceof ApplicationError) {
msgKey = ((ApplicationError) target).getType().getMessageKey();
Tr.error(tc, msgKey);
futureMonitor.setResult(mainInvokeResult, target);
} else {
futureMonitor.setResult(mainInvokeResult, e.getTargetException());
}
} catch (IllegalAccessException | IllegalArgumentException e) {
// Auto FFDC here this should not happen
futureMonitor.setResult(mainInvokeResult, e);
} finally {
AccessController.doPrivileged((PrivilegedAction<Void>) () -> {
Thread.currentThread().setContextClassLoader(execPreviousTccl);
return null;
});
}
});
}
/*
* (non-Javadoc)
*
* @see com.ibm.ws.container.service.app.deploy.extended.ModuleRuntimeContainer#stopModule(com.ibm.ws.container.service.app.deploy.extended.ExtendedModuleInfo)
*/
@Override
public void stopModule(ExtendedModuleInfo moduleInfo) {
SpringBootModuleInfo springBootModuleInfo = (SpringBootModuleInfo) moduleInfo;
springBootModuleInfo.getSpringBootApplication().unregisterSpringConfigFactory();
springBootModuleInfo.getSpringBootApplication().callShutdownHooks();
springBootModuleInfo.destroyThreadContextClassLoader();
}
}
| epl-1.0 |
trylimits/Eclipse-Postfix-Code-Completion | luna/org.eclipse.jdt.core/antadapter/org/eclipse/jdt/core/CheckDebugAttributes.java | 3823 | /*******************************************************************************
* Copyright (c) 2000, 2013 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.jdt.core;
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.eclipse.jdt.core.util.IClassFileReader;
import org.eclipse.jdt.core.util.ICodeAttribute;
import org.eclipse.jdt.core.util.IMethodInfo;
import org.eclipse.jdt.internal.antadapter.AntAdapterMessages;
/**
* <p>An Ant task to find out if a class file or a jar contains debug attributes. If this is the case,
* the property contains the value "has debug" after the call.
* </p>
* <p>
* <code><eclipse.checkDebugAttributes property="hasDebug" file="${basedir}/bin/p/A.class"/></code>
* </p>
* <p>
* For more information on Ant check out the website at http://jakarta.apache.org/ant/ .
* </p>
*
* This is not intended to be subclassed by users.
* @since 2.0
*/
@SuppressWarnings("rawtypes")
public final class CheckDebugAttributes extends Task {
private String file;
private String property;
public void execute() throws BuildException {
if (this.file == null) {
throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.cannot.be.null")); //$NON-NLS-1$
}
if (this.property == null) {
throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.property.argument.cannot.be.null")); //$NON-NLS-1$
}
try {
boolean hasDebugAttributes = false;
if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(this.file)) {
IClassFileReader classFileReader = ToolFactory.createDefaultClassFileReader(this.file, IClassFileReader.ALL);
hasDebugAttributes = checkClassFile(classFileReader);
} else {
ZipFile jarFile = null;
try {
jarFile = new ZipFile(this.file);
} catch (ZipException e) {
throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.file.argument.must.be.a.classfile.or.a.jarfile")); //$NON-NLS-1$
}
for (Enumeration entries = jarFile.entries(); !hasDebugAttributes && entries.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) entries.nextElement();
if (org.eclipse.jdt.internal.compiler.util.Util.isClassFileName(entry.getName())) {
IClassFileReader classFileReader = ToolFactory.createDefaultClassFileReader(this.file, entry.getName(), IClassFileReader.ALL);
hasDebugAttributes = checkClassFile(classFileReader);
}
}
}
if (hasDebugAttributes) {
getProject().setUserProperty(this.property, "has debug"); //$NON-NLS-1$
}
} catch (IOException e) {
throw new BuildException(AntAdapterMessages.getString("checkDebugAttributes.ioexception.occured") + this.file); //$NON-NLS-1$
}
}
private boolean checkClassFile(IClassFileReader classFileReader) {
IMethodInfo[] methodInfos = classFileReader.getMethodInfos();
for (int i = 0, max = methodInfos.length; i < max; i++) {
ICodeAttribute codeAttribute = methodInfos[i].getCodeAttribute();
if (codeAttribute != null && codeAttribute.getLineNumberAttribute() != null) {
return true;
}
}
return false;
}
public void setFile(String value) {
this.file = value;
}
public void setProperty(String value) {
this.property = value;
}
}
| epl-1.0 |
sudaraka94/che | plugins/plugin-languageserver/che-plugin-languageserver-ide/src/test/java/org/eclipse/che/plugin/languageserver/ide/editor/codeassist/CompletionItemBasedCompletionProposalTest.java | 7968 | /*
* Copyright (c) 2012-2017 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.plugin.languageserver.ide.editor.codeassist;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.when;
import com.google.gwtmockito.GwtMockitoTestRunner;
import java.util.Collections;
import org.eclipse.che.api.languageserver.shared.model.ExtendedCompletionItem;
import org.eclipse.che.ide.api.editor.codeassist.Completion;
import org.eclipse.che.ide.api.editor.document.Document;
import org.eclipse.che.ide.api.editor.text.LinearRange;
import org.eclipse.che.ide.api.icon.Icon;
import org.eclipse.che.plugin.languageserver.ide.LanguageServerResources;
import org.eclipse.che.plugin.languageserver.ide.service.TextDocumentServiceClient;
import org.eclipse.lsp4j.CompletionItem;
import org.eclipse.lsp4j.CompletionOptions;
import org.eclipse.lsp4j.Position;
import org.eclipse.lsp4j.Range;
import org.eclipse.lsp4j.ServerCapabilities;
import org.eclipse.lsp4j.TextEdit;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
/** */
@RunWith(GwtMockitoTestRunner.class)
public class CompletionItemBasedCompletionProposalTest {
@Mock private TextDocumentServiceClient documentServiceClient;
@Mock private LanguageServerResources resources;
@Mock private Icon icon;
@Mock private ServerCapabilities serverCapabilities;
@Mock private ExtendedCompletionItem completionItem;
@Mock private CompletionOptions completionOptions;
@Mock private Document document;
@Mock private CompletionItem completion;
private CompletionItemBasedCompletionProposal proposal;
@Before
public void setUp() throws Exception {
proposal =
new CompletionItemBasedCompletionProposal(
completionItem,
"",
documentServiceClient,
resources,
icon,
serverCapabilities,
Collections.emptyList(),
0);
when(completionItem.getItem()).thenReturn(completion);
}
@Test
public void shouldReturnNotNullCompletion() throws Exception {
when(serverCapabilities.getCompletionProvider()).thenReturn(completionOptions);
when(completionOptions.getResolveProvider()).thenReturn(false);
Completion[] completions = new Completion[1];
proposal.getCompletion(completion -> completions[0] = completion);
assertNotNull(completions[0]);
}
@Test
public void shouldUseInsertText() throws Exception {
when(serverCapabilities.getCompletionProvider()).thenReturn(completionOptions);
when(completionOptions.getResolveProvider()).thenReturn(false);
when(document.getCursorOffset()).thenReturn(5);
when(completion.getInsertText()).thenReturn("foo");
Completion[] completions = new Completion[1];
proposal.getCompletion(completion -> completions[0] = completion);
completions[0].apply(document);
verify(document).getCursorOffset();
verify(document, times(1)).replace(eq(5), eq(0), eq("foo"));
verifyNoMoreInteractions(document);
}
@Test
public void shouldUseLabelIfInsertTextIsNull() throws Exception {
when(serverCapabilities.getCompletionProvider()).thenReturn(completionOptions);
when(completionOptions.getResolveProvider()).thenReturn(false);
when(document.getCursorOffset()).thenReturn(5);
when(completion.getInsertText()).thenReturn(null);
when(completion.getLabel()).thenReturn("bar");
Completion[] completions = new Completion[1];
proposal.getCompletion(completion -> completions[0] = completion);
completions[0].apply(document);
verify(document).getCursorOffset();
verify(document, times(1)).replace(eq(5), eq(0), eq("bar"));
verifyNoMoreInteractions(document);
}
@Test
public void shouldUseTextEditFirst() throws Exception {
TextEdit textEdit = mock(TextEdit.class);
Range range = mock(Range.class);
Position startPosition = mock(Position.class);
Position endPosition = mock(Position.class);
when(serverCapabilities.getCompletionProvider()).thenReturn(completionOptions);
when(completionOptions.getResolveProvider()).thenReturn(false);
when(document.getCursorOffset()).thenReturn(5);
when(completion.getInsertText()).thenReturn("foo");
when(completion.getLabel()).thenReturn("bar");
when(completion.getTextEdit()).thenReturn(textEdit);
when(textEdit.getRange()).thenReturn(range);
when(textEdit.getNewText()).thenReturn("fooBar");
when(range.getStart()).thenReturn(startPosition);
when(range.getEnd()).thenReturn(endPosition);
when(startPosition.getLine()).thenReturn(1);
when(startPosition.getCharacter()).thenReturn(5);
when(endPosition.getLine()).thenReturn(1);
when(endPosition.getCharacter()).thenReturn(5);
when(document.getIndexFromPosition(any())).thenReturn(5);
Completion[] completions = new Completion[1];
proposal.getCompletion(completion -> completions[0] = completion);
completions[0].apply(document);
verify(document, times(2)).getIndexFromPosition(any());
verify(document, times(1)).replace(eq(5), eq(0), eq("fooBar"));
verifyNoMoreInteractions(document);
}
@Test
public void shouldPlaceCursorInRightPositionWithTextEdit() throws Exception {
TextEdit textEdit = mock(TextEdit.class);
Range range = mock(Range.class);
Position startPosition = mock(Position.class);
Position endPosition = mock(Position.class);
when(serverCapabilities.getCompletionProvider()).thenReturn(completionOptions);
when(completionOptions.getResolveProvider()).thenReturn(false);
when(document.getCursorOffset()).thenReturn(5);
when(completion.getInsertText()).thenReturn("foo");
when(completion.getLabel()).thenReturn("bar");
when(completion.getTextEdit()).thenReturn(textEdit);
when(textEdit.getRange()).thenReturn(range);
when(textEdit.getNewText()).thenReturn("fooBar");
when(range.getStart()).thenReturn(startPosition);
when(range.getEnd()).thenReturn(endPosition);
when(startPosition.getLine()).thenReturn(1);
when(startPosition.getCharacter()).thenReturn(5);
when(endPosition.getLine()).thenReturn(1);
when(endPosition.getCharacter()).thenReturn(5);
when(document.getIndexFromPosition(any())).thenReturn(5);
Completion[] completions = new Completion[1];
proposal.getCompletion(completion -> completions[0] = completion);
completions[0].apply(document);
LinearRange selection = completions[0].getSelection(document);
assertEquals(11, selection.getStartOffset());
assertEquals(0, selection.getLength());
}
@Test
public void shouldPlaceCursorInRightPositionWithInsertedText() throws Exception {
when(serverCapabilities.getCompletionProvider()).thenReturn(completionOptions);
when(completionOptions.getResolveProvider()).thenReturn(false);
when(document.getCursorOffset()).thenReturn(5);
when(completion.getInsertText()).thenReturn("foo");
when(document.getIndexFromPosition(any())).thenReturn(5);
Completion[] completions = new Completion[1];
proposal.getCompletion(completion -> completions[0] = completion);
completions[0].apply(document);
LinearRange selection = completions[0].getSelection(document);
assertEquals(8, selection.getStartOffset());
assertEquals(0, selection.getLength());
}
}
| epl-1.0 |
ESSICS/org.csstudio.display.builder | org.csstudio.display.builder.model/src/org/csstudio/display/builder/model/widgets/SlideButtonWidget.java | 7198 | /**
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
* Copyright (C) 2016 European Spallation Source ERIC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.csstudio.display.builder.model.widgets;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.newBooleanPropertyDescriptor;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.newStringPropertyDescriptor;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propBit;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propConfirmDialogOptions;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propConfirmMessage;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propEnabled;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propFont;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propForegroundColor;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propOffColor;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propOnColor;
import static org.csstudio.display.builder.model.properties.CommonWidgetProperties.propPassword;
import java.util.Arrays;
import java.util.List;
import org.csstudio.display.builder.model.Messages;
import org.csstudio.display.builder.model.Widget;
import org.csstudio.display.builder.model.WidgetCategory;
import org.csstudio.display.builder.model.WidgetDescriptor;
import org.csstudio.display.builder.model.WidgetProperty;
import org.csstudio.display.builder.model.WidgetPropertyCategory;
import org.csstudio.display.builder.model.WidgetPropertyDescriptor;
import org.csstudio.display.builder.model.persist.NamedWidgetColors;
import org.csstudio.display.builder.model.persist.NamedWidgetFonts;
import org.csstudio.display.builder.model.persist.WidgetColorService;
import org.csstudio.display.builder.model.persist.WidgetFontService;
import org.csstudio.display.builder.model.properties.ConfirmDialog;
import org.csstudio.display.builder.model.properties.WidgetColor;
import org.csstudio.display.builder.model.properties.WidgetFont;
/**
* Widget that provides button for making a binary change.
*
* @author claudiorosati, European Spallation Source ERIC
* @version 1.0.0 21 Aug 2018
*/
public class SlideButtonWidget extends WritablePVWidget {
/**
* Widget descriptor
*/
public static final WidgetDescriptor WIDGET_DESCRIPTOR =
new WidgetDescriptor("slide_button", WidgetCategory.CONTROL,
"Slide Button",
"platform:/plugin/org.csstudio.display.builder.model/icons/slide_button.png",
"Slide button that can toggle one bit of a PV value between 1 and 0",
Arrays.asList("org.csstudio.opibuilder.widgets.BoolSwitch"))
{
@Override
public Widget createWidget ( ) {
return new SlideButtonWidget();
}
};
public static final WidgetPropertyDescriptor<String> propLabel = newStringPropertyDescriptor (WidgetPropertyCategory.WIDGET, "label", Messages.SlideButton_Label);
public static final WidgetPropertyDescriptor<Boolean> propAutoSize = newBooleanPropertyDescriptor(WidgetPropertyCategory.DISPLAY, "auto_size", Messages.AutoSize);
private volatile WidgetProperty<Boolean> auto_size;
private volatile WidgetProperty<Integer> bit;
private volatile WidgetProperty<ConfirmDialog> confirm_dialog;
private volatile WidgetProperty<String> confirm_message;
private volatile WidgetProperty<Boolean> enabled;
private volatile WidgetProperty<WidgetFont> font;
private volatile WidgetProperty<WidgetColor> foreground;
private volatile WidgetProperty<String> label;
private volatile WidgetProperty<WidgetColor> off_color;
private volatile WidgetProperty<WidgetColor> on_color;
private volatile WidgetProperty<String> password;
public SlideButtonWidget () {
super(WIDGET_DESCRIPTOR.getType(), 100, 30);
}
/**
* @return 'auto_size' property
*/
public WidgetProperty<Boolean> propAutoSize ( ) {
return auto_size;
}
/**
* @return 'bit' property.
*/
public WidgetProperty<Integer> propBit ( ) {
return bit;
}
/**
* @return 'confirm_dialog' property.
*/
public WidgetProperty<ConfirmDialog> propConfirmDialog ( ) {
return confirm_dialog;
}
/**
* @return 'confirm_message' property.
*/
public WidgetProperty<String> propConfirmMessage ( ) {
return confirm_message;
}
/**
* @return 'enabled' property.
*/
public WidgetProperty<Boolean> propEnabled ( ) {
return enabled;
}
/**
* @return 'font' property.
*/
public WidgetProperty<WidgetFont> propFont ( ) {
return font;
}
/**
* @return 'foreground_color' property.
*/
public WidgetProperty<WidgetColor> propForegroundColor ( ) {
return foreground;
}
/**
* @return 'label' property.
*/
public WidgetProperty<String> propLabel ( ) {
return label;
}
/**
* @return 'off_color' property.
*/
public WidgetProperty<WidgetColor> propOffColor ( ) {
return off_color;
}
/**
* @return 'on_color' property.
*/
public WidgetProperty<WidgetColor> propOnColor ( ) {
return on_color;
}
/**
* @return 'password' property.
*/
public WidgetProperty<String> propPassword ( ) {
return password;
}
@Override
protected void defineProperties ( final List<WidgetProperty<?>> properties ) {
super.defineProperties(properties);
properties.add(bit = propBit.createProperty(this, 0));
properties.add(label = propLabel.createProperty(this, Messages.SlideButton_Label));
properties.add(off_color = propOffColor.createProperty(this, WidgetColorService.getColor(NamedWidgetColors.BUTTON_BACKGROUND)));
properties.add(on_color = propOnColor.createProperty(this, WidgetColorService.getColor(NamedWidgetColors.ALARM_OK)));
properties.add(font = propFont.createProperty(this, WidgetFontService.get(NamedWidgetFonts.DEFAULT)));
properties.add(foreground = propForegroundColor.createProperty(this, WidgetColorService.getColor(NamedWidgetColors.TEXT)));
properties.add(auto_size = propAutoSize.createProperty(this, false));
properties.add(enabled = propEnabled.createProperty(this, true));
properties.add(confirm_dialog = propConfirmDialogOptions.createProperty(this, ConfirmDialog.NONE));
properties.add(confirm_message = propConfirmMessage.createProperty(this, "Are your sure you want to do this?"));
properties.add(password = propPassword.createProperty(this, ""));
}
}
| epl-1.0 |
AnthonyHullDiamond/scanning | org.eclipse.scanning.test/src/org/eclipse/scanning/test/event/ScanEventPluginTest.java | 1407 | /*-
*******************************************************************************
* Copyright (c) 2011, 2016 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
*
* Contributors:
* Matthew Gerring - initial API and implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.scanning.test.event;
import org.eclipse.scanning.api.event.IEventService;
import org.junit.Before;
/**
* Scan Event Test but with OSGi container.
* @author Matthew Gerring
*
*/
public class ScanEventPluginTest extends AbstractScanEventTest{
private static IEventService service;
public static IEventService getService() {
return service;
}
public static void setService(IEventService service) {
ScanEventPluginTest.service = service;
}
@Before
public void createServices() throws Exception {
eservice = service;
// We use the long winded constructor because we need to pass in the connector.
// In production we would normally
publisher = eservice.createPublisher(uri, IEventService.SCAN_TOPIC);
subscriber = eservice.createSubscriber(uri, IEventService.SCAN_TOPIC);
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.microprofile.graphql.1.0_fat/test-applications/ignoreApp/src/mpGraphQL10/ignore/GraphQLOperation.java | 1530 | /*******************************************************************************
* Copyright (c) 2019 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package mpGraphQL10.ignore;
public class GraphQLOperation {
private String query;
private String variables;
private String operationName;
public String getQuery() {
return query;
}
public void setQuery(String operation) {
this.query = operation;
}
public String getVariables() {
return variables;
}
public void setVariables(String variables) {
this.variables = variables;
}
public String getOperationName() {
return operationName;
}
public void setOperationName(String operationName) {
this.operationName = operationName;
}
@Override
public String toString() {
return super.toString() + "[" + System.lineSeparator() +
" query=\"" + query + "\", " + System.lineSeparator() +
" operationName=\"" + operationName + "\", " + System.lineSeparator() +
" variables=\"" + variables + "\"]";
}
}
| epl-1.0 |
helylinhe/Test | ps/src/com/linkonworks/df/busi/service/impl/PatiOperateServiceImpl.java | 671 | package com.linkonworks.df.busi.service.impl;
import java.util.List;
import com.linkonworks.df.busi.comment.Page;
import com.linkonworks.df.busi.dao.PatiOperateDao;
import com.linkonworks.df.busi.service.PatiOperateService;
import com.linkonworks.df.vo.PatiOperate;
public class PatiOperateServiceImpl implements PatiOperateService {
private PatiOperateDao patiOperateDao;
@Override
public List<PatiOperate> getPageOper(Page page) {
return patiOperateDao.getPageOper(page);
}
public PatiOperateDao getPatiOperateDao() {
return patiOperateDao;
}
public void setPatiOperateDao(PatiOperateDao patiOperateDao) {
this.patiOperateDao = patiOperateDao;
}
}
| epl-1.0 |
lhein/jbosstools-fuse-extras | jboss-fuse-sap-tool-suite/tests/org.fusesource.ide.sap.ui.tests.integration/src/main/java/org/fusesource/ide/sap/ui/tests/integration/util/FuseProject.java | 1988 | /*******************************************************************************
* Copyright (c) 2016 Red Hat, Inc.
* Distributed under license by Red Hat, Inc. All rights reserved.
* This program is 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.fusesource.ide.sap.ui.tests.integration.util;
import java.io.ByteArrayInputStream;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.junit.rules.ExternalResource;
/**
* @author Aurelien Pupier
*
*/
public class FuseProject extends ExternalResource {
private IProject project = null;
private String projectName;
public FuseProject(String projectName) {
this.projectName = projectName;
}
@Override
protected void before() throws Throwable {
super.before();
IWorkspace ws = ResourcesPlugin.getWorkspace();
project = ws.getRoot().getProject(projectName);
if (!project.exists()) {
project.create(null);
}
if (!project.isOpen()) {
project.open(null);
}
// Create a fake pom.xml
IFile pom = project.getFile("pom.xml");
pom.create(new ByteArrayInputStream("".getBytes()), true, new NullProgressMonitor());
}
@Override
protected void after() {
super.after();
if (project != null && project.exists()) {
try {
project.delete(true, new NullProgressMonitor());
} catch (CoreException e) {
e.printStackTrace();
}
}
}
public IProject getProject() {
return project;
}
}
| epl-1.0 |
paulianttila/openhab2 | bundles/org.openhab.binding.xmltv/src/main/java/org/openhab/binding/xmltv/internal/jaxb/WithLangType.java | 1394 | /**
* 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.xmltv.internal.jaxb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* Java class for an XML element value including a language attribute
* information made available to according Media Channels
*
* @author Gaël L'hopital - Initial contribution
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "withLangType")
public class WithLangType {
@XmlValue
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String value;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String lang;
public String getValue() {
return value;
}
public String getLang() {
return lang;
}
}
| epl-1.0 |
stzilli/kapua | service/device/call/kura/src/main/java/org/eclipse/kapua/service/device/call/message/kura/lifecycle/AbstractKuraLifecycleMessage.java | 1573 | /*******************************************************************************
* Copyright (c) 2020, 2021 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech - initial API and implementation
*******************************************************************************/
package org.eclipse.kapua.service.device.call.message.kura.lifecycle;
import org.eclipse.kapua.service.device.call.kura.Kura;
import org.eclipse.kapua.service.device.call.message.kura.KuraMessage;
import org.eclipse.kapua.service.device.call.message.lifecycle.DeviceLifecycleMessage;
import java.util.Date;
/**
* {@code abstract} base class for {@link Kura} {@link DeviceLifecycleMessage}
*
* @since 1.2.0
*/
public class AbstractKuraLifecycleMessage<C extends AbstractKuraLifecycleChannel, P extends AbstractKuraLifecyclePayload> extends KuraMessage<C, P> implements DeviceLifecycleMessage<C, P> {
/**
* Constructor.
*
* @param channel The {@link AbstractKuraLifecycleChannel}.
* @param timestamp The timestamp.
* @param payload The {@link AbstractKuraLifecyclePayload}.
* @see org.eclipse.kapua.service.device.call.message.DeviceMessage
* @since 1.2.0
*/
public AbstractKuraLifecycleMessage(C channel, Date timestamp, P payload) {
super(channel, timestamp, payload);
}
}
| epl-1.0 |
skyHALud/codenameone | Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/awt/src/main/java/common/java/awt/color/ICC_ProfileRGB.java | 3163 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Oleg V. Khaschansky
*/
package java.awt.color;
import org.apache.harmony.awt.internal.nls.Messages;
public class ICC_ProfileRGB extends ICC_Profile {
private static final long serialVersionUID = 8505067385152579334L;
ICC_ProfileRGB(long profileHandle) {
super(profileHandle);
}
public static final int REDCOMPONENT = 0;
public static final int GREENCOMPONENT = 1;
public static final int BLUECOMPONENT = 2;
// awt.15E=Unknown component. Must be REDCOMPONENT, GREENCOMPONENT or BLUECOMPONENT.
private static final String UNKNOWN_COMPONENT_MSG = Messages
.getString("awt.15E"); //$NON-NLS-1$
@Override
public short[] getTRC(int component) {
switch (component) {
case REDCOMPONENT:
return super.getTRC(icSigRedTRCTag);
case GREENCOMPONENT:
return super.getTRC(icSigGreenTRCTag);
case BLUECOMPONENT:
return super.getTRC(icSigBlueTRCTag);
default:
}
throw new IllegalArgumentException(UNKNOWN_COMPONENT_MSG);
}
@Override
public float getGamma(int component) {
switch (component) {
case REDCOMPONENT:
return super.getGamma(icSigRedTRCTag);
case GREENCOMPONENT:
return super.getGamma(icSigGreenTRCTag);
case BLUECOMPONENT:
return super.getGamma(icSigBlueTRCTag);
default:
}
throw new IllegalArgumentException(UNKNOWN_COMPONENT_MSG);
}
public float[][] getMatrix() {
float [][] m = new float[3][3]; // The matrix
float[] redXYZ = getXYZValue(icSigRedColorantTag);
float[] greenXYZ = getXYZValue(icSigGreenColorantTag);
float[] blueXYZ = getXYZValue(icSigBlueColorantTag);
m[0][0] = redXYZ[0];
m[1][0] = redXYZ[1];
m[2][0] = redXYZ[2];
m[0][1] = greenXYZ[0];
m[1][1] = greenXYZ[1];
m[2][1] = greenXYZ[2];
m[0][2] = blueXYZ[0];
m[1][2] = blueXYZ[1];
m[2][2] = blueXYZ[2];
return m;
}
@Override
public float[] getMediaWhitePoint() {
return super.getMediaWhitePoint();
}
}
| gpl-2.0 |
robymus/jabref | src/main/java/net/sf/jabref/gui/PreviewPanel.java | 15812 | /* Copyright (C) 2003-2012 JabRef contributors.
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 net.sf.jabref.gui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.print.PrinterException;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyVetoException;
import java.beans.VetoableChangeListener;
import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import javax.print.attribute.HashPrintRequestAttributeSet;
import javax.print.attribute.PrintRequestAttributeSet;
import javax.print.attribute.standard.JobName;
import javax.swing.*;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;
import net.sf.jabref.*;
import net.sf.jabref.exporter.layout.Layout;
import net.sf.jabref.exporter.layout.LayoutHelper;
import net.sf.jabref.exporter.ExportFormats;
import net.sf.jabref.gui.fieldeditors.PreviewPanelTransferHandler;
import net.sf.jabref.logic.l10n.Localization;
import net.sf.jabref.model.database.BibtexDatabase;
import net.sf.jabref.model.entry.BibtexEntry;
import net.sf.jabref.logic.util.io.JabRefDesktop;
/**
* Displays an BibtexEntry using the given layout format.
*/
public class PreviewPanel extends JPanel implements VetoableChangeListener, SearchTextListener, EntryContainer {
private static final long serialVersionUID = 1L;
/**
* The bibtex entry currently shown
*/
BibtexEntry entry;
private MetaData metaData;
/**
* If a database is set, the preview will attempt to resolve strings in the
* previewed entry using that database.
*/
private BibtexDatabase database;
private Layout layout;
private String layoutFile;
private final JEditorPane previewPane;
private final JScrollPane scrollPane;
private final PdfPreviewPanel pdfPreviewPanel;
private final BasePanel panel;
/**
* @param database
* (may be null) Optionally used to resolve strings.
* @param entry
* (may be null) If given this entry is shown otherwise you have
* to call setEntry to make something visible.
* @param panel
* (may be null) If not given no toolbar is shown on the right
* hand side.
* @param metaData
* (must be given) Used for resolving pdf directories for links.
* @param layoutFile
* (must be given) Used for layout
*/
public PreviewPanel(BibtexDatabase database, BibtexEntry entry,
BasePanel panel, MetaData metaData, String layoutFile) {
this(database, entry, panel, metaData, layoutFile, false);
}
/**
* @param database
* (may be null) Optionally used to resolve strings.
* @param entry
* (may be null) If given this entry is shown otherwise you have
* to call setEntry to make something visible.
* @param panel
* (may be null) If not given no toolbar is shown on the right
* hand side.
* @param metaData
* (must be given) Used for resolving pdf directories for links.
* @param layoutFile
* (must be given) Used for layout
* @param withPDFPreview if true, a PDF preview is included in the PreviewPanel
*/
public PreviewPanel(BibtexDatabase database, BibtexEntry entry,
BasePanel panel, MetaData metaData, String layoutFile, boolean withPDFPreview) {
this(panel, metaData, layoutFile, withPDFPreview);
this.database = database;
setEntry(entry);
}
/**
*
* @param panel
* (may be null) If not given no toolbar is shown on the right
* hand side.
* @param metaData
* (must be given) Used for resolving pdf directories for links.
* @param layoutFile
* (must be given) Used for layout
*/
public PreviewPanel(BasePanel panel, MetaData metaData, String layoutFile) {
this(panel, metaData, layoutFile, false);
}
/**
*
* @param panel
* (may be null) If not given no toolbar is shown on the right
* hand side.
* @param metaData
* (must be given) Used for resolving pdf directories for links.
* @param layoutFile
* (must be given) Used for layout
* @param withPDFPreview if true, a PDF preview is included in the PreviewPanel.
* The user can override this setting by setting the config setting JabRefPreferences.PDF_PREVIEW to false.
*/
private PreviewPanel(BasePanel panel, MetaData metaData, String layoutFile, boolean withPDFPreview) {
super(new BorderLayout(), true);
withPDFPreview = withPDFPreview && JabRefPreferences.getInstance().getBoolean(JabRefPreferences.PDF_PREVIEW);
this.panel = panel;
this.metaData = metaData;
this.layoutFile = layoutFile;
this.previewPane = createPreviewPane();
if (withPDFPreview) {
this.pdfPreviewPanel = new PdfPreviewPanel(metaData);
} else {
this.pdfPreviewPanel = null;
}
if (panel != null) {
// dropped files handler only created for main window
// not for Windows as like the search results window
this.previewPane.setTransferHandler(new PreviewPanelTransferHandler(panel.frame(), this, this.previewPane.getTransferHandler()));
}
// Set up scroll pane for preview pane
scrollPane = new JScrollPane(previewPane,
ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
scrollPane.setBorder(null);
/*
* If we have been given a panel and the preference option
* previewPrintButton is set, show the tool bar
*/
if (panel != null
&& JabRefPreferences.getInstance().getBoolean(JabRefPreferences.PREVIEW_PRINT_BUTTON)) {
add(createToolBar(), BorderLayout.LINE_START);
}
if (withPDFPreview) {
JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT,
scrollPane, pdfPreviewPanel);
splitPane.setOneTouchExpandable(true);
// int oneThird = panel.getWidth()/3;
int oneThird = 400; // arbitrarily set as panel.getWidth() always
// returns 0 at this point
splitPane.setDividerLocation(oneThird * 2);
// Provide minimum sizes for the two components in the split pane
// Dimension minimumSize = new Dimension(oneThird * 2, 50);
// scrollPane.setMinimumSize(minimumSize);
// minimumSize = new Dimension(oneThird, 50);
// pdfScrollPane.setMinimumSize(minimumSize);
add(splitPane);
} else {
add(scrollPane, BorderLayout.CENTER);
}
}
class PrintAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public PrintAction() {
super(Localization.lang("Print Preview"), IconTheme.getImage("psSmall"));
putValue(Action.SHORT_DESCRIPTION, Localization.lang("Print Preview"));
}
//DocumentPrinter printerService;
@Override
public void actionPerformed(ActionEvent arg0) {
// Background this, as it takes a while.
JabRefExecutorService.INSTANCE.execute(new Runnable() {
@Override
public void run() {
try {
PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
pras.add(new JobName(entry.getCiteKey(), null));
previewPane.print(null, null, true, null, pras, false);
} catch (PrinterException e) {
// Inform the user... we don't know what to do.
JOptionPane.showMessageDialog(PreviewPanel.this,
Localization.lang("Could not print preview") + ".\n"
+ e.getMessage(),
Localization.lang("Printing Entry Preview"),
JOptionPane.ERROR_MESSAGE);
}
}
});
}
}
private Action printAction;
private Action getPrintAction() {
if (printAction == null) {
printAction = new PrintAction();
}
return printAction;
}
class CloseAction extends AbstractAction {
private static final long serialVersionUID = 1L;
public CloseAction() {
super(Localization.lang("Close window"), IconTheme.getImage("close"));
putValue(Action.SHORT_DESCRIPTION, Localization.lang("Close window"));
}
@Override
public void actionPerformed(ActionEvent e) {
panel.hideBottomComponent();
}
}
private Action closeAction;
private ArrayList<String> wordsToHighlight;
private Action getCloseAction() {
if (closeAction == null) {
closeAction = new CloseAction();
}
return closeAction;
}
private JPopupMenu createPopupMenu() {
JPopupMenu menu = new JPopupMenu();
menu.add(getPrintAction());
if (panel != null) {
menu.add(panel.frame.switchPreview);
}
return menu;
}
private JToolBar createToolBar() {
JToolBar tlb = new JToolBar(SwingConstants.VERTICAL);
JabRefPreferences prefs = JabRefPreferences.getInstance();
Action printAction = getPrintAction();
Action closeAction = getCloseAction();
tlb.setMargin(new Insets(0, 0, 0, 2));
// The toolbar carries all the key bindings that are valid for the whole
// window.
ActionMap am = tlb.getActionMap();
InputMap im = tlb.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
im.put(prefs.getKey("Close entry preview"), "close");
am.put("close", closeAction);
im.put(prefs.getKey("Print entry preview"), "print");
am.put("print", printAction);
tlb.setFloatable(false);
// Add actions (and thus buttons)
tlb.add(closeAction);
tlb.addSeparator();
tlb.add(printAction);
Component[] comps = tlb.getComponents();
for (Component comp : comps) {
((JComponent) comp).setOpaque(false);
}
return tlb;
}
private JEditorPane createPreviewPane() {
JEditorPane previewPane = new JEditorPane() {
private static final long serialVersionUID = 1L;
@Override
public Dimension getPreferredScrollableViewportSize() {
return getPreferredSize();
}
};
previewPane.setMargin(new Insets(3, 3, 3, 3));
previewPane.setComponentPopupMenu(createPopupMenu());
previewPane.setEditable(false);
previewPane.setDragEnabled(true); // this has an effect only, if no custom transfer handler is registered. We keep the statement if the transfer handler is removed.
previewPane.setContentType("text/html");
previewPane.addHyperlinkListener(new HyperlinkListener() {
@Override
public void hyperlinkUpdate(HyperlinkEvent hyperlinkEvent) {
if (hyperlinkEvent.getEventType() == HyperlinkEvent.EventType.ACTIVATED) {
try {
String address = hyperlinkEvent.getURL().toString();
JabRefDesktop.openExternalViewer(PreviewPanel.this.metaData,
address, "url");
} catch (IOException e) {
e.printStackTrace();
}
}
}
});
return previewPane;
}
public void setDatabase(BibtexDatabase db) {
database = db;
}
public void setMetaData(MetaData metaData) {
this.metaData = metaData;
}
public void readLayout(String layoutFormat) throws Exception {
layoutFile = layoutFormat;
readLayout();
}
private void readLayout() throws Exception {
StringReader sr = new StringReader(layoutFile.replaceAll("__NEWLINE__",
"\n"));
layout = new LayoutHelper(sr)
.getLayoutFromText(Globals.FORMATTER_PACKAGE);
}
public void setLayout(Layout layout) {
this.layout = layout;
}
public void setEntry(BibtexEntry newEntry) {
if (newEntry != entry) {
if (entry != null) {
entry.removePropertyChangeListener(this);
}
newEntry.addPropertyChangeListener(this);
}
entry = newEntry;
try {
readLayout();
update();
} catch (StringIndexOutOfBoundsException ex) {
throw ex;
} catch (Exception ex) {
ex.printStackTrace();
}
}
@Override
public BibtexEntry getEntry() {
return this.entry;
}
public void update() {
StringBuilder sb = new StringBuilder();
ExportFormats.entryNumber = 1; // Set entry number in case that is included in the preview layout.
if (entry != null) {
sb.append(layout.doLayout(entry, database, wordsToHighlight));
}
previewPane.setText(sb.toString());
previewPane.revalidate();
// Scroll to top:
final JScrollBar bar = scrollPane.getVerticalScrollBar();
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
bar.setValue(0);
}
});
// update pdf preview
if (pdfPreviewPanel != null) {
pdfPreviewPanel.updatePanel(entry);
}
}
public boolean hasEntry() {
return entry != null;
}
/**
* The PreviewPanel has registered itself as an event listener with the
* currently displayed BibtexEntry. If the entry changes, an event is
* received here, and we can update the preview immediately.
*/
@Override
public void vetoableChange(PropertyChangeEvent evt)
throws PropertyVetoException {
// TODO updating here is not really necessary isn't it?
// Only if we are visible.
update();
}
@Override
public void searchText(ArrayList<String> words) {
if (Globals.prefs.getBoolean(JabRefPreferences.HIGH_LIGHT_WORDS)) {
this.wordsToHighlight = words;
update();
} else {
if (this.wordsToHighlight != null) {
// setting of JabRefPreferences.HIGH_LIGHT_WORDS seems to have changed.
// clear all highlights and remember the clearing (by wordsToHighlight = null)
this.wordsToHighlight = null;
update();
}
}
}
}
| gpl-2.0 |
wb-goup/webbuilder | wb-office/src/test/java/org/webbuilder/office/word/TestWriter.java | 2290 | package org.webbuilder.office.word;
import org.junit.Test;
import org.webbuilder.office.word.api.poi.POIWordApi4Docx;
import org.webbuilder.office.word.support.template.DOCXTemplateReader;
import org.webbuilder.utils.common.BeanUtils;
import org.webbuilder.utils.common.StringUtils;
import org.webbuilder.utils.file.Resources;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Created by 浩 on 2015-12-18 0018.
*/
public class TestWriter {
@Test
public void testWriteTemplate() throws Exception {
try (InputStream in = new FileInputStream(Resources.getResourceAsFile("docx/test.docx"));
OutputStream out = new FileOutputStream("d:\\test.docx")) {
//构造 模板所需的变量
Map<String, Object> vars = new HashMap<>();
vars.put("name", "姓名");
vars.put("list", new ArrayList<Object>() {
{
add(new HashMap<String, Object>() {
{
put("name", "张三");
put("sex", true);
put("age", 10);
put("remark", "测试");
}
});
add(new HashMap<String, Object>() {
{
put("name", "李四");
put("sex", false);
put("age", 10);
put("remark", "测试2");
}
});
}
});
WordIO.writeTemplate(in, out, vars);
out.flush();
}
}
public static void main(String[] args) throws Exception {
try (FileInputStream template = new FileInputStream("/home/zhouhao/桌面/template.docx");
FileInputStream source = new FileInputStream("/home/zhouhao/桌面/test.docx")) {
List<Map<String,Object>> datas = new DOCXTemplateReader(template, source).read();
for (Map<String, Object> data : datas) {
System.out.println(data);
}
}
}
}
| gpl-2.0 |
samskivert/ikvm-openjdk | build/linux-amd64/impsrc/com/sun/xml/internal/messaging/saaj/util/NamespaceContextIterator.java | 3774 | /*
* Copyright (c) 2005, 2006, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
*
* @author SAAJ RI Development Team
*/
package com.sun.xml.internal.messaging.saaj.util;
import java.util.Iterator;
import java.util.NoSuchElementException;
import org.w3c.dom.*;
public class NamespaceContextIterator implements Iterator {
Node context;
NamedNodeMap attributes = null;
int attributesLength;
int attributeIndex;
Attr next = null;
Attr last = null;
boolean traverseStack = true;
public NamespaceContextIterator(Node context) {
this.context = context;
findContextAttributes();
}
public NamespaceContextIterator(Node context, boolean traverseStack) {
this(context);
this.traverseStack = traverseStack;
}
protected void findContextAttributes() {
while (context != null) {
int type = context.getNodeType();
if (type == Node.ELEMENT_NODE) {
attributes = context.getAttributes();
attributesLength = attributes.getLength();
attributeIndex = 0;
return;
} else {
context = null;
}
}
}
protected void findNext() {
while (next == null && context != null) {
for (; attributeIndex < attributesLength; ++attributeIndex) {
Node currentAttribute = attributes.item(attributeIndex);
String attributeName = currentAttribute.getNodeName();
if (attributeName.startsWith("xmlns")
&& (attributeName.length() == 5
|| attributeName.charAt(5) == ':')) {
next = (Attr) currentAttribute;
++attributeIndex;
return;
}
}
if (traverseStack) {
context = context.getParentNode();
findContextAttributes();
} else {
context = null;
}
}
}
public boolean hasNext() {
findNext();
return next != null;
}
public Object next() {
return getNext();
}
public Attr nextNamespaceAttr() {
return getNext();
}
protected Attr getNext() {
findNext();
if (next == null) {
throw new NoSuchElementException();
}
last = next;
next = null;
return last;
}
public void remove() {
if (last == null) {
throw new IllegalStateException();
}
((Element) context).removeAttributeNode(last);
}
}
| gpl-2.0 |