repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
jashort/kumoreg | src/main/java/org/kumoricon/site/attendee/PrintBadgeView.java | 2670 | package org.kumoricon.site.attendee;
import com.vaadin.event.ShortcutAction;
import com.vaadin.navigator.View;
import com.vaadin.server.StreamResource;
import com.vaadin.ui.*;
import com.vaadin.ui.themes.ValoTheme;
import org.kumoricon.BaseGridView;
import org.kumoricon.model.attendee.Attendee;
import org.kumoricon.site.attendee.search.PrintBadgePresenter;
import javax.annotation.PostConstruct;
import java.util.Arrays;
public abstract class PrintBadgeView extends BaseGridView implements View {
public static final String VIEW_NAME = "order";
public static final String REQUIRED_RIGHT = "print_badge";
private Button btnPrintedSuccessfully = new Button("Printed Successfully?");
private Button btnReprint = new Button("Reprint Selected");
protected PrintBadgePresenter handler;
protected Attendee attendee;
protected BrowserFrame pdf;
public PrintBadgeView(PrintBadgePresenter handler) {
this.handler = handler;
}
@PostConstruct
public void init() {
setColumns(5);
setRows(3);
setColumnExpandRatio(0, 10);
setColumnExpandRatio(4, 10);
setRowExpandRatio(2, 10);
btnPrintedSuccessfully.setClickShortcut(ShortcutAction.KeyCode.ENTER);
btnPrintedSuccessfully.addStyleName(ValoTheme.BUTTON_PRIMARY);
btnPrintedSuccessfully.addClickListener(e -> printedSuccessfullyClicked());
btnReprint.addClickListener(e -> reprintClicked());
}
protected abstract void printedSuccessfullyClicked();
protected abstract void reprintClicked();
protected void showBadge(Attendee attendee) {
this.attendee = attendee;
StreamResource.StreamSource source = handler.getBadgeFormatter(this, Arrays.asList(attendee));
String filename = "badge" + System.currentTimeMillis() + ".pdf";
StreamResource resource = new StreamResource(source, filename);
pdf = new BrowserFrame("", resource);
resource.setMIMEType("application/pdf");
resource.getStream().setParameter("Content-Disposition", "attachment; filename=" + filename);
pdf.setWidth("700px");
pdf.setHeight("500px");
addComponent(pdf, 1, 0, 1, 2);
addComponent(btnPrintedSuccessfully, 2, 0);
addComponent(btnReprint, 2, 1);
}
@Override
public String getRequiredRight() {
return REQUIRED_RIGHT;
}
public void showAttendee(Attendee attendee) {
if (!currentUserHasRight("pre_print_badges") && !attendee.getCheckedIn()) {
notifyError("Error: This attendee hasn't checked in yet");
close();
}
showBadge(attendee);
}
}
| mit |
safris-src/org | libx4j/xsb/compiler/src/main/java/org/libx4j/xsb/compiler/processor/model/element/WhiteSpaceModel.java | 1786 | /* Copyright (c) 2008 lib4j
*
* 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.
*
* You should have received a copy of The MIT License (MIT) along with this
* program. If not, see <http://opensource.org/licenses/MIT/>.
*/
package org.libx4j.xsb.compiler.processor.model.element;
import org.libx4j.xsb.compiler.processor.model.Model;
import org.libx4j.xsb.compiler.processor.model.NamedModel;
import org.libx4j.xsb.compiler.schema.attribute.Value;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
public final class WhiteSpaceModel extends NamedModel {
private Boolean fixed = null;
private Value value = null;
protected WhiteSpaceModel(final Node node, final Model parent) {
super(node, parent);
final NamedNodeMap attributes = node.getAttributes();
for (int i = 0; i < attributes.getLength(); i++) {
final Node attribute = attributes.item(i);
if ("fixed".equals(attribute.getLocalName()))
fixed = Boolean.parseBoolean(attribute.getNodeValue());
else if ("value".equals(attribute.getLocalName()))
value = Value.parseValue(attribute.getNodeValue());
}
}
public final Boolean getFixed() {
return fixed;
}
public final Value getValue() {
return value;
}
} | mit |
mattparks/Flounder-Engine | src/flounder/visual/ValueDriver.java | 838 | package flounder.visual;
/**
* Represents a driver that changes over time.
*/
public abstract class ValueDriver {
private float length;
private float currentTime;
/**
* Creates a new driver with a length.
*
* @param length The drivers length.
*/
public ValueDriver(float length) {
currentTime = 0.0f;
this.length = length;
}
/**
* Updates the driver with the passed time.
*
* @param delta The time between the last update.
*
* @return The calculated value.
*/
public float update(float delta) {
currentTime += delta;
currentTime %= length;
float time = currentTime / length;
return calculateValue(time);
}
/**
* Calculates the new value.
*
* @param time The time into the drivers life.
*
* @return The calculated value.
*/
protected abstract float calculateValue(float time);
}
| mit |
jucimarjr/uarini | examples/headfirst/08_Adapter/Java/DuckAdapter.java | 452 | //Este fonte esta disponivel em: Livro Head First Design Patterns.
//Autores: Freeman, E., Freeman, E., Sierra, K., and Bates, B. (2004).O'Reilly Media Inc., 01st ed.
public class DuckAdapter implements Turkey {
Duck duck;
Random rand;
public DuckAdapter(Duck duck) {
this.duck = duck;
rand = new Random();
}
public void gobble() {
duck.quack();
}
public void fly() {
if (rand.nextInt(5) == 0) {
duck.fly();
}
}
}
| mit |
ptyz030529/skysport | src/main/java/com/skysport/core/model/seqno/service/IncrementNumber.java | 252 | package com.skysport.core.model.seqno.service;
/**
* Created by zhangjh on 2015/6/1.
*/
public interface IncrementNumber {
int nextVal(String name);
int reset();
String nextVal(String kind_name, int length, String currentSeqNo);
}
| mit |
rahulpnath/Blog | GettingStartedOnPhoneGap/SimpleApp/platforms/android/CordovaLib/gen/org/apache/cordova/Manifest.java | 185 | /*___Generated_by_IDEA___*/
package org.apache.cordova;
/* This stub is for using by IDE only. It is NOT the Manifest class actually packed into APK */
public final class Manifest {
} | mit |
Adam8234/the-blue-alliance-android | android/src/main/java/com/thebluealliance/androidclient/helpers/MyTBAHelper.java | 2602 | package com.thebluealliance.androidclient.helpers;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonPrimitive;
import com.thebluealliance.androidclient.Constants;
import com.thebluealliance.androidclient.datafeed.JSONManager;
import java.util.Map;
/**
* File created by phil on 8/13/14.
*/
public class MyTBAHelper {
private static final String INTENT_PACKAGE = "package", INTENT_CLASS = "class", INTENT_EXTRAS = "extras";
public static String createKey(String userName, String modelKey) {
return userName + ":" + modelKey;
}
public static String getFavoritePreferenceKey() {
return "favorite";
}
public static String serializeIntent(Intent intent) {
JsonObject data = new JsonObject(), extras = new JsonObject();
ComponentName activity = intent.getComponent();
data.addProperty(INTENT_PACKAGE, activity.getPackageName());
data.addProperty(INTENT_CLASS, activity.getClassName());
Bundle bundle = intent.getExtras();
if (bundle != null) {
for (String key : bundle.keySet()) {
Object val = bundle.get(key);
if (val instanceof String) {
extras.addProperty(key, bundle.getString(key));
} else if (val instanceof Integer) {
extras.addProperty(key, bundle.getInt(key));
}
}
}
data.add(INTENT_EXTRAS, extras);
Log.d(Constants.LOG_TAG, "Serialized: " + data.toString());
return data.toString();
}
public static Intent deserializeIntent(String input) {
JsonObject data = JSONManager.getasJsonObject(input);
Intent intent = new Intent();
String pack = data.get(INTENT_PACKAGE).getAsString();
String cls = data.get(INTENT_CLASS).getAsString();
Log.d(Constants.LOG_TAG, pack + "/" + cls);
intent.setClassName(pack, cls);
JsonObject extras = data.get(INTENT_EXTRAS).getAsJsonObject();
for (Map.Entry<String, JsonElement> extra : extras.entrySet()) {
JsonPrimitive primitive = extra.getValue().getAsJsonPrimitive();
if (primitive.isString()) {
intent.putExtra(extra.getKey(), primitive.getAsString());
} else if (primitive.isNumber()) {
intent.putExtra(extra.getKey(), primitive.getAsInt());
}
}
return intent;
}
}
| mit |
GoHD/java-angularjs-architecture | api/app-model/src/main/java/com/github/app/common/utils/ValidationUtils.java | 1006 | package com.github.app.common.utils;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import com.github.app.common.exception.AtributosDaEntidadeInvalidosException;
import com.github.app.i18n.MensagensI18n;
public class ValidationUtils {
public static <T> void validaAtributosDaEntidade(final Validator validator, final T entity) {
final Set<ConstraintViolation<T>> errors = validator.validate(entity);
if (!errors.isEmpty()) {
String chaveI18n = MensagensI18n.ERRO_PREENCHIMENTO_CAMPOS.name();
String tituloErro = MensagensI18n.ERRO_PREENCHIMENTO_CAMPOS.mensagem();
AtributosDaEntidadeInvalidosException ex = new AtributosDaEntidadeInvalidosException(chaveI18n, tituloErro);
for (ConstraintViolation<T> cv : errors) {
String atributo = cv.getPropertyPath().toString();
ex.adicionaAtributoInvalido(atributo, cv.getMessage());
}
throw ex;
}
}
} | mit |
chcbaram/Processing_RokitDrone | libraries/GameControlPlus/src/org/gamecontrolplus/gui/MTabManager.java | 3986 | /*
Part of the GUI for Processing library
http://www.lagers.org.uk/g4p/index.html
http://gui4processing.googlecode.com/svn/trunk/
Copyright (c) 2008-12 Peter Lager
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package org.gamecontrolplus.gui;
import java.util.LinkedList;
/**
* Allows TABBING between text controls.
* A tab manager allows the user to use the TAB key to move from one text control
* (GTextField or GTextArea) to the another. This is useful when creating a 'form'
* made from several text controls. <br>
* The tab order is decided by the order the text controls are added to the tab
* manager. The TAB key move the focus forwards and SHIFT+TAB moves it backwards.
* Note that tabbing is not cyclic so pressing TAB on the last control does not
* set the focus on the first control, in fact it will be ignored. Similar
* logic applies to SHIFT_TAB on the first control<br>
* At least 2 controls must be added to the tab manager.
*
* @author Peter Lager
*
*/
public class MTabManager {
private LinkedList<MEditableTextControl> textControls;
public MTabManager(){
textControls = new LinkedList<MEditableTextControl>();
}
/**
* Attempt to add multiple controls to the tab manager. The tab order is determined
* by their order as parameters to this method.
*
* @param controls a comma separated list of text field or text area controls.
* @return true if any or all of the controls were added and false if none were added.
*/
public boolean addControls(MEditableTextControl... controls){
boolean result = false;
for(MEditableTextControl control : controls)
result |= addControl(control);
return result;
}
/**
* Add the next text control to this tab manager.
*
* @param control to add
* @return true if added successfully
*/
public boolean addControl(MEditableTextControl control){
if(!textControls.contains(control)){
control.tabManager = this;
textControls.addLast(control);
return true;
}
return false;
}
/**
* Remove a control from the tab manager. This does not affect the tab
* order of the remaining controls.
*
* @param control
* @return true if remove successfully
*/
public boolean removeControl(MEditableTextControl control){
int index = textControls.lastIndexOf(control);
if(index > 0){
control.tabManager = null;
textControls.remove(index);
return true;
}
return false;
}
/**
* Used when the tab key is pressed to move to the next control
* @param control
* @return true if it found a next control else false
*/
boolean nextControl(MEditableTextControl control){
int index = textControls.lastIndexOf(control);
if(textControls.size() > 1 && index >= 0 && index < textControls.size() - 1){
index++;
MAbstractControl.controlToTakeFocus = textControls.get(index);;
return true;
}
return false;
}
/**
* Used when the shift+tab key is pressed to move to the previous control
* @param control
* @return true if it found a previous control else false
*/
boolean prevControl(MEditableTextControl control){
int index = textControls.lastIndexOf(control);
if(textControls.size() > 1 && index > 0){
index--;
MAbstractControl.controlToTakeFocus = textControls.get(index);
return true;
}
return false;
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/resourcemanager/azure-resourcemanager-redis/src/main/java/com/azure/resourcemanager/redis/package-info.java | 303 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
/** Package containing the classes for RedisManagementClient. REST API for Azure Redis Cache Service. */
package com.azure.resourcemanager.redis;
| mit |
HelloFax/hellosign-java-sdk | src/main/java/com/hellosign/sdk/resource/Team.java | 837 | package com.hellosign.sdk.resource;
import com.hellosign.sdk.HelloSignException;
import java.util.List;
import org.json.JSONObject;
public class Team extends AbstractResource {
public static final String TEAM_KEY = "team";
public static final String TEAM_NAME = "name";
public static final String TEAM_ACCOUNTS = "accounts";
public static final String TEAM_INVITEES = "invited_accounts";
public Team() {
super();
}
public Team(JSONObject json) throws HelloSignException {
super(json, TEAM_KEY);
}
public String getName() {
return getString(TEAM_NAME);
}
public List<Account> getAccounts() {
return getList(Account.class, TEAM_ACCOUNTS);
}
public List<Account> getInvitedAccounts() {
return getList(Account.class, TEAM_INVITEES);
}
}
| mit |
pengzhao001/android-apps | CustomEditText/src/com/errorpoint/customedittext/LauncherActivity.java | 533 | package com.errorpoint.customedittext;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class LauncherActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_launcher);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.launcher, menu);
return true;
}
}
| mit |
navalev/azure-sdk-for-java | sdk/recoveryservices.siterecovery/mgmt-v2018_01_10/src/main/java/com/microsoft/azure/management/recoveryservices/siterecovery/v2018_01_10/EthernetAddressType.java | 1371 | /**
* 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.recoveryservices.siterecovery.v2018_01_10;
import java.util.Collection;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.microsoft.rest.ExpandableStringEnum;
/**
* Defines values for EthernetAddressType.
*/
public final class EthernetAddressType extends ExpandableStringEnum<EthernetAddressType> {
/** Static value Dynamic for EthernetAddressType. */
public static final EthernetAddressType DYNAMIC = fromString("Dynamic");
/** Static value Static for EthernetAddressType. */
public static final EthernetAddressType STATIC = fromString("Static");
/**
* Creates or finds a EthernetAddressType from its string representation.
* @param name a name to look for
* @return the corresponding EthernetAddressType
*/
@JsonCreator
public static EthernetAddressType fromString(String name) {
return fromString(name, EthernetAddressType.class);
}
/**
* @return known EthernetAddressType values
*/
public static Collection<EthernetAddressType> values() {
return values(EthernetAddressType.class);
}
}
| mit |
BrianKolowitz/infsci2560_java | src/infsci2560/week8/Closingframe.java | 439 | /*
* 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 infsci2560.week8;
import java.awt.event.*;
import javax.swing.*;
/**
*
* @author bk
*/
public class Closingframe {
public static void main(String [] args) {
BFrame x;
x = new BFrame();
x.show();
}
}
| mit |
dmpe/Homeworks2 | Aufgabe3/src/de/university/reutlingen/aufgabe2/a3/Main.java | 2107 | package de.university.reutlingen.aufgabe2.a3;
import java.util.ArrayList;
import de.university.reutlingen.aufgabe2.a3.ProductDescription.PriceLevel;
public class Main {
public static void main(String[] args) {
/*
* Das Preissystem der Warenhaussoftware soll umgestellt werden. Produktpreise sollen nicht mehr
* beliebig vergeben werden können. Stattdessen gibt es 4 Preisstufen, denen ein Produkt
* zugeordnet wird. Die Stufen sind LOW (9,99), MEDIUM (19,99), HIGH (49,99) und EXCLUSIVE
* (99,99). Innerhalb der Warenhaussoftware sollen die Preisstufen durch einen Enum-Typ
* (enum PriceLevel) reprasenstiert werden. Programmieren Sie den enum PriceLevel,
* passen Sie die Klasse Product und Ihr Testprogramm aus Teilaufgabe (a) an.
* Hinweis: Der Preis muss als double-Datentyp im enum PriceLevel verwaltet werden.
* enum-Typ muss zusatzlich public String toString() uberschreiben (gibt den Preis
* als String zuruck) und einen privaten Konstruktor besitzen, der den Preis als Argument erhalt.
*/
/*
* this is a hack. Should not do, just for save heaven.
* 1 Possibility
* http://www.angelikalanger.com/GenericsFAQ/FAQSections/ParameterizedTypes.html#FAQ105
*/
Produkt<String>[] products = new Produkt[3];
products[0] = new Produkt<String>("I Hate Apple", PriceLevel.EXCLUSIVE);
products[1] = new Produkt<String>("I Hate Apple", PriceLevel.LOW);
products[2] = new Produkt<String>("I Hate Apple", PriceLevel.MEDIUM);
for (Produkt<String> i : products) {
System.out.println(i.getProduktBeschreibung() + " "+ i.getProduktPreis());
}
System.out.println("");
// This is better, because uses ArrayLists. For me
ArrayList<Produkt<String>> produktLists = new ArrayList<>();
produktLists.add(new Produkt<String>("I have bought Apple for ", PriceLevel.MEDIUM));
produktLists.add(new Produkt<String>("I read the Verge ", PriceLevel.LOW));
for (Produkt<String> g : produktLists) {
System.out.println(g.getProduktBeschreibung()+ " " + g.getProduktPreis());
}
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/containerinstance/mgmt-v2017_08_01_preview/src/main/java/com/microsoft/azure/management/containerinstance/v2017_08_01_preview/ResourceRequirements.java | 1767 | /**
* 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.containerinstance.v2017_08_01_preview;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* The resource requirements.
*/
public class ResourceRequirements {
/**
* The resource requests of this container instance.
*/
@JsonProperty(value = "requests", required = true)
private ResourceRequests requests;
/**
* The resource limits of this container instance.
*/
@JsonProperty(value = "limits")
private ResourceLimits limits;
/**
* Get the resource requests of this container instance.
*
* @return the requests value
*/
public ResourceRequests requests() {
return this.requests;
}
/**
* Set the resource requests of this container instance.
*
* @param requests the requests value to set
* @return the ResourceRequirements object itself.
*/
public ResourceRequirements withRequests(ResourceRequests requests) {
this.requests = requests;
return this;
}
/**
* Get the resource limits of this container instance.
*
* @return the limits value
*/
public ResourceLimits limits() {
return this.limits;
}
/**
* Set the resource limits of this container instance.
*
* @param limits the limits value to set
* @return the ResourceRequirements object itself.
*/
public ResourceRequirements withLimits(ResourceLimits limits) {
this.limits = limits;
return this;
}
}
| mit |
anthonyuitz/FoodApp | FoodApp/app/src/main/java/com/khmkau/codeu/foodapp/NutritionalDetailActivity.java | 1798 | package com.khmkau.codeu.foodapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
public class NutritionalDetailActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_nutritional_detail);
if (savedInstanceState == null) {
// Create the detail fragment and add it to the activity
// using a fragment transaction.
Bundle arguments = new Bundle();
arguments.putParcelable(NutritionalDetailFragment.DETAIL_URI, getIntent().getData());
NutritionalDetailFragment fragment = new NutritionalDetailFragment();
fragment.setArguments(arguments);
getSupportFragmentManager().beginTransaction()
.add(R.id.nutritional_detail_container, fragment)
.commit();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.detail, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
startActivity(new Intent(this, SettingsActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
} | mit |
ziyasal/rospock | src/main/java/lib/impl/PlayerFactory.java | 1348 | package lib.impl;
import com.google.inject.Inject;
import lib.*;
import java.security.InvalidParameterException;
public class PlayerFactory implements IPlayerFactory {
private IGameLogicStrategy gameLogicStrategy;
private IUserWeaponChoiceProvider userWeaponChoiceProvider;
private IRandomProvider randomProvider;
@Inject
public PlayerFactory(IGameLogicStrategy gameLogicStrategy,
IUserWeaponChoiceProvider userWeaponChoiceProvider,
IRandomProvider randomProvider) {
this.gameLogicStrategy = gameLogicStrategy;
this.userWeaponChoiceProvider = userWeaponChoiceProvider;
this.randomProvider = randomProvider;
}
public IPlayer createComputerPlayer(String name) {
if (name.isEmpty()) {
throw new InvalidParameterException("Name must be not empty.");
}
ComputerPlayer player = new ComputerPlayer(this.gameLogicStrategy, this.randomProvider);
player.setName(name);
return player;
}
public IPlayer createUserPlayer(String name) {
if (name.isEmpty()) {
throw new InvalidParameterException("Name must be not empty.");
}
UserPlayer player = new UserPlayer(this.userWeaponChoiceProvider);
player.setName(name);
return player;
}
} | mit |
gizwits/airconditioner-android | src/zxing/CaptureActivity.java | 11734 | /*
* Copyright (C) 2008 ZXing 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 zxing;
import java.io.IOException;
import java.lang.reflect.Field;
import zxing.camera.CameraManager;
import zxing.decoding.DecodeThread;
import zxing.utils.CaptureActivityHandler;
import zxing.utils.InactivityTimer;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import com.gizwits.aircondition.R;
import com.gizwits.framework.activity.BaseActivity;
import com.gizwits.framework.activity.device.DeviceListActivity;
import com.google.zxing.Result;
import com.xpg.common.system.IntentUtils;
import com.xpg.ui.utils.ToastUtils;
/**
* This activity opens the camera and does the actual scanning on a background
* thread. It draws a viewfinder to help the user place the barcode correctly,
* shows feedback as the image processing is happening, and then overlays the
* results when a scan is successful.
*
* @author dswitkin@google.com (Daniel Switkin)
* @author Sean Owen
*/
public final class CaptureActivity extends BaseActivity implements
SurfaceHolder.Callback {
private static final String TAG = CaptureActivity.class.getSimpleName();
private CameraManager cameraManager;
private CaptureActivityHandler handler;
private InactivityTimer inactivityTimer;
private SurfaceView scanPreview = null;
private RelativeLayout scanContainer;
private RelativeLayout scanCropView;
private ImageView scanLine;
private String product_key, passcode, did;
private Button btnCancel;
private ImageView ivReturn;
/**
* ClassName: Enum handler_key. <br/>
* <br/>
* date: 2014-11-26 17:51:10 <br/>
*
* @author Lien
*/
private enum handler_key {
START_BIND,
SUCCESS,
FAILED,
}
/**
* The handler.
*/
Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
handler_key key = handler_key.values()[msg.what];
switch (key) {
case START_BIND:
startBind(passcode, did);
break;
case SUCCESS:
ToastUtils.showShort(CaptureActivity.this, "添加成功");
IntentUtils.getInstance().startActivity(CaptureActivity.this,
DeviceListActivity.class);
finish();
break;
case FAILED:
ToastUtils.showShort(CaptureActivity.this, "添加失败,请返回重试");
finish();
}
}
};
private void startBind(final String passcode, final String did) {
mCenter.cBindDevice(setmanager.getUid(), setmanager.getToken(), did,
passcode, "");
}
private Rect mCropRect = null;
public Handler getHandler() {
return handler;
}
public CameraManager getCameraManager() {
return cameraManager;
}
private boolean isHasSurface = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_capture);
scanPreview = (SurfaceView) findViewById(R.id.capture_preview);
scanContainer = (RelativeLayout) findViewById(R.id.capture_container);
scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view);
scanLine = (ImageView) findViewById(R.id.capture_scan_line);
inactivityTimer = new InactivityTimer(this);
TranslateAnimation animation = new TranslateAnimation(
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, 0.0f,
Animation.RELATIVE_TO_PARENT, -1.0f,
Animation.RELATIVE_TO_PARENT,0.0f);
animation.setDuration(4500);
animation.setRepeatCount(-1);
animation.setRepeatMode(Animation.RESTART);
scanLine.startAnimation(animation);
btnCancel = (Button) findViewById(R.id.btn_cancel);
ivReturn = (ImageView) findViewById(R.id.iv_return);
OnClickListener myClick = new OnClickListener() {
@Override
public void onClick(View arg0) {
CaptureActivity.this.finish();
}
};
btnCancel.setOnClickListener(myClick);
ivReturn.setOnClickListener(myClick);
}
@Override
public void onResume() {
super.onResume();
// CameraManager must be initialized here, not in onCreate(). This is
// necessary because we don't
// want to open the camera driver and measure the screen size if we're
// going to show the help on
// first launch. That led to bugs where the scanning rectangle was the
// wrong size and partially
// off screen.
cameraManager = new CameraManager(getApplication());
handler = null;
if (isHasSurface) {
// The activity was paused but not stopped, so the surface still
// exists. Therefore
// surfaceCreated() won't be called, so init the camera here.
initCamera(scanPreview.getHolder());
} else {
// Install the callback and wait for surfaceCreated() to init the
// camera.
scanPreview.getHolder().addCallback(this);
}
inactivityTimer.onResume();
}
@Override
protected void onPause() {
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
inactivityTimer.onPause();
cameraManager.closeDriver();
if (!isHasSurface) {
scanPreview.getHolder().removeCallback(this);
}
super.onPause();
}
@Override
protected void onDestroy() {
inactivityTimer.shutdown();
super.onDestroy();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
if (holder == null) {
Log.e(TAG,
"*** WARNING *** surfaceCreated() gave us a null surface!");
}
if (!isHasSurface) {
isHasSurface = true;
initCamera(holder);
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
isHasSurface = false;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}
/**
* A valid barcode has been found, so give an indication of success and show
* the results.
*
* @param rawResult
* The contents of the barcode.
*
* @param bundle
* The extras
*/
public void handleDecode(Result rawResult, Bundle bundle) {
String text = rawResult.getText();
Log.i("test", text);
if (text.contains("product_key=") & text.contains("did=")
&& text.contains("passcode=")) {
inactivityTimer.onActivity();
product_key = getParamFomeUrl(text, "product_key");
did = getParamFomeUrl(text, "did");
passcode = getParamFomeUrl(text, "passcode");
Log.i("passcode product_key did", passcode + " " + product_key
+ " " + did);
ToastUtils.showShort(this, "扫码成功");
mHandler.sendEmptyMessage(handler_key.START_BIND.ordinal());
} else {
handler = new CaptureActivityHandler(this, cameraManager,
DecodeThread.ALL_MODE);
}
}
private String getParamFomeUrl(String url, String param) {
String product_key = "";
int startindex = url.indexOf(param + "=");
startindex += (param.length() + 1);
String subString = url.substring(startindex);
int endindex = subString.indexOf("&");
if (endindex == -1) {
product_key = subString;
} else {
product_key = subString.substring(0, endindex);
}
return product_key;
}
@Override
protected void didBindDevice(int error, String errorMessage, String did) {
Log.d("扫描结果", "error=" + error + ";errorMessage=" + errorMessage
+ ";did=" + did);
if (error == 0) {
mHandler.sendEmptyMessage(handler_key.SUCCESS.ordinal());
} else {
Message message = new Message();
message.what = handler_key.FAILED.ordinal();
message.obj = errorMessage;
mHandler.sendMessage(message);
}
}
private void initCamera(SurfaceHolder surfaceHolder) {
if (surfaceHolder == null) {
throw new IllegalStateException("No SurfaceHolder provided");
}
if (cameraManager.isOpen()) {
Log.w(TAG,
"initCamera() while already open -- late SurfaceView callback?");
return;
}
try {
cameraManager.openDriver(surfaceHolder);
// Creating the handler starts the preview, which can also throw a
// RuntimeException.
if (handler == null) {
handler = new CaptureActivityHandler(this, cameraManager,
DecodeThread.ALL_MODE);
}
initCrop();
} catch (IOException ioe) {
Log.w(TAG, ioe);
displayFrameworkBugMessageAndExit();
} catch (RuntimeException e) {
// Barcode Scanner has seen crashes in the wild of this variety:
// java.?lang.?RuntimeException: Fail to connect to camera service
Log.w(TAG, "Unexpected error initializing camera", e);
displayFrameworkBugMessageAndExit();
}
}
private void displayFrameworkBugMessageAndExit() {
// camera error
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage("相机打开出错,请稍后重试");
builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
@Override
public void onCancel(DialogInterface dialog) {
finish();
}
});
builder.show();
}
public void restartPreviewAfterDelay(long delayMS) {
if (handler != null) {
handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
}
}
public Rect getCropRect() {
return mCropRect;
}
/**
* 初始化截取的矩形区域
*/
private void initCrop() {
int cameraWidth = cameraManager.getCameraResolution().y;
int cameraHeight = cameraManager.getCameraResolution().x;
/** 获取布局中扫描框的位置信息 */
int[] location = new int[2];
scanCropView.getLocationInWindow(location);
int cropLeft = location[0];
int cropTop = location[1] - getStatusBarHeight();
int cropWidth = scanCropView.getWidth();
int cropHeight = scanCropView.getHeight();
/** 获取布局容器的宽高 */
int containerWidth = scanContainer.getWidth();
int containerHeight = scanContainer.getHeight();
/** 计算最终截取的矩形的左上角顶点x坐标 */
int x = cropLeft * cameraWidth / containerWidth;
/** 计算最终截取的矩形的左上角顶点y坐标 */
int y = cropTop * cameraHeight / containerHeight;
/** 计算最终截取的矩形的宽度 */
int width = cropWidth * cameraWidth / containerWidth;
/** 计算最终截取的矩形的高度 */
int height = cropHeight * cameraHeight / containerHeight;
/** 生成最终的截取的矩形 */
mCropRect = new Rect(x, y, width + x, height + y);
}
private int getStatusBarHeight() {
try {
Class<?> c = Class.forName("com.android.internal.R$dimen");
Object obj = c.newInstance();
Field field = c.getField("status_bar_height");
int x = Integer.parseInt(field.get(obj).toString());
return getResources().getDimensionPixelSize(x);
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
}
| mit |
DeviceConnect/DeviceConnect-Android | dConnectManager/dConnectManager/dconnect-manager-app/src/main/java/org/deviceconnect/android/manager/setting/TextDialogFragment.java | 2229 | /*
TextDialogFragment.java
Copyright (c) 2016 NTT DOCOMO,INC.
Released under the MIT license
http://opensource.org/licenses/mit-license.php
*/
package org.deviceconnect.android.manager.setting;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import org.deviceconnect.android.manager.R;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
/**
* テキストを表示するためのダイアログ.
*
* @author NTT DOCOMO, INC.
*/
public class TextDialogFragment extends DialogFragment {
/**
* バッファサイズ.
*/
private static final int BUFFER_SIZE = 1024;
@Override
public Dialog onCreateDialog(final Bundle savedInstanceState) {
View view = View.inflate(getActivity(), R.layout.fragment_privacypolicy, null);
TextView text = view.findViewById(android.R.id.text1);
InputStream is = null;
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
is = getActivity().getResources().openRawResource(getArguments().getInt(Intent.EXTRA_TEXT));
byte[] buf = new byte[BUFFER_SIZE];
while (true) {
int len = is.read(buf);
if (len < 0) {
break;
}
os.write(buf, 0, len);
}
text.setText(new String(os.toByteArray(), "UTF-8"));
} catch (IOException e) {
// do-thing
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// do-thing
}
}
}
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(view);
builder.setTitle(getArguments().getInt(Intent.EXTRA_TITLE));
builder.setPositiveButton(R.string.activity_settings_close, (dialog, which) -> {
dialog.dismiss();
});
return builder.create();
}
}
| mit |
Kiandr/CrackingCodingInterview | java/Ch 08. Recursion and Dynamic Programming/Introduction/FibonacciA.java | 873 | package Introduction;
public class FibonacciA {
public static int fibonacci(int i) {
if (i == 0) {
return 0;
}
if (i == 1) {
return 1;
}
return fibonacci(i - 1) + fibonacci(i - 2);
}
/**
* @param args
*/
public static void main(String[] args) {
int max = 35; // WARNING: If you make this above 40ish, your computer may serious slow down.
int trials = 10; // Run code multiple times to compute average time.
double[] times = new double[max]; // Store times
for (int j = 0; j < trials; j++) { // Run this 10 times to compute
for (int i = 0; i < max; i++) {
long start = System.currentTimeMillis();
fibonacci(i);
long end = System.currentTimeMillis();
long time = end - start;
times[i] += time;
}
}
for (int j = 0; j < max; j++) {
System.out.println(j + ": " + times[j] / trials + "ms");
}
}
}
| mit |
bigbang87/deadly-monsters | forge-1.11.2/src/main/java/com/dmonsters/main/MainMod.java | 1608 | package com.dmonsters.main;
import net.minecraft.client.Minecraft;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import org.apache.logging.log4j.Logger;
import com.dmonsters.entityProjectile.EntityLuckyEgg;
import com.dmonsters.proxy.CommonProxy;
@Mod(modid = MainMod.MODID, name = MainMod.MODNAME, version = MainMod.MODVERSION)
public class MainMod {
public static final String MODID = "dmonsters";
public static final String MODNAME = "Deadly Monsters";
public static final String MODVERSION = "1.7";
public static final ModCreativeTabs MOD_CREATIVETAB = new ModCreativeTabs("modTab");
@SidedProxy(clientSide = "com.dmonsters.proxy.ClientProxy", serverSide = "com.dmonsters.proxy.ServerProxy")
public static CommonProxy proxy;
@Mod.Instance
public static MainMod instance;
public static Logger logger;
@Mod.EventHandler
public void preInit(FMLPreInitializationEvent event) {
logger = event.getModLog();
ModSounds.init();
proxy.preInit(event);
}
@Mod.EventHandler
public void init(FMLInitializationEvent e) {
proxy.init(e);
}
@Mod.EventHandler
public void postInit(FMLPostInitializationEvent e) {
proxy.postInit(e);
}
}
| mit |
darshanhs90/Java-InterviewPrep | src/yelpInterview/_Leetcode06atoi.java | 199 | package yelpInterview;
public class _Leetcode06atoi {
public static void main(String[] args) {
}
public int myAtoi(String str) {
return str.length()==0?0:Integer.parseInt(str);
}
}
| mit |
XDrake99/PICalculator | core/src/main/java/it/cavallium/warppi/extra/tetris/GameStatus.java | 110 | package it.cavallium.warppi.extra.tetris;
public enum GameStatus {
INITIAL,
PLAYING,
LOST,
WIN,
ENDED
}
| mit |
wangscript/jresplus | jresplus-common/src/main/java/com/hundsun/jresplus/common/util/io/CharArrayWriter.java | 5023 | package com.hundsun.jresplus.common.util.io;
import java.io.IOException;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
/**
*
* @author LeoHu copy by sagahl copy by fish
*
*/
public final class CharArrayWriter extends Writer {
private static final char[] EMPTY_CHAR_ARRAY = new char[0];
/** 每个buffer的长度,缺省为1K */
private int bufferEntrySize = 1024;
private List<char[]> buffers = new ArrayList<char[]>();
/** 当前使用的buffer下标. */
private int currentBufferIndex;
/** 当前buffer */
private char[] currentBuffer;
/** 已写入的数据长度 */
private int count;
/** 每次写的统计 ,统计10次吧 */
private Turn turn = new Turn(10);
public CharArrayWriter() {
needNewBuffer();
}
public CharArrayWriter(int bufferEntrySize) {
this.bufferEntrySize = bufferEntrySize;
}
public int getBufferEntrySize() {
return this.bufferEntrySize;
}
private char[] getBuffer(int index) {
return buffers.get(index);
}
private int getCurrentBufferPos() {
if (count == 0) {
return 0;
}
int pos = count % bufferEntrySize;
if (pos == 0) {
// 一个buffer用光了
needNewBuffer();
return 0;
}
return pos;
}
private void needNewBuffer() {
if (currentBufferIndex < buffers.size() - 1) {
// 还没有未使用的buffer,继续使用老的buffer
currentBufferIndex++;
currentBuffer = getBuffer(currentBufferIndex);
} else {
// 创建新buffer
char[] createOne = new char[bufferEntrySize];
buffers.add(createOne);
currentBuffer = createOne;
currentBufferIndex++;
}
}
@Override
public void write(char[] cbuf, int off, int len) throws IOException {
if ((off < 0) || (off > cbuf.length) || (len < 0)
|| ((off + len) > cbuf.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException();
} else if (len == 0) {
return;
}
int remaining = len;
int inBufferPos = getCurrentBufferPos();
while (remaining > 0) {
int part = Math.min(remaining, bufferEntrySize - inBufferPos);
System.arraycopy(cbuf, off + len - remaining, currentBuffer,
inBufferPos, part);
remaining -= part;
count += part;
if (remaining > 0) {
inBufferPos = getCurrentBufferPos();
}
}
}
@Override
public void write(int b) {
int inBufferPos = getCurrentBufferPos();
currentBuffer[inBufferPos] = (char) b;
count++;
}
public int size() {
return count;
}
public void reset() {
int leftBufferCount = turn.addCountGetAvg();
count = 0;
currentBufferIndex = 0;
currentBuffer = getBuffer(0);
curtailBuffer(leftBufferCount);
}
private void curtailBuffer(int n) {
if (n < 1) {
return;
}
if (this.buffers.size() <= n) {
return;
}
for (int i = this.buffers.size() - 1; i >= n; i--) {
this.buffers.remove(i);
}
}
public void writeTo(Writer out) throws IOException {
int remaining = count;
for (int i = 0; i < buffers.size(); i++) {
char[] buf = getBuffer(i);
int c = Math.min(buf.length, remaining);
out.write(buf, 0, c);
remaining -= c;
if (remaining == 0) {
break;
}
}
}
public char[] toCharArray() {
int remaining = count;
if (remaining == 0) {
return EMPTY_CHAR_ARRAY;
}
char newbuf[] = new char[remaining];
int pos = 0;
for (int i = 0; i < buffers.size(); i++) {
char[] buf = getBuffer(i);
int c = Math.min(buf.length, remaining);
System.arraycopy(buf, 0, newbuf, pos, c);
pos += c;
remaining -= c;
if (remaining == 0) {
break;
}
}
return newbuf;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder(this.count);
int remaining = this.count;
for (int i = 0; i < buffers.size(); i++) {
char[] buf = getBuffer(i);
int c = Math.min(buf.length, remaining);
sb.append(buf, 0, c);
remaining -= c;
if (remaining == 0) {
break;
}
}
return sb.toString();
}
@Override
public void flush() throws IOException {
// nop
}
@Override
public void close() throws IOException {
// nop
}
/**
* 循环队列
*
*/
private final class Turn {
private Fragment currentFg;
/**
* 创建一个长度为size的循环队列
*/
private Turn(int size) {
Fragment head = new Fragment();
currentFg = head;
for (int i = 0; i < size - 1; i++) {
currentFg.next = new Fragment();
currentFg = currentFg.next;
}
currentFg.next = head;
}
/**
* 增加一个数据并且统计平均值
*/
private int addCountGetAvg() {
if (count != 0) {
currentFg.writeCount = count;
currentFg = currentFg.next;
}
long total = 0L;
int usedFragment = 0;
Fragment f = currentFg.next;
while (f != currentFg) {
total += f.writeCount;
if (f.writeCount != 0) {
usedFragment++;
}
f = f.next;
}
if (usedFragment == 0 || total == 0) {
return count;
}
return (int) (total / usedFragment / bufferEntrySize) + 1;
}
}
private static final class Fragment {
private int writeCount = 0;
private Fragment next;
}
}
| mit |
JonathanJohannsen/Example | chain/src/main/java/com/iluwatar/RequestType.java | 99 | package com.iluwatar;
public enum RequestType {
DEFEND_CASTLE, TORTURE_PRISONER, COLLECT_TAX
}
| mit |
selvasingh/azure-sdk-for-java | sdk/devtestlabs/mgmt-v2018_09_15/src/main/java/com/microsoft/azure/management/devtestlabs/v2018_09_15/implementation/OperationResultImpl.java | 1363 | /**
* 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.implementation;
import com.microsoft.azure.management.devtestlabs.v2018_09_15.OperationResult;
import com.microsoft.azure.arm.model.implementation.WrapperImpl;
import rx.Observable;
import com.microsoft.azure.management.devtestlabs.v2018_09_15.OperationError;
import com.microsoft.azure.management.devtestlabs.v2018_09_15.HttpStatusCode;
class OperationResultImpl extends WrapperImpl<OperationResultInner> implements OperationResult {
private final DevTestLabsManager manager;
private String locationName;
private String name;
OperationResultImpl(OperationResultInner inner, DevTestLabsManager manager) {
super(inner);
this.manager = manager;
}
@Override
public DevTestLabsManager manager() {
return this.manager;
}
@Override
public OperationError error() {
return this.inner().error();
}
@Override
public String status() {
return this.inner().status();
}
@Override
public HttpStatusCode statusCode() {
return this.inner().statusCode();
}
}
| mit |
CDLUC3/dash-xtf | xtf/WEB-INF/src/org/cdlib/xtf/util/SubDirFilter.java | 4222 | package org.cdlib.xtf.util;
/**
* Copyright (c) 2009, Regents of the University of California
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* - Neither the name of the University of California nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
/**
* This class provides an efficient means to determine if a given subdirectory
* is "in" or "out" of the set of directories specified to index. Essentially,
* if a given directory has an ancestor or a descendant in the set, it
* qualifies. That is, ancestors and cousins of the set directories will be
* indexed, but not necessarily all the cousins, nephews, nieces, etc.
*/
public class SubDirFilter
{
private HashSet<String> targets = new HashSet();
private HashSet<String> ancestors = new HashSet();
/** Tell if nothing has been added yet */
public boolean isEmpty() {
return targets.isEmpty();
}
/**
* Adds a directory to the set.
*/
public void add(File dirFile) {
targets.add(dirFile.toString());
for (String a : ancestorOrSelf(dirFile)) {
if (!ancestors.add(a))
break;
}
}
/**
* Returns the number of targets that have been added to the filter.
*/
public int size()
{
return targets.size();
}
/**
* Get a list of all targets in lexicographic order.
*/
public List<String> getTargets()
{
ArrayList<String> list = new ArrayList(targets);
Collections.sort(list);
return list;
}
/**
* Checks if the given directory is in the set, where "in" is defined as
* having an ancestor or descendant within the set.
*/
public boolean approve(String dir) {
return approve(new File(Path.normalizePath(dir)));
}
/**
* Checks if the given directory is in the set, where "in" is defined as
* having an ancestor or descendant within the set.
*/
public boolean approve(File dirFile)
{
// If this dir has descendants in the set, yes.
if (ancestors.contains(dirFile.toString()))
return true;
// If this dir has ancestors in the set, yes.
for (String a : ancestorOrSelf(dirFile)) {
if (targets.contains(a))
return true;
}
// Otherwise, no.
return false;
}
/**
* Make a list of the directory and all its ancestors.
*/
private ArrayList<String> ancestorOrSelf(File dir)
{
ArrayList<String> list = new ArrayList();
boolean found = false;
for (; !found && dir != null; dir = dir.getParentFile())
list.add(dir.toString());
return list;
}
} // class SubdirFilter
| mit |
SINeWang/metamate | status-core-spec/src/main/java/one/kii/kiimate/status/core/ctl/VisitRawStatusCtl.java | 2127 | package one.kii.kiimate.status.core.ctl;
import one.kii.kiimate.status.core.api.VisitRawStatusApi;
import one.kii.summer.asdf.api.VisitApiCaller;
import one.kii.summer.io.context.ErestHeaders;
import one.kii.summer.io.context.ReadContext;
import one.kii.summer.io.receiver.ReadController;
import one.kii.summer.zoom.ZoomOutByName;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import static one.kii.kiimate.status.core.ctl.VisitFatStatusCtl.PROVIDER_ID;
/**
* Created by WangYanJiong on 20/06/2017.
*/
@RestController
@RequestMapping(value = "/api/v1/{" + PROVIDER_ID + "}/raw-status", method = RequestMethod.GET)
@CrossOrigin(origins = "*")
public class VisitRawStatusCtl extends ReadController {
static final String PROVIDER_ID = "provider_id";
static final String GROUP = "group";
static final String NAME = "name";
static final String STABILITY = "stability";
static final String VERSION = "version";
@Autowired
private VisitRawStatusApi api;
@RequestMapping(value = "/{" + GROUP + "}/{" + NAME + "}/{" + STABILITY + "}/{" + VERSION + ":.+}", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public ResponseEntity<?> visit(
@RequestHeader(value = ErestHeaders.REQUEST_ID, required = false) String requestId,
@RequestHeader(ErestHeaders.VISITOR_ID) String visitorId,
@PathVariable(PROVIDER_ID) String providerId,
@PathVariable(GROUP) String group,
@PathVariable(NAME) String name,
@PathVariable(STABILITY) String stability,
@PathVariable(VERSION) String version) {
ReadContext context = buildContext(requestId, providerId, visitorId);
ZoomOutByName form = new ZoomOutByName();
form.setProviderId(providerId);
form.setGroup(group);
form.setName(name);
form.setStability(stability);
form.setVersion(version);
return VisitApiCaller.sync(api, context, form);
}
}
| mit |
jemygraw/qiniu-lab-android | QiniuLab/app/src/main/java/com/qiniu/qiniulab/activity/upload/SimpleUploadUseSaveKeyFromXParamActivity.java | 13669 | package com.qiniu.qiniulab.activity.upload;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.ipaulpro.afilechooser.utils.FileUtils;
import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UpProgressHandler;
import com.qiniu.android.storage.UploadManager;
import com.qiniu.android.storage.UploadOptions;
import com.qiniu.android.utils.AsyncRun;
import com.qiniu.qiniulab.R;
import com.qiniu.qiniulab.config.QiniuLabConfig;
import com.qiniu.qiniulab.utils.Tools;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class SimpleUploadUseSaveKeyFromXParamActivity extends ActionBarActivity {
private static final int REQUEST_CODE = 8090;
private SimpleUploadUseSaveKeyFromXParamActivity context;
private EditText uploadXParamEditText;
private TextView uploadLogTextView;
private LinearLayout uploadStatusLayout;
private ProgressBar uploadProgressBar;
private TextView uploadSpeedTextView;
private TextView uploadFileLengthTextView;
private TextView uploadPercentageTextView;
private UploadManager uploadManager;
private long uploadLastTimePoint;
private long uploadLastOffset;
private long uploadFileLength;
private String uploadFilePath;
public SimpleUploadUseSaveKeyFromXParamActivity() {
this.context = this;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.simple_upload_use_save_key_from_xparam_activity);
this.uploadProgressBar = (ProgressBar) this
.findViewById(R.id.simple_upload_use_save_key_from_xparam_upload_progressbar);
this.uploadProgressBar.setMax(100);
this.uploadStatusLayout = (LinearLayout) this
.findViewById(R.id.simple_upload_use_save_key_status_layout);
this.uploadSpeedTextView = (TextView) this
.findViewById(R.id.simple_upload_use_save_key_from_xparam_upload_speed_textview);
this.uploadFileLengthTextView = (TextView) this
.findViewById(R.id.simple_upload_use_save_key_from_xparam_upload_file_length_textview);
this.uploadPercentageTextView = (TextView) this
.findViewById(R.id.simple_upload_use_save_key_from_xparam_upload_percentage_textview);
this.uploadStatusLayout.setVisibility(LinearLayout.INVISIBLE);
this.uploadXParamEditText = (EditText) this
.findViewById(R.id.simple_upload_use_save_key_from_xparam_file_key);
this.uploadLogTextView = (TextView) this
.findViewById(R.id.simple_upload_use_save_key_from_xparam_log_textview);
}
public void selectUploadFile(View view) {
Intent target = FileUtils.createGetContentIntent();
Intent intent = Intent.createChooser(target,
this.getString(R.string.choose_file));
try {
this.startActivityForResult(intent, REQUEST_CODE);
} catch (ActivityNotFoundException ex) {
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE:
// If the file selection was successful
if (resultCode == RESULT_OK) {
if (data != null) {
// Get the URI of the selected file
final Uri uri = data.getData();
try {
// Get the file path from the URI
final String path = FileUtils.getPath(this, uri);
this.uploadFilePath = path;
this.clearLog();
this.writeLog(context
.getString(R.string.qiniu_select_upload_file)
+ path);
} catch (Exception e) {
Toast.makeText(
context,
context.getString(R.string.qiniu_get_upload_file_failed),
Toast.LENGTH_LONG).show();
}
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
public void uploadFile(View view) {
if (this.uploadFilePath == null) {
return;
}
//从业务服务器获取上传凭证
new Thread(new Runnable() {
@Override
public void run() {
final OkHttpClient httpClient = new OkHttpClient();
Request req = new Request.Builder().url(QiniuLabConfig.makeUrl(
QiniuLabConfig.REMOTE_SERVICE_SERVER,
QiniuLabConfig.SIMPLE_UPLOAD_USE_SAVE_KEY_FROM_XPARAM_PATH)).method("GET", null).build();
Response resp = null;
try {
resp = httpClient.newCall(req).execute();
JSONObject jsonObject = new JSONObject(resp.body().string());
String uploadToken = jsonObject.getString("uptoken");
writeLog(context
.getString(R.string.qiniu_get_upload_token)
+ uploadToken);
upload(uploadToken);
} catch (IOException e) {
AsyncRun.runInMain(new Runnable() {
@Override
public void run() {
Toast.makeText(
context,
context.getString(R.string.qiniu_get_upload_token_failed),
Toast.LENGTH_LONG).show();
}
});
writeLog(context
.getString(R.string.qiniu_get_upload_token_failed)
+ resp.toString());
} catch (JSONException e) {
writeLog(context.getString(R.string.qiniu_get_upload_token_failed));
writeLog("StatusCode:" + resp.code());
if (resp != null) {
writeLog("Response:" + resp.toString());
}
writeLog("Exception:" + e.getMessage());
} finally {
if (resp != null) {
resp.body().close();
}
}
}
}).start();
}
private void upload(String uploadToken) {
if (this.uploadManager == null) {
this.uploadManager = new UploadManager();
}
File uploadFile = new File(this.uploadFilePath);
String uploadXParam = this.uploadXParamEditText.getText().toString();
Map<String, String> xParams = new HashMap<String, String>();
xParams.put("x:saveKeyEx", uploadXParam);
UploadOptions uploadOptions = new UploadOptions(xParams, null, false,
new UpProgressHandler() {
@Override
public void progress(String key, double percent) {
updateStatus(percent);
}
}, null);
final long startTime = System.currentTimeMillis();
final long fileLength = uploadFile.length();
this.uploadFileLength = fileLength;
this.uploadLastTimePoint = startTime;
this.uploadLastOffset = 0;
AsyncRun.runInMain(new Runnable() {
@Override
public void run() {
// prepare status
uploadPercentageTextView.setText("0 %");
uploadSpeedTextView.setText("0 KB/s");
uploadFileLengthTextView.setText(Tools.formatSize(fileLength));
uploadStatusLayout.setVisibility(LinearLayout.VISIBLE);
}
});
writeLog(context.getString(R.string.qiniu_upload_file) + "...");
this.uploadManager.put(uploadFile, null, uploadToken,
new UpCompletionHandler() {
@Override
public void complete(String key, ResponseInfo respInfo,
JSONObject jsonData) {
AsyncRun.runInMain(new Runnable() {
@Override
public void run() {
// reset status
uploadStatusLayout
.setVisibility(LinearLayout.INVISIBLE);
uploadProgressBar.setProgress(0);
}
});
long lastMillis = System.currentTimeMillis()
- startTime;
if (respInfo.isOK()) {
try {
String fileKey = jsonData.getString("key");
String fileHash = jsonData.getString("hash");
writeLog("File Size: "
+ Tools.formatSize(uploadFileLength));
writeLog("File Key: " + fileKey);
writeLog("File Hash: " + fileHash);
writeLog("Last Time: "
+ Tools.formatMilliSeconds(lastMillis));
writeLog("Average Speed: "
+ Tools.formatSpeed(fileLength,
lastMillis));
writeLog("X-Reqid: " + respInfo.reqId);
writeLog("X-Via: " + respInfo.xvia);
writeLog("--------------------------------");
} catch (JSONException e) {
AsyncRun.runInMain(new Runnable() {
@Override
public void run() {
Toast.makeText(
context,
context.getString(R.string.qiniu_upload_file_response_parse_error),
Toast.LENGTH_LONG).show();
}
});
writeLog(context
.getString(R.string.qiniu_upload_file_response_parse_error));
if (jsonData != null) {
writeLog(jsonData.toString());
}
writeLog("--------------------------------");
}
} else {
AsyncRun.runInMain(new Runnable() {
@Override
public void run() {
Toast.makeText(
context,
context.getString(R.string.qiniu_upload_file_failed),
Toast.LENGTH_LONG).show();
}
});
writeLog(respInfo.toString());
if (jsonData != null) {
writeLog(jsonData.toString());
}
writeLog("--------------------------------");
}
}
}, uploadOptions);
}
private void updateStatus(final double percentage) {
long now = System.currentTimeMillis();
long deltaTime = now - uploadLastTimePoint;
long currentOffset = (long) (percentage * uploadFileLength);
long deltaSize = currentOffset - uploadLastOffset;
if (deltaTime <= 100) {
return;
}
final String speed = Tools.formatSpeed(deltaSize, deltaTime);
// update
uploadLastTimePoint = now;
uploadLastOffset = currentOffset;
AsyncRun.runInMain(new Runnable() {
@Override
public void run() {
int progress = (int) (percentage * 100);
uploadProgressBar.setProgress(progress);
uploadPercentageTextView.setText(progress + " %");
uploadSpeedTextView.setText(speed);
}
});
}
private void clearLog() {
this.uploadLogTextView.setText("");
}
private void writeLog(final String msg) {
AsyncRun.runInMain(new Runnable() {
@Override
public void run() {
uploadLogTextView.append(msg);
uploadLogTextView.append("\r\n");
}
});
}
}
| mit |
ZzJing/ugrad-algorithm-intro | tree/MaxTree.java | 1104 |
public class MaxTree {
public TreeNode constructMaximumBinaryTree(int[] nums) {
if (nums == null || nums.length == 0) {
return null;
}
// parameter is not maxIndex - 1 since nums.length is excluded in the loop
return constructTree(nums, 0, nums.length);
}
private TreeNode constructTree(int[] nums, int left, int right) {
if (left == right) {
return null;
}
int maxIndex = maxIndex(nums, left, right);
TreeNode root = new TreeNode(nums[maxIndex]);
// parameter is not maxIndex - 1 since maxIndex is excluded in the loop
root.left = constructTree(nums, left, maxIndex);
root.right = constructTree(nums, maxIndex + 1, right);
return root;
}
private int maxIndex(int[] nums, int left, int right) {
int maxIndex = left; // i < right exclude "right"
for (int i = left; i < right; i++) {
if (nums[maxIndex] < nums[i]) {
maxIndex = i;
}
}
return maxIndex;
}
}
| mit |
PhilipMay/cucumber-jvm | rhino/src/main/java/cucumber/runtime/javascript/JavaScriptSnippet.java | 776 | package cucumber.runtime.javascript;
import cucumber.runtime.snippets.Snippet;
import java.util.List;
import static cucumber.runtime.snippets.SnippetGenerator.untypedArguments;
public class JavaScriptSnippet implements Snippet {
@Override
public String template() {
return "{0}(/{1}/, function({3}) '{'\n" +
" // {4}\n" +
"'}');\n";
}
@Override
public String arguments(List<Class<?>> argumentTypes) {
return untypedArguments(argumentTypes);
}
@Override
public String namedGroupStart() {
return null;
}
@Override
public String namedGroupEnd() {
return null;
}
@Override
public String escapePattern(String pattern) {
return pattern;
}
}
| mit |
sile/sanmoku | analyzer/src/net/reduls/sanmoku/dic/SurfaceId.java | 3178 | package net.reduls.sanmoku.dic;
import java.io.DataInputStream;
import net.reduls.sanmoku.util.Misc;
public final class SurfaceId {
private static final int idOffset;
private static final byte[] nodes;
private static final byte[] exts;
private static final byte[] char_to_chck;
static {
nodes = Misc.readBytesFromFile("surface-id.bin.node", 1);
exts = Misc.readBytesFromFile("surface-id.bin.ext", 1);
char_to_chck = Misc.readBytesFromFile("surface-id.bin.char", 0x100, 1);
idOffset = Misc.readIntFromFile("category.bin");
}
public static void eachCommonPrefix(String text, int start, WordDic.Callback fn) {
long node = getNode(0);
int id = idOffset;
final CodeStream in = new CodeStream(text,start);
for(;;) {
if(isTerminal(node))
WordDic.eachViterbiNode(fn, id++, start, in.position()-start, false);
if(in.isEos())
return;
if(checkEncodedChildren(in, node)==false)
return;
final char arc = read(in);
final long next = getNode(base(node)+arc);
if(chck(next) != arc)
return;
node = next;
id += siblingTotal(node);
}
}
private static char read(CodeStream in) {
return (char)(char_to_chck[in.read()]&0xFF);
}
private static boolean checkEncodedChildren(CodeStream in, long node) {
switch(type(node)) {
case 0:
return checkEC(in,node);
default:
return true;
}
}
private static boolean checkEC(CodeStream in, long node) {
char chck = (char)((node>>27) & 0x7F);
return chck==0 || (read(in) == chck &&
in.isEos() == false);
}
private static char chck(long node) {
return (char)((node>>20) & 0x7F);
}
private static int base(long node) {
return (int)(node & 0x7FFFF);
}
private static boolean isTerminal(long node) {
return ((node>>19) & 1)==1;
}
private static int type(long node) {
if (((node>>39) & 1)==1) {
return 2+(int)((node>>38) & 1);
} else {
return 0;
}
}
private static int siblingTotal(long node) {
switch (type(node)) {
case 0:
return (int)((node>>34) & 0x1F);
case 2:
return (int)((node>>27) & 0x7FF);
default:
{
int i = (int)((node>>27) & 0x7FF);
return
(int)((exts[i*4+0]&0xFF)<<24) |
(int)((exts[i*4+1]&0xFF)<<16) |
(int)((exts[i*4+2]&0xFF)<<8) |
(int)((exts[i*4+3]&0xFF)<<0);
}
}
}
private static long getNode(int i) {
return (((long)(nodes[i*5+0] & 0xff) << 32) |
((long)(nodes[i*5+1] & 0xff) << 24) |
((long)(nodes[i*5+2] & 0xff) << 16) |
((long)(nodes[i*5+3] & 0xff) << 8) |
((long)(nodes[i*5+4] & 0xff)));
}
}
| mit |
coryjthompson/cordova-plugin-multiple-media-selection | src/android/com/busivid/cordova/mediapicker/MediaItem.java | 4230 | package com.busivid.cordova.mediapicker;
import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.os.Parcel;
import android.os.Parcelable;
import android.text.TextUtils;
import com.busivid.cordova.mediapicker.activities.MediaPickerActivity;
import com.busivid.cordova.mediapicker.utils.MediaUtils;
/**
* Contains information of photo or video that selected and return back in
* {@link MediaPickerActivity}
*/
public class MediaItem implements Parcelable {
public static final int PHOTO = 1;
public static final int VIDEO = 2;
private int type;
private Uri uriCropped;
private Uri uriOrigin;
/**
* @param mediaType Whether {@link #PHOTO} or {@link #VIDEO}
* @param uriOrigin {@link Uri} of media item.
*/
public MediaItem(int mediaType, Uri uriOrigin) {
this.type = mediaType;
this.uriOrigin = uriOrigin;
}
/**
* @return type of media item. Whether {@link #PHOTO} or {@link #VIDEO}
*/
public int getType() {
return type;
}
/**
* Set type of media.
*
* @param type is {@link #PHOTO} or {@link #VIDEO}
*/
public void setType(int type) {
this.type = type;
}
public Uri getUriCropped() {
return uriCropped;
}
public void setUriCropped(Uri uriCropped) {
this.uriCropped = uriCropped;
}
public Uri getUriOrigin() {
return uriOrigin;
}
public void setUriOrigin(Uri uriOrigin) {
this.uriOrigin = uriOrigin;
}
public boolean isVideo() {
return type == VIDEO;
}
public boolean isPhoto() {
return type == PHOTO;
}
@Override
public int describeContents() {
return 0;
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(this.type);
if (this.uriCropped == null) {
dest.writeString(null);
} else {
dest.writeString(this.uriCropped.toString());
}
if (this.uriOrigin == null) {
dest.writeString(null);
} else {
dest.writeString(this.uriOrigin.toString());
}
}
public MediaItem(Parcel in) {
this.type = in.readInt();
String crop = in.readString();
if (!TextUtils.isEmpty(crop))
this.uriCropped = Uri.parse(crop);
String origin = in.readString();
if (!TextUtils.isEmpty(origin))
this.uriOrigin = Uri.parse(origin);
}
public static final Creator<MediaItem> CREATOR = new Creator<MediaItem>() {
@Override
public MediaItem[] newArray(int size) {
return new MediaItem[size];
}
@Override
public MediaItem createFromParcel(Parcel source) {
return new MediaItem(source);
}
};
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((uriCropped == null) ? 0 : uriCropped.hashCode());
result = prime * result + ((uriOrigin == null) ? 0 : uriOrigin.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;
MediaItem other = (MediaItem) obj;
if (uriCropped == null) {
if (other.uriCropped != null)
return false;
} else if (!uriCropped.equals(other.uriCropped))
return false;
if (uriOrigin == null) {
if (other.uriOrigin != null)
return false;
} else if (!uriOrigin.equals(other.uriOrigin))
return false;
return true;
}
@Override
public String toString() {
return "MediaItem [type=" + type + ", uriCropped=" + uriCropped + ", uriOrigin=" + uriOrigin + "]";
}
/**
* @param context
* @return Path of origin file.
*/
public String getPathOrigin(Context context) {
return getPathFromUri(context, uriOrigin);
}
/**
* @param context
* @return Path of cropped file.
*/
public String getPathCropped(Context context) {
return getPathFromUri(context, uriCropped);
}
private String getPathFromUri(Context context, Uri uri) {
if (uri == null)
return null;
String scheme = uri.getScheme();
if (scheme.equals(ContentResolver.SCHEME_FILE)) {
return uri.getPath();
} else if (scheme.equals(ContentResolver.SCHEME_CONTENT)) {
if (isPhoto()) {
return MediaUtils.getRealImagePathFromURI(context.getContentResolver(), uri);
} else {
return MediaUtils.getRealVideoPathFromURI(context.getContentResolver(), uri);
}
}
return uri.toString();
}
} | mit |
asposeemail/Aspose_Email_Cloud | Examples/Android/app/src/main/java/com/aspose/email/cloud/Utils.java | 1541 | package com.aspose.email.cloud;
import org.apache.commons.io.IOUtils;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.logging.Logger;
public class Utils {
public static final String STORAGE = null;
public static final String FOLDER = null;
public static final String BASE_PATH = null;
private static final Logger LOGGER = Logger.getLogger(Utils.class.getName());
public static File createTempFile(final String PREFIX, final String SUFFIX) throws IOException {
final File tempFile = File.createTempFile(PREFIX, SUFFIX);
tempFile.deleteOnExit();
return tempFile;
}
public static File stream2file (final String PREFIX, final String SUFFIX, InputStream in) throws IOException {
final File tempFile = File.createTempFile(PREFIX, SUFFIX);
tempFile.deleteOnExit();
try (FileOutputStream out = new FileOutputStream(tempFile)) {
IOUtils.copy(in, out);
}
return tempFile;
}
public static void copyInputStreamToFile( InputStream in, File file ) {
try {
OutputStream out = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
} | mit |
willempx/verifast | examples/java/Automation.java | 1397 | //@ predicate a(boolean x; int y) = x ? b(0, 0, 0, y) : y == 0;
//@ predicate b<t1, t2>(t1 x, t1 y, t2 z1; t2 z2) = x == y ? c<t1, t2>(x, z2) : z2 == z1;
//@ predicate c<tp1, tp2>(tp1 x; tp2 y);
//@ predicate n(;);
//@ predicate p(;) = [1/2]n();
class Automation {
void test1()
//@ requires a(true, 5);
//@ ensures true;
{
//@ assert c(0, 5);
}
void test2()
//@ requires p();
//@ ensures true;
{
//@ assert [1/2]n();
}
}
/*@
predicate_family cell(Class c)(Cell c;);
predicate_family_instance cell(CellImpl.class)(CellImpl c) = c.value |-> _;
predicate_family_instance cell(BackupCell.class)(BackupCell c) = cell(CellImpl.class)(c);
predicate_family_instance cell(BackupCellWrapper.class)(BackupCellWrapper c) = c.b |-> ?b &*& b ? c.myvalue |-> _ : cell(BackupCell.class)(c);
@*/
interface Cell {
}
class CellImpl implements Cell {
int value;
}
class BackupCell extends CellImpl {
}
class BackupCellWrapper extends CellImpl {
boolean b;
int myvalue;
}
class Test {
void test1(CellImpl c)
//@ requires cell(BackupCell.class)(c);
//@ ensures true;
{
c.value = 5;
}
void test2(BackupCellWrapper c)
//@ requires cell(BackupCellWrapper.class)(c);
//@ ensures true;
{
if(! c.b) {
c.value = 5;
} else {
c.myvalue = 10;
}
}
}
| mit |
meiyi1986/GPJSS | src/ec/app/majority/func/W.java | 1133 | /*
Copyright 2013 by Sean Luke
Licensed under the Academic Free License version 3.0
See the file "LICENSE" for more information
*/
package ec.app.majority.func;
import ec.*;
import ec.app.majority.*;
import ec.gp.*;
import ec.util.*;
public class W extends GPNode
{
public String toString() { return "w"; }
public int expectedChildren() { return 0; }
public static long X0 = 0;
public static long X1 = 0;
static
{
for(int i = 0 ; i < 64; i++)
{
long val = (i >> 4) & 0x1; // west element
X0 = X0 | (val << i);
}
for(int i = 64 ; i < 128; i++)
{
long val = (i >> 4) & 0x1; // west element
X1 = X1 | (val << (i - 64));
}
}
public void eval(final EvolutionState state,
final int thread,
final GPData input,
final ADFStack stack,
final GPIndividual individual,
final Problem problem)
{
MajorityData md = (MajorityData) input;
md.data0 = X0;
md.data1 = X1;
}
}
| mit |
giraud/reasonml-idea-plugin | src/com/reason/lang/core/psi/PsiSExpr.java | 423 | package com.reason.lang.core.psi;
import com.intellij.lang.ASTNode;
import com.reason.lang.core.psi.impl.PsiToken;
import com.reason.lang.dune.DuneTypes;
import org.jetbrains.annotations.NotNull;
public class PsiSExpr extends PsiToken<DuneTypes> {
public PsiSExpr(@NotNull DuneTypes types, @NotNull ASTNode node) {
super(types, node);
}
@NotNull
@Override
public String toString() {
return "(";
}
}
| mit |
georghinkel/ttc2017smartGrids | solutions/eMoflon/rgse.ttc17.emoflon.tgg.task1/gen/rgse/ttc17/emoflon/tgg/task1/Rules/impl/PositionPointLinkImpl.java | 63327 | /**
*/
package rgse.ttc17.emoflon.tgg.task1.Rules.impl;
import gluemodel.CIM.IEC61968.Assets.Asset;
import gluemodel.CIM.IEC61968.Common.Location;
import gluemodel.CIM.IEC61968.Common.PositionPoint;
import gluemodel.CIM.IEC61968.Metering.MeterAsset;
import gluemodel.MeterAssetPhysicalDevicePair;
import java.lang.Iterable;
import java.lang.reflect.InvocationTargetException;
import java.util.LinkedList;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EOperation;
import org.moflon.tgg.language.csp.CSP;
import org.moflon.tgg.runtime.AttributeConstraintsRuleResult;
import org.moflon.tgg.runtime.EMoflonEdge;
import org.moflon.tgg.runtime.EObjectContainer;
import org.moflon.tgg.runtime.IsApplicableMatch;
import org.moflon.tgg.runtime.IsApplicableRuleResult;
import org.moflon.tgg.runtime.Match;
import org.moflon.tgg.runtime.PerformRuleResult;
import org.moflon.tgg.runtime.RuntimeFactory;
import org.moflon.tgg.runtime.TripleMatch;
import org.moflon.tgg.runtime.impl.AbstractRuleImpl;
import rgse.ttc17.emoflon.tgg.task1.LocationToLocation;
import rgse.ttc17.emoflon.tgg.task1.PositionPointToPositionPoint;
import rgse.ttc17.emoflon.tgg.task1.Rules.PositionPointLink;
import rgse.ttc17.emoflon.tgg.task1.Rules.RulesPackage;
// <-- [user defined imports]
import org.moflon.tgg.csp.*;
import rgse.ttc17.emoflon.tgg.task1.csp.constraints.*;
import org.moflon.tgg.csp.constraints.*;
import org.moflon.tgg.language.csp.*;
import org.moflon.tgg.runtime.TripleMatchNodeMapping;
import java.util.Optional;
import org.moflon.tgg.algorithm.delta.attribute.CheckAttributeHelper;
import SDMLanguage.expressions.ComparingOperator;
// [user defined imports] -->
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Position Point Link</b></em>'.
* <!-- end-user-doc -->
* <p>
* </p>
*
* @generated
*/
public class PositionPointLinkImpl extends AbstractRuleImpl implements PositionPointLink {
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected PositionPointLinkImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return RulesPackage.eINSTANCE.getPositionPointLink();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isAppropriate_FWD(Match match, Location srcLocation, PositionPoint positionPoint,
MeterAssetPhysicalDevicePair pair, MeterAsset asset) {
// initial bindings
Object[] result1_black = PositionPointLinkImpl.pattern_PositionPointLink_0_1_initialbindings_blackBBBBBB(this,
match, srcLocation, positionPoint, pair, asset);
if (result1_black == null) {
throw new RuntimeException("Pattern matching in node [initial bindings] failed." + " Variables: "
+ "[this] = " + this + ", " + "[match] = " + match + ", " + "[srcLocation] = " + srcLocation + ", "
+ "[positionPoint] = " + positionPoint + ", " + "[pair] = " + pair + ", " + "[asset] = " + asset
+ ".");
}
// Solve CSP
Object[] result2_bindingAndBlack = PositionPointLinkImpl
.pattern_PositionPointLink_0_2_SolveCSP_bindingAndBlackFBBBBBB(this, match, srcLocation, positionPoint,
pair, asset);
if (result2_bindingAndBlack == null) {
throw new RuntimeException("Pattern matching in node [Solve CSP] failed." + " Variables: " + "[this] = "
+ this + ", " + "[match] = " + match + ", " + "[srcLocation] = " + srcLocation + ", "
+ "[positionPoint] = " + positionPoint + ", " + "[pair] = " + pair + ", " + "[asset] = " + asset
+ ".");
}
CSP csp = (CSP) result2_bindingAndBlack[0];
// Check CSP
if (PositionPointLinkImpl.pattern_PositionPointLink_0_3_CheckCSP_expressionFBB(this, csp)) {
// collect elements to be translated
Object[] result4_black = PositionPointLinkImpl
.pattern_PositionPointLink_0_4_collectelementstobetranslated_blackBBBBB(match, srcLocation,
positionPoint, pair, asset);
if (result4_black == null) {
throw new RuntimeException("Pattern matching in node [collect elements to be translated] failed."
+ " Variables: " + "[match] = " + match + ", " + "[srcLocation] = " + srcLocation + ", "
+ "[positionPoint] = " + positionPoint + ", " + "[pair] = " + pair + ", " + "[asset] = " + asset
+ ".");
}
PositionPointLinkImpl.pattern_PositionPointLink_0_4_collectelementstobetranslated_greenBBBF(match,
srcLocation, positionPoint);
// EMoflonEdge srcLocation__positionPoint____Position = (EMoflonEdge) result4_green[3];
// collect context elements
Object[] result5_black = PositionPointLinkImpl
.pattern_PositionPointLink_0_5_collectcontextelements_blackBBBBB(match, srcLocation, positionPoint,
pair, asset);
if (result5_black == null) {
throw new RuntimeException(
"Pattern matching in node [collect context elements] failed." + " Variables: " + "[match] = "
+ match + ", " + "[srcLocation] = " + srcLocation + ", " + "[positionPoint] = "
+ positionPoint + ", " + "[pair] = " + pair + ", " + "[asset] = " + asset + ".");
}
PositionPointLinkImpl.pattern_PositionPointLink_0_5_collectcontextelements_greenBBBBBFFF(match, srcLocation,
positionPoint, pair, asset);
// EMoflonEdge pair__asset____a = (EMoflonEdge) result5_green[5];
// EMoflonEdge asset__srcLocation____Location = (EMoflonEdge) result5_green[6];
// EMoflonEdge srcLocation__asset____Assets = (EMoflonEdge) result5_green[7];
// register objects to match
PositionPointLinkImpl.pattern_PositionPointLink_0_6_registerobjectstomatch_expressionBBBBBB(this, match,
srcLocation, positionPoint, pair, asset);
return PositionPointLinkImpl.pattern_PositionPointLink_0_7_expressionF();
} else {
return PositionPointLinkImpl.pattern_PositionPointLink_0_8_expressionF();
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public PerformRuleResult perform_FWD(IsApplicableMatch isApplicableMatch) {
// perform transformation
Object[] result1_bindingAndBlack = PositionPointLinkImpl
.pattern_PositionPointLink_1_1_performtransformation_bindingAndBlackFFFFFFFFFBB(this,
isApplicableMatch);
if (result1_bindingAndBlack == null) {
throw new RuntimeException("Pattern matching in node [perform transformation] failed." + " Variables: "
+ "[this] = " + this + ", " + "[isApplicableMatch] = " + isApplicableMatch + ".");
}
Location srcLocation = (Location) result1_bindingAndBlack[0];
LocationToLocation locationToLocation = (LocationToLocation) result1_bindingAndBlack[1];
PositionPoint positionPoint = (PositionPoint) result1_bindingAndBlack[2];
outageDetectionJointarget.PositionPoint trgPositionPoint = (outageDetectionJointarget.PositionPoint) result1_bindingAndBlack[3];
outageDetectionJointarget.Location trgLocation = (outageDetectionJointarget.Location) result1_bindingAndBlack[4];
MeterAssetPhysicalDevicePair pair = (MeterAssetPhysicalDevicePair) result1_bindingAndBlack[5];
MeterAsset asset = (MeterAsset) result1_bindingAndBlack[6];
PositionPointToPositionPoint positionCorr = (PositionPointToPositionPoint) result1_bindingAndBlack[7];
// CSP csp = (CSP) result1_bindingAndBlack[8];
PositionPointLinkImpl.pattern_PositionPointLink_1_1_performtransformation_greenBB(trgPositionPoint,
trgLocation);
// collect translated elements
Object[] result2_green = PositionPointLinkImpl.pattern_PositionPointLink_1_2_collecttranslatedelements_greenF();
if (result2_green == null) {
throw new RuntimeException("Pattern matching in node [collect translated elements] failed.");
}
PerformRuleResult ruleresult = (PerformRuleResult) result2_green[0];
// bookkeeping for edges
Object[] result3_black = PositionPointLinkImpl.pattern_PositionPointLink_1_3_bookkeepingforedges_blackBBBBBBBBB(
ruleresult, srcLocation, locationToLocation, positionPoint, trgPositionPoint, trgLocation, pair, asset,
positionCorr);
if (result3_black == null) {
throw new RuntimeException("Pattern matching in node [bookkeeping for edges] failed." + " Variables: "
+ "[ruleresult] = " + ruleresult + ", " + "[srcLocation] = " + srcLocation + ", "
+ "[locationToLocation] = " + locationToLocation + ", " + "[positionPoint] = " + positionPoint
+ ", " + "[trgPositionPoint] = " + trgPositionPoint + ", " + "[trgLocation] = " + trgLocation + ", "
+ "[pair] = " + pair + ", " + "[asset] = " + asset + ", " + "[positionCorr] = " + positionCorr
+ ".");
}
PositionPointLinkImpl.pattern_PositionPointLink_1_3_bookkeepingforedges_greenBBBBBFF(ruleresult, srcLocation,
positionPoint, trgPositionPoint, trgLocation);
// EMoflonEdge trgLocation__trgPositionPoint____Position = (EMoflonEdge) result3_green[5];
// EMoflonEdge srcLocation__positionPoint____Position = (EMoflonEdge) result3_green[6];
// perform postprocessing story node is empty
// register objects
PositionPointLinkImpl.pattern_PositionPointLink_1_5_registerobjects_expressionBBBBBBBBBB(this, ruleresult,
srcLocation, locationToLocation, positionPoint, trgPositionPoint, trgLocation, pair, asset,
positionCorr);
return PositionPointLinkImpl.pattern_PositionPointLink_1_6_expressionFB(ruleresult);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IsApplicableRuleResult isApplicable_FWD(Match match) {
// prepare return value
Object[] result1_bindingAndBlack = PositionPointLinkImpl
.pattern_PositionPointLink_2_1_preparereturnvalue_bindingAndBlackFFB(this);
if (result1_bindingAndBlack == null) {
throw new RuntimeException("Pattern matching in node [prepare return value] failed." + " Variables: "
+ "[this] = " + this + ".");
}
EOperation performOperation = (EOperation) result1_bindingAndBlack[0];
// EClass eClass = (EClass) result1_bindingAndBlack[1];
Object[] result1_green = PositionPointLinkImpl
.pattern_PositionPointLink_2_1_preparereturnvalue_greenBF(performOperation);
IsApplicableRuleResult ruleresult = (IsApplicableRuleResult) result1_green[1];
// ForEach core match
Object[] result2_binding = PositionPointLinkImpl.pattern_PositionPointLink_2_2_corematch_bindingFFFFB(match);
if (result2_binding == null) {
throw new RuntimeException(
"Binding in node core match failed." + " Variables: " + "[match] = " + match + ".");
}
Location srcLocation = (Location) result2_binding[0];
PositionPoint positionPoint = (PositionPoint) result2_binding[1];
MeterAssetPhysicalDevicePair pair = (MeterAssetPhysicalDevicePair) result2_binding[2];
MeterAsset asset = (MeterAsset) result2_binding[3];
for (Object[] result2_black : PositionPointLinkImpl.pattern_PositionPointLink_2_2_corematch_blackBFBFFBBFB(
srcLocation, positionPoint, pair, asset, match)) {
LocationToLocation locationToLocation = (LocationToLocation) result2_black[1];
outageDetectionJointarget.PositionPoint trgPositionPoint = (outageDetectionJointarget.PositionPoint) result2_black[3];
outageDetectionJointarget.Location trgLocation = (outageDetectionJointarget.Location) result2_black[4];
PositionPointToPositionPoint positionCorr = (PositionPointToPositionPoint) result2_black[7];
// ForEach find context
for (Object[] result3_black : PositionPointLinkImpl.pattern_PositionPointLink_2_3_findcontext_blackBBBBBBBB(
srcLocation, locationToLocation, positionPoint, trgPositionPoint, trgLocation, pair, asset,
positionCorr)) {
Object[] result3_green = PositionPointLinkImpl
.pattern_PositionPointLink_2_3_findcontext_greenBBBBBBBBFFFFFFFFF(srcLocation,
locationToLocation, positionPoint, trgPositionPoint, trgLocation, pair, asset,
positionCorr);
IsApplicableMatch isApplicableMatch = (IsApplicableMatch) result3_green[8];
// EMoflonEdge locationToLocation__trgLocation____target = (EMoflonEdge) result3_green[9];
// EMoflonEdge pair__asset____a = (EMoflonEdge) result3_green[10];
// EMoflonEdge locationToLocation__srcLocation____source = (EMoflonEdge) result3_green[11];
// EMoflonEdge asset__srcLocation____Location = (EMoflonEdge) result3_green[12];
// EMoflonEdge srcLocation__asset____Assets = (EMoflonEdge) result3_green[13];
// EMoflonEdge srcLocation__positionPoint____Position = (EMoflonEdge) result3_green[14];
// EMoflonEdge positionCorr__trgPositionPoint____target = (EMoflonEdge) result3_green[15];
// EMoflonEdge positionCorr__positionPoint____source = (EMoflonEdge) result3_green[16];
// solve CSP
Object[] result4_bindingAndBlack = PositionPointLinkImpl
.pattern_PositionPointLink_2_4_solveCSP_bindingAndBlackFBBBBBBBBBB(this, isApplicableMatch,
srcLocation, locationToLocation, positionPoint, trgPositionPoint, trgLocation, pair,
asset, positionCorr);
if (result4_bindingAndBlack == null) {
throw new RuntimeException("Pattern matching in node [solve CSP] failed." + " Variables: "
+ "[this] = " + this + ", " + "[isApplicableMatch] = " + isApplicableMatch + ", "
+ "[srcLocation] = " + srcLocation + ", " + "[locationToLocation] = " + locationToLocation
+ ", " + "[positionPoint] = " + positionPoint + ", " + "[trgPositionPoint] = "
+ trgPositionPoint + ", " + "[trgLocation] = " + trgLocation + ", " + "[pair] = " + pair
+ ", " + "[asset] = " + asset + ", " + "[positionCorr] = " + positionCorr + ".");
}
CSP csp = (CSP) result4_bindingAndBlack[0];
// check CSP
if (PositionPointLinkImpl.pattern_PositionPointLink_2_5_checkCSP_expressionFBB(this, csp)) {
// add match to rule result
Object[] result6_black = PositionPointLinkImpl
.pattern_PositionPointLink_2_6_addmatchtoruleresult_blackBB(ruleresult, isApplicableMatch);
if (result6_black == null) {
throw new RuntimeException("Pattern matching in node [add match to rule result] failed."
+ " Variables: " + "[ruleresult] = " + ruleresult + ", " + "[isApplicableMatch] = "
+ isApplicableMatch + ".");
}
PositionPointLinkImpl.pattern_PositionPointLink_2_6_addmatchtoruleresult_greenBB(ruleresult,
isApplicableMatch);
} else {
}
}
}
return PositionPointLinkImpl.pattern_PositionPointLink_2_7_expressionFB(ruleresult);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void registerObjectsToMatch_FWD(Match match, Location srcLocation, PositionPoint positionPoint,
MeterAssetPhysicalDevicePair pair, MeterAsset asset) {
match.registerObject("srcLocation", srcLocation);
match.registerObject("positionPoint", positionPoint);
match.registerObject("pair", pair);
match.registerObject("asset", asset);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CSP isAppropriate_solveCsp_FWD(Match match, Location srcLocation, PositionPoint positionPoint,
MeterAssetPhysicalDevicePair pair, MeterAsset asset) {// Create CSP
CSP csp = CspFactory.eINSTANCE.createCSP();
// Create literals
// Create attribute variables
// Create unbound variables
// Create constraints
// Solve CSP
return csp;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isAppropriate_checkCsp_FWD(CSP csp) {
return csp.check();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public CSP isApplicable_solveCsp_FWD(IsApplicableMatch isApplicableMatch, Location srcLocation,
LocationToLocation locationToLocation, PositionPoint positionPoint,
outageDetectionJointarget.PositionPoint trgPositionPoint, outageDetectionJointarget.Location trgLocation,
MeterAssetPhysicalDevicePair pair, MeterAsset asset, PositionPointToPositionPoint positionCorr) {// Create CSP
CSP csp = CspFactory.eINSTANCE.createCSP();
isApplicableMatch.getAttributeInfo().add(csp);
// Create literals
// Create attribute variables
// Create unbound variables
// Create constraints
// Solve CSP
// Snapshot pattern match on which CSP is solved
isApplicableMatch.registerObject("srcLocation", srcLocation);
isApplicableMatch.registerObject("locationToLocation", locationToLocation);
isApplicableMatch.registerObject("positionPoint", positionPoint);
isApplicableMatch.registerObject("trgPositionPoint", trgPositionPoint);
isApplicableMatch.registerObject("trgLocation", trgLocation);
isApplicableMatch.registerObject("pair", pair);
isApplicableMatch.registerObject("asset", asset);
isApplicableMatch.registerObject("positionCorr", positionCorr);
return csp;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean isApplicable_checkCsp_FWD(CSP csp) {
return csp.check();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void registerObjects_FWD(PerformRuleResult ruleresult, EObject srcLocation, EObject locationToLocation,
EObject positionPoint, EObject trgPositionPoint, EObject trgLocation, EObject pair, EObject asset,
EObject positionCorr) {
ruleresult.registerObject("srcLocation", srcLocation);
ruleresult.registerObject("locationToLocation", locationToLocation);
ruleresult.registerObject("positionPoint", positionPoint);
ruleresult.registerObject("trgPositionPoint", trgPositionPoint);
ruleresult.registerObject("trgLocation", trgLocation);
ruleresult.registerObject("pair", pair);
ruleresult.registerObject("asset", asset);
ruleresult.registerObject("positionCorr", positionCorr);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean checkTypes_FWD(Match match) {
return true;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EObjectContainer isAppropriate_FWD_EMoflonEdge_18(EMoflonEdge _edge_Position) {
// prepare return value
Object[] result1_bindingAndBlack = PositionPointLinkImpl
.pattern_PositionPointLink_10_1_preparereturnvalue_bindingAndBlackFFBF(this);
if (result1_bindingAndBlack == null) {
throw new RuntimeException("Pattern matching in node [prepare return value] failed." + " Variables: "
+ "[this] = " + this + ".");
}
EOperation __performOperation = (EOperation) result1_bindingAndBlack[0];
EClass __eClass = (EClass) result1_bindingAndBlack[1];
EOperation isApplicableCC = (EOperation) result1_bindingAndBlack[3];
Object[] result1_green = PositionPointLinkImpl.pattern_PositionPointLink_10_1_preparereturnvalue_greenF();
EObjectContainer __result = (EObjectContainer) result1_green[0];
// ForEach test core match and DECs
for (Object[] result2_black : PositionPointLinkImpl
.pattern_PositionPointLink_10_2_testcorematchandDECs_blackFFFFB(_edge_Position)) {
Location srcLocation = (Location) result2_black[0];
PositionPoint positionPoint = (PositionPoint) result2_black[1];
MeterAssetPhysicalDevicePair pair = (MeterAssetPhysicalDevicePair) result2_black[2];
MeterAsset asset = (MeterAsset) result2_black[3];
Object[] result2_green = PositionPointLinkImpl
.pattern_PositionPointLink_10_2_testcorematchandDECs_greenFB(__eClass);
Match match = (Match) result2_green[0];
// bookkeeping with generic isAppropriate method
if (PositionPointLinkImpl
.pattern_PositionPointLink_10_3_bookkeepingwithgenericisAppropriatemethod_expressionFBBBBBB(this,
match, srcLocation, positionPoint, pair, asset)) {
// Ensure that the correct types of elements are matched
if (PositionPointLinkImpl
.pattern_PositionPointLink_10_4_Ensurethatthecorrecttypesofelementsarematched_expressionFBB(
this, match)) {
// Add match to rule result
Object[] result5_black = PositionPointLinkImpl
.pattern_PositionPointLink_10_5_Addmatchtoruleresult_blackBBBB(match, __performOperation,
__result, isApplicableCC);
if (result5_black == null) {
throw new RuntimeException("Pattern matching in node [Add match to rule result] failed."
+ " Variables: " + "[match] = " + match + ", " + "[__performOperation] = "
+ __performOperation + ", " + "[__result] = " + __result + ", " + "[isApplicableCC] = "
+ isApplicableCC + ".");
}
PositionPointLinkImpl.pattern_PositionPointLink_10_5_Addmatchtoruleresult_greenBBBB(match,
__performOperation, __result, isApplicableCC);
} else {
}
} else {
}
}
return PositionPointLinkImpl.pattern_PositionPointLink_10_6_expressionFB(__result);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public AttributeConstraintsRuleResult checkAttributes_FWD(TripleMatch __tripleMatch) {
AttributeConstraintsRuleResult ruleResult = org.moflon.tgg.runtime.RuntimeFactory.eINSTANCE
.createAttributeConstraintsRuleResult();
ruleResult.setRule("PositionPointLink");
ruleResult.setSuccess(true);
CSP csp = CspFactory.eINSTANCE.createCSP();
CheckAttributeHelper __helper = new CheckAttributeHelper(__tripleMatch);
if (csp.check()) {
ruleResult.setSuccess(true);
} else {
if (csp.check()) {
ruleResult.setSuccess(true);
ruleResult.setRequiredChange(true);
} else {
ruleResult.setSuccess(false);
return ruleResult;
}
}
return ruleResult;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public IsApplicableRuleResult isApplicable_CC(Match sourceMatch, Match targetMatch) {
// [user code injected with eMoflon]
// TODO: implement this method here but do not remove the injection marker
throw new UnsupportedOperationException();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public boolean checkDEC_FWD(Location srcLocation, PositionPoint positionPoint, MeterAssetPhysicalDevicePair pair,
MeterAsset asset) {// match tgg pattern
Object[] result1_black = PositionPointLinkImpl
.pattern_PositionPointLink_13_1_matchtggpattern_blackBBBB(srcLocation, positionPoint, pair, asset);
if (result1_black != null) {
return PositionPointLinkImpl.pattern_PositionPointLink_13_2_expressionF();
} else {
return PositionPointLinkImpl.pattern_PositionPointLink_13_3_expressionF();
}
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eInvoke(int operationID, EList<?> arguments) throws InvocationTargetException {
switch (operationID) {
case RulesPackage.POSITION_POINT_LINK___IS_APPROPRIATE_FWD__MATCH_LOCATION_POSITIONPOINT_METERASSETPHYSICALDEVICEPAIR_METERASSET:
return isAppropriate_FWD((Match) arguments.get(0), (Location) arguments.get(1),
(PositionPoint) arguments.get(2), (MeterAssetPhysicalDevicePair) arguments.get(3),
(MeterAsset) arguments.get(4));
case RulesPackage.POSITION_POINT_LINK___PERFORM_FWD__ISAPPLICABLEMATCH:
return perform_FWD((IsApplicableMatch) arguments.get(0));
case RulesPackage.POSITION_POINT_LINK___IS_APPLICABLE_FWD__MATCH:
return isApplicable_FWD((Match) arguments.get(0));
case RulesPackage.POSITION_POINT_LINK___REGISTER_OBJECTS_TO_MATCH_FWD__MATCH_LOCATION_POSITIONPOINT_METERASSETPHYSICALDEVICEPAIR_METERASSET:
registerObjectsToMatch_FWD((Match) arguments.get(0), (Location) arguments.get(1),
(PositionPoint) arguments.get(2), (MeterAssetPhysicalDevicePair) arguments.get(3),
(MeterAsset) arguments.get(4));
return null;
case RulesPackage.POSITION_POINT_LINK___IS_APPROPRIATE_SOLVE_CSP_FWD__MATCH_LOCATION_POSITIONPOINT_METERASSETPHYSICALDEVICEPAIR_METERASSET:
return isAppropriate_solveCsp_FWD((Match) arguments.get(0), (Location) arguments.get(1),
(PositionPoint) arguments.get(2), (MeterAssetPhysicalDevicePair) arguments.get(3),
(MeterAsset) arguments.get(4));
case RulesPackage.POSITION_POINT_LINK___IS_APPROPRIATE_CHECK_CSP_FWD__CSP:
return isAppropriate_checkCsp_FWD((CSP) arguments.get(0));
case RulesPackage.POSITION_POINT_LINK___IS_APPLICABLE_SOLVE_CSP_FWD__ISAPPLICABLEMATCH_LOCATION_LOCATIONTOLOCATION_POSITIONPOINT_POSITIONPOINT_LOCATION_METERASSETPHYSICALDEVICEPAIR_METERASSET_POSITIONPOINTTOPOSITIONPOINT:
return isApplicable_solveCsp_FWD((IsApplicableMatch) arguments.get(0), (Location) arguments.get(1),
(LocationToLocation) arguments.get(2), (PositionPoint) arguments.get(3),
(outageDetectionJointarget.PositionPoint) arguments.get(4),
(outageDetectionJointarget.Location) arguments.get(5),
(MeterAssetPhysicalDevicePair) arguments.get(6), (MeterAsset) arguments.get(7),
(PositionPointToPositionPoint) arguments.get(8));
case RulesPackage.POSITION_POINT_LINK___IS_APPLICABLE_CHECK_CSP_FWD__CSP:
return isApplicable_checkCsp_FWD((CSP) arguments.get(0));
case RulesPackage.POSITION_POINT_LINK___REGISTER_OBJECTS_FWD__PERFORMRULERESULT_EOBJECT_EOBJECT_EOBJECT_EOBJECT_EOBJECT_EOBJECT_EOBJECT_EOBJECT:
registerObjects_FWD((PerformRuleResult) arguments.get(0), (EObject) arguments.get(1),
(EObject) arguments.get(2), (EObject) arguments.get(3), (EObject) arguments.get(4),
(EObject) arguments.get(5), (EObject) arguments.get(6), (EObject) arguments.get(7),
(EObject) arguments.get(8));
return null;
case RulesPackage.POSITION_POINT_LINK___CHECK_TYPES_FWD__MATCH:
return checkTypes_FWD((Match) arguments.get(0));
case RulesPackage.POSITION_POINT_LINK___IS_APPROPRIATE_FWD_EMOFLON_EDGE_18__EMOFLONEDGE:
return isAppropriate_FWD_EMoflonEdge_18((EMoflonEdge) arguments.get(0));
case RulesPackage.POSITION_POINT_LINK___CHECK_ATTRIBUTES_FWD__TRIPLEMATCH:
return checkAttributes_FWD((TripleMatch) arguments.get(0));
case RulesPackage.POSITION_POINT_LINK___IS_APPLICABLE_CC__MATCH_MATCH:
return isApplicable_CC((Match) arguments.get(0), (Match) arguments.get(1));
case RulesPackage.POSITION_POINT_LINK___CHECK_DEC_FWD__LOCATION_POSITIONPOINT_METERASSETPHYSICALDEVICEPAIR_METERASSET:
return checkDEC_FWD((Location) arguments.get(0), (PositionPoint) arguments.get(1),
(MeterAssetPhysicalDevicePair) arguments.get(2), (MeterAsset) arguments.get(3));
}
return super.eInvoke(operationID, arguments);
}
public static final Object[] pattern_PositionPointLink_0_1_initialbindings_blackBBBBBB(PositionPointLink _this,
Match match, Location srcLocation, PositionPoint positionPoint, MeterAssetPhysicalDevicePair pair,
MeterAsset asset) {
return new Object[] { _this, match, srcLocation, positionPoint, pair, asset };
}
public static final Object[] pattern_PositionPointLink_0_2_SolveCSP_bindingFBBBBBB(PositionPointLink _this,
Match match, Location srcLocation, PositionPoint positionPoint, MeterAssetPhysicalDevicePair pair,
MeterAsset asset) {
CSP _localVariable_0 = _this.isAppropriate_solveCsp_FWD(match, srcLocation, positionPoint, pair, asset);
CSP csp = _localVariable_0;
if (csp != null) {
return new Object[] { csp, _this, match, srcLocation, positionPoint, pair, asset };
}
return null;
}
public static final Object[] pattern_PositionPointLink_0_2_SolveCSP_blackB(CSP csp) {
return new Object[] { csp };
}
public static final Object[] pattern_PositionPointLink_0_2_SolveCSP_bindingAndBlackFBBBBBB(PositionPointLink _this,
Match match, Location srcLocation, PositionPoint positionPoint, MeterAssetPhysicalDevicePair pair,
MeterAsset asset) {
Object[] result_pattern_PositionPointLink_0_2_SolveCSP_binding = pattern_PositionPointLink_0_2_SolveCSP_bindingFBBBBBB(
_this, match, srcLocation, positionPoint, pair, asset);
if (result_pattern_PositionPointLink_0_2_SolveCSP_binding != null) {
CSP csp = (CSP) result_pattern_PositionPointLink_0_2_SolveCSP_binding[0];
Object[] result_pattern_PositionPointLink_0_2_SolveCSP_black = pattern_PositionPointLink_0_2_SolveCSP_blackB(
csp);
if (result_pattern_PositionPointLink_0_2_SolveCSP_black != null) {
return new Object[] { csp, _this, match, srcLocation, positionPoint, pair, asset };
}
}
return null;
}
public static final boolean pattern_PositionPointLink_0_3_CheckCSP_expressionFBB(PositionPointLink _this, CSP csp) {
boolean _localVariable_0 = _this.isAppropriate_checkCsp_FWD(csp);
boolean _result = Boolean.valueOf(_localVariable_0);
return _result;
}
public static final Object[] pattern_PositionPointLink_0_4_collectelementstobetranslated_blackBBBBB(Match match,
Location srcLocation, PositionPoint positionPoint, MeterAssetPhysicalDevicePair pair, MeterAsset asset) {
return new Object[] { match, srcLocation, positionPoint, pair, asset };
}
public static final Object[] pattern_PositionPointLink_0_4_collectelementstobetranslated_greenBBBF(Match match,
Location srcLocation, PositionPoint positionPoint) {
EMoflonEdge srcLocation__positionPoint____Position = RuntimeFactory.eINSTANCE.createEMoflonEdge();
String srcLocation__positionPoint____Position_name_prime = "Position";
srcLocation__positionPoint____Position.setSrc(srcLocation);
srcLocation__positionPoint____Position.setTrg(positionPoint);
match.getToBeTranslatedEdges().add(srcLocation__positionPoint____Position);
srcLocation__positionPoint____Position.setName(srcLocation__positionPoint____Position_name_prime);
return new Object[] { match, srcLocation, positionPoint, srcLocation__positionPoint____Position };
}
public static final Object[] pattern_PositionPointLink_0_5_collectcontextelements_blackBBBBB(Match match,
Location srcLocation, PositionPoint positionPoint, MeterAssetPhysicalDevicePair pair, MeterAsset asset) {
return new Object[] { match, srcLocation, positionPoint, pair, asset };
}
public static final Object[] pattern_PositionPointLink_0_5_collectcontextelements_greenBBBBBFFF(Match match,
Location srcLocation, PositionPoint positionPoint, MeterAssetPhysicalDevicePair pair, MeterAsset asset) {
EMoflonEdge pair__asset____a = RuntimeFactory.eINSTANCE.createEMoflonEdge();
EMoflonEdge asset__srcLocation____Location = RuntimeFactory.eINSTANCE.createEMoflonEdge();
EMoflonEdge srcLocation__asset____Assets = RuntimeFactory.eINSTANCE.createEMoflonEdge();
match.getContextNodes().add(srcLocation);
match.getContextNodes().add(positionPoint);
match.getContextNodes().add(pair);
match.getContextNodes().add(asset);
String pair__asset____a_name_prime = "a";
String asset__srcLocation____Location_name_prime = "Location";
String srcLocation__asset____Assets_name_prime = "Assets";
pair__asset____a.setSrc(pair);
pair__asset____a.setTrg(asset);
match.getContextEdges().add(pair__asset____a);
asset__srcLocation____Location.setSrc(asset);
asset__srcLocation____Location.setTrg(srcLocation);
match.getContextEdges().add(asset__srcLocation____Location);
srcLocation__asset____Assets.setSrc(srcLocation);
srcLocation__asset____Assets.setTrg(asset);
match.getContextEdges().add(srcLocation__asset____Assets);
pair__asset____a.setName(pair__asset____a_name_prime);
asset__srcLocation____Location.setName(asset__srcLocation____Location_name_prime);
srcLocation__asset____Assets.setName(srcLocation__asset____Assets_name_prime);
return new Object[] { match, srcLocation, positionPoint, pair, asset, pair__asset____a,
asset__srcLocation____Location, srcLocation__asset____Assets };
}
public static final void pattern_PositionPointLink_0_6_registerobjectstomatch_expressionBBBBBB(
PositionPointLink _this, Match match, Location srcLocation, PositionPoint positionPoint,
MeterAssetPhysicalDevicePair pair, MeterAsset asset) {
_this.registerObjectsToMatch_FWD(match, srcLocation, positionPoint, pair, asset);
}
public static final boolean pattern_PositionPointLink_0_7_expressionF() {
boolean _result = Boolean.valueOf(true);
return _result;
}
public static final boolean pattern_PositionPointLink_0_8_expressionF() {
boolean _result = Boolean.valueOf(false);
return _result;
}
public static final Object[] pattern_PositionPointLink_1_1_performtransformation_bindingFFFFFFFFB(
IsApplicableMatch isApplicableMatch) {
EObject _localVariable_0 = isApplicableMatch.getObject("srcLocation");
EObject _localVariable_1 = isApplicableMatch.getObject("locationToLocation");
EObject _localVariable_2 = isApplicableMatch.getObject("positionPoint");
EObject _localVariable_3 = isApplicableMatch.getObject("trgPositionPoint");
EObject _localVariable_4 = isApplicableMatch.getObject("trgLocation");
EObject _localVariable_5 = isApplicableMatch.getObject("pair");
EObject _localVariable_6 = isApplicableMatch.getObject("asset");
EObject _localVariable_7 = isApplicableMatch.getObject("positionCorr");
EObject tmpSrcLocation = _localVariable_0;
EObject tmpLocationToLocation = _localVariable_1;
EObject tmpPositionPoint = _localVariable_2;
EObject tmpTrgPositionPoint = _localVariable_3;
EObject tmpTrgLocation = _localVariable_4;
EObject tmpPair = _localVariable_5;
EObject tmpAsset = _localVariable_6;
EObject tmpPositionCorr = _localVariable_7;
if (tmpSrcLocation instanceof Location) {
Location srcLocation = (Location) tmpSrcLocation;
if (tmpLocationToLocation instanceof LocationToLocation) {
LocationToLocation locationToLocation = (LocationToLocation) tmpLocationToLocation;
if (tmpPositionPoint instanceof PositionPoint) {
PositionPoint positionPoint = (PositionPoint) tmpPositionPoint;
if (tmpTrgPositionPoint instanceof outageDetectionJointarget.PositionPoint) {
outageDetectionJointarget.PositionPoint trgPositionPoint = (outageDetectionJointarget.PositionPoint) tmpTrgPositionPoint;
if (tmpTrgLocation instanceof outageDetectionJointarget.Location) {
outageDetectionJointarget.Location trgLocation = (outageDetectionJointarget.Location) tmpTrgLocation;
if (tmpPair instanceof MeterAssetPhysicalDevicePair) {
MeterAssetPhysicalDevicePair pair = (MeterAssetPhysicalDevicePair) tmpPair;
if (tmpAsset instanceof MeterAsset) {
MeterAsset asset = (MeterAsset) tmpAsset;
if (tmpPositionCorr instanceof PositionPointToPositionPoint) {
PositionPointToPositionPoint positionCorr = (PositionPointToPositionPoint) tmpPositionCorr;
return new Object[] { srcLocation, locationToLocation, positionPoint,
trgPositionPoint, trgLocation, pair, asset, positionCorr,
isApplicableMatch };
}
}
}
}
}
}
}
}
return null;
}
public static final Object[] pattern_PositionPointLink_1_1_performtransformation_blackBBBBBBBBFBB(
Location srcLocation, LocationToLocation locationToLocation, PositionPoint positionPoint,
outageDetectionJointarget.PositionPoint trgPositionPoint, outageDetectionJointarget.Location trgLocation,
MeterAssetPhysicalDevicePair pair, MeterAsset asset, PositionPointToPositionPoint positionCorr,
PositionPointLink _this, IsApplicableMatch isApplicableMatch) {
for (EObject tmpCsp : isApplicableMatch.getAttributeInfo()) {
if (tmpCsp instanceof CSP) {
CSP csp = (CSP) tmpCsp;
return new Object[] { srcLocation, locationToLocation, positionPoint, trgPositionPoint, trgLocation,
pair, asset, positionCorr, csp, _this, isApplicableMatch };
}
}
return null;
}
public static final Object[] pattern_PositionPointLink_1_1_performtransformation_bindingAndBlackFFFFFFFFFBB(
PositionPointLink _this, IsApplicableMatch isApplicableMatch) {
Object[] result_pattern_PositionPointLink_1_1_performtransformation_binding = pattern_PositionPointLink_1_1_performtransformation_bindingFFFFFFFFB(
isApplicableMatch);
if (result_pattern_PositionPointLink_1_1_performtransformation_binding != null) {
Location srcLocation = (Location) result_pattern_PositionPointLink_1_1_performtransformation_binding[0];
LocationToLocation locationToLocation = (LocationToLocation) result_pattern_PositionPointLink_1_1_performtransformation_binding[1];
PositionPoint positionPoint = (PositionPoint) result_pattern_PositionPointLink_1_1_performtransformation_binding[2];
outageDetectionJointarget.PositionPoint trgPositionPoint = (outageDetectionJointarget.PositionPoint) result_pattern_PositionPointLink_1_1_performtransformation_binding[3];
outageDetectionJointarget.Location trgLocation = (outageDetectionJointarget.Location) result_pattern_PositionPointLink_1_1_performtransformation_binding[4];
MeterAssetPhysicalDevicePair pair = (MeterAssetPhysicalDevicePair) result_pattern_PositionPointLink_1_1_performtransformation_binding[5];
MeterAsset asset = (MeterAsset) result_pattern_PositionPointLink_1_1_performtransformation_binding[6];
PositionPointToPositionPoint positionCorr = (PositionPointToPositionPoint) result_pattern_PositionPointLink_1_1_performtransformation_binding[7];
Object[] result_pattern_PositionPointLink_1_1_performtransformation_black = pattern_PositionPointLink_1_1_performtransformation_blackBBBBBBBBFBB(
srcLocation, locationToLocation, positionPoint, trgPositionPoint, trgLocation, pair, asset,
positionCorr, _this, isApplicableMatch);
if (result_pattern_PositionPointLink_1_1_performtransformation_black != null) {
CSP csp = (CSP) result_pattern_PositionPointLink_1_1_performtransformation_black[8];
return new Object[] { srcLocation, locationToLocation, positionPoint, trgPositionPoint, trgLocation,
pair, asset, positionCorr, csp, _this, isApplicableMatch };
}
}
return null;
}
public static final Object[] pattern_PositionPointLink_1_1_performtransformation_greenBB(
outageDetectionJointarget.PositionPoint trgPositionPoint, outageDetectionJointarget.Location trgLocation) {
trgLocation.setPosition(trgPositionPoint);
return new Object[] { trgPositionPoint, trgLocation };
}
public static final Object[] pattern_PositionPointLink_1_2_collecttranslatedelements_greenF() {
PerformRuleResult ruleresult = RuntimeFactory.eINSTANCE.createPerformRuleResult();
return new Object[] { ruleresult };
}
public static final Object[] pattern_PositionPointLink_1_3_bookkeepingforedges_blackBBBBBBBBB(
PerformRuleResult ruleresult, EObject srcLocation, EObject locationToLocation, EObject positionPoint,
EObject trgPositionPoint, EObject trgLocation, EObject pair, EObject asset, EObject positionCorr) {
if (!srcLocation.equals(trgPositionPoint)) {
if (!srcLocation.equals(trgLocation)) {
if (!locationToLocation.equals(srcLocation)) {
if (!locationToLocation.equals(positionPoint)) {
if (!locationToLocation.equals(trgPositionPoint)) {
if (!locationToLocation.equals(trgLocation)) {
if (!locationToLocation.equals(pair)) {
if (!locationToLocation.equals(positionCorr)) {
if (!positionPoint.equals(srcLocation)) {
if (!positionPoint.equals(trgPositionPoint)) {
if (!positionPoint.equals(trgLocation)) {
if (!trgLocation.equals(trgPositionPoint)) {
if (!pair.equals(srcLocation)) {
if (!pair.equals(positionPoint)) {
if (!pair.equals(trgPositionPoint)) {
if (!pair.equals(trgLocation)) {
if (!pair.equals(positionCorr)) {
if (!asset.equals(srcLocation)) {
if (!asset.equals(locationToLocation)) {
if (!asset.equals(positionPoint)) {
if (!asset.equals(
trgPositionPoint)) {
if (!asset.equals(
trgLocation)) {
if (!asset
.equals(pair)) {
if (!asset.equals(
positionCorr)) {
if (!positionCorr
.equals(srcLocation)) {
if (!positionCorr
.equals(positionPoint)) {
if (!positionCorr
.equals(trgPositionPoint)) {
if (!positionCorr
.equals(trgLocation)) {
return new Object[] {
ruleresult,
srcLocation,
locationToLocation,
positionPoint,
trgPositionPoint,
trgLocation,
pair,
asset,
positionCorr };
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
return null;
}
public static final Object[] pattern_PositionPointLink_1_3_bookkeepingforedges_greenBBBBBFF(
PerformRuleResult ruleresult, EObject srcLocation, EObject positionPoint, EObject trgPositionPoint,
EObject trgLocation) {
EMoflonEdge trgLocation__trgPositionPoint____Position = RuntimeFactory.eINSTANCE.createEMoflonEdge();
EMoflonEdge srcLocation__positionPoint____Position = RuntimeFactory.eINSTANCE.createEMoflonEdge();
String ruleresult_ruleName_prime = "PositionPointLink";
String trgLocation__trgPositionPoint____Position_name_prime = "Position";
String srcLocation__positionPoint____Position_name_prime = "Position";
trgLocation__trgPositionPoint____Position.setSrc(trgLocation);
trgLocation__trgPositionPoint____Position.setTrg(trgPositionPoint);
ruleresult.getCreatedEdges().add(trgLocation__trgPositionPoint____Position);
srcLocation__positionPoint____Position.setSrc(srcLocation);
srcLocation__positionPoint____Position.setTrg(positionPoint);
ruleresult.getTranslatedEdges().add(srcLocation__positionPoint____Position);
ruleresult.setRuleName(ruleresult_ruleName_prime);
trgLocation__trgPositionPoint____Position.setName(trgLocation__trgPositionPoint____Position_name_prime);
srcLocation__positionPoint____Position.setName(srcLocation__positionPoint____Position_name_prime);
return new Object[] { ruleresult, srcLocation, positionPoint, trgPositionPoint, trgLocation,
trgLocation__trgPositionPoint____Position, srcLocation__positionPoint____Position };
}
public static final void pattern_PositionPointLink_1_5_registerobjects_expressionBBBBBBBBBB(PositionPointLink _this,
PerformRuleResult ruleresult, EObject srcLocation, EObject locationToLocation, EObject positionPoint,
EObject trgPositionPoint, EObject trgLocation, EObject pair, EObject asset, EObject positionCorr) {
_this.registerObjects_FWD(ruleresult, srcLocation, locationToLocation, positionPoint, trgPositionPoint,
trgLocation, pair, asset, positionCorr);
}
public static final PerformRuleResult pattern_PositionPointLink_1_6_expressionFB(PerformRuleResult ruleresult) {
PerformRuleResult _result = ruleresult;
return _result;
}
public static final Object[] pattern_PositionPointLink_2_1_preparereturnvalue_bindingFB(PositionPointLink _this) {
EClass _localVariable_0 = _this.eClass();
EClass eClass = _localVariable_0;
if (eClass != null) {
return new Object[] { eClass, _this };
}
return null;
}
public static final Object[] pattern_PositionPointLink_2_1_preparereturnvalue_blackFBB(EClass eClass,
PositionPointLink _this) {
for (EOperation performOperation : eClass.getEOperations()) {
String performOperation_name = performOperation.getName();
if (performOperation_name.equals("perform_FWD")) {
return new Object[] { performOperation, eClass, _this };
}
}
return null;
}
public static final Object[] pattern_PositionPointLink_2_1_preparereturnvalue_bindingAndBlackFFB(
PositionPointLink _this) {
Object[] result_pattern_PositionPointLink_2_1_preparereturnvalue_binding = pattern_PositionPointLink_2_1_preparereturnvalue_bindingFB(
_this);
if (result_pattern_PositionPointLink_2_1_preparereturnvalue_binding != null) {
EClass eClass = (EClass) result_pattern_PositionPointLink_2_1_preparereturnvalue_binding[0];
Object[] result_pattern_PositionPointLink_2_1_preparereturnvalue_black = pattern_PositionPointLink_2_1_preparereturnvalue_blackFBB(
eClass, _this);
if (result_pattern_PositionPointLink_2_1_preparereturnvalue_black != null) {
EOperation performOperation = (EOperation) result_pattern_PositionPointLink_2_1_preparereturnvalue_black[0];
return new Object[] { performOperation, eClass, _this };
}
}
return null;
}
public static final Object[] pattern_PositionPointLink_2_1_preparereturnvalue_greenBF(EOperation performOperation) {
IsApplicableRuleResult ruleresult = RuntimeFactory.eINSTANCE.createIsApplicableRuleResult();
boolean ruleresult_success_prime = Boolean.valueOf(false);
String ruleresult_rule_prime = "PositionPointLink";
ruleresult.setPerformOperation(performOperation);
ruleresult.setSuccess(Boolean.valueOf(ruleresult_success_prime));
ruleresult.setRule(ruleresult_rule_prime);
return new Object[] { performOperation, ruleresult };
}
public static final Object[] pattern_PositionPointLink_2_2_corematch_bindingFFFFB(Match match) {
EObject _localVariable_0 = match.getObject("srcLocation");
EObject _localVariable_1 = match.getObject("positionPoint");
EObject _localVariable_2 = match.getObject("pair");
EObject _localVariable_3 = match.getObject("asset");
EObject tmpSrcLocation = _localVariable_0;
EObject tmpPositionPoint = _localVariable_1;
EObject tmpPair = _localVariable_2;
EObject tmpAsset = _localVariable_3;
if (tmpSrcLocation instanceof Location) {
Location srcLocation = (Location) tmpSrcLocation;
if (tmpPositionPoint instanceof PositionPoint) {
PositionPoint positionPoint = (PositionPoint) tmpPositionPoint;
if (tmpPair instanceof MeterAssetPhysicalDevicePair) {
MeterAssetPhysicalDevicePair pair = (MeterAssetPhysicalDevicePair) tmpPair;
if (tmpAsset instanceof MeterAsset) {
MeterAsset asset = (MeterAsset) tmpAsset;
return new Object[] { srcLocation, positionPoint, pair, asset, match };
}
}
}
}
return null;
}
public static final Iterable<Object[]> pattern_PositionPointLink_2_2_corematch_blackBFBFFBBFB(Location srcLocation,
PositionPoint positionPoint, MeterAssetPhysicalDevicePair pair, MeterAsset asset, Match match) {
LinkedList<Object[]> _result = new LinkedList<Object[]>();
for (LocationToLocation locationToLocation : org.moflon.core.utilities.eMoflonEMFUtil
.getOppositeReferenceTyped(srcLocation, LocationToLocation.class, "source")) {
outageDetectionJointarget.Location trgLocation = locationToLocation.getTarget();
if (trgLocation != null) {
for (PositionPointToPositionPoint positionCorr : org.moflon.core.utilities.eMoflonEMFUtil
.getOppositeReferenceTyped(positionPoint, PositionPointToPositionPoint.class, "source")) {
outageDetectionJointarget.PositionPoint trgPositionPoint = positionCorr.getTarget();
if (trgPositionPoint != null) {
_result.add(new Object[] { srcLocation, locationToLocation, positionPoint, trgPositionPoint,
trgLocation, pair, asset, positionCorr, match });
}
}
}
}
return _result;
}
public static final Iterable<Object[]> pattern_PositionPointLink_2_3_findcontext_blackBBBBBBBB(Location srcLocation,
LocationToLocation locationToLocation, PositionPoint positionPoint,
outageDetectionJointarget.PositionPoint trgPositionPoint, outageDetectionJointarget.Location trgLocation,
MeterAssetPhysicalDevicePair pair, MeterAsset asset, PositionPointToPositionPoint positionCorr) {
LinkedList<Object[]> _result = new LinkedList<Object[]>();
if (trgLocation.equals(locationToLocation.getTarget())) {
if (asset.equals(pair.getA())) {
if (srcLocation.equals(locationToLocation.getSource())) {
if (srcLocation.equals(asset.getLocation())) {
if (positionPoint.equals(srcLocation.getPosition())) {
if (trgPositionPoint.equals(positionCorr.getTarget())) {
if (positionPoint.equals(positionCorr.getSource())) {
_result.add(new Object[] { srcLocation, locationToLocation, positionPoint,
trgPositionPoint, trgLocation, pair, asset, positionCorr });
}
}
}
}
}
}
}
return _result;
}
public static final Object[] pattern_PositionPointLink_2_3_findcontext_greenBBBBBBBBFFFFFFFFF(Location srcLocation,
LocationToLocation locationToLocation, PositionPoint positionPoint,
outageDetectionJointarget.PositionPoint trgPositionPoint, outageDetectionJointarget.Location trgLocation,
MeterAssetPhysicalDevicePair pair, MeterAsset asset, PositionPointToPositionPoint positionCorr) {
IsApplicableMatch isApplicableMatch = RuntimeFactory.eINSTANCE.createIsApplicableMatch();
EMoflonEdge locationToLocation__trgLocation____target = RuntimeFactory.eINSTANCE.createEMoflonEdge();
EMoflonEdge pair__asset____a = RuntimeFactory.eINSTANCE.createEMoflonEdge();
EMoflonEdge locationToLocation__srcLocation____source = RuntimeFactory.eINSTANCE.createEMoflonEdge();
EMoflonEdge asset__srcLocation____Location = RuntimeFactory.eINSTANCE.createEMoflonEdge();
EMoflonEdge srcLocation__asset____Assets = RuntimeFactory.eINSTANCE.createEMoflonEdge();
EMoflonEdge srcLocation__positionPoint____Position = RuntimeFactory.eINSTANCE.createEMoflonEdge();
EMoflonEdge positionCorr__trgPositionPoint____target = RuntimeFactory.eINSTANCE.createEMoflonEdge();
EMoflonEdge positionCorr__positionPoint____source = RuntimeFactory.eINSTANCE.createEMoflonEdge();
String locationToLocation__trgLocation____target_name_prime = "target";
String pair__asset____a_name_prime = "a";
String locationToLocation__srcLocation____source_name_prime = "source";
String asset__srcLocation____Location_name_prime = "Location";
String srcLocation__asset____Assets_name_prime = "Assets";
String srcLocation__positionPoint____Position_name_prime = "Position";
String positionCorr__trgPositionPoint____target_name_prime = "target";
String positionCorr__positionPoint____source_name_prime = "source";
isApplicableMatch.getAllContextElements().add(srcLocation);
isApplicableMatch.getAllContextElements().add(locationToLocation);
isApplicableMatch.getAllContextElements().add(positionPoint);
isApplicableMatch.getAllContextElements().add(trgPositionPoint);
isApplicableMatch.getAllContextElements().add(trgLocation);
isApplicableMatch.getAllContextElements().add(pair);
isApplicableMatch.getAllContextElements().add(asset);
isApplicableMatch.getAllContextElements().add(positionCorr);
locationToLocation__trgLocation____target.setSrc(locationToLocation);
locationToLocation__trgLocation____target.setTrg(trgLocation);
isApplicableMatch.getAllContextElements().add(locationToLocation__trgLocation____target);
pair__asset____a.setSrc(pair);
pair__asset____a.setTrg(asset);
isApplicableMatch.getAllContextElements().add(pair__asset____a);
locationToLocation__srcLocation____source.setSrc(locationToLocation);
locationToLocation__srcLocation____source.setTrg(srcLocation);
isApplicableMatch.getAllContextElements().add(locationToLocation__srcLocation____source);
asset__srcLocation____Location.setSrc(asset);
asset__srcLocation____Location.setTrg(srcLocation);
isApplicableMatch.getAllContextElements().add(asset__srcLocation____Location);
srcLocation__asset____Assets.setSrc(srcLocation);
srcLocation__asset____Assets.setTrg(asset);
isApplicableMatch.getAllContextElements().add(srcLocation__asset____Assets);
srcLocation__positionPoint____Position.setSrc(srcLocation);
srcLocation__positionPoint____Position.setTrg(positionPoint);
isApplicableMatch.getAllContextElements().add(srcLocation__positionPoint____Position);
positionCorr__trgPositionPoint____target.setSrc(positionCorr);
positionCorr__trgPositionPoint____target.setTrg(trgPositionPoint);
isApplicableMatch.getAllContextElements().add(positionCorr__trgPositionPoint____target);
positionCorr__positionPoint____source.setSrc(positionCorr);
positionCorr__positionPoint____source.setTrg(positionPoint);
isApplicableMatch.getAllContextElements().add(positionCorr__positionPoint____source);
locationToLocation__trgLocation____target.setName(locationToLocation__trgLocation____target_name_prime);
pair__asset____a.setName(pair__asset____a_name_prime);
locationToLocation__srcLocation____source.setName(locationToLocation__srcLocation____source_name_prime);
asset__srcLocation____Location.setName(asset__srcLocation____Location_name_prime);
srcLocation__asset____Assets.setName(srcLocation__asset____Assets_name_prime);
srcLocation__positionPoint____Position.setName(srcLocation__positionPoint____Position_name_prime);
positionCorr__trgPositionPoint____target.setName(positionCorr__trgPositionPoint____target_name_prime);
positionCorr__positionPoint____source.setName(positionCorr__positionPoint____source_name_prime);
return new Object[] { srcLocation, locationToLocation, positionPoint, trgPositionPoint, trgLocation, pair,
asset, positionCorr, isApplicableMatch, locationToLocation__trgLocation____target, pair__asset____a,
locationToLocation__srcLocation____source, asset__srcLocation____Location, srcLocation__asset____Assets,
srcLocation__positionPoint____Position, positionCorr__trgPositionPoint____target,
positionCorr__positionPoint____source };
}
public static final Object[] pattern_PositionPointLink_2_4_solveCSP_bindingFBBBBBBBBBB(PositionPointLink _this,
IsApplicableMatch isApplicableMatch, Location srcLocation, LocationToLocation locationToLocation,
PositionPoint positionPoint, outageDetectionJointarget.PositionPoint trgPositionPoint,
outageDetectionJointarget.Location trgLocation, MeterAssetPhysicalDevicePair pair, MeterAsset asset,
PositionPointToPositionPoint positionCorr) {
CSP _localVariable_0 = _this.isApplicable_solveCsp_FWD(isApplicableMatch, srcLocation, locationToLocation,
positionPoint, trgPositionPoint, trgLocation, pair, asset, positionCorr);
CSP csp = _localVariable_0;
if (csp != null) {
return new Object[] { csp, _this, isApplicableMatch, srcLocation, locationToLocation, positionPoint,
trgPositionPoint, trgLocation, pair, asset, positionCorr };
}
return null;
}
public static final Object[] pattern_PositionPointLink_2_4_solveCSP_blackB(CSP csp) {
return new Object[] { csp };
}
public static final Object[] pattern_PositionPointLink_2_4_solveCSP_bindingAndBlackFBBBBBBBBBB(
PositionPointLink _this, IsApplicableMatch isApplicableMatch, Location srcLocation,
LocationToLocation locationToLocation, PositionPoint positionPoint,
outageDetectionJointarget.PositionPoint trgPositionPoint, outageDetectionJointarget.Location trgLocation,
MeterAssetPhysicalDevicePair pair, MeterAsset asset, PositionPointToPositionPoint positionCorr) {
Object[] result_pattern_PositionPointLink_2_4_solveCSP_binding = pattern_PositionPointLink_2_4_solveCSP_bindingFBBBBBBBBBB(
_this, isApplicableMatch, srcLocation, locationToLocation, positionPoint, trgPositionPoint, trgLocation,
pair, asset, positionCorr);
if (result_pattern_PositionPointLink_2_4_solveCSP_binding != null) {
CSP csp = (CSP) result_pattern_PositionPointLink_2_4_solveCSP_binding[0];
Object[] result_pattern_PositionPointLink_2_4_solveCSP_black = pattern_PositionPointLink_2_4_solveCSP_blackB(
csp);
if (result_pattern_PositionPointLink_2_4_solveCSP_black != null) {
return new Object[] { csp, _this, isApplicableMatch, srcLocation, locationToLocation, positionPoint,
trgPositionPoint, trgLocation, pair, asset, positionCorr };
}
}
return null;
}
public static final boolean pattern_PositionPointLink_2_5_checkCSP_expressionFBB(PositionPointLink _this, CSP csp) {
boolean _localVariable_0 = _this.isApplicable_checkCsp_FWD(csp);
boolean _result = Boolean.valueOf(_localVariable_0);
return _result;
}
public static final Object[] pattern_PositionPointLink_2_6_addmatchtoruleresult_blackBB(
IsApplicableRuleResult ruleresult, IsApplicableMatch isApplicableMatch) {
return new Object[] { ruleresult, isApplicableMatch };
}
public static final Object[] pattern_PositionPointLink_2_6_addmatchtoruleresult_greenBB(
IsApplicableRuleResult ruleresult, IsApplicableMatch isApplicableMatch) {
ruleresult.getIsApplicableMatch().add(isApplicableMatch);
boolean ruleresult_success_prime = Boolean.valueOf(true);
String isApplicableMatch_ruleName_prime = "PositionPointLink";
ruleresult.setSuccess(Boolean.valueOf(ruleresult_success_prime));
isApplicableMatch.setRuleName(isApplicableMatch_ruleName_prime);
return new Object[] { ruleresult, isApplicableMatch };
}
public static final IsApplicableRuleResult pattern_PositionPointLink_2_7_expressionFB(
IsApplicableRuleResult ruleresult) {
IsApplicableRuleResult _result = ruleresult;
return _result;
}
public static final Object[] pattern_PositionPointLink_10_1_preparereturnvalue_bindingFB(PositionPointLink _this) {
EClass _localVariable_0 = _this.eClass();
EClass __eClass = _localVariable_0;
if (__eClass != null) {
return new Object[] { __eClass, _this };
}
return null;
}
public static final Object[] pattern_PositionPointLink_10_1_preparereturnvalue_blackFBBF(EClass __eClass,
PositionPointLink _this) {
for (EOperation __performOperation : __eClass.getEOperations()) {
String __performOperation_name = __performOperation.getName();
if (__performOperation_name.equals("isApplicable_FWD")) {
for (EOperation isApplicableCC : __eClass.getEOperations()) {
if (!__performOperation.equals(isApplicableCC)) {
String isApplicableCC_name = isApplicableCC.getName();
if (isApplicableCC_name.equals("isApplicable_CC")) {
return new Object[] { __performOperation, __eClass, _this, isApplicableCC };
}
}
}
}
}
return null;
}
public static final Object[] pattern_PositionPointLink_10_1_preparereturnvalue_bindingAndBlackFFBF(
PositionPointLink _this) {
Object[] result_pattern_PositionPointLink_10_1_preparereturnvalue_binding = pattern_PositionPointLink_10_1_preparereturnvalue_bindingFB(
_this);
if (result_pattern_PositionPointLink_10_1_preparereturnvalue_binding != null) {
EClass __eClass = (EClass) result_pattern_PositionPointLink_10_1_preparereturnvalue_binding[0];
Object[] result_pattern_PositionPointLink_10_1_preparereturnvalue_black = pattern_PositionPointLink_10_1_preparereturnvalue_blackFBBF(
__eClass, _this);
if (result_pattern_PositionPointLink_10_1_preparereturnvalue_black != null) {
EOperation __performOperation = (EOperation) result_pattern_PositionPointLink_10_1_preparereturnvalue_black[0];
EOperation isApplicableCC = (EOperation) result_pattern_PositionPointLink_10_1_preparereturnvalue_black[3];
return new Object[] { __performOperation, __eClass, _this, isApplicableCC };
}
}
return null;
}
public static final Object[] pattern_PositionPointLink_10_1_preparereturnvalue_greenF() {
EObjectContainer __result = RuntimeFactory.eINSTANCE.createEObjectContainer();
return new Object[] { __result };
}
public static final Iterable<Object[]> pattern_PositionPointLink_10_2_testcorematchandDECs_blackFFFFB(
EMoflonEdge _edge_Position) {
LinkedList<Object[]> _result = new LinkedList<Object[]>();
EObject tmpSrcLocation = _edge_Position.getSrc();
if (tmpSrcLocation instanceof Location) {
Location srcLocation = (Location) tmpSrcLocation;
EObject tmpPositionPoint = _edge_Position.getTrg();
if (tmpPositionPoint instanceof PositionPoint) {
PositionPoint positionPoint = (PositionPoint) tmpPositionPoint;
if (positionPoint.equals(srcLocation.getPosition())) {
for (Asset tmpAsset : srcLocation.getAssets()) {
if (tmpAsset instanceof MeterAsset) {
MeterAsset asset = (MeterAsset) tmpAsset;
for (MeterAssetPhysicalDevicePair pair : org.moflon.core.utilities.eMoflonEMFUtil
.getOppositeReferenceTyped(asset, MeterAssetPhysicalDevicePair.class, "a")) {
_result.add(new Object[] { srcLocation, positionPoint, pair, asset, _edge_Position });
}
}
}
}
}
}
return _result;
}
public static final Object[] pattern_PositionPointLink_10_2_testcorematchandDECs_greenFB(EClass __eClass) {
Match match = RuntimeFactory.eINSTANCE.createMatch();
String __eClass_name = __eClass.getName();
String match_ruleName_prime = __eClass_name;
match.setRuleName(match_ruleName_prime);
return new Object[] { match, __eClass };
}
public static final boolean pattern_PositionPointLink_10_3_bookkeepingwithgenericisAppropriatemethod_expressionFBBBBBB(
PositionPointLink _this, Match match, Location srcLocation, PositionPoint positionPoint,
MeterAssetPhysicalDevicePair pair, MeterAsset asset) {
boolean _localVariable_0 = _this.isAppropriate_FWD(match, srcLocation, positionPoint, pair, asset);
boolean _result = Boolean.valueOf(_localVariable_0);
return _result;
}
public static final boolean pattern_PositionPointLink_10_4_Ensurethatthecorrecttypesofelementsarematched_expressionFBB(
PositionPointLink _this, Match match) {
boolean _localVariable_0 = _this.checkTypes_FWD(match);
boolean _result = Boolean.valueOf(_localVariable_0);
return _result;
}
public static final Object[] pattern_PositionPointLink_10_5_Addmatchtoruleresult_blackBBBB(Match match,
EOperation __performOperation, EObjectContainer __result, EOperation isApplicableCC) {
if (!__performOperation.equals(isApplicableCC)) {
return new Object[] { match, __performOperation, __result, isApplicableCC };
}
return null;
}
public static final Object[] pattern_PositionPointLink_10_5_Addmatchtoruleresult_greenBBBB(Match match,
EOperation __performOperation, EObjectContainer __result, EOperation isApplicableCC) {
__result.getContents().add(match);
match.setIsApplicableOperation(__performOperation);
match.setIsApplicableCCOperation(isApplicableCC);
return new Object[] { match, __performOperation, __result, isApplicableCC };
}
public static final EObjectContainer pattern_PositionPointLink_10_6_expressionFB(EObjectContainer __result) {
EObjectContainer _result = __result;
return _result;
}
public static final Object[] pattern_PositionPointLink_13_1_matchtggpattern_blackBBBB(Location srcLocation,
PositionPoint positionPoint, MeterAssetPhysicalDevicePair pair, MeterAsset asset) {
if (asset.equals(pair.getA())) {
if (srcLocation.equals(asset.getLocation())) {
if (positionPoint.equals(srcLocation.getPosition())) {
return new Object[] { srcLocation, positionPoint, pair, asset };
}
}
}
return null;
}
public static final boolean pattern_PositionPointLink_13_2_expressionF() {
boolean _result = Boolean.valueOf(true);
return _result;
}
public static final boolean pattern_PositionPointLink_13_3_expressionF() {
boolean _result = Boolean.valueOf(false);
return _result;
}
// <-- [user code injected with eMoflon]
// [user code injected with eMoflon] -->
} //PositionPointLinkImpl
| mit |
yzhnasa/TASSEL-iRods | src/net/maizegenetics/plugindef/DataSet.java | 5597 | /*
* DataSet.java
*
*/
package net.maizegenetics.plugindef;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
/**
* This is a set of Datum.
*/
public class DataSet implements Serializable {
private static final long serialVersionUID = -5197800047652332969L;
private final List<Datum> myList;
private final Plugin myCreator;
/**
* Creates a new instance of Datum
*
* @param list list of data elements.
* @param creator creating plugin.
*
*/
public DataSet(List<Datum> list, Plugin creator) {
if (list == null) {
myList = new ArrayList<Datum>();
} else {
myList = new ArrayList<Datum>(list);
}
myCreator = creator;
}
/**
* Convenience constructor for a single Datum
*
* @param theDatum a single Datum
* @param creator creating plugin.
*
*/
public DataSet(Datum theDatum, Plugin creator) {
if (theDatum == null) {
myList = new ArrayList<Datum>();
} else {
myList = new ArrayList<Datum>();
myList.add(theDatum);
}
myCreator = creator;
}
/**
* Creates a new instance of Datum
*
* @param list list of data elements.
* @param creator creating plugin.
*
*/
public DataSet(Datum[] list, Plugin creator) {
if (list == null) {
myList = new ArrayList<Datum>();
} else {
myList = new ArrayList<Datum>(Arrays.asList(list));
}
myCreator = creator;
}
/**
* Combines multiple data sets.
*
* @param list list of data sets.
* @param creator creating plugin.
*
*/
public static DataSet getDataSet(List<DataSet> list, Plugin creator) {
List temp = new ArrayList();
if (list != null) {
Iterator itr = list.iterator();
while (itr.hasNext()) {
DataSet current = (DataSet) itr.next();
if (current != null) {
temp.addAll(current.getDataSet());
}
}
}
return new DataSet(temp, creator);
}
public List getDataSet() {
return new ArrayList(myList);
}
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append("DataSet...\n");
if (getCreator() != null) {
buffer.append("Creator: ");
buffer.append(getCreator().getClass().getName());
buffer.append("\n");
}
Iterator itr = myList.iterator();
while (itr.hasNext()) {
Datum current = (Datum) itr.next();
buffer.append("name: ");
buffer.append(current.getName());
buffer.append(" type: ");
buffer.append(current.getDataType());
buffer.append("\n");
}
return buffer.toString();
}
public Datum getData(int i) {
if (i < myList.size()) {
return myList.get(i);
} else {
return null;
}
}
public int getSize() {
return myList.size();
}
public Plugin getCreator() {
return myCreator;
}
public List<Datum> getDataOfType(Class theClass) {
if (theClass == null) {
return null;
}
List<Datum> list = new ArrayList<Datum>();
Iterator itr = myList.iterator();
while (itr.hasNext()) {
Datum current = (Datum) itr.next();
if (theClass.isInstance(current.getData())) {
list.add(current);
}
}
return list;
}
public List<Datum> getDataOfType(Class[] classes) {
if ((classes == null) || (classes.length == 0)) {
return new ArrayList(myList);
}
List<Datum> result = null;
for (int i = 0, n = classes.length; i < n; i++) {
List current = getDataOfType(classes[i]);
if (result == null) {
result = current;
} else {
result.addAll(current);
}
}
return result;
}
public List<Datum> getDataWithName(String name) {
if (name == null) {
return null;
}
List<Datum> list = new ArrayList<Datum>();
Iterator itr = myList.iterator();
while (itr.hasNext()) {
Datum current = (Datum) itr.next();
if (name.equals(current.getName())) {
list.add(current);
}
}
return list;
}
public List<Datum> getDataWithName(String[] names) {
if ((names == null) || (names.length == 0)) {
return new ArrayList(myList);
}
List<Datum> result = null;
for (int i = 0, n = names.length; i < n; i++) {
List current = getDataWithName(names[i]);
if (result == null) {
result = current;
} else {
result.addAll(current);
}
}
return result;
}
public List<Datum> getDataOfTypeWithName(Class[] classes, String[] names) {
return (new DataSet(getDataOfType(classes), null)).getDataWithName(names);
}
}
| mit |
dhemery/generator | src/main/java/com/dhemery/aggregator/internal/TypeReferences.java | 288 | package com.dhemery.aggregator.internal;
import javax.lang.model.type.DeclaredType;
import javax.lang.model.type.TypeMirror;
import java.util.Set;
public interface TypeReferences {
Set<String> fullNames();
String nameOf(TypeMirror type);
String nameOf(DeclaredType type);
}
| mit |
vishrut/rcss | src/futility/Vector2D.java | 3545 | /** @file Vector2D.java
* Generic 2D Vector class.
*
* @author Team F(utility)
*/
package futility;
/**
* Generic 2D Vector class.
*/
public class Vector2D {
private double x;
private double y;
///////////////////////////////////////////////////////////////////////////
// CONSTRUCTORS
///////////////////////////////////////////////////////////////////////////
/**
* Empty constructor.
*/
public Vector2D() {
this.reset();
}
/**
* Constructor taking only a magnitude. Current implementation assumes the direction is the
* positive x axis.
*
* @param magnitude
*/
public Vector2D(double magnitude) {
this.x = magnitude;
}
/**
* Constructor takign x and y parameters.
*
* @param x the x-coordinate of the vector
* @param y the y-coordinate of the vector
*/
public Vector2D(double x, double y) {
this.x = x;
this.y = y;
}
///////////////////////////////////////////////////////////////////////////
// METHODS
///////////////////////////////////////////////////////////////////////////
/**
* Returns the zero vector.
*
* @return the zero vector
*/
public static Vector2D ZeroVector() {
return new Vector2D(0.0, 0.0);
}
///////////////////////////////////////////////////////////////////////////
// GETTERS AND SETTERS
///////////////////////////////////////////////////////////////////////////
/**
* Gets the x-coordinate of this vector.
*
* @return the x-coordinate of this vector
*/
public final double getX() {
return this.x;
}
/**
* Sets the x-coordinate of this vector.
*
* @param x the value for x
*/
protected final void setX(double x) {
this.x = x;
}
/**
* Gets the y-coordinate of this vector.
*
* @return the y-coordinate of this vector
*/
public final double getY() {
return this.y;
}
/**
* Sets the y-coordinate of this vector.
*
* @param y the value for y
*/
protected final void setY(double y) {
this.y = y;
}
/**
* Returns this vector's magnitude.
*
* @return this vector's magnitude
*/
public final double magnitude() {
return Math.hypot(x, y);
}
/**
* Returns the result of adding a given polar vector to this one.
*
* @param dir direction in radians of the other vector
* @param mag magnitude of the other vector
*/
public final Vector2D addPolar(double dir, double mag) {
double x = mag * Math.cos(dir);
double y = mag * Math.sin(dir);
return new Vector2D(x, y).add(this);
}
/**
* Returns the direction, in radians, represented by the vector.
*
* @return the direction, in radians, represented by the vector
*/
public final double direction() {
return Math.atan2(this.y, this.x);
}
/**
* Adds two vectors. Converts to Cartesian coordinates in order to do so.
*
* @param that the other direction vector
* @return the result as a direction vector
*/
public final Vector2D add(Vector2D that) {
return new Vector2D(this.x + that.getX(), this.y + that.getY());
}
/**
* Resets this vector.
*/
public void reset() {
this.x = Double.NaN;
this.y = Double.NaN;
}
}
| mit |
evpaassen/ews-java-api | src/main/java/microsoft/exchange/webservices/data/OrderByCollection.java | 7364 | /**************************************************************************
Exchange Web Services Java API
Copyright (c) Microsoft Corporation
All rights reserved.
MIT License
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 microsoft.exchange.webservices.data;
import javax.xml.stream.XMLStreamException;
import java.util.*;
/**
* Represents an ordered collection of property definitions qualified with a
* sort direction.
*/
public final class OrderByCollection implements
Iterable<Map<PropertyDefinitionBase, SortDirection>> {
/**
* The prop def sort order pair list.
*/
private List<Map<PropertyDefinitionBase,
SortDirection>> propDefSortOrderPairList;
/**
* Initializes a new instance of the OrderByCollection class.
*/
protected OrderByCollection() {
this.propDefSortOrderPairList = new
ArrayList<Map<PropertyDefinitionBase, SortDirection>>();
}
/**
* Adds the specified property definition / sort direction pair to the
* collection.
*
* @param propertyDefinition the property definition
* @param sortDirection the sort direction
* @throws ServiceLocalException the service local exception
*/
public void add(PropertyDefinitionBase propertyDefinition,
SortDirection sortDirection) throws ServiceLocalException {
if (this.contains(propertyDefinition)) {
throw new ServiceLocalException(String.format(
Strings.PropertyAlreadyExistsInOrderByCollection,
propertyDefinition.getPrintableName()));
}
Map<PropertyDefinitionBase, SortDirection> propertyDefinitionSortDirectionPair = new
HashMap<PropertyDefinitionBase, SortDirection>();
propertyDefinitionSortDirectionPair.put(propertyDefinition,
sortDirection);
this.propDefSortOrderPairList.add(propertyDefinitionSortDirectionPair);
}
/**
* Removes all elements from the collection.
*/
public void clear() {
this.propDefSortOrderPairList.clear();
}
/**
* Determines whether the collection contains the specified property
* definition.
*
* @param propertyDefinition the property definition
* @return True if the collection contains the specified property
* definition; otherwise, false.
*/
protected boolean contains(PropertyDefinitionBase propertyDefinition) {
for (Map<PropertyDefinitionBase, SortDirection> propDefSortOrderPair : propDefSortOrderPairList) {
return propDefSortOrderPair.containsKey(propertyDefinition);
}
return false;
}
/**
* Gets the number of elements contained in the collection.
*
* @return the int
*/
public int count() {
return this.propDefSortOrderPairList.size();
}
/**
* Removes the specified property definition from the collection.
*
* @param propertyDefinition the property definition
* @return True if the property definition is successfully removed;
* otherwise, false
*/
public boolean remove(PropertyDefinitionBase propertyDefinition) {
List<Map<PropertyDefinitionBase, SortDirection>> removeList = new
ArrayList<Map<PropertyDefinitionBase, SortDirection>>();
for (Map<PropertyDefinitionBase, SortDirection> propDefSortOrderPair : propDefSortOrderPairList) {
if (propDefSortOrderPair.containsKey(propertyDefinition)) {
removeList.add(propDefSortOrderPair);
}
}
this.propDefSortOrderPairList.removeAll(removeList);
return removeList.size() > 0;
}
/**
* Removes the element at the specified index from the collection.
*
* @param index the index
*/
public void removeAt(int index) {
this.propDefSortOrderPairList.remove(index);
}
/**
* Tries to get the value for a property definition in the collection.
*
* @param propertyDefinition the property definition
* @param sortDirection the sort direction
* @return True if collection contains property definition, otherwise false.
*/
public boolean tryGetValue(PropertyDefinitionBase propertyDefinition,
OutParam<SortDirection> sortDirection) {
for (Map<PropertyDefinitionBase, SortDirection> pair : this.propDefSortOrderPairList) {
if (pair.containsKey(propertyDefinition)) {
sortDirection.setParam(pair.get(propertyDefinition));
return true;
}
}
sortDirection.setParam(SortDirection.Ascending); // out parameter has to
// be set to some
// value.
return false;
}
/**
* Writes to XML.
*
* @param writer the writer
* @param xmlElementName the xml element name
* @throws javax.xml.stream.XMLStreamException the xML stream exception
* @throws ServiceXmlSerializationException the service xml serialization exception
*/
protected void writeToXml(EwsServiceXmlWriter writer, String xmlElementName)
throws XMLStreamException, ServiceXmlSerializationException {
if (this.count() > 0) {
writer.writeStartElement(XmlNamespace.Messages, xmlElementName);
for (Map<PropertyDefinitionBase, SortDirection> keyValuePair : this.propDefSortOrderPairList) {
writer.writeStartElement(XmlNamespace.Types,
XmlElementNames.FieldOrder);
writer.writeAttributeValue(XmlAttributeNames.Order,
keyValuePair.values().iterator().next());
keyValuePair.keySet().iterator().next().writeToXml(writer);
writer.writeEndElement(); // FieldOrder
}
writer.writeEndElement();
}
}
/*
* (non-Javadoc)
*
* @see java.lang.Iterable#iterator()
*/
@Override
public Iterator<Map<PropertyDefinitionBase, SortDirection>> iterator() {
return this.propDefSortOrderPairList.iterator();
}
/**
* Gets the element at the specified index from the collection.
*
* @param index the index
* @return the property definition sort direction pair
*/
public Map<PropertyDefinitionBase,
SortDirection> getPropertyDefinitionSortDirectionPair(
int index) {
return this.propDefSortOrderPairList.get(index);
}
/**
* Returns an enumerator that iterates through the collection.
*
* @return A Iterator that can be used to iterate through the collection.
*/
public Iterator<Map<PropertyDefinitionBase,
SortDirection>> getEnumerator() {
return (this.propDefSortOrderPairList.iterator());
}
}
| mit |
rextrebat/ecloudmanager | tmrk-cloudapi/src/main/java/org/ecloudmanager/tmrk/cloudapi/model/DetachedDiskReferenceListType.java | 1147 | //
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911
// .1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.07.16 at 03:24:22 PM EEST
//
package org.ecloudmanager.tmrk.cloudapi.model;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for DetachedDiskReferenceListType complex type.
* <p/>
* <p>The following schema fragment specifies the expected content contained within this class.
* <p/>
* <pre>
* <complexType name="DetachedDiskReferenceListType">
* <complexContent>
* <extension base="{}DetachedDiskReferencesResourceType">
* </extension>
* </complexContent>
* </complexType>
* </pre>
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "DetachedDiskReferenceListType")
public class DetachedDiskReferenceListType
extends DetachedDiskReferencesResourceType {
}
| mit |
Azure/azure-sdk-for-java | sdk/resourcemanagerhybrid/azure-resourcemanager-appservice/src/main/java/com/azure/resourcemanager/appservice/fluent/models/DeletedAppRestoreRequestProperties.java | 4742 | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.
package com.azure.resourcemanager.appservice.fluent.models;
import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
/** DeletedAppRestoreRequest resource specific properties. */
@Fluent
public final class DeletedAppRestoreRequestProperties {
@JsonIgnore private final ClientLogger logger = new ClientLogger(DeletedAppRestoreRequestProperties.class);
/*
* ARM resource ID of the deleted app. Example:
* /subscriptions/{subId}/providers/Microsoft.Web/deletedSites/{deletedSiteId}
*/
@JsonProperty(value = "deletedSiteId")
private String deletedSiteId;
/*
* If true, deleted site configuration, in addition to content, will be
* restored.
*/
@JsonProperty(value = "recoverConfiguration")
private Boolean recoverConfiguration;
/*
* Point in time to restore the deleted app from, formatted as a DateTime
* string.
* If unspecified, default value is the time that the app was deleted.
*/
@JsonProperty(value = "snapshotTime")
private String snapshotTime;
/*
* If true, the snapshot is retrieved from DRSecondary endpoint.
*/
@JsonProperty(value = "useDRSecondary")
private Boolean useDRSecondary;
/**
* Get the deletedSiteId property: ARM resource ID of the deleted app. Example:
* /subscriptions/{subId}/providers/Microsoft.Web/deletedSites/{deletedSiteId}.
*
* @return the deletedSiteId value.
*/
public String deletedSiteId() {
return this.deletedSiteId;
}
/**
* Set the deletedSiteId property: ARM resource ID of the deleted app. Example:
* /subscriptions/{subId}/providers/Microsoft.Web/deletedSites/{deletedSiteId}.
*
* @param deletedSiteId the deletedSiteId value to set.
* @return the DeletedAppRestoreRequestProperties object itself.
*/
public DeletedAppRestoreRequestProperties withDeletedSiteId(String deletedSiteId) {
this.deletedSiteId = deletedSiteId;
return this;
}
/**
* Get the recoverConfiguration property: If true, deleted site configuration, in addition to content, will be
* restored.
*
* @return the recoverConfiguration value.
*/
public Boolean recoverConfiguration() {
return this.recoverConfiguration;
}
/**
* Set the recoverConfiguration property: If true, deleted site configuration, in addition to content, will be
* restored.
*
* @param recoverConfiguration the recoverConfiguration value to set.
* @return the DeletedAppRestoreRequestProperties object itself.
*/
public DeletedAppRestoreRequestProperties withRecoverConfiguration(Boolean recoverConfiguration) {
this.recoverConfiguration = recoverConfiguration;
return this;
}
/**
* Get the snapshotTime property: Point in time to restore the deleted app from, formatted as a DateTime string. If
* unspecified, default value is the time that the app was deleted.
*
* @return the snapshotTime value.
*/
public String snapshotTime() {
return this.snapshotTime;
}
/**
* Set the snapshotTime property: Point in time to restore the deleted app from, formatted as a DateTime string. If
* unspecified, default value is the time that the app was deleted.
*
* @param snapshotTime the snapshotTime value to set.
* @return the DeletedAppRestoreRequestProperties object itself.
*/
public DeletedAppRestoreRequestProperties withSnapshotTime(String snapshotTime) {
this.snapshotTime = snapshotTime;
return this;
}
/**
* Get the useDRSecondary property: If true, the snapshot is retrieved from DRSecondary endpoint.
*
* @return the useDRSecondary value.
*/
public Boolean useDRSecondary() {
return this.useDRSecondary;
}
/**
* Set the useDRSecondary property: If true, the snapshot is retrieved from DRSecondary endpoint.
*
* @param useDRSecondary the useDRSecondary value to set.
* @return the DeletedAppRestoreRequestProperties object itself.
*/
public DeletedAppRestoreRequestProperties withUseDRSecondary(Boolean useDRSecondary) {
this.useDRSecondary = useDRSecondary;
return this;
}
/**
* Validates the instance.
*
* @throws IllegalArgumentException thrown if the instance is not valid.
*/
public void validate() {
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/datamigration/mgmt-v2018_07_15_preview/src/main/java/com/microsoft/azure/management/datamigration/v2018_07_15_preview/MigrateSqlServerSqlDbSyncTaskOutputError.java | 1080 | /**
* 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.datamigration.v2018_07_15_preview;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
/**
* The MigrateSqlServerSqlDbSyncTaskOutputError model.
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "resultType")
@JsonTypeName("ErrorOutput")
public class MigrateSqlServerSqlDbSyncTaskOutputError extends MigrateSqlServerSqlDbSyncTaskOutput {
/**
* Migration error.
*/
@JsonProperty(value = "error", access = JsonProperty.Access.WRITE_ONLY)
private ReportableException error;
/**
* Get migration error.
*
* @return the error value
*/
public ReportableException error() {
return this.error;
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/edgegateway/mgmt-v2019_03_01/src/main/java/com/microsoft/azure/management/edgegateway/v2019_03_01/BandwidthSchedules.java | 2088 | /**
* 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.edgegateway.v2019_03_01;
import com.microsoft.azure.arm.collection.SupportsCreating;
import rx.Completable;
import rx.Observable;
import com.microsoft.azure.management.edgegateway.v2019_03_01.implementation.BandwidthSchedulesInner;
import com.microsoft.azure.arm.model.HasInner;
/**
* Type representing BandwidthSchedules.
*/
public interface BandwidthSchedules extends SupportsCreating<BandwidthSchedule.DefinitionStages.Blank>, HasInner<BandwidthSchedulesInner> {
/**
* Gets the properties of the specified bandwidth schedule.
*
* @param deviceName The device name.
* @param name The bandwidth schedule name.
* @param resourceGroupName The resource group name.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Observable<BandwidthSchedule> getAsync(String deviceName, String name, String resourceGroupName);
/**
* Gets all the bandwidth schedules for a data box edge/gateway device.
*
* @param deviceName The device name.
* @param resourceGroupName The resource group name.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Observable<BandwidthSchedule> listByDataBoxEdgeDeviceAsync(final String deviceName, final String resourceGroupName);
/**
* Deletes the specified bandwidth schedule.
*
* @param deviceName The device name.
* @param name The bandwidth schedule name.
* @param resourceGroupName The resource group name.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Completable deleteAsync(String deviceName, String name, String resourceGroupName);
}
| mit |
panurg/thinking-in-java | initialization.09/src/App.java | 296 | public class App {
int x = 0;
App(int x) {
this.x = x;
}
App() {
this(42);
}
public void printInfo() {
System.out.println("x = " + x);
}
public static void main(String[] args) {
App a = new App();
a.printInfo();
}
}
| mit |
HexogenDev/Hexogen-API | src/main/java/net/hexogendev/hexogen/api/material/items/ToolItemMaterial.java | 1652 | package net.hexogendev.hexogen.api.material.items;
import net.hexogendev.hexogen.api.entity.EntityLivingBase;
import net.hexogendev.hexogen.api.entity.alive.player.Player;
import net.hexogendev.hexogen.api.inventory.item.ItemStack;
import net.hexogendev.hexogen.api.material.Material;
import net.hexogendev.hexogen.api.utils.BlockSide;
import net.hexogendev.hexogen.api.world.Position;
import net.hexogendev.hexogen.api.world.World;
public class ToolItemMaterial extends ItemMaterial {
private boolean damageable;
private int maxDurability;
public ToolItemMaterial(String StringId, int Id, int metadata, int customData) {
super(StringId, Id, metadata, customData);
}
public ToolItemMaterial(String stringId, int Id, int metadata) {
this(stringId, Id, metadata, 0);
}
public ToolItemMaterial(String stringId, int Id) {
this(stringId, Id, 0);
}
public ToolItemMaterial(Material material) {
this(material.getStringId(), material.getId(), material.getMinecraftData(), material.getCustomData());
}
public int getMaxDurability() {
return maxDurability;
}
public void setMaxDurability(int durability) {
maxDurability = durability;
}
public boolean isDamageable() {
return damageable;
}
public void setDamageable(boolean flag) {
damageable = flag;
}
@Override
public boolean onItemUse(ItemStack stack, Player player, World world, Position pos, BlockSide side) {
stack.setDurability(stack.getDurability() - 1);
return true;
}
@Override
public boolean onHitEntity(ItemStack stack, EntityLivingBase target, EntityLivingBase attacker) {
stack.setDurability(stack.getDurability() - 1);
return true;
}
}
| mit |
jmue/Gitskarios | app/src/main/java/com/alorma/github/ui/fragment/repos/MembershipReposFragment.java | 1094 | package com.alorma.github.ui.fragment.repos;
import com.alorma.github.R;
import com.alorma.github.sdk.services.repos.MemberReposClient;
/**
* Created by Bernat on 18/07/2015.
*/
public class MembershipReposFragment extends BaseReposListFragment {
public static MembershipReposFragment newInstance() {
return new MembershipReposFragment();
}
@Override
protected void loadArguments() {
}
@Override
protected void executeRequest() {
super.executeRequest();
MemberReposClient memberReposClient = new MemberReposClient(getActivity());
memberReposClient.setOnResultCallback(this);
memberReposClient.execute();
}
@Override
protected void executePaginatedRequest(int page) {
super.executePaginatedRequest(page);
MemberReposClient memberReposClient = new MemberReposClient(getActivity(), page);
memberReposClient.setOnResultCallback(this);
memberReposClient.execute();
}
@Override
protected int getNoDataText() {
return R.string.no_member_repositories;
}
}
| mit |
Tyriar/java-design-patterns | src/com/growingwiththeweb/designpatterns/visitor/VisitorInterface.java | 191 | package com.growingwiththeweb.designpatterns.visitor;
public interface VisitorInterface {
public void visit(ConcreteElementA element);
public void visit(ConcreteElementB element);
}
| mit |
robrua/Orianna | orianna/src/main/java/com/merakianalytics/orianna/types/data/staticdata/SummonerSpells.java | 3800 | package com.merakianalytics.orianna.types.data.staticdata;
import java.util.Set;
import com.merakianalytics.orianna.types.data.CoreData;
public class SummonerSpells extends CoreData.ListProxy<SummonerSpell> {
private static final long serialVersionUID = -1083191958513156896L;
private Set<String> includedData;
private String version, locale, type, platform;
public SummonerSpells() {
super();
}
public SummonerSpells(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 SummonerSpells other = (SummonerSpells)obj;
if(includedData == null) {
if(other.includedData != null) {
return false;
}
} else if(!includedData.equals(other.includedData)) {
return false;
}
if(locale == null) {
if(other.locale != null) {
return false;
}
} else if(!locale.equals(other.locale)) {
return false;
}
if(platform == null) {
if(other.platform != null) {
return false;
}
} else if(!platform.equals(other.platform)) {
return false;
}
if(type == null) {
if(other.type != null) {
return false;
}
} else if(!type.equals(other.type)) {
return false;
}
if(version == null) {
if(other.version != null) {
return false;
}
} else if(!version.equals(other.version)) {
return false;
}
return true;
}
/**
* @return the includedData
*/
public Set<String> getIncludedData() {
return includedData;
}
/**
* @return the locale
*/
public String getLocale() {
return locale;
}
/**
* @return the platform
*/
public String getPlatform() {
return platform;
}
/**
* @return the type
*/
public String getType() {
return type;
}
/**
* @return the version
*/
public String getVersion() {
return version;
}
@Override
public int hashCode() {
final int prime = 31;
int result = super.hashCode();
result = prime * result + (includedData == null ? 0 : includedData.hashCode());
result = prime * result + (locale == null ? 0 : locale.hashCode());
result = prime * result + (platform == null ? 0 : platform.hashCode());
result = prime * result + (type == null ? 0 : type.hashCode());
result = prime * result + (version == null ? 0 : version.hashCode());
return result;
}
/**
* @param includedData
* the includedData to set
*/
public void setIncludedData(final Set<String> includedData) {
this.includedData = includedData;
}
/**
* @param locale
* the locale to set
*/
public void setLocale(final String locale) {
this.locale = locale;
}
/**
* @param platform
* the platform to set
*/
public void setPlatform(final String platform) {
this.platform = platform;
}
/**
* @param type
* the type to set
*/
public void setType(final String type) {
this.type = type;
}
/**
* @param version
* the version to set
*/
public void setVersion(final String version) {
this.version = version;
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2019_07_01/src/main/java/com/microsoft/azure/management/network/v2019_07_01/FirewallPolicyFilterRuleAction.java | 1224 | /**
* 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.network.v2019_07_01;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Properties of the FirewallPolicyFilterRuleAction.
*/
public class FirewallPolicyFilterRuleAction {
/**
* The type of action. Possible values include: 'Allow', 'Deny', 'Alert '.
*/
@JsonProperty(value = "type")
private FirewallPolicyFilterRuleActionType type;
/**
* Get the type of action. Possible values include: 'Allow', 'Deny', 'Alert '.
*
* @return the type value
*/
public FirewallPolicyFilterRuleActionType type() {
return this.type;
}
/**
* Set the type of action. Possible values include: 'Allow', 'Deny', 'Alert '.
*
* @param type the type value to set
* @return the FirewallPolicyFilterRuleAction object itself.
*/
public FirewallPolicyFilterRuleAction withType(FirewallPolicyFilterRuleActionType type) {
this.type = type;
return this;
}
}
| mit |
stexfires/stexfires | src/main/java/stexfires/io/markdown/list/MarkdownListFileSpec.java | 4131 | package stexfires.io.markdown.list;
import org.jetbrains.annotations.Nullable;
import stexfires.io.spec.AbstractRecordFileSpec;
import stexfires.util.LineSeparator;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.nio.charset.CodingErrorAction;
import java.nio.file.Path;
import java.util.Objects;
/**
* @author Mathias Kalb
* @since 0.1
*/
public final class MarkdownListFileSpec extends AbstractRecordFileSpec {
public enum BulletPoint {
NUMBER, STAR, DASH
}
public static final String BULLET_POINT_NUMBER = ".";
public static final String BULLET_POINT_STAR = "*";
public static final String BULLET_POINT_DASH = "-";
public static final String FILL_CHARACTER = " ";
public static final long START_NUMBER = 1L;
// DEFAULT - write
public static final BulletPoint DEFAULT_BULLET_POINT = BulletPoint.STAR;
public static final boolean DEFAULT_SKIP_NULL_VALUE = false;
// FIELD - write
private final String beforeList;
private final String afterList;
private final BulletPoint bulletPoint;
private final boolean skipNullValue;
public MarkdownListFileSpec(Charset charset, CodingErrorAction codingErrorAction,
LineSeparator lineSeparator,
@Nullable String beforeList, @Nullable String afterList,
BulletPoint bulletPoint, boolean skipNullValue) {
super(charset, codingErrorAction, lineSeparator);
Objects.requireNonNull(bulletPoint);
// write
this.beforeList = beforeList;
this.afterList = afterList;
this.bulletPoint = bulletPoint;
this.skipNullValue = skipNullValue;
}
public static MarkdownListFileSpec write(Charset charset,
LineSeparator lineSeparator) {
return new MarkdownListFileSpec(charset, DEFAULT_CODING_ERROR_ACTION,
lineSeparator,
null, null,
DEFAULT_BULLET_POINT, DEFAULT_SKIP_NULL_VALUE);
}
public static MarkdownListFileSpec write(Charset charset, CodingErrorAction codingErrorAction,
LineSeparator lineSeparator) {
return new MarkdownListFileSpec(charset, codingErrorAction,
lineSeparator,
null, null,
DEFAULT_BULLET_POINT, DEFAULT_SKIP_NULL_VALUE);
}
public static MarkdownListFileSpec write(Charset charset,
LineSeparator lineSeparator,
@Nullable String beforeList, @Nullable String afterList,
BulletPoint bulletPoint, boolean skipNullValue) {
return new MarkdownListFileSpec(charset, DEFAULT_CODING_ERROR_ACTION,
lineSeparator,
beforeList, afterList,
bulletPoint, skipNullValue);
}
public static MarkdownListFileSpec write(Charset charset, CodingErrorAction codingErrorAction,
LineSeparator lineSeparator,
@Nullable String beforeList, @Nullable String afterList,
BulletPoint bulletPoint, boolean skipNullValue) {
return new MarkdownListFileSpec(charset, codingErrorAction,
lineSeparator,
beforeList, afterList,
bulletPoint, skipNullValue);
}
@Override
public MarkdownListFile file(Path path) {
return new MarkdownListFile(path, this);
}
public MarkdownListConsumer consumer(OutputStream outputStream) {
return new MarkdownListConsumer(newBufferedWriter(outputStream), this);
}
public @Nullable String getBeforeList() {
return beforeList;
}
public @Nullable String getAfterList() {
return afterList;
}
public BulletPoint getBulletPoint() {
return bulletPoint;
}
public boolean isSkipNullValue() {
return skipNullValue;
}
}
| mit |
maniekstasz/messenger | messenger-client/Messenger/src/messenger/views/StartView.java | 7906 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/*
* StartView.java
*
* Created on 2011-02-10, 19:16:30
*/
package messenger.views;
import java.awt.Dimension;
import java.awt.Toolkit;
import javax.swing.JOptionPane;
import messenger.controller.MainAppController;
import messenger.controller.UserController;
public class StartView extends javax.swing.JFrame {
private MainAppController controller;
/** Creates new form StartView
* @param userController */
public StartView(MainAppController mainAppController) {
this.setLocationRelativeTo(getRootPane());
initComponents();
this.controller = mainAppController;
this.setLocationRelativeTo(null);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel1 = new javax.swing.JLabel();
loginField = new javax.swing.JTextField();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
registerButton = new javax.swing.JButton();
loginButton = new javax.swing.JButton();
cancelButton = new javax.swing.JButton();
passwordField = new javax.swing.JPasswordField();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
setTitle("Jadu");
jLabel1.setText("Hasło:");
jLabel2.setText("Username:");
jLabel3.setText("Nie masz konta?");
registerButton.setText("Zarejestruj się");
registerButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
registerButtonActionPerformed(evt);
}
});
loginButton.setText("Zaloguj");
loginButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
loginButtonActionPerformed(evt);
}
});
cancelButton.setText("Anuluj");
cancelButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
cancelButtonActionPerformed(evt);
}
});
passwordField.setName("password"); // NOI18N
passwordField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
passwordFieldActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addComponent(jLabel1)
.addComponent(jLabel2))
.addGap(18, 18, 18)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(loginField)
.addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createSequentialGroup()
.addComponent(loginButton)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 66, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel3)
.addComponent(registerButton))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGap(0, 151, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel2)
.addComponent(loginField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(jLabel1)
.addComponent(passwordField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(loginButton)
.addComponent(cancelButton, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel3)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(registerButton)
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void registerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_registerButtonActionPerformed
controller.showRegisterFrame();
}//GEN-LAST:event_registerButtonActionPerformed
private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
System.exit(0);
}//GEN-LAST:event_cancelButtonActionPerformed
private void passwordFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_passwordFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_passwordFieldActionPerformed
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {
String login = loginField.getText();
char[] pass = passwordField.getPassword();
String password = UserController.arrayToString(pass);
if(login.equals("") || password.equals("")){
JOptionPane.showMessageDialog(null, "Wypełnij wszystkie pola!", "Błąd", JOptionPane.ERROR_MESSAGE);
return;
}
controller.logIn(login, password);
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
// new StartView().setVisible(true);
}
});
}
private javax.swing.JButton cancelButton;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JButton loginButton;
private javax.swing.JTextField loginField;
private javax.swing.JPasswordField passwordField;
private javax.swing.JButton registerButton;
}
| mit |
omegasoft7/DBFlow | library/src/main/java/com/raizlabs/android/dbflow/sql/migration/Migration.java | 832 | package com.raizlabs.android.dbflow.sql.migration;
import android.database.sqlite.SQLiteDatabase;
/**
* Description: Called when the Database is migrating. We can perform custom migrations here. A {@link com.raizlabs.android.dbflow.annotation.Migration}
* is required for registering this class to automatically be called in an upgrade of the DB.
*/
public interface Migration {
/**
* Called before we migrate data. Instantiate migration data before releasing it in {@link #onPostMigrate()}
*/
public void onPreMigrate();
/**
* Perform your migrations here
*
* @param database The database to operate on
*/
public void migrate(SQLiteDatabase database);
/**
* Called after the migration completes. Release migration data here.
*/
public void onPostMigrate();
}
| mit |
jsquared21/Intro-to-Java-Programming | Exercise_10/Exercise_10_06/StackOfIntegers.java | 1046 | public class StackOfIntegers {
private int[] elements;
private int size;
public static final int DEFAULT_CAPACITY = 16;
/** Construct a stack with the default capacity 16 */
public StackOfIntegers() {
this (DEFAULT_CAPACITY);
}
/** Construct a stack with the specified maximum capacity */
public StackOfIntegers(int capacity) {
elements = new int[capacity];
}
/** Push a new integer to the top of the stack */
public void push(int value) {
if (size >= elements.length) {
int[] temp = new int[elements.length * 2];
System.arraycopy(elements, 0, temp, 0, elements.length);
elements = temp;
}
elements[size++] = value;
}
/** Return and remove the top element from the stack */
public int pop() {
return elements[--size];
}
/** Return the top element from the stack */
public int peek() {
return elements[size - 1];
}
/** Test whether the stack is empty */
public boolean empty() {
return size == 0;
}
/** Return the number of elements in the stack */
public int getSize() {
return size;
}
} | mit |
awong1900/WiFi_Iot_Node_App | app/src/main/java/cc/seeed/iot/util/UmengUtils.java | 5590 | package cc.seeed.iot.util;
import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import com.facebook.share.model.ShareLinkContent;
import com.facebook.share.widget.MessageDialog;
import com.facebook.share.widget.ShareDialog;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMAuthListener;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import java.util.Map;
import cc.seeed.iot.App;
import cc.seeed.iot.R;
/**
* Created by seeed on 2016/3/10.
*/
public class UmengUtils {
static ShareAction shareAction;
static Activity activity;
static UMShareAPI mShareAPI;
public static void initUmengShare() {
//微信 appid appsecret
// PlatformConfig.setWeixin("wx43881f3372d0a832", "f0a59af4fa6b7381af44ffb45bbe62f3");
PlatformConfig.setTwitter("W7dkMSuiGFzCrfETuri3giEov", "Wp93a4FFrCFlzhMiwXBy7QKX9KjhgCbhgrHEz8QCsqGe4pg5Sv");
// PlatformConfig.setTwitter("739753776953712640", "koX7vp9UBAbekl2xPBEhHy5aYdaERxdgHtPQgdHfLA8tk");
//Twitter appid appkey
}
public static UMShareAPI getUMShareAPI() {
if (mShareAPI == null) {
mShareAPI = UMShareAPI.get(activity);
}
return mShareAPI;
}
public static void share(Activity activity, SHARE_MEDIA share_media, String title, String content, String url, String imgUrl) {
if (mShareAPI == null)
mShareAPI = UMShareAPI.get(activity);
UMImage image = null;
if (!mShareAPI.isInstall(activity, share_media)) {
if (share_media == SHARE_MEDIA.WHATSAPP && ToolUtil.isInstallByread("com.whatsapp")) {
}else if (share_media == SHARE_MEDIA.GOOGLEPLUS && ToolUtil.isInstallByread("com.google.android.apps.plus")) {
}else {
App.showToastShrot("App not installed");
return;
}
}
if (ToolUtil.isNetworkAvailable() && imgUrl != null) {
image = new UMImage(activity, imgUrl);
} else {
image = new UMImage(activity, BitmapFactory.decodeResource(activity.getResources(), R.drawable.logo));
}
if (share_media.equals(SHARE_MEDIA.WEIXIN_CIRCLE)) {
new ShareAction(activity)
.setPlatform(share_media)
.setCallback(umShareListener)
.withText(title + " " + content)
.withTargetUrl(url)
.withTitle(title + " " + content)
.withMedia(image)
.share();
} else {
new ShareAction(activity)
.setPlatform(share_media)
.setCallback(umShareListener)
.withText(content)
.withTitle(title)
.withTargetUrl(url)
// .withMedia(image)
.share();
}
}
public static void shareToTwitter(Activity activity, String content) {
new ShareAction(activity).setPlatform(SHARE_MEDIA.TWITTER).setCallback(umShareListener)
.withText(content)
.share();
/* new ShareAction(activity).setDisplayList(SHARE_MEDIA.TWITTER, SHARE_MEDIA.FACEBOOK, SHARE_MEDIA.GOOGLEPLUS)
.withText("来自友盟分享面板")
.setCallback(umShareListener)
.open();*/
}
public static void shareFacebook(Activity activity, String url, String imgUrl) {
ShareLinkContent content = new ShareLinkContent.Builder()
.setContentUrl(Uri.parse(url))
.setContentDescription(url)
.setContentTitle("Wio")
// .setImageUrl(imgUri)
.build();
ShareDialog.show(activity, content);
}
static UMShareListener umShareListener = new UMShareListener() {
@Override
public void onResult(SHARE_MEDIA platform) {
// Toast.makeText(ShareActivity.this,platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
App.showToastShrot("Success");
}
@Override
public void onError(SHARE_MEDIA platform, Throwable t) {
// Toast.makeText(ShareActivity.this,platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
App.showToastShrot("Fail");
}
@Override
public void onCancel(SHARE_MEDIA platform) {
// Toast.makeText(ShareActivity.this,platform + " 分享取消了", Toast.LENGTH_SHORT).show();
App.showToastShrot("Cancel");
}
};
public static void login(Activity activity) {
mShareAPI = UMShareAPI.get(activity);
SHARE_MEDIA platform = SHARE_MEDIA.WEIXIN;
mShareAPI.doOauthVerify(activity, platform, umAuthListener);
}
private static UMAuthListener umAuthListener = new UMAuthListener() {
@Override
public void onComplete(SHARE_MEDIA platform, int action, Map<String, String> data) {
App.showToastShrot("Authorize succeed");
}
@Override
public void onError(SHARE_MEDIA platform, int action, Throwable t) {
App.showToastShrot("Authorize fail");
}
@Override
public void onCancel(SHARE_MEDIA platform, int action) {
App.showToastShrot("Authorize cancel");
}
};
}
| mit |
broadinstitute/picard | src/test/java/picard/sam/SamFormatConverterTest.java | 3862 | /*
* The MIT License
*
* Copyright (c) 2014 The Broad Institute
*
* 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 picard.sam;
import htsjdk.samtools.Defaults;
import htsjdk.samtools.SamReader;
import htsjdk.samtools.SamReaderFactory;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import picard.sam.util.SamComparison;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertTrue;
public class SamFormatConverterTest {
private static final File TEST_DATA_DIR = new File("testdata/picard/sam/SamFormatConverterTest");
private static final File unmappedSam = new File(TEST_DATA_DIR, "unmapped.sam");
private static final File unmappedBam = new File(TEST_DATA_DIR, "unmapped.bam");
private static final File unmappedCram = new File(TEST_DATA_DIR, "unmapped.cram");
private static final File ESSENTIALLY_EMPTY_REFERENCE_TO_USE_WITH_UNMAPPED_CRAM = new File(TEST_DATA_DIR, "basicallyEmpty.fasta");
@DataProvider
public Object[][] conversionCases() {
return new Object[][]{
{unmappedSam, unmappedBam, ".bam"},
{unmappedSam, unmappedCram, ".cram"},
{unmappedBam, unmappedCram, ".cram"},
{unmappedBam, unmappedSam, ".sam"},
{unmappedCram, unmappedBam, ".bam"},
{unmappedCram, unmappedSam, ".sam"},
};
}
@Test(dataProvider = "conversionCases")
public void testConvert(File input, File expected, String extension) throws IOException {
convertFile(input, expected, extension);
}
private void convertFile(final File inputFile, final File fileToCompare, final String extension) throws IOException {
final List<File> samFiles = new ArrayList<>();
final ValidateSamFile validateSamFile = new ValidateSamFile();
final File output = File.createTempFile("SamFormatConverterTest." + inputFile.getName(), extension);
output.deleteOnExit();
SamFormatConverter.convert(inputFile, output, ESSENTIALLY_EMPTY_REFERENCE_TO_USE_WITH_UNMAPPED_CRAM, Defaults.CREATE_INDEX);
validateSamFile.INPUT = output;
assertEquals(validateSamFile.doWork(), 0);
final SamReaderFactory samReaderFactory = SamReaderFactory.makeDefault().referenceSequence(ESSENTIALLY_EMPTY_REFERENCE_TO_USE_WITH_UNMAPPED_CRAM);
try (final SamReader samReader1 = samReaderFactory.open(output);
final SamReader samReader2 = samReaderFactory.open(fileToCompare)) {
final SamComparison samComparison = new SamComparison(samReader1, samReader2);
Assert.assertTrue(samComparison.areEqual());
}
}
}
| mit |
cokejcm/queue-cache | base-arch/src/main/java/com/demo/app/domain/Entity.java | 2597 | package com.demo.app.domain;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.persistence.MappedSuperclass;
import org.apache.commons.lang3.SerializationUtils;
import com.demo.app.configuration.exceptions.AppException;
import com.demo.app.configuration.fakedata.CommonEntity;
import com.demo.app.util.Util;
@MappedSuperclass
public abstract class Entity implements Serializable, Cloneable, CommonEntity, Comparable<Entity> {
private static final long serialVersionUID = 5908519522358747038L;
public abstract String getId();
public abstract void setId(String id);
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (getId() == null ? 0 : getId().hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
Entity other = (Entity) obj;
if (getId() == null) {
if (other.getId() != null) {
return false;
}
} else if (!getId().equals(other.getId())) {
return false;
}
return true;
}
public Entity clone(String[] notCloneableFieldNames, Object[] notCloneableFieldValues) throws Exception {
if (notCloneableFieldNames.length != notCloneableFieldValues.length) {
throw new AppException("The list of elements and values differs when cloning entity when Entity.clone");
}
Entity e = SerializationUtils.clone(this);
for (int i = 0; i < notCloneableFieldNames.length; i++) {
Field field = e.getClass().getDeclaredField(notCloneableFieldNames[i]);
Method getMethod = field.getDeclaringClass().getMethod("get" + Util.capitalize(field.getName()));
Class<?> c = getMethod.getReturnType();
if (!c.isAssignableFrom(notCloneableFieldValues[i].getClass())) {
throw new AppException("Class not assignable from " + notCloneableFieldValues[i].getClass() + "when Entity.clone");
}
Method method = field.getDeclaringClass().getMethod("set" + Util.capitalize(field.getName()), c);
method.invoke(e, new Object[] { notCloneableFieldValues[i] });
}
// set id to null
Field fieldId = e.getClass().getDeclaredField("id");
Method method = fieldId.getDeclaringClass().getMethod("set" + Util.capitalize(fieldId.getName()), String.class);
method.invoke(e, new Object[] { null });
return e;
}
@Override
public int compareTo(Entity o) {
return this.getId().compareTo(o.getId());
}
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
}
| mit |
sureshsajja/CodeRevisited | src/main/java/com/hackerearth/julyeasy15/TheRiseOfTheWeirdThings.java | 3096 | /*
* The MIT License (MIT)
*
* Copyright (c) 2015 CodeRevisited.com
*
* 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.hackerearth.julyeasy15;
import java.io.*;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.StringTokenizer;
import static java.lang.Integer.parseInt;
import static java.lang.System.in;
import static java.lang.System.out;
/**
* User : Suresh
* Date : 04/07/15
* Version : v1
*/
/**
* https://www.hackerearth.com/july-easy-15/algorithm/the-rise-of-the-weird-things-1/
*/
public class TheRiseOfTheWeirdThings {
private static BufferedReader reader;
private static StringTokenizer tokenizer;
private static String next() throws IOException {
while (!tokenizer.hasMoreTokens()) {
tokenizer = new StringTokenizer(
reader.readLine());
}
return tokenizer.nextToken();
}
private static int nextInt() throws IOException {
return parseInt(next());
}
public static void main(String[] args) throws IOException {
reader = new BufferedReader(new InputStreamReader(in));
tokenizer = new StringTokenizer("");
PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out)));
int N = nextInt();
List<Integer> evens = new LinkedList<>();
List<Integer> odds = new LinkedList<>();
int oddSum = 0;
int evenSum = 0;
for (int n = 0; n < N; n++) {
int i = nextInt();
if (i % 2 == 0) {
evenSum += i;
evens.add(i);
} else {
oddSum += i;
odds.add(i);
}
}
Collections.sort(evens);
Collections.sort(odds);
for (Integer i : evens) {
pw.print(i + " ");
}
pw.print(evenSum + " ");
for (Integer i : odds) {
pw.print(i + " ");
}
pw.println(oddSum);
reader.close();
pw.close();
}
}
| mit |
aamine/bricolage-streaming-preprocessor | src/main/java/org/bricolages/streaming/preflight/domains/DateDomain.java | 1287 | package org.bricolages.streaming.preflight.domains;
import org.bricolages.streaming.preflight.definition.ColumnEncoding;
import org.bricolages.streaming.preflight.definition.OperatorDefinitionEntry;
import org.bricolages.streaming.preflight.ReferenceGenerator.MultilineDescription;
import org.bricolages.streaming.stream.StreamColumn;
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonTypeName;
import lombok.*;
@JsonTypeName("date")
@MultilineDescription("Date")
@NoArgsConstructor
public class DateDomain extends PrimitiveDomain {
@Getter private final String type = "date";
@Getter private final ColumnEncoding encoding = ColumnEncoding.ZSTD;
@Getter
@MultilineDescription("Source timezone, given by the string like '+00:00'")
private String sourceOffset;
@Getter
@MultilineDescription("Target timezone, given by the string like '+09:00'")
private String zoneOffset;
// This is necessary to accept empty value
@JsonCreator public DateDomain(String nil) { /* noop */ }
public StreamColumn.Params getStreamColumnParams() {
val params = super.getStreamColumnParams();
params.sourceOffset = sourceOffset;
params.zoneOffset = zoneOffset;
return params;
}
}
| mit |
kzantow/blueocean-plugin | blueocean-github-pipeline/src/main/java/io/jenkins/blueocean/blueocean_github_pipeline/GithubCredentialUtils.java | 880 | package io.jenkins.blueocean.blueocean_github_pipeline;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
/**
* @author cliffmeyers
*/
public class GithubCredentialUtils {
/**
* Create proper credentialId for GitHub and GitHub Enterprise.
* If null/empty credentialId value is passed in, will compute proper default value.
*
* @param scmId "github" or "github-enterprise"
* @param apiUrl apiUrl, for enterprise only
* @return credentialId
*/
static String computeCredentialId(String credentialId, String scmId, String apiUrl) {
if(StringUtils.isNotBlank(credentialId)) {
return credentialId;
}
if (GithubScm.ID.equals(scmId)) {
return scmId;
}
return GithubEnterpriseScm.ID + ":" + DigestUtils.sha256Hex(apiUrl);
}
}
| mit |
georghinkel/ttc2017smartGrids | solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/CIM/IEC61968/Metering/util/MeteringAdapterFactory.java | 22793 | /**
*/
package gluemodel.CIM.IEC61968.Metering.util;
import gluemodel.CIM.Element;
import gluemodel.CIM.IEC61968.Assets.Asset;
import gluemodel.CIM.IEC61968.Assets.AssetContainer;
import gluemodel.CIM.IEC61968.Assets.AssetFunction;
import gluemodel.CIM.IEC61968.Common.ActivityRecord;
import gluemodel.CIM.IEC61968.Common.Document;
import gluemodel.CIM.IEC61968.Common.Location;
import gluemodel.CIM.IEC61968.Metering.*;
import gluemodel.CIM.IEC61968.Work.Work;
import gluemodel.CIM.IEC61970.Core.IdentifiedObject;
import gluemodel.CIM.IEC61970.Meas.MeasurementValue;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.notify.impl.AdapterFactoryImpl;
import org.eclipse.emf.ecore.EObject;
/**
* <!-- begin-user-doc -->
* The <b>Adapter Factory</b> for the model.
* It provides an adapter <code>createXXX</code> method for each class of the model.
* <!-- end-user-doc -->
* @see gluemodel.CIM.IEC61968.Metering.MeteringPackage
* @generated
*/
public class MeteringAdapterFactory extends AdapterFactoryImpl {
/**
* The cached model package.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected static MeteringPackage modelPackage;
/**
* Creates an instance of the adapter factory.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public MeteringAdapterFactory() {
if (modelPackage == null) {
modelPackage = MeteringPackage.eINSTANCE;
}
}
/**
* Returns whether this factory is applicable for the type of the object.
* <!-- begin-user-doc -->
* This implementation returns <code>true</code> if the object is either the model's package or is an instance object of the model.
* <!-- end-user-doc -->
* @return whether this factory is applicable for the type of the object.
* @generated
*/
@Override
public boolean isFactoryForType(Object object) {
if (object == modelPackage) {
return true;
}
if (object instanceof EObject) {
return ((EObject)object).eClass().getEPackage() == modelPackage;
}
return false;
}
/**
* The switch that delegates to the <code>createXXX</code> methods.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected MeteringSwitch<Adapter> modelSwitch =
new MeteringSwitch<Adapter>() {
@Override
public Adapter caseEndDeviceEvent(EndDeviceEvent object) {
return createEndDeviceEventAdapter();
}
@Override
public Adapter caseReadingType(ReadingType object) {
return createReadingTypeAdapter();
}
@Override
public Adapter caseMeterServiceWork(MeterServiceWork object) {
return createMeterServiceWorkAdapter();
}
@Override
public Adapter caseDeviceFunction(DeviceFunction object) {
return createDeviceFunctionAdapter();
}
@Override
public Adapter caseEndDeviceGroup(EndDeviceGroup object) {
return createEndDeviceGroupAdapter();
}
@Override
public Adapter caseDynamicDemand(DynamicDemand object) {
return createDynamicDemandAdapter();
}
@Override
public Adapter caseIntervalReading(IntervalReading object) {
return createIntervalReadingAdapter();
}
@Override
public Adapter caseSDPLocation(SDPLocation object) {
return createSDPLocationAdapter();
}
@Override
public Adapter caseEndDeviceAsset(EndDeviceAsset object) {
return createEndDeviceAssetAdapter();
}
@Override
public Adapter caseIntervalBlock(IntervalBlock object) {
return createIntervalBlockAdapter();
}
@Override
public Adapter caseReadingQuality(ReadingQuality object) {
return createReadingQualityAdapter();
}
@Override
public Adapter caseMeterAsset(MeterAsset object) {
return createMeterAssetAdapter();
}
@Override
public Adapter caseMeterReading(MeterReading object) {
return createMeterReadingAdapter();
}
@Override
public Adapter caseReading(Reading object) {
return createReadingAdapter();
}
@Override
public Adapter caseDemandResponseProgram(DemandResponseProgram object) {
return createDemandResponseProgramAdapter();
}
@Override
public Adapter caseComFunction(ComFunction object) {
return createComFunctionAdapter();
}
@Override
public Adapter caseServiceDeliveryPoint(ServiceDeliveryPoint object) {
return createServiceDeliveryPointAdapter();
}
@Override
public Adapter caseRegister(Register object) {
return createRegisterAdapter();
}
@Override
public Adapter caseEndDeviceControl(EndDeviceControl object) {
return createEndDeviceControlAdapter();
}
@Override
public Adapter casePending(Pending object) {
return createPendingAdapter();
}
@Override
public Adapter caseElectricMeteringFunction(ElectricMeteringFunction object) {
return createElectricMeteringFunctionAdapter();
}
@Override
public Adapter caseElement(Element object) {
return createElementAdapter();
}
@Override
public Adapter caseIdentifiedObject(IdentifiedObject object) {
return createIdentifiedObjectAdapter();
}
@Override
public Adapter caseActivityRecord(ActivityRecord object) {
return createActivityRecordAdapter();
}
@Override
public Adapter caseDocument(Document object) {
return createDocumentAdapter();
}
@Override
public Adapter caseWork(Work object) {
return createWorkAdapter();
}
@Override
public Adapter caseAssetFunction(AssetFunction object) {
return createAssetFunctionAdapter();
}
@Override
public Adapter caseMeasurementValue(MeasurementValue object) {
return createMeasurementValueAdapter();
}
@Override
public Adapter caseLocation(Location object) {
return createLocationAdapter();
}
@Override
public Adapter caseAsset(Asset object) {
return createAssetAdapter();
}
@Override
public Adapter caseAssetContainer(AssetContainer object) {
return createAssetContainerAdapter();
}
@Override
public Adapter defaultCase(EObject object) {
return createEObjectAdapter();
}
};
/**
* Creates an adapter for the <code>target</code>.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param target the object to adapt.
* @return the adapter for the <code>target</code>.
* @generated
*/
@Override
public Adapter createAdapter(Notifier target) {
return modelSwitch.doSwitch((EObject)target);
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.EndDeviceEvent <em>End Device Event</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.EndDeviceEvent
* @generated
*/
public Adapter createEndDeviceEventAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.ReadingType <em>Reading Type</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.ReadingType
* @generated
*/
public Adapter createReadingTypeAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.MeterServiceWork <em>Meter Service Work</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.MeterServiceWork
* @generated
*/
public Adapter createMeterServiceWorkAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.DeviceFunction <em>Device Function</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.DeviceFunction
* @generated
*/
public Adapter createDeviceFunctionAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.EndDeviceGroup <em>End Device Group</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.EndDeviceGroup
* @generated
*/
public Adapter createEndDeviceGroupAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.DynamicDemand <em>Dynamic Demand</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.DynamicDemand
* @generated
*/
public Adapter createDynamicDemandAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.IntervalReading <em>Interval Reading</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.IntervalReading
* @generated
*/
public Adapter createIntervalReadingAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.SDPLocation <em>SDP Location</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.SDPLocation
* @generated
*/
public Adapter createSDPLocationAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.EndDeviceAsset <em>End Device Asset</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.EndDeviceAsset
* @generated
*/
public Adapter createEndDeviceAssetAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.IntervalBlock <em>Interval Block</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.IntervalBlock
* @generated
*/
public Adapter createIntervalBlockAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.ReadingQuality <em>Reading Quality</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.ReadingQuality
* @generated
*/
public Adapter createReadingQualityAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.MeterAsset <em>Meter Asset</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.MeterAsset
* @generated
*/
public Adapter createMeterAssetAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.MeterReading <em>Meter Reading</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.MeterReading
* @generated
*/
public Adapter createMeterReadingAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.Reading <em>Reading</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.Reading
* @generated
*/
public Adapter createReadingAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.DemandResponseProgram <em>Demand Response Program</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.DemandResponseProgram
* @generated
*/
public Adapter createDemandResponseProgramAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.ComFunction <em>Com Function</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.ComFunction
* @generated
*/
public Adapter createComFunctionAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.ServiceDeliveryPoint <em>Service Delivery Point</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.ServiceDeliveryPoint
* @generated
*/
public Adapter createServiceDeliveryPointAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.Register <em>Register</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.Register
* @generated
*/
public Adapter createRegisterAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.EndDeviceControl <em>End Device Control</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.EndDeviceControl
* @generated
*/
public Adapter createEndDeviceControlAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.Pending <em>Pending</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.Pending
* @generated
*/
public Adapter createPendingAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Metering.ElectricMeteringFunction <em>Electric Metering Function</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Metering.ElectricMeteringFunction
* @generated
*/
public Adapter createElectricMeteringFunctionAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.Element <em>Element</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.Element
* @generated
*/
public Adapter createElementAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61970.Core.IdentifiedObject <em>Identified Object</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61970.Core.IdentifiedObject
* @generated
*/
public Adapter createIdentifiedObjectAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Common.ActivityRecord <em>Activity Record</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Common.ActivityRecord
* @generated
*/
public Adapter createActivityRecordAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Common.Document <em>Document</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Common.Document
* @generated
*/
public Adapter createDocumentAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Work.Work <em>Work</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Work.Work
* @generated
*/
public Adapter createWorkAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Assets.AssetFunction <em>Asset Function</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Assets.AssetFunction
* @generated
*/
public Adapter createAssetFunctionAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61970.Meas.MeasurementValue <em>Measurement Value</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61970.Meas.MeasurementValue
* @generated
*/
public Adapter createMeasurementValueAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Common.Location <em>Location</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Common.Location
* @generated
*/
public Adapter createLocationAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Assets.Asset <em>Asset</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Assets.Asset
* @generated
*/
public Adapter createAssetAdapter() {
return null;
}
/**
* Creates a new adapter for an object of class '{@link gluemodel.CIM.IEC61968.Assets.AssetContainer <em>Asset Container</em>}'.
* <!-- begin-user-doc -->
* This default implementation returns null so that we can easily ignore cases;
* it's useful to ignore a case when inheritance will catch all the cases anyway.
* <!-- end-user-doc -->
* @return the new adapter.
* @see gluemodel.CIM.IEC61968.Assets.AssetContainer
* @generated
*/
public Adapter createAssetContainerAdapter() {
return null;
}
/**
* Creates a new adapter for the default case.
* <!-- begin-user-doc -->
* This default implementation returns null.
* <!-- end-user-doc -->
* @return the new adapter.
* @generated
*/
public Adapter createEObjectAdapter() {
return null;
}
} //MeteringAdapterFactory
| mit |
natasha-pel/hadoop-etl-udfs | src/main/java/com/exasol/hadoop/hdfs/MultiPartitionFilter.java | 1944 | package com.exasol.hadoop.hdfs;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Utility Methods to work with a multi partition filter, i.e. user specified multiple filters (logically connected by OR)
*/
public class MultiPartitionFilter {
public static List<PartitionFilter> parseMultiFilter(String filter) {
List<PartitionFilter> partitionFilters = new ArrayList<>();
if (filter == null || filter.isEmpty()) {
return partitionFilters;
}
String[] filterSpecs = filter.split(",");
for (String filterSpec : filterSpecs) {
String[] filterParts = filterSpec.split("/");
Map<String, String> partitionFilter = new HashMap<>();
for (String filterPart : filterParts) {
String[] keyValue = filterPart.trim().split("=");
partitionFilter.put(keyValue[0], keyValue[1]);
}
partitionFilters.add(new PartitionFilter(partitionFilter));
}
return partitionFilters;
}
public static boolean matchesAnyFilter(Map<String, String> partitionValues, List<PartitionFilter> filters) {
if (filters.isEmpty()) {
return true;
}
for (PartitionFilter filter : filters) {
if (matchesSingleFilter(partitionValues, filter)) {
return true;
}
}
return false;
}
private static boolean matchesSingleFilter(Map<String, String> partitionValues, PartitionFilter filter) {
// Does not match if any partition is mentioned in the filter with a different value
for (String partition : partitionValues.keySet()) {
if (filter.containsPartition(partition) && !filter.getPartitionValue(partition).equals(partitionValues.get(partition))) {
return false;
}
}
return true;
}
}
| mit |
djpowell/liverepl | liverepl-agent/src/net/djpowell/liverepl/discovery/ClassLoaderDiscovery.java | 555 | package net.djpowell.liverepl.discovery;
import java.util.Collection;
/**
* SPI Interface for providing implementations to discover ClassLoaders.
*/
public interface ClassLoaderDiscovery {
/**
* Return information about the available ClassLoaders.
* Implementations must register each ClassLoader with the application's ClassLoaderRegistry,
* and use the id returned by the registry in the ClassLoaderInfo instances returned.
*/
Collection<ClassLoaderInfo> listClassLoaders();
String discoveryName();
}
| mit |
GlowstonePlusPlus/GlowstonePlusPlus | src/main/java/net/glowstone/entity/monster/GlowVindicator.java | 860 | package net.glowstone.entity.monster;
import org.bukkit.Location;
import org.bukkit.Sound;
import org.bukkit.entity.EntityType;
import org.bukkit.entity.Vindicator;
public class GlowVindicator extends GlowIllager implements Vindicator {
private boolean johnny;
public GlowVindicator(Location loc) {
super(loc, EntityType.VINDICATOR, 24);
setBoundingBox(0.5, 0.8);
}
public boolean isJohnny() {
return johnny;
}
public void setJohnny(boolean johnny) {
this.johnny = johnny;
}
@Override
protected Sound getHurtSound() {
return Sound.ENTITY_VINDICATOR_HURT;
}
@Override
protected Sound getDeathSound() {
return Sound.ENTITY_VINDICATOR_DEATH;
}
@Override
protected Sound getAmbientSound() {
return Sound.ENTITY_VINDICATOR_AMBIENT;
}
}
| mit |
AnthonyHullDiamond/scanning | org.eclipse.scanning.api/src/org/eclipse/scanning/api/event/status/Status.java | 1793 | /*-
*******************************************************************************
* 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.api.event.status;
/**
* States of jobs on the cluster.
*
* @author Matthew Gerring
*
*/
public enum Status { // TODO Should this be called QueueStatus or JobStatus to avoid confusion?
SUBMITTED, QUEUED, RUNNING, REQUEST_PAUSE, PAUSED, REQUEST_RESUME, RESUMED, REQUEST_TERMINATE, TERMINATED, FAILED, COMPLETE, UNFINISHED, NONE;
/**
*
* @return true if the run was taken from the queue and something was actually executed on it.
*/
public boolean isStarted() {
return this!=SUBMITTED;
}
public boolean isFinal() {
return this==TERMINATED || this==FAILED || this==COMPLETE || this==UNFINISHED || this==NONE;
}
public boolean isRunning() {
return this==RUNNING || this==RESUMED;
}
public boolean isRequest() {
return toString().startsWith("REQUEST_");
}
public boolean isPaused() {
return this==REQUEST_PAUSE || this==PAUSED;
}
public boolean isResumed() {
return this==REQUEST_RESUME || this==RESUMED;
}
/**
* Being actively run, including pause.
* @return
*/
public boolean isActive() {
return (isRunning() || isPaused()) && !isFinal();
}
public boolean isTerminated() {
return this==REQUEST_TERMINATE || this==TERMINATED;
}
}
| epl-1.0 |
openhab/openhab | bundles/binding/org.openhab.binding.zwave/src/main/java/org/openhab/binding/zwave/internal/protocol/ZWaveController.java | 71347 | /**
* Copyright (c) 2010-2020 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.zwave.internal.protocol;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Timer;
import java.util.TimerTask;
import java.util.TooManyListenersException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.PriorityBlockingQueue;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.openhab.binding.zwave.internal.protocol.SerialMessage.SerialMessageClass;
import org.openhab.binding.zwave.internal.protocol.SerialMessage.SerialMessagePriority;
import org.openhab.binding.zwave.internal.protocol.SerialMessage.SerialMessageType;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClass.CommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveCommandClassDynamicState;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveMultiInstanceCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveSecurityCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveSwitchAllCommandClass;
import org.openhab.binding.zwave.internal.protocol.commandclass.ZWaveWakeUpCommandClass;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveEvent;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveInclusionEvent;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveNetworkEvent;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveNodeStatusEvent;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveTransactionCompletedEvent;
import org.openhab.binding.zwave.internal.protocol.initialization.ZWaveNodeSerializer;
import org.openhab.binding.zwave.internal.protocol.serialmessage.AddNodeMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.AssignReturnRouteMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.AssignSucReturnRouteMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.ControllerSetDefaultMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.DeleteReturnRouteMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.EnableSucMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.GetControllerCapabilitiesMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.GetRoutingInfoMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.GetSucNodeIdMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.GetVersionMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.IdentifyNodeMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.IsFailedNodeMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.MemoryGetIdMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.RemoveFailedNodeMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.RemoveNodeMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.RequestNodeInfoMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.RequestNodeNeighborUpdateMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.SendDataMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.SerialApiGetCapabilitiesMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.SerialApiGetInitDataMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.SerialApiSetTimeoutsMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.SerialApiSoftResetMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.SetSucNodeMessageClass;
import org.openhab.binding.zwave.internal.protocol.serialmessage.ZWaveCommandProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
/**
* ZWave controller class. Implements communication with the Z-Wave
* controller stick using serial messages.
*
* @author Victor Belov
* @author Brian Crosby
* @author Chris Jackson
* @since 1.3.0
*/
public class ZWaveController {
private static final Logger logger = LoggerFactory.getLogger(ZWaveController.class);
private static final int ZWAVE_RESPONSE_TIMEOUT = 5000; // 5000 ms ZWAVE_RESPONSE TIMEOUT
private static final int ZWAVE_RECEIVE_TIMEOUT = 1000; // 1000 ms ZWAVE_RECEIVE_TIMEOUT
private static final int INITIAL_TX_QUEUE_SIZE = 128;
private static final int INITIAL_RX_QUEUE_SIZE = 8;
private static final long WATCHDOG_TIMER_PERIOD = 10000; // 10 seconds watchdog timer
public static final int TRANSMIT_OPTION_ACK = 0x01;
public static final int TRANSMIT_OPTION_AUTO_ROUTE = 0x04;
private static final int TRANSMIT_OPTION_EXPLORE = 0x20;
private final ConcurrentHashMap<Integer, ZWaveNode> zwaveNodes = new ConcurrentHashMap<Integer, ZWaveNode>();
private final ArrayList<ZWaveEventListener> zwaveEventListeners = new ArrayList<ZWaveEventListener>();
private final PriorityBlockingQueue<SerialMessage> sendQueue = new PriorityBlockingQueue<SerialMessage>(
INITIAL_TX_QUEUE_SIZE, new SerialMessage.SerialMessageComparator(this));
private final PriorityBlockingQueue<SerialMessage> recvQueue = new PriorityBlockingQueue<SerialMessage>(
INITIAL_RX_QUEUE_SIZE, new SerialMessage.SerialMessageComparator(this));
private ZWaveSendThread sendThread;
private ZWaveReceiveThread receiveThread;
private ZWaveInputThread inputThread;
private final Semaphore sendAllowed = new Semaphore(1);
private final Semaphore transactionCompleted = new Semaphore(1);
private volatile SerialMessage lastSentMessage = null;
private long lastMessageStartTime = 0;
private long longestResponseTime = 0;
private SerialPort serialPort;
private int zWaveResponseTimeout = ZWAVE_RESPONSE_TIMEOUT;
private Timer watchdog;
private String zWaveVersion = "Unknown";
private String serialAPIVersion = "Unknown";
private int homeId = 0;
private int ownNodeId = 0;
private int manufactureId = 0;
private int deviceType = 0;
private int deviceId = 0;
private int ZWaveLibraryType = 0;
private int sentDataPointer = 1;
private boolean setSUC = false;
private ZWaveDeviceType controllerType = ZWaveDeviceType.UNKNOWN;
private int sucID = 0;
private boolean softReset = false;
private boolean masterController = false;
private int SOFCount = 0;
private int CANCount = 0;
private int NAKCount = 0;
private int ACKCount = 0;
private int OOFCount = 0;
private AtomicInteger timeOutCount = new AtomicInteger(0);
private boolean isConnected;
/**
* This is required for secure pairing. see {@link ZWaveSecurityCommandClass}
*/
private ZWaveInclusionEvent lastIncludeSlaveFoundEvent;
// Constructors
/**
* Constructor. Creates a new instance of the Z-Wave controller class.
*
* @param serialPortName the serial port name to use for
* communication with the Z-Wave controller stick.
* @throws SerialInterfaceException when a connection error occurs.
*/
public ZWaveController(final boolean masterController, final boolean isSUC, final String serialPortName,
final Integer timeout, final boolean reset) throws SerialInterfaceException {
logger.info("Starting Z-Wave controller");
this.masterController = masterController;
this.setSUC = isSUC;
this.softReset = reset;
if (timeout != null && timeout >= 1500 && timeout <= 10000) {
zWaveResponseTimeout = timeout;
}
logger.info("Z-Wave timeout is set to {}ms. Soft reset is {}.", zWaveResponseTimeout, reset);
connect(serialPortName);
this.watchdog = new Timer(true);
this.watchdog.schedule(new WatchDogTimerTask(serialPortName), WATCHDOG_TIMER_PERIOD, WATCHDOG_TIMER_PERIOD);
// We have a delay in running the initialisation sequence to allow any
// frames queued in the controller to be received before sending the init
// sequence. This avoids protocol errors (CAN errors).
Timer initTimer = new Timer();
initTimer.schedule(new InitializeDelayTask(), 3000);
}
private class InitializeDelayTask extends TimerTask {
private final Logger logger = LoggerFactory.getLogger(WatchDogTimerTask.class);
/**
* {@inheritDoc}
*/
@Override
public void run() {
logger.debug("Initialising network");
initialize();
}
}
// Incoming message handlers
/**
* Handles incoming Serial Messages. Serial messages can either be messages
* that are a response to our own requests, or the stick asking us information.
*
* @param incomingMessage the incoming message to process.
*/
private void handleIncomingMessage(SerialMessage incomingMessage) {
logger.debug(incomingMessage.toString());
switch (incomingMessage.getMessageType()) {
case Request:
handleIncomingRequestMessage(incomingMessage);
break;
case Response:
handleIncomingResponseMessage(incomingMessage);
break;
default:
logger.warn("Unsupported incomingMessageType: {}", incomingMessage.getMessageType());
}
}
/**
* Handles an incoming request message.
* An incoming request message is a message initiated by a node or the controller.
*
* @param incomingMessage the incoming message to process.
*/
private void handleIncomingRequestMessage(SerialMessage incomingMessage) {
logger.trace("Incoming Message type = REQUEST");
ZWaveCommandProcessor processor = ZWaveCommandProcessor.getMessageDispatcher(incomingMessage.getMessageClass());
if (processor == null) {
logger.warn(String.format("TODO: Implement processing of Request Message = %s (0x%02X)",
incomingMessage.getMessageClass().getLabel(), incomingMessage.getMessageClass().getKey()));
return;
}
boolean result = processor.handleRequest(this, lastSentMessage, incomingMessage);
if (processor.isTransactionComplete()) {
notifyEventListeners(new ZWaveTransactionCompletedEvent(this.lastSentMessage, result));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
}
/**
* Handles a failed SendData request. This can either be because of the stick actively reporting it
* or because of a time-out of the transaction in the send thread.
*
* @param originalMessage the original message that was sent
*/
private void handleFailedSendDataRequest(SerialMessage originalMessage) {
new SendDataMessageClass().handleFailedSendDataRequest(this, originalMessage);
}
/**
* Handles an incoming response message.
* An incoming response message is a response, based one of our own requests.
*
* @param incomingMessage the response message to process.
*/
private void handleIncomingResponseMessage(SerialMessage incomingMessage) {
logger.trace("Incoming Message type = RESPONSE");
ZWaveCommandProcessor processor = ZWaveCommandProcessor.getMessageDispatcher(incomingMessage.getMessageClass());
if (processor == null) {
logger.warn(String.format("TODO: Implement processing of Response Message = %s (0x%02X)",
incomingMessage.getMessageClass().getLabel(), incomingMessage.getMessageClass().getKey()));
return;
}
boolean result = processor.handleResponse(this, lastSentMessage, incomingMessage);
if (processor.isTransactionComplete()) {
notifyEventListeners(new ZWaveTransactionCompletedEvent(this.lastSentMessage, result));
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}", transactionCompleted.availablePermits());
}
switch (incomingMessage.getMessageClass()) {
case GetVersion:
this.zWaveVersion = ((GetVersionMessageClass) processor).getVersion();
this.ZWaveLibraryType = ((GetVersionMessageClass) processor).getLibraryType();
break;
case MemoryGetId:
this.ownNodeId = ((MemoryGetIdMessageClass) processor).getNodeId();
this.homeId = ((MemoryGetIdMessageClass) processor).getHomeId();
break;
case SerialApiGetInitData:
this.isConnected = true;
for (Integer nodeId : ((SerialApiGetInitDataMessageClass) processor).getNodes()) {
addNode(nodeId);
}
break;
case GetSucNodeId:
// Remember the SUC ID
this.sucID = ((GetSucNodeIdMessageClass) processor).getSucNodeId();
// If we want to be the SUC, enable it here
if (this.setSUC == true && this.sucID == 0) {
// We want to be SUC
this.enqueue(new EnableSucMessageClass().doRequest(EnableSucMessageClass.SUCType.SERVER));
this.enqueue(new SetSucNodeMessageClass().doRequest(this.ownNodeId,
SetSucNodeMessageClass.SUCType.SERVER));
} else if (this.setSUC == false && this.sucID == this.ownNodeId) {
// We don't want to be SUC, but we currently are!
// Disable SERVER functionality, and set the node to 0
this.enqueue(new EnableSucMessageClass().doRequest(EnableSucMessageClass.SUCType.NONE));
this.enqueue(new SetSucNodeMessageClass().doRequest(this.ownNodeId,
SetSucNodeMessageClass.SUCType.NONE));
}
this.enqueue(new GetControllerCapabilitiesMessageClass().doRequest());
break;
case SerialApiGetCapabilities:
this.serialAPIVersion = ((SerialApiGetCapabilitiesMessageClass) processor).getSerialAPIVersion();
this.manufactureId = ((SerialApiGetCapabilitiesMessageClass) processor).getManufactureId();
this.deviceId = ((SerialApiGetCapabilitiesMessageClass) processor).getDeviceId();
this.deviceType = ((SerialApiGetCapabilitiesMessageClass) processor).getDeviceType();
this.enqueue(new SerialApiGetInitDataMessageClass().doRequest());
break;
case GetControllerCapabilities:
this.controllerType = ((GetControllerCapabilitiesMessageClass) processor).getDeviceType();
break;
default:
break;
}
}
// Controller methods
/**
* Connects to the comm port and starts send and receive threads.
*
* @param serialPortName the port name to open
* @throws SerialInterfaceException when a connection error occurs.
*/
public void connect(final String serialPortName) throws SerialInterfaceException {
logger.info("Connecting to serial port {}", serialPortName);
try {
CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(serialPortName);
CommPort commPort = portIdentifier.open("org.openhab.binding.zwave", 2000);
this.serialPort = (SerialPort) commPort;
this.serialPort.setSerialPortParams(115200, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
this.serialPort.enableReceiveThreshold(1);
this.serialPort.enableReceiveTimeout(ZWAVE_RECEIVE_TIMEOUT);
this.receiveThread = new ZWaveReceiveThread();
this.receiveThread.start();
this.sendThread = new ZWaveSendThread();
this.sendThread.start();
this.inputThread = new ZWaveInputThread();
this.inputThread.start();
// RXTX serial port library causes high CPU load
// Start event listener, which will just sleep and slow down event loop
serialPort.addEventListener(this.receiveThread);
serialPort.notifyOnDataAvailable(true);
logger.info("Serial port is initialized");
} catch (NoSuchPortException e) {
logger.error("Serial Error: Port {} does not exist", serialPortName);
throw new SerialInterfaceException(String.format("Port %s does not exist", serialPortName), e);
} catch (PortInUseException e) {
logger.error("Serial Error: Port {} in use.", serialPortName);
throw new SerialInterfaceException(String.format("Port %s in use.", serialPortName), e);
} catch (UnsupportedCommOperationException e) {
logger.error("Serial Error: Unsupported comm operation on Port {}.", serialPortName);
throw new SerialInterfaceException(String.format("Unsupported comm operation on Port %s.", serialPortName),
e);
} catch (TooManyListenersException e) {
logger.error("Serial Error: Too many listeners on Port {}.", serialPortName);
e.printStackTrace();
}
}
/**
* Closes the connection to the Z-Wave controller.
*/
public void close() {
logger.debug("Stopping Z-Wave controller");
if (watchdog != null) {
watchdog.cancel();
watchdog = null;
}
disconnect();
// clear nodes collection and send queue
ArrayList<ZWaveEventListener> copy = new ArrayList<ZWaveEventListener>(this.zwaveEventListeners);
for (Object listener : copy.toArray()) {
if (!(listener instanceof ZWaveNode)) {
continue;
}
this.zwaveEventListeners.remove(listener);
}
this.zwaveNodes.clear();
this.sendQueue.clear();
this.recvQueue.clear();
logger.info("Stopped Z-Wave controller");
}
/**
* Disconnects from the serial interface and stops
* send and receive threads.
*/
public void disconnect() {
logger.debug("Disconnecting from serial port...");
if (sendThread != null) {
sendThread.interrupt();
try {
sendThread.join();
} catch (InterruptedException e) {
}
sendThread = null;
}
if (receiveThread != null) {
receiveThread.interrupt();
try {
receiveThread.join();
} catch (InterruptedException e) {
}
receiveThread = null;
}
if (inputThread != null) {
inputThread.interrupt();
try {
inputThread.join();
} catch (InterruptedException e) {
}
inputThread = null;
}
if (transactionCompleted.availablePermits() < 0) {
transactionCompleted.release(transactionCompleted.availablePermits());
}
transactionCompleted.drainPermits();
if (this.serialPort != null) {
this.serialPort.close();
this.serialPort = null;
}
logger.info("Disconnected from serial port");
}
/**
* Removes the node, and restarts the initialisation sequence
*
* @param nodeId
*/
public void reinitialiseNode(int nodeId) {
this.zwaveNodes.remove(nodeId);
addNode(nodeId);
}
/**
* Add a node to the controller
*
* @param nodeId the node number to add
*/
private void addNode(int nodeId) {
new ZWaveInitNodeThread(this, nodeId).start();
}
/**
* Send All On message to all devices that support the Switch All command class
*/
public void allOn() {
Enumeration<Integer> nodeIds = this.zwaveNodes.keys();
while (nodeIds.hasMoreElements()) {
Integer nodeId = nodeIds.nextElement();
ZWaveNode node = this.getNode(nodeId);
ZWaveSwitchAllCommandClass switchAllCommandClass = (ZWaveSwitchAllCommandClass) node
.getCommandClass(ZWaveCommandClass.CommandClass.SWITCH_ALL);
if (switchAllCommandClass != null) {
logger.debug("NODE {}: Supports Switch All Command Class Sending AllOn Message", nodeId);
switchAllCommandClass.setNode(node);
switchAllCommandClass.setController(this);
this.enqueue(switchAllCommandClass.allOnMessage());
continue;
}
}
}
/**
* Send All Off message to all devices that support the Switch All command class
*/
public void allOff() {
Enumeration<Integer> nodeIds = this.zwaveNodes.keys();
while (nodeIds.hasMoreElements()) {
Integer nodeId = nodeIds.nextElement();
ZWaveNode node = this.getNode(nodeId);
ZWaveSwitchAllCommandClass switchAllCommandClass = (ZWaveSwitchAllCommandClass) node
.getCommandClass(ZWaveCommandClass.CommandClass.SWITCH_ALL);
if (switchAllCommandClass != null) {
logger.debug("NODE {}: Supports Switch All Command Class Sending AllOff Message", nodeId);
switchAllCommandClass.setNode(node);
switchAllCommandClass.setController(this);
this.enqueue(switchAllCommandClass.allOffMessage());
continue;
}
}
}
private class ZWaveInitNodeThread extends Thread {
int nodeId;
ZWaveController controller;
ZWaveInitNodeThread(ZWaveController controller, int nodeId) {
this.nodeId = nodeId;
this.controller = controller;
}
@Override
public void run() {
logger.debug("NODE {}: Init node thread start", nodeId);
// Check if the node exists
if (zwaveNodes.get(nodeId) != null) {
logger.warn("NODE {}: Attempting to add node that already exists", nodeId);
return;
}
ZWaveNode node = null;
try {
ZWaveNodeSerializer nodeSerializer = new ZWaveNodeSerializer();
node = nodeSerializer.DeserializeNode(nodeId);
} catch (Exception e) {
logger.error("NODE {}: Restore from config: Error deserialising XML file. {}", nodeId, e.toString());
node = null;
}
String name = null;
String location = null;
// Did the node deserialise ok?
if (node != null) {
// Remember the name and location - in case we decide the file was invalid
name = node.getName();
location = node.getLocation();
// Sanity check the data from the file
if (node.getManufacturer() == Integer.MAX_VALUE || node.getHomeId() != controller.homeId
|| node.getNodeId() != nodeId) {
logger.warn("NODE {}: Restore from config: Error. Data invalid, ignoring config.", nodeId);
node = null;
} else {
// The restore was ok, but we have some work to set up the links that aren't
// made as the deserialiser doesn't call the constructor
logger.debug("NODE {}: Restore from config: Ok.", nodeId);
node.setRestoredFromConfigfile(controller);
// Set the controller and node references for all command classes
for (ZWaveCommandClass commandClass : node.getCommandClasses()) {
commandClass.setController(controller);
commandClass.setNode(node);
// Handle event handlers
if (commandClass instanceof ZWaveEventListener) {
controller.addEventListener((ZWaveEventListener) commandClass);
}
// If this is the multi-instance class, add all command classes for the endpoints
if (commandClass instanceof ZWaveMultiInstanceCommandClass) {
for (ZWaveEndpoint endPoint : ((ZWaveMultiInstanceCommandClass) commandClass)
.getEndpoints()) {
for (ZWaveCommandClass endpointCommandClass : endPoint.getCommandClasses()) {
endpointCommandClass.setController(controller);
endpointCommandClass.setNode(node);
endpointCommandClass.setEndpoint(endPoint);
// Handle event handlers
if (endpointCommandClass instanceof ZWaveEventListener) {
controller.addEventListener((ZWaveEventListener) endpointCommandClass);
}
}
}
}
}
}
}
// Create a new node if it wasn't deserialised ok
if (node == null) {
node = new ZWaveNode(controller.homeId, nodeId, controller);
// Try to maintain the name and location (user supplied data)
// even if the XML file was considered corrupt and we reload data from the device.
node.setName(name);
node.setLocation(location);
}
if (nodeId == controller.ownNodeId) {
// This is the controller node.
// We already know the device type, id, manufacturer so set it here
// It won't be set later as we probably won't request the manufacturer specific data
node.setDeviceId(controller.getDeviceId());
node.setDeviceType(controller.getDeviceType());
node.setManufacturer(controller.getManufactureId());
}
// Place nodes in the local ZWave Controller
controller.zwaveNodes.putIfAbsent(nodeId, node);
node.initialiseNode();
logger.debug("NODE {}: Init node thread finished", nodeId);
}
}
/**
* Enqueues a message for sending on the send queue.
*
* @param serialMessage the serial message to enqueue.
*/
public void enqueue(SerialMessage serialMessage) {
// Sanity check!
if (serialMessage == null) {
return;
}
// First try and get the node
// If we're sending to a node, then this obviously isn't to the controller, and we should
// queue anything to a battery node (ie a node supporting the WAKEUP class)!
ZWaveNode node = this.getNode(serialMessage.getMessageNode());
if (node != null) {
// Does this message need to be security encapsulated?
if (node.doesMessageRequireSecurityEncapsulation(serialMessage)) {
ZWaveSecurityCommandClass securityCommandClass = (ZWaveSecurityCommandClass) node
.getCommandClass(CommandClass.SECURITY);
securityCommandClass.queueMessageForEncapsulationAndTransmission(serialMessage);
// the above call will call enqueue again with the <b>encapsulated<b/> message,
// so we discard this one without putting it on the queue
return;
}
// Keep track of the number of packets sent to this device
node.incrementSendCount();
// If the device isn't listening, queue the message if it supports the wakeup class
if (!node.isListening() && !node.isFrequentlyListening()) {
ZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass) node
.getCommandClass(CommandClass.WAKE_UP);
// If it's a battery operated device, check if it's awake or place in wake-up queue.
if (wakeUpCommandClass != null && !wakeUpCommandClass.processOutgoingWakeupMessage(serialMessage)) {
return;
}
}
}
// Add the message to the queue
this.sendQueue.add(serialMessage);
if (logger.isTraceEnabled()) {
logger.debug("Enqueueing message. Queue length = {}, Queue = {}", this.sendQueue.size(), this.sendQueue);
} else {
logger.debug("Enqueueing message. Queue length = {}", this.sendQueue.size());
}
}
/**
* Returns the size of the send queue.
*/
public int getSendQueueLength() {
return this.sendQueue.size();
}
/**
* Notify our own event listeners of a Z-Wave event.
*
* @param event the event to send.
*/
public void notifyEventListeners(ZWaveEvent event) {
logger.debug("NODE {}: Notifying event listeners: {}", event.getNodeId(), event.getClass().getSimpleName());
ArrayList<ZWaveEventListener> copy = new ArrayList<ZWaveEventListener>(this.zwaveEventListeners);
for (ZWaveEventListener listener : copy) {
listener.ZWaveIncomingEvent(event);
}
// We also need to handle the inclusion internally within the controller
if (event instanceof ZWaveInclusionEvent) {
ZWaveInclusionEvent incEvent = (ZWaveInclusionEvent) event;
switch (incEvent.getEvent()) {
case IncludeSlaveFound: // TODO: DB any potential negative consequences by changing from IncludeDone to
// IncludeSlaveFound?
// Trigger by IncludeSlaveFound since security based devices need the initial exchange to take place
// immediately or they will time out
logger.debug("NODE {}: Including node.", incEvent.getNodeId());
// First make sure this isn't an existing node
if (getNode(incEvent.getNodeId()) != null) {
logger.debug("NODE {}: Newly included node already exists - not initialising.",
incEvent.getNodeId());
break;
}
this.lastIncludeSlaveFoundEvent = incEvent;
// Initialise the new node
addNode(incEvent.getNodeId());
break;
case ExcludeDone:
logger.debug("NODE {}: Excluding node.", incEvent.getNodeId());
// Remove the node from the controller
if (getNode(incEvent.getNodeId()) == null) {
logger.debug("NODE {}: Excluding node that doesn't exist.", incEvent.getNodeId());
break;
}
this.zwaveNodes.remove(incEvent.getNodeId());
// Remove the XML file
ZWaveNodeSerializer nodeSerializer = new ZWaveNodeSerializer();
nodeSerializer.DeleteNode(event.getNodeId());
break;
default:
break;
}
} else if (event instanceof ZWaveNetworkEvent) {
ZWaveNetworkEvent networkEvent = (ZWaveNetworkEvent) event;
switch (networkEvent.getEvent()) {
case DeleteNode:
if (getNode(networkEvent.getNodeId()) == null) {
logger.debug("NODE {}: Deleting a node that doesn't exist.", networkEvent.getNodeId());
break;
}
this.zwaveNodes.remove(networkEvent.getNodeId());
// Remove the XML file
ZWaveNodeSerializer nodeSerializer = new ZWaveNodeSerializer();
nodeSerializer.DeleteNode(event.getNodeId());
break;
default:
break;
}
} else if (event instanceof ZWaveNodeStatusEvent) {
ZWaveNodeStatusEvent statusEvent = (ZWaveNodeStatusEvent) event;
logger.debug("NODE {}: Node Status event - Node is {}", statusEvent.getNodeId(), statusEvent.getState());
// Get the node
ZWaveNode node = getNode(event.getNodeId());
if (node == null) {
logger.error("NODE {}: Node is unknown!", statusEvent.getNodeId());
return;
}
// Handle node state changes
switch (statusEvent.getState()) {
case DEAD:
break;
case FAILED:
break;
case ALIVE:
break;
}
}
}
/**
* Initializes communication with the Z-Wave controller stick.
*/
public void initialize() {
this.enqueue(new GetVersionMessageClass().doRequest());
this.enqueue(new MemoryGetIdMessageClass().doRequest());
this.enqueue(new SerialApiGetCapabilitiesMessageClass().doRequest());
this.enqueue(new SerialApiSetTimeoutsMessageClass().doRequest(150, 15));
this.enqueue(new GetSucNodeIdMessageClass().doRequest());
}
/**
* Send Identify Node message to the controller.
*
* @param nodeId the nodeId of the node to identify
*/
public void identifyNode(int nodeId) {
this.enqueue(new IdentifyNodeMessageClass().doRequest(nodeId));
}
/**
* Send Request Node info message to the controller.
*
* @param nodeId the nodeId of the node to identify
*/
public void requestNodeInfo(int nodeId) {
this.enqueue(new RequestNodeInfoMessageClass().doRequest(nodeId));
}
/**
* Polls a node for any dynamic information
*
* @param node
*/
public void pollNode(ZWaveNode node) {
for (ZWaveCommandClass zwaveCommandClass : node.getCommandClasses()) {
logger.trace("NODE {}: Inspecting command class {}", node.getNodeId(),
zwaveCommandClass.getCommandClass().getLabel());
if (zwaveCommandClass instanceof ZWaveCommandClassDynamicState) {
logger.debug("NODE {}: Found dynamic state command class {}", node.getNodeId(),
zwaveCommandClass.getCommandClass().getLabel());
ZWaveCommandClassDynamicState zdds = (ZWaveCommandClassDynamicState) zwaveCommandClass;
int instances = zwaveCommandClass.getInstances();
if (instances == 1) {
Collection<SerialMessage> dynamicQueries = zdds.getDynamicValues(true);
for (SerialMessage serialMessage : dynamicQueries) {
sendData(serialMessage);
}
} else {
for (int i = 1; i <= instances; i++) {
Collection<SerialMessage> dynamicQueries = zdds.getDynamicValues(true);
for (SerialMessage serialMessage : dynamicQueries) {
sendData(node.encapsulate(serialMessage, zwaveCommandClass, i));
}
}
}
} else if (zwaveCommandClass instanceof ZWaveMultiInstanceCommandClass) {
ZWaveMultiInstanceCommandClass multiInstanceCommandClass = (ZWaveMultiInstanceCommandClass) zwaveCommandClass;
for (ZWaveEndpoint endpoint : multiInstanceCommandClass.getEndpoints()) {
for (ZWaveCommandClass endpointCommandClass : endpoint.getCommandClasses()) {
logger.trace("NODE {}: Inspecting command class {} for endpoint {}", node.getNodeId(),
endpointCommandClass.getCommandClass().getLabel(), endpoint.getEndpointId());
if (endpointCommandClass instanceof ZWaveCommandClassDynamicState) {
logger.debug("NODE {}: Found dynamic state command class {}", node.getNodeId(),
endpointCommandClass.getCommandClass().getLabel());
ZWaveCommandClassDynamicState zdds2 = (ZWaveCommandClassDynamicState) endpointCommandClass;
Collection<SerialMessage> dynamicQueries = zdds2.getDynamicValues(true);
for (SerialMessage serialMessage : dynamicQueries) {
sendData(node.encapsulate(serialMessage, endpointCommandClass,
endpoint.getEndpointId()));
}
}
}
}
}
}
}
/**
* Request the node routing information.
*
* @param nodeId The address of the node to update
*/
public void requestNodeRoutingInfo(int nodeId) {
this.enqueue(new GetRoutingInfoMessageClass().doRequest(nodeId));
}
/**
* Request the node neighbor list to be updated for the specified node.
* Once this is complete, the requestNodeRoutingInfo will be called
* automatically to update the data in the binding.
*
* @param nodeId The address of the node to update
*/
public void requestNodeNeighborUpdate(int nodeId) {
this.enqueue(new RequestNodeNeighborUpdateMessageClass().doRequest(nodeId));
}
/**
* Puts the controller into inclusion mode to add new nodes
*/
public void requestAddNodesStart() {
this.enqueue(new AddNodeMessageClass().doRequestStart(true));
logger.info("Starting inclusion mode");
}
/**
* Terminates the inclusion mode
*/
public void requestAddNodesStop() {
this.enqueue(new AddNodeMessageClass().doRequestStop());
logger.info("Ending inclusion mode");
}
/**
* Puts the controller into exclusion mode to remove new nodes
*/
public void requestRemoveNodesStart() {
this.enqueue(new RemoveNodeMessageClass().doRequestStart(true));
}
/**
* Terminates the exclusion mode
*/
public void requestRemoveNodesStop() {
this.enqueue(new RemoveNodeMessageClass().doRequestStop());
}
/**
* Sends a request to perform a soft reset on the controller.
* This will just reset the controller - probably similar to a power cycle.
* It doesn't reinitialise the network, or change the network configuration.
*
* NOTE: At least for some (most!) sticks, this doesn't return a response.
* Therefore, the number of retries is set to 1.
* NOTE: On some (most!) ZWave-Plus sticks, this can cause the stick to hang.
*/
public void requestSoftReset() {
logger.info("Performing soft reset on controller");
SerialMessage msg = new SerialApiSoftResetMessageClass().doRequest();
msg.attempts = 1;
this.enqueue(msg);
}
/**
* Sends a request to perform a hard reset on the controller.
* This will reset the controller to its default, resetting the network completely
*/
public void requestHardReset() {
logger.info("Performing hard reset on controller");
// Clear the queues
// If we're resetting, there's no point in queuing messages!
sendQueue.clear();
recvQueue.clear();
// Hard reset the stick - everything will be reset to factory default
SerialMessage msg = new ControllerSetDefaultMessageClass().doRequest();
msg.attempts = 1;
this.enqueue(msg);
// Clear all the nodes and we'll reinitialise
this.zwaveNodes.clear();
this.enqueue(new SerialApiGetInitDataMessageClass().doRequest());
}
/**
* Request if the node is currently marked as failed by the controller.
*
* @param nodeId The address of the node to check
*/
public void requestIsFailedNode(int nodeId) {
this.enqueue(new IsFailedNodeMessageClass().doRequest(nodeId));
}
/**
* Removes a failed node from the network.
* Note that this won't remove nodes that have not failed.
*
* @param nodeId The address of the node to remove
*/
public void requestRemoveFailedNode(int nodeId) {
this.enqueue(new RemoveFailedNodeMessageClass().doRequest(nodeId));
}
/**
* Delete all return nodes from the specified node. This should be performed
* before updating the routes
*
* @param nodeId
*/
public void requestDeleteAllReturnRoutes(int nodeId) {
this.enqueue(new DeleteReturnRouteMessageClass().doRequest(nodeId));
}
/**
* Request the controller to set the return route between two nodes
*
* @param nodeId
* Source node
* @param destinationId
* Destination node
*/
public void requestAssignReturnRoute(int nodeId, int destinationId) {
this.enqueue(new AssignReturnRouteMessageClass().doRequest(nodeId, destinationId, getCallbackId()));
}
/**
* Request the controller to set the return route from a node to the controller
*
* @param nodeId
* Source node
*/
public void requestAssignSucReturnRoute(int nodeId) {
this.enqueue(new AssignSucReturnRouteMessageClass().doRequest(nodeId, getCallbackId()));
}
/**
* Returns the next callback ID
*
* @return callback ID
*/
public int getCallbackId() {
if (++sentDataPointer > 0xFF) {
sentDataPointer = 1;
}
logger.debug("Callback ID = {}", sentDataPointer);
return sentDataPointer;
}
/**
* Transmits the SerialMessage to a single Z-Wave Node.
* Sets the transmission options as well.
*
* @param serialMessage the Serial message to send.
*/
public void sendData(SerialMessage serialMessage) {
if (serialMessage == null) {
logger.error("Null message for sendData");
return;
}
if (serialMessage.getMessageClass() != SerialMessageClass.SendData) {
logger.error(String.format("Invalid message class %s (0x%02X) for sendData",
serialMessage.getMessageClass().getLabel(), serialMessage.getMessageClass().getKey()));
return;
}
if (serialMessage.getMessageType() != SerialMessageType.Request) {
logger.error("Only request messages can be sent");
return;
}
// We need to wait on the ACK from the controller before completing the transaction.
// This is required in case the Application Message is received from the SendData ACK
serialMessage.setAckRequired();
// ZWaveSecurityCommandClass needs to set it's own transmit options. Only set them here if not already done
if (!serialMessage.areTransmitOptionsSet()) {
serialMessage
.setTransmitOptions(TRANSMIT_OPTION_ACK | TRANSMIT_OPTION_AUTO_ROUTE | TRANSMIT_OPTION_EXPLORE);
}
serialMessage.setCallbackId(getCallbackId());
this.enqueue(serialMessage);
}
/**
* Add a listener for Z-Wave events to this controller.
*
* @param eventListener the event listener to add.
*/
public void addEventListener(ZWaveEventListener eventListener) {
synchronized (this.zwaveEventListeners) {
this.zwaveEventListeners.add(eventListener);
}
}
/**
* Remove a listener for Z-Wave events to this controller.
*
* @param eventListener the event listener to remove.
*/
public void removeEventListener(ZWaveEventListener eventListener) {
synchronized (this.zwaveEventListeners) {
this.zwaveEventListeners.remove(eventListener);
}
}
/**
* Gets the API Version of the controller.
*
* @return the serialAPIVersion
*/
public String getSerialAPIVersion() {
return serialAPIVersion;
}
/**
* Gets the zWave Version of the controller.
*
* @return the zWaveVersion
*/
public String getZWaveVersion() {
return zWaveVersion;
}
/**
* Gets the Manufacturer ID of the controller.
*
* @return the manufactureId
*/
public int getManufactureId() {
return manufactureId;
}
/**
* Gets the device type of the controller;
*
* @return the deviceType
*/
public int getDeviceType() {
return deviceType;
}
/**
* Gets the device ID of the controller.
*
* @return the deviceId
*/
public int getDeviceId() {
return deviceId;
}
/**
* Gets the node ID of the controller.
*
* @return the deviceId
*/
public int getOwnNodeId() {
return ownNodeId;
}
/**
* Gets the device type of the controller.
*
* @return the device type
*/
public ZWaveDeviceType getControllerType() {
return controllerType;
}
/**
* Gets the networks SUC controller ID.
*
* @return the device id of the SUC, or 0 if none exists
*/
public int getSucId() {
return sucID;
}
/**
* Returns true if the binding is the master controller in the network.
* The master controller simply means that we get notifications.
*
* @return true if this is the master
*/
public boolean isMasterController() {
return masterController;
}
/**
* Gets the node object using it's node ID as key.
* Returns null if the node is not found
*
* @param nodeId the Node ID of the node to get.
* @return node object
*/
public ZWaveNode getNode(int nodeId) {
return this.zwaveNodes.get(nodeId);
}
/**
* Gets the node list
*
* @return
*/
public Collection<ZWaveNode> getNodes() {
return this.zwaveNodes.values();
}
/**
* Indicates a working connection to the
* Z-Wave controller stick and initialization complete
*
* @return isConnected;
*/
public boolean isConnected() {
return isConnected; // && initializationComplete;
}
/**
* Gets the number of Start Of Frames received.
*
* @return the sOFCount
*/
public int getSOFCount() {
return SOFCount;
}
/**
* Gets the number of Canceled Frames received.
*
* @return the cANCount
*/
public int getCANCount() {
return CANCount;
}
/**
* Gets the number of Not Acknowledged Frames received.
*
* @return the nAKCount
*/
public int getNAKCount() {
return NAKCount;
}
/**
* Gets the number of Acknowledged Frames received.
*
* @return the aCKCount
*/
public int getACKCount() {
return ACKCount;
}
/**
* Returns the number of Out of Order frames received.
*
* @return the OOFCount
*/
public int getOOFCount() {
return OOFCount;
}
/**
* Returns the number of Time-Outs while sending.
*
* @return the timeoutCount
*/
public int getTimeOutCount() {
return timeOutCount.get();
}
/**
* This is required by {@link ZWaveSecurityCommandClass} for the secure pairing process.
* {@link ZWaveSecurityCommandClass} can't use the event handling because the
* object won't exist when this occurs, so we hold it here so {@link ZWaveSecurityCommandClass}
* can access it
*
* @return
*/
public ZWaveInclusionEvent getLastIncludeSlaveFoundEvent() {
return lastIncludeSlaveFoundEvent;
}
// Nested classes and enumerations
/**
* Input thread. This processes incoming messages - it decouples the receive thread,
* which responds to messages from the controller, and the actual processing of messages
* to ensure we respond to the controller in a timely manner
*
* @author Chris Jackson
*/
private class ZWaveInputThread extends Thread {
private ZWaveInputThread() {
super("ZWaveInputThread");
}
/**
* Run method. Runs the actual receiving process.
*/
@Override
public void run() {
logger.debug("Starting Z-Wave thread: Input");
SerialMessage recvMessage;
while (!interrupted()) {
try {
if (recvQueue.size() == 0) {
sendAllowed.release();
}
recvMessage = recvQueue.take();
logger.debug("Receive queue TAKE: Length={}", recvQueue.size());
logger.debug("Process Message = {}", SerialMessage.bb2hex(recvMessage.getMessageBuffer()));
handleIncomingMessage(recvMessage);
sendAllowed.tryAcquire();
} catch (InterruptedException e) {
break;
} catch (Exception e) {
logger.error("Exception during Z-Wave thread: Input.", e);
}
}
logger.debug("Stopped Z-Wave thread: Input");
}
}
/**
* Z-Wave controller Send Thread. Takes care of sending all messages.
* It uses a semaphore to synchronize communication with the receiving thread.
*
* @author Jan-Willem Spuij
* @author Chris Jackson
* @since 1.3.0
*/
private class ZWaveSendThread extends Thread {
private final Logger logger = LoggerFactory.getLogger(ZWaveSendThread.class);
private ZWaveSendThread() {
super("ZWaveSendThread");
}
/**
* Run method. Runs the actual sending process.
*/
@Override
public void run() {
logger.debug("Starting Z-Wave thread: Send");
try {
while (!interrupted()) {
// To avoid sending lots of frames when we still have input frames to
// process, we wait here until we've processed all receive frames
if (!sendAllowed.tryAcquire(1, zWaveResponseTimeout, TimeUnit.MILLISECONDS)) {
logger.warn("Receive queue TIMEOUT:", recvQueue.size());
continue;
}
sendAllowed.release();
// Take the next message from the send queue
try {
lastSentMessage = sendQueue.take();
logger.debug("Took message from queue for sending. Queue length = {}", sendQueue.size());
} catch (InterruptedException e1) {
logger.error("InterruptedException during Z-Wave thread: sendQueue.take {}", e1);
break;
}
// Check we got a message
if (lastSentMessage == null) {
continue;
}
// Get the node for this message
ZWaveNode node = getNode(lastSentMessage.getMessageNode());
// If it's a battery device, it needs to be awake, or we queue the frame until it is.
if (node != null && !node.isListening() && !node.isFrequentlyListening()) {
ZWaveWakeUpCommandClass wakeUpCommandClass = (ZWaveWakeUpCommandClass) node
.getCommandClass(CommandClass.WAKE_UP);
// If it's a battery operated device, check if it's awake or place in wake-up queue.
if (wakeUpCommandClass != null
&& !wakeUpCommandClass.processOutgoingWakeupMessage(lastSentMessage)) {
continue;
}
}
// A transaction consists of (up to) 4 parts -:
// 1) We send a REQUEST to the controller.
// 2) The controller sends a RESPONSE almost immediately.
// This RESPONSE typically tells us that the message was,
// or wasn't, added to the sticks queue.
// 3) The controller sends a REQUEST once it's received
// the response from the device.
// We need to be aware that there is no synchronization of
// messages between steps 2 and 3 so we can get other messages
// received at step 3 that are not related to our original
// request.
// 4) We ultimately receive the requested message from the device
// if we're requesting such a message.
//
// A transaction is generally completed at the completion of step 4.
// However, for some messages, there may not be a further REQUEST
// so the transaction is terminated at step 2. This is handled
// by the serial message class processor by setting
// transactionCompleted.
//
// It seems that some of these steps may occur out of order. For
// example, the requested message at step 4 may be received before
// the REQUEST at step 3. This can (I guess) occur if the message to
// the device is received by the device, but the ACK back to the controller
// is lost. The device then sends the requested data, and then finally
// the ACK is received.
// We cover this by setting an 'AckPending' flag in the sent message.
// This needs to be cleared before the transacion is completed.
// Clear the semaphore used to acknowledge the completed transaction.
transactionCompleted.drainPermits();
// Send the REQUEST message TO the controller
byte[] buffer = lastSentMessage.getMessageBuffer();
logger.debug("NODE {}: Sending REQUEST Message = {}", lastSentMessage.getMessageNode(),
SerialMessage.bb2hex(buffer));
lastMessageStartTime = System.currentTimeMillis();
try {
synchronized (serialPort.getOutputStream()) {
serialPort.getOutputStream().write(buffer);
serialPort.getOutputStream().flush();
logger.trace("Message SENT");
}
} catch (IOException e) {
logger.error("Got I/O exception {} during sending. exiting thread.", e.getLocalizedMessage());
break;
}
if (lastSentMessage instanceof SecurityEncapsulatedSerialMessage) {
// now that we've sent the encapsulated version, replace lastSentMessage with the original
// this is required because a resend requires a new nonce to be requested and a new
// security encapsulated message to be built
((SecurityEncapsulatedSerialMessage) lastSentMessage).setTransmittedAt();
// Take the callbackid from the encapsulated version and copy it to the original message
int callbackId = lastSentMessage.getCallbackId();
lastSentMessage = ((SecurityEncapsulatedSerialMessage) lastSentMessage)
.getMessageBeingEncapsulated();
lastSentMessage.setCallbackId(callbackId);
}
// Now wait for the RESPONSE, or REQUEST message FROM the controller
// This will terminate when the transactionCompleted flag gets set
// So, this might complete on a RESPONSE if there's an error (or no further REQUEST expected)
// or it might complete on a subsequent REQUEST.
try {
if (!transactionCompleted.tryAcquire(1, zWaveResponseTimeout, TimeUnit.MILLISECONDS)) {
timeOutCount.incrementAndGet();
// If this is a SendData message, then we need to abort
// This should only be sent if we didn't get the initial ACK!!!
// So we need to check the ACK flag and only abort if it's not set
if (lastSentMessage.getMessageClass() == SerialMessageClass.SendData
&& lastSentMessage.isAckPending()) {
buffer = new SerialMessage(SerialMessageClass.SendDataAbort, SerialMessageType.Request,
SerialMessageClass.SendData, SerialMessagePriority.Immediate)
.getMessageBuffer();
logger.debug("NODE {}: Sending ABORT Message = {}", lastSentMessage.getMessageNode(),
SerialMessage.bb2hex(buffer));
try {
synchronized (serialPort.getOutputStream()) {
serialPort.getOutputStream().write(buffer);
serialPort.getOutputStream().flush();
}
} catch (IOException e) {
logger.error("Got I/O exception {} during sending. exiting thread.",
e.getLocalizedMessage());
break;
}
}
// Check if we've exceeded the number of retries.
// Requeue if we're ok, otherwise discard the message
if (--lastSentMessage.attempts >= 0) {
logger.error("NODE {}: Timeout while sending message. Requeueing - {} attempts left!",
lastSentMessage.getMessageNode(), lastSentMessage.attempts);
if (lastSentMessage.getMessageClass() == SerialMessageClass.SendData) {
handleFailedSendDataRequest(lastSentMessage);
} else {
enqueue(lastSentMessage);
}
} else {
logger.warn("NODE {}: Too many retries. Discarding message: {}",
lastSentMessage.getMessageNode(), lastSentMessage.toString());
}
continue;
}
long responseTime = System.currentTimeMillis() - lastMessageStartTime;
if (responseTime > longestResponseTime) {
longestResponseTime = responseTime;
}
logger.debug("NODE {}: Response processed for callback id {} after {}ms/{}ms.",
lastSentMessage.getMessageNode(), lastSentMessage.getCallbackId(), responseTime,
longestResponseTime);
logger.trace("Acquired. Transaction completed permit count -> {}",
transactionCompleted.availablePermits());
} catch (InterruptedException e) {
logger.error("InterruptedException during Z-Wave thread: tryAcquire", e);
break;
}
}
} catch (Exception e) {
logger.error("Exception during Z-Wave thread: Send", e);
}
logger.debug("Stopped Z-Wave thread: Send");
}
}
/**
* Z-Wave controller Receive Thread. Takes care of receiving all messages.
* It uses a semaphore to synchronize communication with the sending thread.
*
* @author Jan-Willem Spuij
* @since 1.3.0
*/
private class ZWaveReceiveThread extends Thread implements SerialPortEventListener {
private static final int SOF = 0x01;
private static final int ACK = 0x06;
private static final int NAK = 0x15;
private static final int CAN = 0x18;
private final Logger logger = LoggerFactory.getLogger(ZWaveReceiveThread.class);
private ZWaveReceiveThread() {
super("ZWaveReceiveThread");
}
@Override
public void serialEvent(SerialPortEvent arg0) {
try {
logger.trace("RXTX library CPU load workaround, sleep forever");
Thread.sleep(Long.MAX_VALUE);
} catch (InterruptedException e) {
}
}
/**
* Sends 1 byte frame response.
*
* @param response the response code to send.
*/
private void sendResponse(int response) {
try {
synchronized (serialPort.getOutputStream()) {
serialPort.getOutputStream().write(response);
serialPort.getOutputStream().flush();
logger.trace("Response SENT");
}
} catch (IOException e) {
logger.error(e.getMessage());
}
}
/**
* Processes incoming message and notifies event handlers.
*
* @param buffer the buffer to process.
* @throws InterruptedException
*/
private void processIncomingMessage(byte[] buffer) throws InterruptedException {
SerialMessage recvMessage = new SerialMessage(buffer);
if (recvMessage.isValid) {
logger.trace("Message is valid, sending ACK");
sendResponse(ACK);
} else {
logger.error("Message is not valid, discarding");
sendResponse(NAK);
// The semaphore is acquired when we start the receive.
// We need to release it now...
if (recvQueue.size() == 0) {
sendAllowed.release();
}
return;
}
recvQueue.add(recvMessage);
logger.debug("Receive queue ADD: Length={}", recvQueue.size());
}
/**
* Run method. Runs the actual receiving process.
*/
@Override
public void run() {
logger.debug("Starting Z-Wave thread: Receive");
try {
// Send a NAK to resynchronise communications
sendResponse(NAK);
// If we want to do a soft reset on the serial interfaces, do it here.
// It seems there's no response to this message, so sending it through
// 'normal' channels will cause a timeout.
if (softReset == true) {
try {
synchronized (serialPort.getOutputStream()) {
SerialMessage resetMsg = new SerialApiSoftResetMessageClass().doRequest();
byte[] buffer = resetMsg.getMessageBuffer();
serialPort.getOutputStream().write(buffer);
serialPort.getOutputStream().flush();
}
} catch (IOException e) {
logger.error("Error sending soft reset on initialisation: {}", e.getMessage());
}
}
while (!interrupted()) {
int nextByte;
try {
nextByte = serialPort.getInputStream().read();
if (nextByte == -1) {
continue;
}
} catch (IOException e) {
logger.error("Got I/O exception {} during receiving. exiting thread.", e.getLocalizedMessage());
break;
}
switch (nextByte) {
case SOF:
// Use the sendAllowed semaphore to signal that the receive queue is not empty!
try {
sendAllowed.acquire();
} catch (InterruptedException e) {
logger.debug("Interrupted waiting for 'sendAllowed.acquire'.");
// break;
}
SOFCount++;
int messageLength;
try {
messageLength = serialPort.getInputStream().read();
} catch (IOException e) {
logger.error("Got I/O exception {} during receiving. exiting thread.",
e.getLocalizedMessage());
sendAllowed.release();
break;
}
byte[] buffer = new byte[messageLength + 2];
buffer[0] = SOF;
buffer[1] = (byte) messageLength;
int total = 0;
while (total < messageLength) {
try {
int read = serialPort.getInputStream().read(buffer, total + 2,
messageLength - total);
total += (read > 0 ? read : 0);
} catch (IOException e) {
logger.error("Got I/O exception {} during receiving. exiting thread.",
e.getLocalizedMessage());
return;
}
}
logger.debug("Receive Message = {}", SerialMessage.bb2hex(buffer));
processIncomingMessage(buffer);
break;
case ACK:
ACKCount++;
logger.trace("Received ACK");
break;
case NAK:
NAKCount++;
logger.error("Protocol error (NAK), discarding");
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}",
transactionCompleted.availablePermits());
break;
case CAN:
CANCount++;
logger.error("Protocol error (CAN), resending");
try {
Thread.sleep(100);
} catch (InterruptedException e) {
break;
}
enqueue(lastSentMessage);
transactionCompleted.release();
logger.trace("Released. Transaction completed permit count -> {}",
transactionCompleted.availablePermits());
break;
default:
OOFCount++;
logger.warn(String.format("Protocol error (OOF). Got 0x%02X. Sending NAK.", nextByte));
sendResponse(NAK);
break;
}
}
} catch (Exception e) {
logger.error("Exception during Z-Wave thread: Receive", e);
}
logger.debug("Stopped Z-Wave thread: Receive");
serialPort.removeEventListener();
}
}
/**
* WatchDogTimerTask class. Acts as a watch dog and
* checks the serial threads to see whether they are
* still running.
*
* @author Jan-Willem Spuij
* @since 1.3.0
*/
private class WatchDogTimerTask extends TimerTask {
private final Logger logger = LoggerFactory.getLogger(WatchDogTimerTask.class);
private final String serialPortName;
/**
* Creates a new instance of the WatchDogTimerTask class.
*
* @param serialPortName the serial port name to reconnect to
* in case the serial threads have died.
*/
public WatchDogTimerTask(String serialPortName) {
this.serialPortName = serialPortName;
}
/**
* {@inheritDoc}
*/
@Override
public void run() {
logger.trace("Watchdog: Checking Serial threads");
if ((receiveThread != null && !receiveThread.isAlive()) || (sendThread != null && !sendThread.isAlive())
|| (inputThread != null && !inputThread.isAlive())) {
logger.warn("Threads not alive, respawning");
disconnect();
try {
connect(serialPortName);
} catch (SerialInterfaceException e) {
logger.error("Unable to restart Serial threads: {}", e.getLocalizedMessage());
}
}
}
}
}
| epl-1.0 |
522986491/yangtools | yang/yang-model-util/src/test/java/org/opendaylight/yangtools/yang/model/util/SchemaContextUtilTest.java | 2344 | /*
* Copyright (c) 2014 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.yangtools.yang.model.util;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.opendaylight.yangtools.yang.common.QName;
import org.opendaylight.yangtools.yang.model.api.SchemaContext;
import org.opendaylight.yangtools.yang.model.api.Module;
import org.opendaylight.yangtools.yang.model.api.SchemaPath;
import org.opendaylight.yangtools.yang.model.api.RevisionAwareXPath;
import org.opendaylight.yangtools.yang.model.api.SchemaNode;
import java.util.Collections;
import static org.junit.Assert.assertEquals;
public class SchemaContextUtilTest {
@Mock private SchemaContext mockSchemaContext;
@Mock private Module mockModule;
@Test
public void testFindDummyData() {
MockitoAnnotations.initMocks(this);
QName qName = QName.create("TestQName");
SchemaPath schemaPath = SchemaPath.create(Collections.singletonList(qName), true);
assertEquals("Should be null. Module TestQName not found", null,
SchemaContextUtil.findDataSchemaNode(mockSchemaContext, schemaPath));
RevisionAwareXPath xPath = new RevisionAwareXPathImpl("/bookstore/book/title", true);
assertEquals("Should be null. Module bookstore not found", null,
SchemaContextUtil.findDataSchemaNode(mockSchemaContext, mockModule, xPath));
SchemaNode schemaNode = Int32.getInstance();
RevisionAwareXPath xPathRelative = new RevisionAwareXPathImpl("../prefix", false);
assertEquals("Should be null, Module prefix not found", null,
SchemaContextUtil.findDataSchemaNodeForRelativeXPath(
mockSchemaContext, mockModule, schemaNode, xPathRelative));
assertEquals("Should be null. Module TestQName not found", null,
SchemaContextUtil.findNodeInSchemaContext(mockSchemaContext, Collections.singleton(qName)));
assertEquals("Should be null.", null, SchemaContextUtil.findParentModule(mockSchemaContext, schemaNode));
}
} | epl-1.0 |
Panthro/che-plugins | plugin-java/che-plugin-java-ext-java/src/main/java/org/eclipse/che/ide/ext/java/client/project/node/PackageNode.java | 7512 | /*******************************************************************************
* Copyright (c) 2012-2015 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.ext.java.client.project.node;
import com.google.inject.Inject;
import com.google.inject.assistedinject.Assisted;
import com.google.web.bindery.event.shared.EventBus;
import org.eclipse.che.api.project.shared.dto.ItemReference;
import org.eclipse.che.api.project.shared.dto.ProjectDescriptor;
import org.eclipse.che.api.promises.client.Function;
import org.eclipse.che.api.promises.client.FunctionException;
import org.eclipse.che.api.promises.client.Promise;
import org.eclipse.che.api.promises.client.callback.AsyncPromiseHelper;
import org.eclipse.che.api.promises.client.js.Promises;
import org.eclipse.che.ide.api.project.node.HasStorablePath;
import org.eclipse.che.ide.api.project.node.Node;
import org.eclipse.che.ide.ext.java.client.project.settings.JavaNodeSettings;
import org.eclipse.che.ide.project.node.FolderReferenceNode;
import org.eclipse.che.ide.project.node.ItemReferenceChainFilter;
import org.eclipse.che.ide.project.node.resource.ItemReferenceProcessor;
import org.eclipse.che.ide.ui.smartTree.presentation.NodePresentation;
import org.eclipse.che.ide.util.loging.Log;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* @author Vlad Zhukovskiy
*/
public class PackageNode extends FolderReferenceNode {
private final JavaNodeManager nodeManager;
@Inject
public PackageNode(@Assisted ItemReference itemReference,
@Assisted ProjectDescriptor projectDescriptor,
@Assisted JavaNodeSettings nodeSettings,
@Nonnull EventBus eventBus,
@Nonnull JavaNodeManager nodeManager,
@Nonnull ItemReferenceProcessor resourceProcessor) {
super(itemReference, projectDescriptor, nodeSettings, eventBus, nodeManager, resourceProcessor);
this.nodeManager = nodeManager;
}
@Nonnull
@Override
protected Promise<List<Node>> getChildrenImpl() {
return nodeManager.getChildren(getData(),
getProjectDescriptor(),
getSettings(),
emptyMiddlePackageFilter());
}
private ItemReferenceChainFilter emptyMiddlePackageFilter() {
return new ItemReferenceChainFilter() {
@Override
public Promise<List<ItemReference>> process(List<ItemReference> referenceList) {
if (referenceList.isEmpty() || referenceList.size() > 1) {
//if children in directory more than one
final List<ItemReference> files = new ArrayList<>();
List<ItemReference> otherNodes = new ArrayList<>();
//filter folders to proceed deep child
for (ItemReference itemReference : referenceList) {
if ("file".equals(itemReference.getType())) {
files.add(itemReference);
} else {
otherNodes.add(itemReference);
}
}
if (!otherNodes.isEmpty()) {
if (otherNodes.size() == 1) {
return foundFirstNonEmpty(otherNodes.get(0)).thenPromise(new Function<List<ItemReference>, Promise<List<ItemReference>>>() {
@Override
public Promise<List<ItemReference>> apply(List<ItemReference> arg) throws FunctionException {
arg.addAll(files);
return Promises.resolve(arg);
}
});
}
}
return Promises.resolve(referenceList);
}
//else we have one child. check if it file
if ("file".equals(referenceList.get(0).getType())) {
return Promises.resolve(referenceList);
}
//so start check if we have single folder, just seek all children to find non empty directory
return foundFirstNonEmpty(referenceList.get(0));
}
};
}
private Promise<List<ItemReference>> foundFirstNonEmpty(ItemReference parent) {
return AsyncPromiseHelper.createFromAsyncRequest(nodeManager.getItemReferenceRC(parent.getPath()))
.thenPromise(checkForEmptiness(parent));
}
private Function<List<ItemReference>, Promise<List<ItemReference>>> checkForEmptiness(final ItemReference parent) {
return new Function<List<ItemReference>, Promise<List<ItemReference>>>() {
@Override
public Promise<List<ItemReference>> apply(List<ItemReference> children) throws FunctionException {
if (children.isEmpty() || children.size() > 1) {
List<ItemReference> list = new ArrayList<>();
list.add(parent);
return Promises.resolve(list);
}
if ("file".equals(children.get(0).getType())) {
List<ItemReference> list = new ArrayList<>();
list.add(parent);
return Promises.resolve(list);
} else {
return foundFirstNonEmpty(children.get(0));
}
}
};
}
@Override
public void updatePresentation(@Nonnull NodePresentation presentation) {
presentation.setPresentableText(getDisplayFqn());
presentation.setPresentableIcon(nodeManager.getJavaNodesResources().packageFolder());
}
private String getDisplayFqn() {
Node parent = getParent();
if (parent != null && parent instanceof HasStorablePath) {
String parentPath = ((HasStorablePath)parent).getStorablePath();
String pkgPath = getStorablePath();
String fqnPath = pkgPath.replaceFirst(parentPath, "");
if (fqnPath.startsWith("/")) {
fqnPath = fqnPath.substring(1);
}
fqnPath = fqnPath.replaceAll("/", ".");
return fqnPath;
}
return getData().getPath();
}
public String getQualifiedName() {
String fqn = "";
Node parent = getParent();
while (parent != null) {
if (parent instanceof FolderReferenceNode && ((FolderReferenceNode)parent).getAttributes().containsKey("javaContentRoot")) {
String parentStorablePath = ((FolderReferenceNode)parent).getStorablePath();
String currentStorablePath = getStorablePath();
fqn = currentStorablePath.substring(parentStorablePath.length() + 1).replace('/', '.');
break;
}
parent = parent.getParent();
}
return fqn;
}
}
| epl-1.0 |
RandallDW/Aruba_plugin | plugins/org.python.pydev.shared_core/src/org/python/pydev/shared_core/string/StringScanner.java | 3003 | /******************************************************************************
* Copyright (C) 2015 Fabio Zadrozny 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:
* Fabio Zadrozny <fabiofz@gmail.com> - initial API and implementation
******************************************************************************/
package org.python.pydev.shared_core.string;
import org.eclipse.jface.text.rules.ICharacterScanner;
import org.python.pydev.shared_core.structure.FastStack;
public class StringScanner implements ICharacterScanner {
private final String contents;
private int offset;
private final int length;
public StringScanner(String contents) {
this.contents = contents;
this.length = contents.length();
}
@Override
public int read() {
if (offset < length) {
// Most common case first.
char ret = contents.charAt(offset);
offset += 1;
return ret;
}
if (offset == length) {
offset++;
return StringScanner.EOF; //EOF
}
// offset > length!
throw new RuntimeException("Reading past EOF!");
}
// peek(0) reads the char at the current offset, peek(-1) reads the previous, peek(1) reads the next
// and so on (all without changing the current offset).
public int peek(int i) {
int checkAt = offset + i;
if (checkAt >= length || checkAt < 0) {
return StringScanner.EOF;
}
return contents.charAt(checkAt);
}
@Override
public void unread() {
offset -= 1;
if (offset < 0) {
throw new RuntimeException("Reading before begin of stream.");
}
}
public int getMark() {
return offset;
}
public String getContents() {
return this.contents;
}
final FastStack<char[]> endLevel = new FastStack<>(3);
public void addLevelFinishingAt(char... endLevelChar) {
endLevel.push(endLevelChar);
}
public void popLevel() {
endLevel.pop();
}
public void setMark(int mark) {
this.offset = mark;
}
public boolean isEndLevelChar(int c) {
if (!endLevel.isEmpty()) {
char[] peek = endLevel.peek();
int len = peek.length;
for (int i = 0; i < len; i++) {
if (peek[i] == c) {
return true;
}
}
}
return false;
}
public int getLevel() {
return endLevel.size();
}
@Override
public char[][] getLegalLineDelimiters() {
throw new AssertionError("Not implemented");
}
@Override
public int getColumn() {
throw new AssertionError("Not implemented");
}
} | epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.anno_fat/test-applications/TestServlet40.war/src/testservlet40/war/servlets/Util_3.java | 768 | /*******************************************************************************
* Copyright (c) 2018 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 testservlet40.war.servlets;
/**
* Simple utility class: Present to force the jar over the write limit, which defaults to 16.
*/
@Util_Anno(value = true)
public class Util_3 {
public Util_3() {
super();
}
}
| epl-1.0 |
RandallDW/Aruba_plugin | plugins/com.python.pydev/src/com/python/pydev/interactiveconsole/EvaluateActionSetter.java | 5854 | /**
* 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.
*/
/*
* Created on Mar 7, 2006
*/
package com.python.pydev.interactiveconsole;
import java.io.File;
import java.util.ListResourceBundle;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.widgets.Display;
import org.python.pydev.core.docutils.PySelection;
import org.python.pydev.core.log.Log;
import org.python.pydev.debug.newconsole.PydevConsoleFactory;
import org.python.pydev.debug.newconsole.prefs.InteractiveConsolePrefs;
import org.python.pydev.editor.PyEdit;
import org.python.pydev.shared_interactive_console.console.codegen.PythonSnippetUtils;
import org.python.pydev.shared_interactive_console.console.ui.ScriptConsole;
import org.python.pydev.shared_interactive_console.console.ui.internal.ScriptConsoleViewer;
import org.python.pydev.shared_interactive_console.console.ui.internal.actions.IInteractiveConsoleConstants;
import org.python.pydev.shared_ui.editor.BaseEditor;
import org.python.pydev.shared_ui.editor.IPyEditListener;
/**
* This class will setup the editor so that we can create interactive consoles, send code to it or make an execfile.
*
* It is as a 'singleton' for all PyEdit editors.
*/
public class EvaluateActionSetter implements IPyEditListener {
private class EvaluateAction extends Action {
private final PyEdit edit;
private EvaluateAction(PyEdit edit) {
super();
this.edit = edit;
}
@Override
public void run() {
try {
PySelection selection = new PySelection(edit);
ScriptConsole console = ScriptConsole.getActiveScriptConsole();
if (console == null) {
//if no console is available, create it (if possible).
PydevConsoleFactory factory = new PydevConsoleFactory();
String cmd = null;
//Check if the current selection should be sent to the editor.
if (InteractiveConsolePrefs.getSendCommandOnCreationFromEditor()) {
cmd = getCommandToSend(edit, selection);
if (cmd != null) {
cmd = "\n" + cmd;
}
}
factory.createConsole(cmd);
} else {
if (console instanceof ScriptConsole) {
//ok, console available
sendCommandToConsole(selection, console, this.edit);
}
}
} catch (Exception e) {
Log.log(e);
}
}
}
/**
* Sends the current selected text/editor to the console.
*/
private static void sendCommandToConsole(PySelection selection, ScriptConsole console, PyEdit edit)
throws BadLocationException {
ScriptConsole pydevConsole = console;
IDocument document = pydevConsole.getDocument();
String cmd = getCommandToSend(edit, selection);
if (cmd != null) {
document.replace(document.getLength(), 0, cmd);
}
if (InteractiveConsolePrefs.getFocusConsoleOnSendCommand()) {
ScriptConsoleViewer viewer = pydevConsole.getViewer();
if (viewer == null) {
return;
}
StyledText textWidget = viewer.getTextWidget();
if (textWidget == null) {
return;
}
textWidget.setFocus();
}
}
/**
* Gets the command to send to the console (either the selected text or a runfile with the editor).
*/
private static String getCommandToSend(PyEdit edit, PySelection selection) {
String cmd = null;
String code = selection.getTextSelection().getText();
if (code.length() != 0) {
cmd = code + "\n";
} else {
//no code available: do a runfile in the current context
File editorFile = edit.getEditorFile();
if (editorFile != null) {
cmd = PythonSnippetUtils.getRunfileCommand(editorFile);
}
}
return cmd;
}
/**
* This method associates Ctrl+new line with the evaluation of commands in the console.
*/
@Override
public void onCreateActions(ListResourceBundle resources, final BaseEditor baseEditor, IProgressMonitor monitor) {
final PyEdit edit = (PyEdit) baseEditor;
final EvaluateAction evaluateAction = new EvaluateAction(edit);
evaluateAction.setActionDefinitionId(IInteractiveConsoleConstants.EVALUATE_ACTION_ID);
evaluateAction.setId(IInteractiveConsoleConstants.EVALUATE_ACTION_ID);
Runnable runnable = new Runnable() {
@Override
public void run() {
if (!edit.isDisposed()) {
edit.setAction(IInteractiveConsoleConstants.EVALUATE_ACTION_ID, evaluateAction);
}
}
};
Display.getDefault().syncExec(runnable);
}
@Override
public void onSave(BaseEditor baseEditor, IProgressMonitor monitor) {
//ignore
}
@Override
public void onDispose(BaseEditor baseEditor, IProgressMonitor monitor) {
//ignore
}
@Override
public void onSetDocument(IDocument document, BaseEditor baseEditor, IProgressMonitor monitor) {
//ignore
}
}
| epl-1.0 |
inocybe/odl-bgpcep | pcep/spi/src/main/java/org/opendaylight/protocol/pcep/spi/pojo/SimpleTlvRegistry.java | 2251 | /*
* Copyright (c) 2013 Cisco Systems, Inc. and others. All rights reserved.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*/
package org.opendaylight.protocol.pcep.spi.pojo;
import com.google.common.base.Preconditions;
import io.netty.buffer.ByteBuf;
import org.opendaylight.protocol.concepts.HandlerRegistry;
import org.opendaylight.protocol.pcep.spi.PCEPDeserializerException;
import org.opendaylight.protocol.pcep.spi.TlvParser;
import org.opendaylight.protocol.pcep.spi.TlvRegistry;
import org.opendaylight.protocol.pcep.spi.TlvSerializer;
import org.opendaylight.protocol.util.Values;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.pcep.types.rev131005.Tlv;
import org.opendaylight.yangtools.yang.binding.DataContainer;
/**
*
*/
public final class SimpleTlvRegistry implements TlvRegistry {
private final HandlerRegistry<DataContainer, TlvParser, TlvSerializer> handlers = new HandlerRegistry<>();
public AutoCloseable registerTlvParser(final int tlvType, final TlvParser parser) {
Preconditions.checkArgument(tlvType >= 0 && tlvType < Values.UNSIGNED_SHORT_MAX_VALUE);
return this.handlers.registerParser(tlvType, parser);
}
public AutoCloseable registerTlvSerializer(final Class<? extends Tlv> tlvClass, final TlvSerializer serializer) {
return this.handlers.registerSerializer(tlvClass, serializer);
}
@Override
public Tlv parseTlv(final int type, final ByteBuf buffer) throws PCEPDeserializerException {
Preconditions.checkArgument(type >= 0 && type <= Values.UNSIGNED_SHORT_MAX_VALUE);
final TlvParser parser = this.handlers.getParser(type);
if (parser == null) {
return null;
}
return parser.parseTlv(buffer);
}
@Override
public void serializeTlv(final Tlv tlv, final ByteBuf buffer) {
final TlvSerializer serializer = this.handlers.getSerializer(tlv.getImplementedInterface());
if (serializer == null) {
return;
}
serializer.serializeTlv(tlv, buffer);
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.logging_fat/test-bundles/sample.source.handler/src/sample/source/handler/SampleHandlerImpl.java | 5173 | /*******************************************************************************
* Copyright (c) 2018 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 sample.source.handler;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import com.ibm.websphere.ras.Tr;
import com.ibm.websphere.ras.TraceComponent;
import com.ibm.websphere.ras.annotation.Trivial;
import com.ibm.ws.ffdc.annotation.FFDCIgnore;
import com.ibm.wsspi.collector.manager.BufferManager;
import com.ibm.wsspi.collector.manager.CollectorManager;
import com.ibm.wsspi.collector.manager.Handler;
/**
*
*/
public class SampleHandlerImpl implements Handler {
private static final TraceComponent tc = Tr.register(SampleHandlerImpl.class, "sampleSourceHandler",
"sample.source.handler.SampleSourceImplMessages");
private volatile CollectorManager collectorMgr;
private volatile ExecutorService executorSrvc = null;
private volatile Future<?> handlerTaskRef = null;
private volatile BufferManager bufferMgr = null;
private final List<String> sourceIds = new ArrayList<String>() {
{
add("com.ibm.ws.collector.manager.sample.source|memory");
}
};
protected void activate(Map<String, Object> configuration) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Activating " + this);
}
}
protected void deactivate(int reason) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, " Deactivating " + this, " reason = " + reason);
}
}
protected void modified(Map<String, Object> configuration) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled())
Tr.event(tc, " Modified");
}
protected void setExecutor(ExecutorService executorSrvc) {
this.executorSrvc = executorSrvc;
}
protected void unsetExecutor(ExecutorService executorSrvc) {
this.executorSrvc = null;
}
/** {@inheritDoc} */
@Override
public String getHandlerName() {
return "SampleHandler";
}
/** {@inheritDoc} */
@Override
public void init(CollectorManager collectorMgr) {
try {
this.collectorMgr = collectorMgr;
this.collectorMgr.subscribe(this, sourceIds);
} catch (Exception e) {
}
}
/** {@inheritDoc} */
@Override
public void setBufferManager(String sourceId, BufferManager bufferMgr) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Setting buffer manager " + this);
}
this.bufferMgr = bufferMgr;
startHandler();
}
/** {@inheritDoc} */
@Override
public void unsetBufferManager(String sourcdId, BufferManager bufferMgr) {
if (TraceComponent.isAnyTracingEnabled() && tc.isEventEnabled()) {
Tr.event(tc, "Un-setting buffer manager " + this);
}
stopHandler();
this.bufferMgr = null;
}
/** Starts the handler task **/
public void startHandler() {
if (handlerTaskRef == null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Starting handler task", this);
}
handlerTaskRef = executorSrvc.submit(handlerTask);
}
}
/** Stops the handler task **/
public void stopHandler() {
if (handlerTaskRef != null) {
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Stopping handler task", this);
}
handlerTaskRef.cancel(true);
handlerTaskRef = null;
}
}
private final Runnable handlerTask = new Runnable() {
@FFDCIgnore(value = { InterruptedException.class })
@Trivial
@Override
public void run() {
int count = 1;
while (count < 3) {
try {
Object event = bufferMgr.getNextEvent(getHandlerName());
// System.out.println("GC event " + event + "\n");
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "Received event: " + event, this);
}
count++;
} catch (InterruptedException exit) {
break; //Break out of the loop; ending thread
} catch (Exception e) {
e.printStackTrace();
stopHandler();
}
}
}
};
}
| epl-1.0 |
kgibm/open-liberty | dev/com.ibm.ws.app.manager.war/test/com/ibm/ws/app/manager/ear/internal/EARStructureHelperTest.java | 12172 | /*******************************************************************************
* Copyright (c) 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 com.ibm.ws.app.manager.ear.internal;
import java.util.Arrays;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.junit.Assert;
import org.junit.Test;
import com.ibm.ws.adaptable.module.structure.StructureHelper;
import com.ibm.wsspi.artifact.ArtifactContainer;
public class EARStructureHelperTest {
private final StructureHelper sh = EARStructureHelper.getUnknownRootInstance();
private final StructureHelper shExplicit = EARStructureHelper.create(Arrays.asList("/explicit", "/dir/explicit"));
private final Mockery mockery = new Mockery();
private final ArtifactContainer root = mockArtifactContainer("/", null, null);
private final ArtifactContainer file = mockArtifactContainer("/file", null, null);
private final ArtifactContainer war = mockArtifactContainer("/x.war", root, null);
private final ArtifactContainer warWebInf = mockArtifactContainer("/x.war/WEB-INF", root, null);
private final ArtifactContainer warWebInfLib = mockArtifactContainer("/x.war/WEB-INF/lib", root, null);
private final ArtifactContainer warWebInfLibJar = mockArtifactContainer("/x.war/WEB-INF/x.jar", root, null);
private final ArtifactContainer warJar = mockArtifactContainer("/x.war/x.jar", root, null);
private final ArtifactContainer warJarFile = mockArtifactContainer("/x.war/x.jar/file", root, null);
private final ArtifactContainer explicit = mockArtifactContainer("/explicit", root, null);
private final ArtifactContainer explicitWebInf = mockArtifactContainer("/explicit/WEB-INF", root, null);
private final ArtifactContainer explicitWebInfLib = mockArtifactContainer("/explicit/WEB-INF/lib", root, null);
private final ArtifactContainer explicitWebInfLibJar = mockArtifactContainer("/explicit/WEB-INF/x.jar", root, null);
private final ArtifactContainer explicitJar = mockArtifactContainer("/explicit/x.jar", root, null);
private final ArtifactContainer explicitJarFile = mockArtifactContainer("/explicit/x.jar/file", root, null);
private final ArtifactContainer dir = mockArtifactContainer("/dir", root, null);
private final ArtifactContainer dirWar = mockArtifactContainer("/dir/x.war", root, null);
private final ArtifactContainer dirWarWebInf = mockArtifactContainer("/dir/x.war/WEB-INF", root, null);
private final ArtifactContainer dirWarWebInfLib = mockArtifactContainer("/dir/x.war/WEB-INF/lib", root, null);
private final ArtifactContainer dirWarWebInfLibJar = mockArtifactContainer("/dir/x.war/WEB-INF/x.jar", root, null);
private final ArtifactContainer dirWarDirjar = mockArtifactContainer("/dir/x.war/x.jar", root, null);
private final ArtifactContainer dirWarDirjarFile = mockArtifactContainer("/dir/x.war/x.jar/file", root, null);
private final ArtifactContainer dirExplicit = mockArtifactContainer("/dir/explicit", root, null);
private final ArtifactContainer dirExplicitWebInf = mockArtifactContainer("/dir/explicit/WEB-INF", root, null);
private final ArtifactContainer dirExplicitWebInfLib = mockArtifactContainer("/dir/explicit/WEB-INF/lib", root, null);
private final ArtifactContainer dirExplicitWebInfLibJar = mockArtifactContainer("/dir/explicit/WEB-INF/x.jar", root, null);
private final ArtifactContainer dirExplicitDirjar = mockArtifactContainer("/dir/explicit/x.jar", root, null);
private final ArtifactContainer dirExplicitDirjarFile = mockArtifactContainer("/dir/explicit/x.jar/file", root, null);
private final ArtifactContainer dirjar = mockArtifactContainer("/x.jar", root, null);
private final ArtifactContainer dirjarFile = mockArtifactContainer("/x.jar/file", root, null);
private final ArtifactContainer dirDirjar = mockArtifactContainer("/dir/x.jar", root, null);
private final ArtifactContainer dirDirjarFile = mockArtifactContainer("/dir/x.jar/file", root, null);
private final ArtifactContainer innerRoot = mockArtifactContainer("/", null, root);
private final ArtifactContainer innerWar = mockArtifactContainer("/x.war", null, root);
private final ArtifactContainer innerWarFile = mockArtifactContainer("/x.war/file", null, root);
private ArtifactContainer mockArtifactContainer(final String path, final ArtifactContainer root, final ArtifactContainer enclosing) {
final ArtifactContainer ac = mockery.mock(ArtifactContainer.class,
"AC(" + (enclosing == null ? path : path + " -> " + enclosing) + ")");
mockery.checking(new Expectations() {
{
allowing(ac).isRoot();
will(returnValue(path.equals("/")));
allowing(ac).getRoot();
will(returnValue(root == null ? ac : root));
allowing(ac).getPath();
will(returnValue(path));
allowing(ac).getEnclosingContainer();
will(returnValue(enclosing));
}
});
return ac;
}
@Test
public void testIsRoot() {
Assert.assertFalse(sh.isRoot(root));
Assert.assertFalse(sh.isRoot(file));
Assert.assertFalse(shExplicit.isRoot(root));
Assert.assertFalse(shExplicit.isRoot(file));
Assert.assertTrue(sh.isRoot(war));
Assert.assertFalse(sh.isRoot(warWebInf));
Assert.assertFalse(sh.isRoot(warWebInfLib));
Assert.assertFalse(sh.isRoot(warWebInfLibJar));
Assert.assertFalse(sh.isRoot(warJar));
Assert.assertFalse(sh.isRoot(warJarFile));
Assert.assertTrue(shExplicit.isRoot(explicit));
Assert.assertFalse(shExplicit.isRoot(explicitWebInf));
Assert.assertFalse(shExplicit.isRoot(explicitWebInfLib));
Assert.assertFalse(shExplicit.isRoot(explicitWebInfLibJar));
Assert.assertFalse(shExplicit.isRoot(explicitJar));
Assert.assertFalse(shExplicit.isRoot(explicitJarFile));
Assert.assertTrue(sh.isRoot(dirWar));
Assert.assertFalse(sh.isRoot(dirWarWebInf));
Assert.assertFalse(sh.isRoot(dirWarWebInfLib));
Assert.assertFalse(sh.isRoot(dirWarWebInfLibJar));
Assert.assertFalse(sh.isRoot(dirWarDirjar));
Assert.assertFalse(sh.isRoot(dirWarDirjarFile));
Assert.assertTrue(shExplicit.isRoot(dirExplicit));
Assert.assertFalse(shExplicit.isRoot(dirExplicitWebInf));
Assert.assertFalse(shExplicit.isRoot(dirExplicitWebInfLib));
Assert.assertFalse(shExplicit.isRoot(dirExplicitWebInfLibJar));
Assert.assertFalse(shExplicit.isRoot(dirExplicitDirjar));
Assert.assertFalse(shExplicit.isRoot(dirExplicitDirjarFile));
Assert.assertTrue(sh.isRoot(dirjar));
Assert.assertFalse(sh.isRoot(dirjarFile));
Assert.assertTrue(sh.isRoot(dirDirjar));
Assert.assertFalse(sh.isRoot(dirDirjarFile));
Assert.assertFalse(sh.isRoot(innerRoot));
Assert.assertFalse(sh.isRoot(innerWar));
Assert.assertFalse(sh.isRoot(innerWarFile));
}
@Test
public void testIsValid() {
for (ArtifactContainer ac : new ArtifactContainer[] { root, war, dirWar, dirjar, dirDirjar }) {
Assert.assertTrue(sh.isValid(ac, "/"));
Assert.assertTrue(sh.isValid(ac, "/file"));
Assert.assertTrue(shExplicit.isValid(ac, "/"));
Assert.assertTrue(shExplicit.isValid(ac, "/file"));
Assert.assertTrue(sh.isValid(ac, "/x.war"));
Assert.assertFalse(sh.isValid(ac, "/x.war/WEB-INF"));
Assert.assertFalse(sh.isValid(ac, "/x.war/WEB-INF/lib"));
Assert.assertFalse(sh.isValid(ac, "/x.war/WEB-INF/lib/x.jar"));
Assert.assertTrue(shExplicit.isValid(ac, "/explicit"));
Assert.assertFalse(shExplicit.isValid(ac, "/explicit/WEB-INF"));
Assert.assertFalse(shExplicit.isValid(ac, "/explicit/WEB-INF/lib"));
Assert.assertFalse(shExplicit.isValid(ac, "/explicit/WEB-INF/lib/x.jar"));
Assert.assertTrue(sh.isValid(ac, "/dir"));
Assert.assertTrue(sh.isValid(ac, "/dir/x.war"));
Assert.assertFalse(sh.isValid(ac, "/dir/x.war/WEB-INF"));
Assert.assertFalse(sh.isValid(ac, "/dir/x.war/WEB-INF/lib"));
Assert.assertFalse(sh.isValid(ac, "/dir/x.war/WEB-INF/lib/x.jar"));
Assert.assertFalse(sh.isValid(ac, "/dir/x.war/x.jar"));
Assert.assertFalse(sh.isValid(ac, "/dir/x.war/x.jar/file"));
Assert.assertTrue(shExplicit.isValid(ac, "/dir/explicit"));
Assert.assertFalse(shExplicit.isValid(ac, "/dir/explicit/WEB-INF"));
Assert.assertFalse(shExplicit.isValid(ac, "/dir/explicit/WEB-INF/lib"));
Assert.assertFalse(shExplicit.isValid(ac, "/dir/explicit/WEB-INF/lib/x.jar"));
Assert.assertFalse(shExplicit.isValid(ac, "/dir/explicit/x.jar"));
Assert.assertFalse(shExplicit.isValid(ac, "/dir/explicit/x.jar/file"));
Assert.assertTrue(sh.isValid(ac, "/dir/x.jar"));
Assert.assertFalse(sh.isValid(ac, "/dir/x.jar/file"));
Assert.assertTrue(sh.isValid(ac, "/dir/x.jar"));
Assert.assertFalse(sh.isValid(ac, "/dir/x.jar/file"));
}
Assert.assertTrue(sh.isValid(war, "WEB-INF"));
Assert.assertTrue(sh.isValid(war, "WEB-INF/lib"));
Assert.assertTrue(sh.isValid(war, "WEB-INF/lib/x.jar"));
Assert.assertTrue(sh.isValid(war, "x.jar"));
Assert.assertTrue(sh.isValid(war, "x.jar/file"));
Assert.assertTrue(shExplicit.isValid(explicit, "WEB-INF"));
Assert.assertTrue(shExplicit.isValid(explicit, "WEB-INF/lib"));
Assert.assertTrue(shExplicit.isValid(explicit, "WEB-INF/lib/x.jar"));
Assert.assertTrue(shExplicit.isValid(explicit, "x.jar"));
Assert.assertTrue(shExplicit.isValid(explicit, "x.jar/file"));
Assert.assertTrue(sh.isValid(dir, "x.war"));
Assert.assertFalse(sh.isValid(dir, "x.war/WEB-INF"));
Assert.assertFalse(sh.isValid(dir, "x.war/WEB-INF/lib"));
Assert.assertFalse(sh.isValid(dir, "x.war/WEB-INF/lib/x.jar"));
Assert.assertFalse(sh.isValid(dir, "x.war/x.jar"));
Assert.assertFalse(sh.isValid(dir, "x.war/x.jar/file"));
Assert.assertTrue(shExplicit.isValid(dir, "explicit"));
Assert.assertFalse(shExplicit.isValid(dir, "explicit/WEB-INF"));
Assert.assertFalse(shExplicit.isValid(dir, "explicit/WEB-INF/lib"));
Assert.assertFalse(shExplicit.isValid(dir, "explicit/WEB-INF/lib/x.jar"));
Assert.assertFalse(shExplicit.isValid(dir, "explicit/x.jar"));
Assert.assertFalse(shExplicit.isValid(dir, "explicit/x.jar/file"));
Assert.assertTrue(sh.isValid(dirWar, "WEB-INF"));
Assert.assertTrue(sh.isValid(dirWar, "WEB-INF/lib"));
Assert.assertTrue(sh.isValid(dirWar, "WEB-INF/lib/x.jar"));
Assert.assertTrue(sh.isValid(dirWar, "x.jar"));
Assert.assertTrue(sh.isValid(dirWar, "x.jar/file"));
Assert.assertTrue(shExplicit.isValid(dirExplicit, "WEB-INF"));
Assert.assertTrue(shExplicit.isValid(dirExplicit, "WEB-INF/lib"));
Assert.assertTrue(shExplicit.isValid(dirExplicit, "WEB-INF/lib/x.jar"));
Assert.assertTrue(shExplicit.isValid(dirExplicit, "x.jar"));
Assert.assertTrue(shExplicit.isValid(dirExplicit, "x.jar/file"));
Assert.assertTrue(sh.isValid(dirjar, "file"));
Assert.assertTrue(sh.isValid(dirDirjar, "file"));
Assert.assertTrue(sh.isValid(innerRoot, "file"));
Assert.assertTrue(sh.isValid(innerRoot, "x.war"));
Assert.assertTrue(sh.isValid(innerRoot, "x.war/file"));
}
}
| epl-1.0 |
TypeFox/che | plugins/plugin-debugger/che-plugin-debugger-ide/src/main/java/org/eclipse/che/plugin/debugger/ide/debug/DebuggerView.java | 3754 | /*
* 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.debugger.ide.debug;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import java.util.List;
import javax.validation.constraints.NotNull;
import org.eclipse.che.api.debug.shared.model.Breakpoint;
import org.eclipse.che.api.debug.shared.model.Location;
import org.eclipse.che.api.debug.shared.model.MutableVariable;
import org.eclipse.che.api.debug.shared.model.SimpleValue;
import org.eclipse.che.api.debug.shared.model.StackFrameDump;
import org.eclipse.che.api.debug.shared.model.ThreadState;
import org.eclipse.che.api.debug.shared.model.Variable;
import org.eclipse.che.commons.annotation.Nullable;
import org.eclipse.che.ide.api.mvp.View;
import org.eclipse.che.ide.api.parts.base.BaseActionDelegate;
/**
* Provides methods which allow change view representation of debugger panel. Also the interface
* contains inner action delegate interface which provides methods which allows react on user's
* actions.
*
* @author Andrey Plotnikov
* @author Dmitry Shnurenko
*/
public interface DebuggerView extends View<DebuggerView.ActionDelegate> {
/** Needs for delegate some function into Debugger view. */
interface ActionDelegate extends BaseActionDelegate {
/**
* Performs any actions appropriate in response to the user having pressed the expand button in
* variables tree.
*/
void onExpandVariablesTree(MutableVariable variable);
/** Is invoked when a new thread is selected. */
void onSelectedThread(long threadId);
/**
* Is invoked when a new frame is selected.
*
* @param frameIndex the frame index inside a thread
*/
void onSelectedFrame(int frameIndex);
}
/**
* Sets information about the execution point.
*
* @param location information about the execution point
*/
void setExecutionPoint(@NotNull Location location);
/**
* Sets variables.
*
* @param variables available variables
*/
void setVariables(@NotNull List<? extends Variable> variables);
/** Updates variable in the list */
void setVariableValue(@NotNull Variable variable, @NotNull SimpleValue value);
/**
* Sets breakpoints.
*
* @param breakPoints available breakpoints
*/
void setBreakpoints(@NotNull List<Breakpoint> breakPoints);
/**
* Sets thread dump and select the thread with {@link ThreadState#getId()} equal to {@code
* activeThreadId}.
*/
void setThreadDump(@NotNull List<? extends ThreadState> threadDump, long threadIdToSelect);
/** Sets the list of frames for selected thread. */
void setFrames(@NotNull List<? extends StackFrameDump> stackFrameDumps);
/**
* Sets java virtual machine name and version.
*
* @param name virtual machine name
*/
void setVMName(@Nullable String name);
/**
* Sets title.
*
* @param title title of view
*/
void setTitle(@NotNull String title);
/** Returns selected thread id {@link ThreadState#getId()} or -1 if there is no selection. */
long getSelectedThreadId();
/** Returns selected frame index inside thread or -1 if there is no selection. */
int getSelectedFrameIndex();
/**
* Returns selected variable in the variables list on debugger panel or null if no selection.
*
* @return selected variable or null if no selection.
*/
MutableVariable getSelectedDebuggerVariable();
AcceptsOneWidget getDebuggerToolbarPanel();
}
| epl-1.0 |
mondo-project/mondo-integration | uk.ac.york.mondo.integration.api/src-gen/uk/ac/york/mondo/integration/api/File.java | 15148 | /**
* Autogenerated by Thrift Compiler (0.9.3)
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
package uk.ac.york.mondo.integration.api;
import org.apache.thrift.scheme.IScheme;
import org.apache.thrift.scheme.SchemeFactory;
import org.apache.thrift.scheme.StandardScheme;
import org.apache.thrift.scheme.TupleScheme;
import org.apache.thrift.protocol.TTupleProtocol;
import org.apache.thrift.protocol.TProtocolException;
import org.apache.thrift.EncodingUtils;
import org.apache.thrift.TException;
import org.apache.thrift.async.AsyncMethodCallback;
import org.apache.thrift.server.AbstractNonblockingServer.*;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.HashMap;
import java.util.EnumMap;
import java.util.Set;
import java.util.HashSet;
import java.util.EnumSet;
import java.util.Collections;
import java.util.BitSet;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Generated;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@SuppressWarnings({"cast", "rawtypes", "serial", "unchecked"})
@Generated(value = "Autogenerated by Thrift Compiler (0.9.3)", date = "2016-03-23")
public class File implements org.apache.thrift.TBase<File, File._Fields>, java.io.Serializable, Cloneable, Comparable<File> {
private static final org.apache.thrift.protocol.TStruct STRUCT_DESC = new org.apache.thrift.protocol.TStruct("File");
private static final org.apache.thrift.protocol.TField NAME_FIELD_DESC = new org.apache.thrift.protocol.TField("name", org.apache.thrift.protocol.TType.STRING, (short)1);
private static final org.apache.thrift.protocol.TField CONTENTS_FIELD_DESC = new org.apache.thrift.protocol.TField("contents", org.apache.thrift.protocol.TType.STRING, (short)2);
private static final Map<Class<? extends IScheme>, SchemeFactory> schemes = new HashMap<Class<? extends IScheme>, SchemeFactory>();
static {
schemes.put(StandardScheme.class, new FileStandardSchemeFactory());
schemes.put(TupleScheme.class, new FileTupleSchemeFactory());
}
public String name; // required
public ByteBuffer contents; // required
/** The set of fields this struct contains, along with convenience methods for finding and manipulating them. */
public enum _Fields implements org.apache.thrift.TFieldIdEnum {
NAME((short)1, "name"),
CONTENTS((short)2, "contents");
private static final Map<String, _Fields> byName = new HashMap<String, _Fields>();
static {
for (_Fields field : EnumSet.allOf(_Fields.class)) {
byName.put(field.getFieldName(), field);
}
}
/**
* Find the _Fields constant that matches fieldId, or null if its not found.
*/
public static _Fields findByThriftId(int fieldId) {
switch(fieldId) {
case 1: // NAME
return NAME;
case 2: // CONTENTS
return CONTENTS;
default:
return null;
}
}
/**
* Find the _Fields constant that matches fieldId, throwing an exception
* if it is not found.
*/
public static _Fields findByThriftIdOrThrow(int fieldId) {
_Fields fields = findByThriftId(fieldId);
if (fields == null) throw new IllegalArgumentException("Field " + fieldId + " doesn't exist!");
return fields;
}
/**
* Find the _Fields constant that matches name, or null if its not found.
*/
public static _Fields findByName(String name) {
return byName.get(name);
}
private final short _thriftId;
private final String _fieldName;
_Fields(short thriftId, String fieldName) {
_thriftId = thriftId;
_fieldName = fieldName;
}
public short getThriftFieldId() {
return _thriftId;
}
public String getFieldName() {
return _fieldName;
}
}
// isset id assignments
public static final Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> metaDataMap;
static {
Map<_Fields, org.apache.thrift.meta_data.FieldMetaData> tmpMap = new EnumMap<_Fields, org.apache.thrift.meta_data.FieldMetaData>(_Fields.class);
tmpMap.put(_Fields.NAME, new org.apache.thrift.meta_data.FieldMetaData("name", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING)));
tmpMap.put(_Fields.CONTENTS, new org.apache.thrift.meta_data.FieldMetaData("contents", org.apache.thrift.TFieldRequirementType.REQUIRED,
new org.apache.thrift.meta_data.FieldValueMetaData(org.apache.thrift.protocol.TType.STRING , true)));
metaDataMap = Collections.unmodifiableMap(tmpMap);
org.apache.thrift.meta_data.FieldMetaData.addStructMetaDataMap(File.class, metaDataMap);
}
public File() {
}
public File(
String name,
ByteBuffer contents)
{
this();
this.name = name;
this.contents = org.apache.thrift.TBaseHelper.copyBinary(contents);
}
/**
* Performs a deep copy on <i>other</i>.
*/
public File(File other) {
if (other.isSetName()) {
this.name = other.name;
}
if (other.isSetContents()) {
this.contents = org.apache.thrift.TBaseHelper.copyBinary(other.contents);
}
}
public File deepCopy() {
return new File(this);
}
@Override
public void clear() {
this.name = null;
this.contents = null;
}
public String getName() {
return this.name;
}
public File setName(String name) {
this.name = name;
return this;
}
public void unsetName() {
this.name = null;
}
/** Returns true if field name is set (has been assigned a value) and false otherwise */
public boolean isSetName() {
return this.name != null;
}
public void setNameIsSet(boolean value) {
if (!value) {
this.name = null;
}
}
public byte[] getContents() {
setContents(org.apache.thrift.TBaseHelper.rightSize(contents));
return contents == null ? null : contents.array();
}
public ByteBuffer bufferForContents() {
return org.apache.thrift.TBaseHelper.copyBinary(contents);
}
public File setContents(byte[] contents) {
this.contents = contents == null ? (ByteBuffer)null : ByteBuffer.wrap(Arrays.copyOf(contents, contents.length));
return this;
}
public File setContents(ByteBuffer contents) {
this.contents = org.apache.thrift.TBaseHelper.copyBinary(contents);
return this;
}
public void unsetContents() {
this.contents = null;
}
/** Returns true if field contents is set (has been assigned a value) and false otherwise */
public boolean isSetContents() {
return this.contents != null;
}
public void setContentsIsSet(boolean value) {
if (!value) {
this.contents = null;
}
}
public void setFieldValue(_Fields field, Object value) {
switch (field) {
case NAME:
if (value == null) {
unsetName();
} else {
setName((String)value);
}
break;
case CONTENTS:
if (value == null) {
unsetContents();
} else {
setContents((ByteBuffer)value);
}
break;
}
}
public Object getFieldValue(_Fields field) {
switch (field) {
case NAME:
return getName();
case CONTENTS:
return getContents();
}
throw new IllegalStateException();
}
/** Returns true if field corresponding to fieldID is set (has been assigned a value) and false otherwise */
public boolean isSet(_Fields field) {
if (field == null) {
throw new IllegalArgumentException();
}
switch (field) {
case NAME:
return isSetName();
case CONTENTS:
return isSetContents();
}
throw new IllegalStateException();
}
@Override
public boolean equals(Object that) {
if (that == null)
return false;
if (that instanceof File)
return this.equals((File)that);
return false;
}
public boolean equals(File that) {
if (that == null)
return false;
boolean this_present_name = true && this.isSetName();
boolean that_present_name = true && that.isSetName();
if (this_present_name || that_present_name) {
if (!(this_present_name && that_present_name))
return false;
if (!this.name.equals(that.name))
return false;
}
boolean this_present_contents = true && this.isSetContents();
boolean that_present_contents = true && that.isSetContents();
if (this_present_contents || that_present_contents) {
if (!(this_present_contents && that_present_contents))
return false;
if (!this.contents.equals(that.contents))
return false;
}
return true;
}
@Override
public int hashCode() {
List<Object> list = new ArrayList<Object>();
boolean present_name = true && (isSetName());
list.add(present_name);
if (present_name)
list.add(name);
boolean present_contents = true && (isSetContents());
list.add(present_contents);
if (present_contents)
list.add(contents);
return list.hashCode();
}
@Override
public int compareTo(File other) {
if (!getClass().equals(other.getClass())) {
return getClass().getName().compareTo(other.getClass().getName());
}
int lastComparison = 0;
lastComparison = Boolean.valueOf(isSetName()).compareTo(other.isSetName());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetName()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.name, other.name);
if (lastComparison != 0) {
return lastComparison;
}
}
lastComparison = Boolean.valueOf(isSetContents()).compareTo(other.isSetContents());
if (lastComparison != 0) {
return lastComparison;
}
if (isSetContents()) {
lastComparison = org.apache.thrift.TBaseHelper.compareTo(this.contents, other.contents);
if (lastComparison != 0) {
return lastComparison;
}
}
return 0;
}
public _Fields fieldForId(int fieldId) {
return _Fields.findByThriftId(fieldId);
}
public void read(org.apache.thrift.protocol.TProtocol iprot) throws org.apache.thrift.TException {
schemes.get(iprot.getScheme()).getScheme().read(iprot, this);
}
public void write(org.apache.thrift.protocol.TProtocol oprot) throws org.apache.thrift.TException {
schemes.get(oprot.getScheme()).getScheme().write(oprot, this);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder("File(");
boolean first = true;
sb.append("name:");
if (this.name == null) {
sb.append("null");
} else {
sb.append(this.name);
}
first = false;
if (!first) sb.append(", ");
sb.append("contents:");
if (this.contents == null) {
sb.append("null");
} else {
org.apache.thrift.TBaseHelper.toString(this.contents, sb);
}
first = false;
sb.append(")");
return sb.toString();
}
public void validate() throws org.apache.thrift.TException {
// check for required fields
if (name == null) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'name' was not present! Struct: " + toString());
}
if (contents == null) {
throw new org.apache.thrift.protocol.TProtocolException("Required field 'contents' was not present! Struct: " + toString());
}
// check for sub-struct validity
}
private void writeObject(java.io.ObjectOutputStream out) throws java.io.IOException {
try {
write(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(out)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private void readObject(java.io.ObjectInputStream in) throws java.io.IOException, ClassNotFoundException {
try {
read(new org.apache.thrift.protocol.TCompactProtocol(new org.apache.thrift.transport.TIOStreamTransport(in)));
} catch (org.apache.thrift.TException te) {
throw new java.io.IOException(te);
}
}
private static class FileStandardSchemeFactory implements SchemeFactory {
public FileStandardScheme getScheme() {
return new FileStandardScheme();
}
}
private static class FileStandardScheme extends StandardScheme<File> {
public void read(org.apache.thrift.protocol.TProtocol iprot, File struct) throws org.apache.thrift.TException {
org.apache.thrift.protocol.TField schemeField;
iprot.readStructBegin();
while (true)
{
schemeField = iprot.readFieldBegin();
if (schemeField.type == org.apache.thrift.protocol.TType.STOP) {
break;
}
switch (schemeField.id) {
case 1: // NAME
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.name = iprot.readString();
struct.setNameIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
case 2: // CONTENTS
if (schemeField.type == org.apache.thrift.protocol.TType.STRING) {
struct.contents = iprot.readBinary();
struct.setContentsIsSet(true);
} else {
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
break;
default:
org.apache.thrift.protocol.TProtocolUtil.skip(iprot, schemeField.type);
}
iprot.readFieldEnd();
}
iprot.readStructEnd();
// check for required fields of primitive type, which can't be checked in the validate method
struct.validate();
}
public void write(org.apache.thrift.protocol.TProtocol oprot, File struct) throws org.apache.thrift.TException {
struct.validate();
oprot.writeStructBegin(STRUCT_DESC);
if (struct.name != null) {
oprot.writeFieldBegin(NAME_FIELD_DESC);
oprot.writeString(struct.name);
oprot.writeFieldEnd();
}
if (struct.contents != null) {
oprot.writeFieldBegin(CONTENTS_FIELD_DESC);
oprot.writeBinary(struct.contents);
oprot.writeFieldEnd();
}
oprot.writeFieldStop();
oprot.writeStructEnd();
}
}
private static class FileTupleSchemeFactory implements SchemeFactory {
public FileTupleScheme getScheme() {
return new FileTupleScheme();
}
}
private static class FileTupleScheme extends TupleScheme<File> {
@Override
public void write(org.apache.thrift.protocol.TProtocol prot, File struct) throws org.apache.thrift.TException {
TTupleProtocol oprot = (TTupleProtocol) prot;
oprot.writeString(struct.name);
oprot.writeBinary(struct.contents);
}
@Override
public void read(org.apache.thrift.protocol.TProtocol prot, File struct) throws org.apache.thrift.TException {
TTupleProtocol iprot = (TTupleProtocol) prot;
struct.name = iprot.readString();
struct.setNameIsSet(true);
struct.contents = iprot.readBinary();
struct.setContentsIsSet(true);
}
}
}
| epl-1.0 |
eclipse/hawkbit | hawkbit-rest/hawkbit-mgmt-resource/src/main/java/org/eclipse/hawkbit/mgmt/rest/resource/MgmtDownloadResource.java | 3722 | /**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.mgmt.rest.resource;
import java.io.InputStream;
import org.eclipse.hawkbit.artifact.repository.ArtifactRepository;
import org.eclipse.hawkbit.artifact.repository.model.AbstractDbArtifact;
import org.eclipse.hawkbit.cache.DownloadArtifactCache;
import org.eclipse.hawkbit.cache.DownloadIdCache;
import org.eclipse.hawkbit.cache.DownloadType;
import org.eclipse.hawkbit.mgmt.rest.api.MgmtDownloadRestApi;
import org.eclipse.hawkbit.rest.util.FileStreamingUtil;
import org.eclipse.hawkbit.rest.util.RequestResponseContextHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.WebApplicationContext;
/**
* A resource for download artifacts.
*/
@RestController
@Scope(value = WebApplicationContext.SCOPE_REQUEST)
public class MgmtDownloadResource implements MgmtDownloadRestApi {
private static final Logger LOGGER = LoggerFactory.getLogger(MgmtDownloadResource.class);
private final ArtifactRepository artifactRepository;
private final DownloadIdCache downloadIdCache;
private final RequestResponseContextHolder requestResponseContextHolder;
MgmtDownloadResource(final ArtifactRepository artifactRepository, final DownloadIdCache downloadIdCache,
final RequestResponseContextHolder requestResponseContextHolder) {
this.artifactRepository = artifactRepository;
this.downloadIdCache = downloadIdCache;
this.requestResponseContextHolder = requestResponseContextHolder;
}
@Override
@ResponseBody
public ResponseEntity<InputStream> downloadArtifactByDownloadId(@PathVariable("tenant") final String tenant,
@PathVariable("downloadId") final String downloadId) {
try {
final DownloadArtifactCache artifactCache = downloadIdCache.get(downloadId);
if (artifactCache == null) {
LOGGER.warn("Download Id {} could not be found", downloadId);
return ResponseEntity.notFound().build();
}
AbstractDbArtifact artifact = null;
if (DownloadType.BY_SHA1 == artifactCache.getDownloadType()) {
artifact = artifactRepository.existsByTenantAndSha1(tenant, artifactCache.getId())
? artifactRepository.getArtifactBySha1(tenant, artifactCache.getId())
: null;
} else {
LOGGER.warn("Download Type {} not supported", artifactCache.getDownloadType());
}
if (artifact == null) {
LOGGER.warn("Artifact with cached id {} and download type {} could not be found.",
artifactCache.getId(), artifactCache.getDownloadType());
return ResponseEntity.notFound().build();
}
return FileStreamingUtil.writeFileResponse(artifact, downloadId, 0L,
requestResponseContextHolder.getHttpServletResponse(),
requestResponseContextHolder.getHttpServletRequest(), null);
} finally {
downloadIdCache.evict(downloadId);
}
}
}
| epl-1.0 |
stzilli/kapua | console/module/job/src/main/java/org/eclipse/kapua/app/console/module/job/client/schedule/JobTabSchedulesDescriptor.java | 1604 | /*******************************************************************************
* Copyright (c) 2017, 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.app.console.module.job.client.schedule;
import org.eclipse.kapua.app.console.module.api.client.ui.view.descriptor.AbstractEntityTabDescriptor;
import org.eclipse.kapua.app.console.module.api.shared.model.session.GwtSession;
import org.eclipse.kapua.app.console.module.job.client.JobView;
import org.eclipse.kapua.app.console.module.job.shared.model.GwtJob;
import org.eclipse.kapua.app.console.module.job.shared.model.permission.SchedulerSessionPermission;
public class JobTabSchedulesDescriptor extends AbstractEntityTabDescriptor<GwtJob, JobTabSchedules, JobView> {
@Override
public JobTabSchedules getTabViewInstance(JobView view, GwtSession currentSession) {
return new JobTabSchedules(currentSession);
}
@Override
public String getViewId() {
return "job.schedules";
}
@Override
public Integer getOrder() {
return 400;
}
@Override
public Boolean isEnabled(GwtSession currentSession) {
return currentSession.hasPermission(SchedulerSessionPermission.read());
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsf.2.2/src/org/apache/myfaces/resource/TempDirFileCacheContractResourceLoader.java | 9755 | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.apache.myfaces.resource;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.faces.FacesException;
import javax.faces.application.Resource;
import javax.faces.context.FacesContext;
import org.apache.myfaces.application.ResourceHandlerImpl;
import org.apache.myfaces.shared.resource.ContractResourceLoader;
import org.apache.myfaces.shared.resource.ContractResourceLoaderWrapper;
import org.apache.myfaces.shared.resource.ResourceMeta;
import org.apache.myfaces.shared.util.WebConfigParamUtils;
/**
* ResourceLoader that uses a temporal folder to cache resources, avoiding the problem
* described on MYFACES-3586 (Performance improvement in Resource loading -
* HIGH CPU inflating bytes in ResourceHandlerImpl.handleResourceRequest).
*
* @author Leonardo Uribe
*/
public class TempDirFileCacheContractResourceLoader extends ContractResourceLoaderWrapper
{
public final static String TEMP_FILES_LOCK_MAP = "oam.rh.con.TEMP_FILES_LOCK_MAP";
/**
* Subdir of the ServletContext tmp dir to store temporal resources.
*/
private static final String TEMP_FOLDER_BASE_DIR = "oam-rh-cache/";
/**
* Suffix for temporal files.
*/
private static final String TEMP_FILE_SUFFIX = ".tmp";
private final ContractResourceLoader delegate;
private volatile File _tempDir;
private int _resourceBufferSize = -1;
public TempDirFileCacheContractResourceLoader(ContractResourceLoader delegate)
{
this.delegate = delegate;
initialize();
}
protected void initialize()
{
//Get startup FacesContext
FacesContext facesContext = FacesContext.getCurrentInstance();
//1. Create temporal directory for temporal resources
Map<String, Object> applicationMap = facesContext.getExternalContext().getApplicationMap();
File tempdir = (File) applicationMap.get("javax.servlet.context.tempdir");
File imagesDir = new File(tempdir, TEMP_FOLDER_BASE_DIR);
if (!imagesDir.exists())
{
imagesDir.mkdirs();
}
else
{
//Clear the cache
deleteDir(imagesDir);
imagesDir.mkdirs();
}
_tempDir = imagesDir;
//2. Create map for register temporal resources
Map<String, FileProducer> temporalFilesLockMap = new ConcurrentHashMap<String, FileProducer>();
facesContext.getExternalContext().getApplicationMap().put(TEMP_FILES_LOCK_MAP, temporalFilesLockMap);
}
private static boolean deleteDir(File dir)
{
if (dir.isDirectory())
{
String[] children = dir.list();
for (int i = 0; i < children.length; i++)
{
boolean success = deleteDir(new File(dir, children[i]));
if (!success)
{
return false;
}
}
}
return dir.delete();
}
@Override
public URL getResourceURL(ResourceMeta resourceMeta)
{
FacesContext facesContext = FacesContext.getCurrentInstance();
if (resourceExists(resourceMeta))
{
File file = createOrGetTempFile(facesContext, resourceMeta);
try
{
return file.toURL();
}
catch (MalformedURLException e)
{
throw new FacesException(e);
}
}
else
{
return null;
}
}
public InputStream getResourceInputStream(ResourceMeta resourceMeta, Resource resource)
{
FacesContext facesContext = FacesContext.getCurrentInstance();
if (resourceExists(resourceMeta))
{
File file = createOrGetTempFile(facesContext, resourceMeta);
try
{
return new BufferedInputStream(new FileInputStream(file));
}
catch (FileNotFoundException e)
{
throw new FacesException(e);
}
}
else
{
return null;
}
}
@Override
public InputStream getResourceInputStream(ResourceMeta resourceMeta)
{
return getResourceInputStream(resourceMeta, null);
}
@Override
public boolean resourceExists(ResourceMeta resourceMeta)
{
return super.resourceExists(resourceMeta);
}
@SuppressWarnings("unchecked")
private File createOrGetTempFile(FacesContext facesContext, ResourceMeta resourceMeta)
{
String identifier = resourceMeta.getResourceIdentifier()+"_"+resourceMeta.getContractName();
File file = getTemporalFile(resourceMeta);
if (!file.exists())
{
Map<String, FileProducer> map = (Map<String, FileProducer>)
facesContext.getExternalContext().getApplicationMap().get(TEMP_FILES_LOCK_MAP);
FileProducer creator = map.get(identifier);
if (creator == null)
{
synchronized(this)
{
creator = map.get(identifier);
if (creator == null)
{
creator = new FileProducer();
map.put(identifier, creator);
}
}
}
if (!creator.isCreated())
{
creator.createFile(facesContext, resourceMeta, file, this);
}
}
return file;
}
private File getTemporalFile(ResourceMeta resourceMeta)
{
return new File(_tempDir,
resourceMeta.getResourceIdentifier()+"_"+ resourceMeta.getContractName() + TEMP_FILE_SUFFIX);
}
protected void createTemporalFileVersion(FacesContext facesContext, ResourceMeta resourceMeta, File target)
{
target.mkdirs(); // ensure necessary directories exist
target.delete(); // remove any existing file
InputStream inputStream = null;
FileOutputStream fileOutputStream;
try
{
inputStream = getWrapped().getResourceInputStream(resourceMeta);
fileOutputStream = new FileOutputStream(target);
byte[] buffer = new byte[this.getResourceBufferSize()];
pipeBytes(inputStream, fileOutputStream, buffer);
}
catch (FileNotFoundException e)
{
throw new FacesException("Unexpected exception while create file:", e);
}
catch (IOException e)
{
throw new FacesException("Unexpected exception while create file:", e);
}
finally
{
if (inputStream != null)
{
try
{
inputStream.close();
}
catch (IOException e)
{
// Ignore
}
}
}
}
/**
* Reads the specified input stream into the provided byte array storage and
* writes it to the output stream.
*/
private static void pipeBytes(InputStream in, OutputStream out, byte[] buffer) throws IOException
{
int length;
while ((length = (in.read(buffer))) >= 0)
{
out.write(buffer, 0, length);
}
}
public static class FileProducer
{
public volatile boolean created = false;
public FileProducer()
{
super();
}
public boolean isCreated()
{
return created;
}
public synchronized void createFile(FacesContext facesContext,
ResourceMeta resourceMeta, File file, TempDirFileCacheContractResourceLoader loader)
{
if (!created)
{
loader.createTemporalFileVersion(facesContext, resourceMeta, file);
created = true;
}
}
}
protected int getResourceBufferSize()
{
if (_resourceBufferSize == -1)
{
_resourceBufferSize = WebConfigParamUtils.getIntegerInitParameter(
FacesContext.getCurrentInstance().getExternalContext(),
ResourceHandlerImpl.INIT_PARAM_RESOURCE_BUFFER_SIZE,
ResourceHandlerImpl.INIT_PARAM_RESOURCE_BUFFER_SIZE_DEFAULT);
}
return _resourceBufferSize;
}
public ContractResourceLoader getWrapped()
{
return delegate;
}
}
| epl-1.0 |
stzilli/kapua | service/device/call/api/src/main/java/org/eclipse/kapua/service/device/call/exception/DeviceCallException.java | 1588 | /*******************************************************************************
* Copyright (c) 2016, 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.exception;
import org.eclipse.kapua.KapuaException;
import javax.validation.constraints.NotNull;
/**
* {@link DeviceCallException} definition.
* <p>
* Base class for {@code kapua-device-call-api} {@link Exception}s.
*
* @since 1.1.0
*/
public abstract class DeviceCallException extends KapuaException {
private static final String KAPUA_ERROR_MESSAGES = "device-call-error-messages";
/**
* @since 1.1.0
*/
protected DeviceCallException(@NotNull DeviceCallErrorCodes code) {
super(code);
}
/**
* @since 1.1.0
*/
protected DeviceCallException(@NotNull DeviceCallErrorCodes code, Object... arguments) {
super(code, arguments);
}
/*
* @since 1.1.0
*/
protected DeviceCallException(@NotNull DeviceCallErrorCodes code, @NotNull Throwable cause, Object... arguments) {
super(code, cause, arguments);
}
@Override
protected String getKapuaErrorMessagesBundle() {
return KAPUA_ERROR_MESSAGES;
}
}
| epl-1.0 |
codenvy/che-core | ide/che-core-ide-jseditor/src/main/java/org/eclipse/che/ide/jseditor/client/annotation/ListTooltipFactory.java | 3084 | /*******************************************************************************
* Copyright (c) 2012-2016 Codenvy, S.A.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Codenvy, S.A. - initial API and implementation
*******************************************************************************/
package org.eclipse.che.ide.jseditor.client.annotation;
import elemental.dom.Element;
import elemental.html.LIElement;
import org.eclipse.che.ide.ui.Tooltip;
import org.eclipse.che.ide.ui.Tooltip.Builder;
import org.eclipse.che.ide.ui.Tooltip.TooltipPositionerBuilder;
import org.eclipse.che.ide.ui.Tooltip.TooltipRenderer;
import org.eclipse.che.ide.ui.menu.PositionController;
import org.eclipse.che.ide.ui.menu.PositionController.Positioner;
import org.eclipse.che.ide.ui.menu.PositionController.PositionerBuilder;
import org.eclipse.che.ide.util.dom.Elements;
/**
* Factory for a tooltip that shows list of messages.
*/
public final class ListTooltipFactory {
private ListTooltipFactory() {
}
/** Static factory method for creating a list tooltip. */
public static Tooltip create(final Element targetElement,
final String header,
final PositionController.VerticalAlign vAlign,
final PositionController.HorizontalAlign hAlign,
final String... tooltipText) {
final PositionerBuilder positionrBuilder = new TooltipPositionerBuilder()
.setVerticalAlign(vAlign)
.setHorizontalAlign(hAlign);
final Positioner positioner = positionrBuilder.buildAnchorPositioner(targetElement);
final Builder builder = new Builder(targetElement, positioner);
builder.setTooltipRenderer(new ListRenderer(header, tooltipText));
return builder.build();
}
private static class ListRenderer implements TooltipRenderer {
private final String header;
private final String[] tooltipText;
ListRenderer(final String header, final String... tooltipText) {
this.tooltipText = tooltipText;
this.header = header;
}
@Override
public Element renderDom() {
final Element content = Elements.createSpanElement();
content.setInnerText(header);
final Element list = Elements.createUListElement();
for (final String tooltip : tooltipText) {
final LIElement item = Elements.createLiElement();
item.appendChild(Elements.createTextNode(tooltip));
list.appendChild(item);
}
content.appendChild(list);
return content;
}
}
}
| epl-1.0 |
babelomics/pvs | csvs-lib/src/main/java/org/babelomics/csvs/lib/config/CSVSConfiguration.java | 1889 | package org.babelomics.csvs.lib.config;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.babelomics.csvs.lib.models.DiseaseGroup;
import org.babelomics.csvs.lib.models.Technology;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class CSVSConfiguration {
private List<DiseaseGroup> diseasesGroups;
private List<Technology> technologies;
public CSVSConfiguration() {
}
public CSVSConfiguration(List<DiseaseGroup> diseasesGroups, List<Technology> technologies) {
this.diseasesGroups = diseasesGroups;
this.technologies = technologies;
}
public static CSVSConfiguration load(InputStream configurationInputStream) throws IOException {
ObjectMapper jsonMapper = new ObjectMapper();
CSVSConfiguration prioCNVsConfiguration =null;
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(JsonParser.Feature.AUTO_CLOSE_SOURCE, true);
try {
prioCNVsConfiguration = jsonMapper.readValue(configurationInputStream, CSVSConfiguration.class);
} catch (Exception e) {
e.printStackTrace();
}
return prioCNVsConfiguration;
}
public static CSVSConfiguration load(String nameFile) throws IOException {
InputStream io = CSVSConfiguration.class.getClassLoader().getResourceAsStream(nameFile);
return load(io);
}
public List<DiseaseGroup> getDiseasesGroups() {
return diseasesGroups;
}
public void setDiseasesGroups(List<DiseaseGroup> diseasesGroups) {
this.diseasesGroups = diseasesGroups;
}
public List<Technology> getTechnologies() {
return technologies;
}
public void setTechnologies(List<Technology> technologies) {
this.technologies = technologies;
}
}
| gpl-2.0 |
genjosanzo/galaxy-ce | gwt-client/src/main/java/org/mule/galaxy/web/client/ui/panel/AboutPanel.java | 1567 | /*
* $Id: LicenseHeader-GPLv2.txt 288 2008-05-14 00:59:35Z mark $
* --------------------------------------------------------------------------------------
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.mule.galaxy.web.client.ui.panel;
import org.mule.galaxy.web.client.ui.help.GalaxyConstants;
import com.extjs.gxt.ui.client.widget.Html;
import com.google.gwt.core.client.GWT;
/**
* Used to display version and license information
*/
public class AboutPanel extends AbstractInfoPanel {
private static final GalaxyConstants galaxyMessages = (GalaxyConstants) GWT.create(GalaxyConstants.class);
public AboutPanel() {
super();
}
public AboutPanel(int height) {
super(height);
}
public String getHeading() {
return galaxyMessages.aboutSpace();
}
@Override
public Html getText() {
return new Html();
}
}
| gpl-2.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest10269.java | 2220 | /**
* OWASP Benchmark Project v1.1
*
* This file is part of the Open Web Application Security Project (OWASP)
* Benchmark Project. For details, please see
* <a href="https://www.owasp.org/index.php/Benchmark">https://www.owasp.org/index.php/Benchmark</a>.
*
* The Benchmark is free software: you can redistribute it and/or modify it under the terms
* of the GNU General Public License as published by the Free Software Foundation, version 2.
*
* The Benchmark is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details
*
* @author Dave Wichers <a href="https://www.aspectsecurity.com">Aspect Security</a>
* @created 2015
*/
package org.owasp.benchmark.testcode;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/BenchmarkTest10269")
public class BenchmarkTest10269 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = request.getParameter("foo");
String bar = new Test().doSomething(param);
String sql = "SELECT * from USERS where USERNAME='foo' and PASSWORD='"+ bar +"'";
try {
java.sql.Statement statement = org.owasp.benchmark.helpers.DatabaseHelper.getSqlStatement();
statement.execute( sql, new int[] { 1, 2 } );
} catch (java.sql.SQLException e) {
throw new ServletException(e);
}
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar = org.owasp.esapi.ESAPI.encoder().encodeForHTML(param);
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
DigitalLabApp/Gramy | persianmaterialdatetimepicker/src/main/java/com/mohamadamin/persianmaterialdatetimepicker/utils/PersianCalendarUtils.java | 4008 | /**
* Persian Calendar see: http://code.google.com/p/persian-calendar/
Copyright (C) 2012 Mortezaadi@gmail.com
PersianCalendarUtils.java
Persian Calendar is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mohamadamin.persianmaterialdatetimepicker.utils;
/**
* algorithms for converting Julian days to the Persian calendar, and vice versa
* are adopted from <a
* href="casema.nl/couprie/calmath/persian/index.html">couprie.nl</a> written in
* VB. The algorithms is not exactly the same as its original. I've done some
* minor changes in the sake of performances and corrected some bugs.
*
* @author Morteza contact: <a
* href="mailto:Mortezaadi@gmail.com">Mortezaadi@gmail.com</a>
* @version 1.0
*
*/
public class PersianCalendarUtils {
/**
* Converts a provided Persian (Shamsi) date to the Julian Day Number (i.e.
* the number of days since January 1 in the year 4713 BC). Since the
* Persian calendar is a highly regular calendar, converting to and from a
* Julian Day Number is not as difficult as it looks. Basically it's a
* mather of dividing, rounding and multiplying. This routine uses Julian
* Day Number 1948321 as focal point, since that Julian Day Number
* corresponds with 1 Farvardin (1) 1.
*
* @param year
* int persian year
* @param month
* int persian month
* @param day
* int persian day
* @return long
*/
public static long persianToJulian(long year, int month, int day) {
return 365L * ((ceil(year - 474L, 2820D) + 474L) - 1L) + ((long) Math.floor((682L * (ceil(year - 474L, 2820D) + 474L) - 110L) / 2816D)) + (PersianCalendarConstants.PERSIAN_EPOCH - 1L) + 1029983L
* ((long) Math.floor((year - 474L) / 2820D)) + (month < 7 ? 31 * month : 30 * month + 6) + day;
}
/**
* Calculate whether current year is Leap year in persian or not
*
* @return boolean
*/
public static boolean isPersianLeapYear(int persianYear) {
return PersianCalendarUtils.ceil((38D + (PersianCalendarUtils.ceil(persianYear - 474L, 2820L) + 474L)) * 682D, 2816D) < 682L;
}
/**
* Converts a provided Julian Day Number (i.e. the number of days since
* January 1 in the year 4713 BC) to the Persian (Shamsi) date. Since the
* Persian calendar is a highly regular calendar, converting to and from a
* Julian Day Number is not as difficult as it looks. Basically it's a
* mather of dividing, rounding and multiplying.
*
* @param julianDate
* @return long
*/
public static long julianToPersian(long julianDate) {
long persianEpochInJulian = julianDate - persianToJulian(475L, 0, 1);
long cyear = ceil(persianEpochInJulian, 1029983D);
long ycycle = cyear != 1029982L ? ((long) Math.floor((2816D * (double) cyear + 1031337D) / 1028522D)) : 2820L;
long year = 474L + 2820L * ((long) Math.floor(persianEpochInJulian / 1029983D)) + ycycle;
long aux = (1L + julianDate) - persianToJulian(year, 0, 1);
int month = (int) (aux > 186L ? Math.ceil((double) (aux - 6L) / 30D) - 1 : Math.ceil((double) aux / 31D) - 1);
int day = (int) (julianDate - (persianToJulian(year, month, 1) - 1L));
return (year << 16) | (month << 8) | day;
}
/**
* Ceil function in original algorithm
*
* @param double1
* @param double2
* @return long
*/
public static long ceil(double double1, double double2) {
return (long) (double1 - double2 * Math.floor(double1 / double2));
}
}
| gpl-2.0 |
OpenSourceConsulting/gradle_sample | src/main/java/com/osc/edu/commons/employees/dao/EmployeesDao.java | 1586 | /*
* Copyright (C) 2012-2014 Open Source Consulting, Inc. All rights reserved by Open Source Consulting, Inc.
*
* 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.
*
* Revision History
* Author Date Description
* --------------- ---------------- ------------
* Sang-cheon Park 2014. 1. 7. First Draft.
*/
package com.osc.edu.commons.employees.dao;
import java.util.List;
import com.osc.edu.commons.employees.dto.EmployeesDto;
/**
* <pre>
* Data Access Object Interface for Employees table
* </pre>
* @author Sang-cheon Park
* @version 1.0
*/
public interface EmployeesDao {
public void setUseMapper(boolean useMapper);
public List<EmployeesDto> getEmployeesList();
public EmployeesDto getEmployees(Integer id);
public void insertEmployees(EmployeesDto customers);
public void updateEmployees(EmployeesDto customers);
public void deleteEmployees(Integer id);
}
//end of EmployeesDao.java | gpl-2.0 |
mixaceh/openyu-socklet | openyu-socklet-core/src/main/java/org/openyu/socklet/context/service/event/ContextAttributeEvent.java | 1397 | package org.openyu.socklet.context.service.event;
import java.util.EventListener;
import org.openyu.commons.lang.event.EventDispatchable;
import org.openyu.commons.lang.event.supporter.BaseEventSupporter;
public class ContextAttributeEvent extends BaseEventSupporter implements
EventDispatchable {
private static final long serialVersionUID = -3372946637436591911L;
public static final int ATTRIBUTE_ADDED = 1;
public static final int ATTRIBUTE_REMOVED = 2;
public static final int ATTRIBUTE_REPLACED = 3;
private String key;
private Object value;
/**
*
* @param source
* ContextService
* @param type
* @param key
* @param value
*/
public ContextAttributeEvent(Object source, int type, String key,
Object value) {
super(source, type);
this.key = key;
this.value = value;
}
/**
* 取得key
*
* @return
*/
public String getKey() {
return this.key;
}
/**
* 取得value
*
* @return
*/
public Object getValue() {
return this.value;
}
public void dispatch(EventListener listener) {
switch (getType()) {
case ATTRIBUTE_ADDED:
((ContextAttributeListener) listener).attributeAdded(this);
break;
case ATTRIBUTE_REMOVED:
((ContextAttributeListener) listener).attributeRemoved(this);
break;
case ATTRIBUTE_REPLACED:
((ContextAttributeListener) listener).attributeReplaced(this);
break;
}
}
}
| gpl-2.0 |
mots/haxsync | src/org/mots/haxsync/activities/AboutPopup.java | 866 | package org.mots.haxsync.activities;
import org.mots.haxsync.R;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.text.method.LinkMovementMethod;
import android.widget.TextView;
public class AboutPopup extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.about_popup);
TextView thanksView = (TextView) findViewById(R.id.thanksView);
thanksView.setClickable(true);
thanksView.setMovementMethod(LinkMovementMethod.getInstance());
thanksView.setText(Html.fromHtml(getString(R.string.thanks)));
/*AlertDialog.Builder dialog = new AlertDialog.Builder(this);
dialog.setMessage("Copyright (c) 2011 Mathias Roth. \n" +
"Uses Code by Sam Steele (www.c99.org) licensed under the Apache Public license.");
dialog.show();*/
}
}
| gpl-2.0 |
chenjunqian/here | Marker-Global-version/Here/app/src/main/java/com/eason/marker/emchat/chatuidemo/domain/VideoEntity.java | 184 | package com.eason.marker.emchat.chatuidemo.domain;
public class VideoEntity {
public int ID;
public String title;
public String filePath;
public int size;
public int duration;
}
| gpl-2.0 |
deathspeeder/class-guard | spring-framework-3.2.x/spring-context/src/test/java/org/springframework/jmx/export/NotificationPublisherTests.java | 7877 | /*
* Copyright 2002-2012 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.springframework.jmx.export;
import javax.management.Attribute;
import javax.management.AttributeList;
import javax.management.AttributeNotFoundException;
import javax.management.DynamicMBean;
import javax.management.InvalidAttributeValueException;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanConstructorInfo;
import javax.management.MBeanException;
import javax.management.MBeanInfo;
import javax.management.MBeanNotificationInfo;
import javax.management.MBeanOperationInfo;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationListener;
import javax.management.ReflectionException;
import org.junit.Test;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.jmx.AbstractMBeanServerTests;
import org.springframework.jmx.export.notification.NotificationPublisher;
import org.springframework.jmx.export.notification.NotificationPublisherAware;
import org.springframework.jmx.support.ObjectNameManager;
import static org.junit.Assert.*;
/**
* Integration tests for the Spring JMX {@link NotificationPublisher} functionality.
*
* @author Rob Harrop
* @author Juergen Hoeller
*/
public class NotificationPublisherTests extends AbstractMBeanServerTests {
private CountingNotificationListener listener = new CountingNotificationListener();
@Test
public void testSimpleBean() throws Exception {
// start the MBeanExporter
ConfigurableApplicationContext ctx = loadContext("org/springframework/jmx/export/notificationPublisherTests.xml");
this.server.addNotificationListener(ObjectNameManager.getInstance("spring:type=Publisher"), listener, null,
null);
MyNotificationPublisher publisher = (MyNotificationPublisher) ctx.getBean("publisher");
assertNotNull("NotificationPublisher should not be null", publisher.getNotificationPublisher());
publisher.sendNotification();
assertEquals("Notification not sent", 1, listener.count);
}
@Test
public void testSimpleBeanRegisteredManually() throws Exception {
// start the MBeanExporter
ConfigurableApplicationContext ctx = loadContext("org/springframework/jmx/export/notificationPublisherTests.xml");
MBeanExporter exporter = (MBeanExporter) ctx.getBean("exporter");
MyNotificationPublisher publisher = new MyNotificationPublisher();
exporter.registerManagedResource(publisher, ObjectNameManager.getInstance("spring:type=Publisher2"));
this.server.addNotificationListener(ObjectNameManager.getInstance("spring:type=Publisher2"), listener, null,
null);
assertNotNull("NotificationPublisher should not be null", publisher.getNotificationPublisher());
publisher.sendNotification();
assertEquals("Notification not sent", 1, listener.count);
}
@Test
public void testMBean() throws Exception {
// start the MBeanExporter
ConfigurableApplicationContext ctx = loadContext("org/springframework/jmx/export/notificationPublisherTests.xml");
this.server.addNotificationListener(ObjectNameManager.getInstance("spring:type=PublisherMBean"), listener,
null, null);
MyNotificationPublisherMBean publisher = (MyNotificationPublisherMBean) ctx.getBean("publisherMBean");
publisher.sendNotification();
assertEquals("Notification not sent", 1, listener.count);
}
/*
@Test
public void testStandardMBean() throws Exception {
// start the MBeanExporter
ApplicationContext ctx = new ClassPathXmlApplicationContext("org/springframework/jmx/export/notificationPublisherTests.xml");
this.server.addNotificationListener(ObjectNameManager.getInstance("spring:type=PublisherStandardMBean"), listener, null, null);
MyNotificationPublisherStandardMBean publisher = (MyNotificationPublisherStandardMBean) ctx.getBean("publisherStandardMBean");
publisher.sendNotification();
assertEquals("Notification not sent", 1, listener.count);
}
*/
@Test
public void testLazyInit() throws Exception {
// start the MBeanExporter
ConfigurableApplicationContext ctx = loadContext("org/springframework/jmx/export/notificationPublisherLazyTests.xml");
assertFalse("Should not have instantiated the bean yet", ctx.getBeanFactory().containsSingleton("publisher"));
// need to touch the MBean proxy
server.getAttribute(ObjectNameManager.getInstance("spring:type=Publisher"), "Name");
this.server.addNotificationListener(ObjectNameManager.getInstance("spring:type=Publisher"), listener, null,
null);
MyNotificationPublisher publisher = (MyNotificationPublisher) ctx.getBean("publisher");
assertNotNull("NotificationPublisher should not be null", publisher.getNotificationPublisher());
publisher.sendNotification();
assertEquals("Notification not sent", 1, listener.count);
}
private static class CountingNotificationListener implements NotificationListener {
private int count;
private Notification lastNotification;
@Override
public void handleNotification(Notification notification, Object handback) {
this.lastNotification = notification;
this.count++;
}
@SuppressWarnings("unused")
public int getCount() {
return count;
}
@SuppressWarnings("unused")
public Notification getLastNotification() {
return lastNotification;
}
}
public static class MyNotificationPublisher implements NotificationPublisherAware {
private NotificationPublisher notificationPublisher;
@Override
public void setNotificationPublisher(NotificationPublisher notificationPublisher) {
this.notificationPublisher = notificationPublisher;
}
public NotificationPublisher getNotificationPublisher() {
return notificationPublisher;
}
public void sendNotification() {
this.notificationPublisher.sendNotification(new Notification("test", this, 1));
}
public String getName() {
return "Rob Harrop";
}
}
public static class MyNotificationPublisherMBean extends NotificationBroadcasterSupport implements DynamicMBean {
@Override
public Object getAttribute(String attribute) throws AttributeNotFoundException, MBeanException,
ReflectionException {
return null;
}
@Override
public void setAttribute(Attribute attribute) throws AttributeNotFoundException,
InvalidAttributeValueException, MBeanException, ReflectionException {
}
@Override
public AttributeList getAttributes(String[] attributes) {
return null;
}
@Override
public AttributeList setAttributes(AttributeList attributes) {
return null;
}
@Override
public Object invoke(String actionName, Object params[], String signature[]) throws MBeanException,
ReflectionException {
return null;
}
@Override
public MBeanInfo getMBeanInfo() {
return new MBeanInfo(MyNotificationPublisherMBean.class.getName(), "", new MBeanAttributeInfo[0],
new MBeanConstructorInfo[0], new MBeanOperationInfo[0], new MBeanNotificationInfo[0]);
}
public void sendNotification() {
sendNotification(new Notification("test", this, 1));
}
}
public static class MyNotificationPublisherStandardMBean extends NotificationBroadcasterSupport implements MyMBean {
@Override
public void sendNotification() {
sendNotification(new Notification("test", this, 1));
}
}
public interface MyMBean {
void sendNotification();
}
}
| gpl-2.0 |
shane-axiom/SOS | coding/sensorML-v20/src/main/java/org/n52/sos/encode/Iso19139GcoEncoder.java | 4426 | /**
* Copyright (C) 2012-2015 52°North Initiative for Geospatial Open Source
* Software GmbH
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published
* by the Free Software Foundation.
*
* If the program is linked with libraries which are licensed under one of
* the following licenses, the combination of the program with the linked
* library is not considered a "derivative work" of the program:
*
* - Apache License, version 2.0
* - Apache Software License, version 1.0
* - GNU Lesser General Public License, version 3
* - Mozilla Public License, versions 1.0, 1.1 and 2.0
* - Common Development and Distribution License (CDDL), version 1.0
*
* Therefore the distribution of the program linked with libraries licensed
* under the aforementioned licenses, is permitted by the copyright holders
* if the distribution is compliant with both the GNU General Public
* License version 2 and the aforementioned licenses.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*/
package org.n52.sos.encode;
import static org.n52.sos.util.CodingHelper.encoderKeysForElements;
import static org.n52.sos.util.CollectionHelper.union;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.apache.xmlbeans.XmlObject;
import org.isotc211.x2005.gco.CodeListValueType;
import org.n52.sos.Role;
import org.n52.sos.exception.ows.concrete.UnsupportedEncoderInputException;
import org.n52.sos.iso.GcoConstants;
import org.n52.sos.ogc.ows.OwsExceptionReport;
import org.n52.sos.ogc.sos.SosConstants.HelperValues;
import org.n52.sos.service.ServiceConstants.SupportedTypeKey;
import org.n52.sos.util.XmlHelper;
import org.n52.sos.util.XmlOptionsHelper;
import org.n52.sos.w3c.SchemaLocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Joiner;
import com.google.common.collect.Sets;
/**
* {@link AbstractXmlEncoder} class to decode ISO TC211 Geographic COmmon (GCO) extensible
* markup language.
*
* @author Carsten Hollmann <c.hollmann@52north.org>
* @since 4.2.0
*
*/
public class Iso19139GcoEncoder extends AbstractXmlEncoder<Object> {
private static final Logger LOGGER = LoggerFactory.getLogger(Iso19139GcoEncoder.class);
@SuppressWarnings("unchecked")
private static final Set<EncoderKey> ENCODER_KEYS = union(encoderKeysForElements(GcoConstants.NS_GCO,
Role.class));
public Iso19139GcoEncoder() {
LOGGER.debug("Encoder for the following keys initialized successfully: {}!", Joiner.on(", ")
.join(ENCODER_KEYS));
}
@Override
public Set<EncoderKey> getEncoderKeyType() {
return Collections.unmodifiableSet(ENCODER_KEYS);
}
@Override
public Map<SupportedTypeKey, Set<String>> getSupportedTypes() {
return Collections.emptyMap();
}
@Override
public void addNamespacePrefixToMap(final Map<String, String> nameSpacePrefixMap) {
nameSpacePrefixMap.put(GcoConstants.NS_GCO, GcoConstants.NS_GCO_PREFIX);
}
@Override
public Set<SchemaLocation> getSchemaLocations() {
return Sets.newHashSet(GcoConstants.GCO_SCHEMA_LOCATION);
}
@Override
public XmlObject encode(Object element, Map<HelperValues, String> additionalValues) throws OwsExceptionReport,
UnsupportedEncoderInputException {
XmlObject encodedObject = null;
if (element instanceof Role) {
encodedObject = encodeRole((Role) element);
} else {
throw new UnsupportedEncoderInputException(this, element);
}
LOGGER.debug("Encoded object {} is valid: {}", encodedObject.schemaType().toString(),
XmlHelper.validateDocument(encodedObject));
return encodedObject;
}
private XmlObject encodeRole(Role role) {
CodeListValueType circ =
CodeListValueType.Factory.newInstance(XmlOptionsHelper.getInstance().getXmlOptions());
circ.setStringValue(role.getValue());
circ.setCodeList(role.getCodeList());
circ.setCodeListValue(role.getCodeListValue());
return circ;
}
}
| gpl-2.0 |
universsky/openjdk | jdk/src/java.base/share/classes/sun/reflect/annotation/AnnotationParser.java | 34917 | /*
* Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package sun.reflect.annotation;
import java.lang.annotation.*;
import java.util.*;
import java.nio.ByteBuffer;
import java.nio.BufferUnderflowException;
import java.lang.reflect.*;
import java.security.AccessController;
import java.security.PrivilegedAction;
import sun.reflect.ConstantPool;
import sun.reflect.generics.parser.SignatureParser;
import sun.reflect.generics.tree.TypeSignature;
import sun.reflect.generics.factory.GenericsFactory;
import sun.reflect.generics.factory.CoreReflectionFactory;
import sun.reflect.generics.visitor.Reifier;
import sun.reflect.generics.scope.ClassScope;
/**
* Parser for Java programming language annotations. Translates
* annotation byte streams emitted by compiler into annotation objects.
*
* @author Josh Bloch
* @since 1.5
*/
public class AnnotationParser {
/**
* Parses the annotations described by the specified byte array.
* resolving constant references in the specified constant pool.
* The array must contain an array of annotations as described
* in the RuntimeVisibleAnnotations_attribute:
*
* u2 num_annotations;
* annotation annotations[num_annotations];
*
* @throws AnnotationFormatError if an annotation is found to be
* malformed.
*/
public static Map<Class<? extends Annotation>, Annotation> parseAnnotations(
byte[] rawAnnotations,
ConstantPool constPool,
Class<?> container) {
if (rawAnnotations == null)
return Collections.emptyMap();
try {
return parseAnnotations2(rawAnnotations, constPool, container, null);
} catch(BufferUnderflowException e) {
throw new AnnotationFormatError("Unexpected end of annotations.");
} catch(IllegalArgumentException e) {
// Type mismatch in constant pool
throw new AnnotationFormatError(e);
}
}
/**
* Like {@link #parseAnnotations(byte[], sun.reflect.ConstantPool, Class)}
* with an additional parameter {@code selectAnnotationClasses} which selects the
* annotation types to parse (other than selected are quickly skipped).<p>
* This method is only used to parse select meta annotations in the construction
* phase of {@link AnnotationType} instances to prevent infinite recursion.
*
* @param selectAnnotationClasses an array of annotation types to select when parsing
*/
@SafeVarargs
@SuppressWarnings("varargs") // selectAnnotationClasses is used safely
static Map<Class<? extends Annotation>, Annotation> parseSelectAnnotations(
byte[] rawAnnotations,
ConstantPool constPool,
Class<?> container,
Class<? extends Annotation> ... selectAnnotationClasses) {
if (rawAnnotations == null)
return Collections.emptyMap();
try {
return parseAnnotations2(rawAnnotations, constPool, container, selectAnnotationClasses);
} catch(BufferUnderflowException e) {
throw new AnnotationFormatError("Unexpected end of annotations.");
} catch(IllegalArgumentException e) {
// Type mismatch in constant pool
throw new AnnotationFormatError(e);
}
}
private static Map<Class<? extends Annotation>, Annotation> parseAnnotations2(
byte[] rawAnnotations,
ConstantPool constPool,
Class<?> container,
Class<? extends Annotation>[] selectAnnotationClasses) {
Map<Class<? extends Annotation>, Annotation> result =
new LinkedHashMap<Class<? extends Annotation>, Annotation>();
ByteBuffer buf = ByteBuffer.wrap(rawAnnotations);
int numAnnotations = buf.getShort() & 0xFFFF;
for (int i = 0; i < numAnnotations; i++) {
Annotation a = parseAnnotation2(buf, constPool, container, false, selectAnnotationClasses);
if (a != null) {
Class<? extends Annotation> klass = a.annotationType();
if (AnnotationType.getInstance(klass).retention() == RetentionPolicy.RUNTIME &&
result.put(klass, a) != null) {
throw new AnnotationFormatError(
"Duplicate annotation for class: "+klass+": " + a);
}
}
}
return result;
}
/**
* Parses the parameter annotations described by the specified byte array.
* resolving constant references in the specified constant pool.
* The array must contain an array of annotations as described
* in the RuntimeVisibleParameterAnnotations_attribute:
*
* u1 num_parameters;
* {
* u2 num_annotations;
* annotation annotations[num_annotations];
* } parameter_annotations[num_parameters];
*
* Unlike parseAnnotations, rawAnnotations must not be null!
* A null value must be handled by the caller. This is so because
* we cannot determine the number of parameters if rawAnnotations
* is null. Also, the caller should check that the number
* of parameters indicated by the return value of this method
* matches the actual number of method parameters. A mismatch
* indicates that an AnnotationFormatError should be thrown.
*
* @throws AnnotationFormatError if an annotation is found to be
* malformed.
*/
public static Annotation[][] parseParameterAnnotations(
byte[] rawAnnotations,
ConstantPool constPool,
Class<?> container) {
try {
return parseParameterAnnotations2(rawAnnotations, constPool, container);
} catch(BufferUnderflowException e) {
throw new AnnotationFormatError(
"Unexpected end of parameter annotations.");
} catch(IllegalArgumentException e) {
// Type mismatch in constant pool
throw new AnnotationFormatError(e);
}
}
private static Annotation[][] parseParameterAnnotations2(
byte[] rawAnnotations,
ConstantPool constPool,
Class<?> container) {
ByteBuffer buf = ByteBuffer.wrap(rawAnnotations);
int numParameters = buf.get() & 0xFF;
Annotation[][] result = new Annotation[numParameters][];
for (int i = 0; i < numParameters; i++) {
int numAnnotations = buf.getShort() & 0xFFFF;
List<Annotation> annotations =
new ArrayList<Annotation>(numAnnotations);
for (int j = 0; j < numAnnotations; j++) {
Annotation a = parseAnnotation(buf, constPool, container, false);
if (a != null) {
AnnotationType type = AnnotationType.getInstance(
a.annotationType());
if (type.retention() == RetentionPolicy.RUNTIME)
annotations.add(a);
}
}
result[i] = annotations.toArray(EMPTY_ANNOTATIONS_ARRAY);
}
return result;
}
private static final Annotation[] EMPTY_ANNOTATIONS_ARRAY =
new Annotation[0];
/**
* Parses the annotation at the current position in the specified
* byte buffer, resolving constant references in the specified constant
* pool. The cursor of the byte buffer must point to an "annotation
* structure" as described in the RuntimeVisibleAnnotations_attribute:
*
* annotation {
* u2 type_index;
* u2 num_member_value_pairs;
* { u2 member_name_index;
* member_value value;
* } member_value_pairs[num_member_value_pairs];
* }
* }
*
* Returns the annotation, or null if the annotation's type cannot
* be found by the VM, or is not a valid annotation type.
*
* @param exceptionOnMissingAnnotationClass if true, throw
* TypeNotPresentException if a referenced annotation type is not
* available at runtime
*/
static Annotation parseAnnotation(ByteBuffer buf,
ConstantPool constPool,
Class<?> container,
boolean exceptionOnMissingAnnotationClass) {
return parseAnnotation2(buf, constPool, container, exceptionOnMissingAnnotationClass, null);
}
@SuppressWarnings("unchecked")
private static Annotation parseAnnotation2(ByteBuffer buf,
ConstantPool constPool,
Class<?> container,
boolean exceptionOnMissingAnnotationClass,
Class<? extends Annotation>[] selectAnnotationClasses) {
int typeIndex = buf.getShort() & 0xFFFF;
Class<? extends Annotation> annotationClass = null;
String sig = "[unknown]";
try {
try {
sig = constPool.getUTF8At(typeIndex);
annotationClass = (Class<? extends Annotation>)parseSig(sig, container);
} catch (IllegalArgumentException ex) {
// support obsolete early jsr175 format class files
annotationClass = (Class<? extends Annotation>)constPool.getClassAt(typeIndex);
}
} catch (NoClassDefFoundError e) {
if (exceptionOnMissingAnnotationClass)
// note: at this point sig is "[unknown]" or VM-style
// name instead of a binary name
throw new TypeNotPresentException(sig, e);
skipAnnotation(buf, false);
return null;
}
catch (TypeNotPresentException e) {
if (exceptionOnMissingAnnotationClass)
throw e;
skipAnnotation(buf, false);
return null;
}
if (selectAnnotationClasses != null && !contains(selectAnnotationClasses, annotationClass)) {
skipAnnotation(buf, false);
return null;
}
AnnotationType type = null;
try {
type = AnnotationType.getInstance(annotationClass);
} catch (IllegalArgumentException e) {
skipAnnotation(buf, false);
return null;
}
Map<String, Class<?>> memberTypes = type.memberTypes();
Map<String, Object> memberValues =
new LinkedHashMap<String, Object>(type.memberDefaults());
int numMembers = buf.getShort() & 0xFFFF;
for (int i = 0; i < numMembers; i++) {
int memberNameIndex = buf.getShort() & 0xFFFF;
String memberName = constPool.getUTF8At(memberNameIndex);
Class<?> memberType = memberTypes.get(memberName);
if (memberType == null) {
// Member is no longer present in annotation type; ignore it
skipMemberValue(buf);
} else {
Object value = parseMemberValue(memberType, buf, constPool, container);
if (value instanceof AnnotationTypeMismatchExceptionProxy)
((AnnotationTypeMismatchExceptionProxy) value).
setMember(type.members().get(memberName));
memberValues.put(memberName, value);
}
}
return annotationForMap(annotationClass, memberValues);
}
/**
* Returns an annotation of the given type backed by the given
* member {@literal ->} value map.
*/
public static Annotation annotationForMap(final Class<? extends Annotation> type,
final Map<String, Object> memberValues)
{
return AccessController.doPrivileged(new PrivilegedAction<Annotation>() {
public Annotation run() {
return (Annotation) Proxy.newProxyInstance(
type.getClassLoader(), new Class<?>[] { type },
new AnnotationInvocationHandler(type, memberValues));
}});
}
/**
* Parses the annotation member value at the current position in the
* specified byte buffer, resolving constant references in the specified
* constant pool. The cursor of the byte buffer must point to a
* "member_value structure" as described in the
* RuntimeVisibleAnnotations_attribute:
*
* member_value {
* u1 tag;
* union {
* u2 const_value_index;
* {
* u2 type_name_index;
* u2 const_name_index;
* } enum_const_value;
* u2 class_info_index;
* annotation annotation_value;
* {
* u2 num_values;
* member_value values[num_values];
* } array_value;
* } value;
* }
*
* The member must be of the indicated type. If it is not, this
* method returns an AnnotationTypeMismatchExceptionProxy.
*/
@SuppressWarnings("unchecked")
public static Object parseMemberValue(Class<?> memberType,
ByteBuffer buf,
ConstantPool constPool,
Class<?> container) {
Object result = null;
int tag = buf.get();
switch(tag) {
case 'e':
return parseEnumValue((Class<? extends Enum<?>>)memberType, buf, constPool, container);
case 'c':
result = parseClassValue(buf, constPool, container);
break;
case '@':
result = parseAnnotation(buf, constPool, container, true);
break;
case '[':
return parseArray(memberType, buf, constPool, container);
default:
result = parseConst(tag, buf, constPool);
}
if (!(result instanceof ExceptionProxy) &&
!memberType.isInstance(result))
result = new AnnotationTypeMismatchExceptionProxy(
result.getClass() + "[" + result + "]");
return result;
}
/**
* Parses the primitive or String annotation member value indicated by
* the specified tag byte at the current position in the specified byte
* buffer, resolving constant reference in the specified constant pool.
* The cursor of the byte buffer must point to an annotation member value
* of the type indicated by the specified tag, as described in the
* RuntimeVisibleAnnotations_attribute:
*
* u2 const_value_index;
*/
private static Object parseConst(int tag,
ByteBuffer buf, ConstantPool constPool) {
int constIndex = buf.getShort() & 0xFFFF;
switch(tag) {
case 'B':
return Byte.valueOf((byte) constPool.getIntAt(constIndex));
case 'C':
return Character.valueOf((char) constPool.getIntAt(constIndex));
case 'D':
return Double.valueOf(constPool.getDoubleAt(constIndex));
case 'F':
return Float.valueOf(constPool.getFloatAt(constIndex));
case 'I':
return Integer.valueOf(constPool.getIntAt(constIndex));
case 'J':
return Long.valueOf(constPool.getLongAt(constIndex));
case 'S':
return Short.valueOf((short) constPool.getIntAt(constIndex));
case 'Z':
return Boolean.valueOf(constPool.getIntAt(constIndex) != 0);
case 's':
return constPool.getUTF8At(constIndex);
default:
throw new AnnotationFormatError(
"Invalid member-value tag in annotation: " + tag);
}
}
/**
* Parses the Class member value at the current position in the
* specified byte buffer, resolving constant references in the specified
* constant pool. The cursor of the byte buffer must point to a "class
* info index" as described in the RuntimeVisibleAnnotations_attribute:
*
* u2 class_info_index;
*/
private static Object parseClassValue(ByteBuffer buf,
ConstantPool constPool,
Class<?> container) {
int classIndex = buf.getShort() & 0xFFFF;
try {
try {
String sig = constPool.getUTF8At(classIndex);
return parseSig(sig, container);
} catch (IllegalArgumentException ex) {
// support obsolete early jsr175 format class files
return constPool.getClassAt(classIndex);
}
} catch (NoClassDefFoundError e) {
return new TypeNotPresentExceptionProxy("[unknown]", e);
}
catch (TypeNotPresentException e) {
return new TypeNotPresentExceptionProxy(e.typeName(), e.getCause());
}
}
private static Class<?> parseSig(String sig, Class<?> container) {
if (sig.equals("V")) return void.class;
SignatureParser parser = SignatureParser.make();
TypeSignature typeSig = parser.parseTypeSig(sig);
GenericsFactory factory = CoreReflectionFactory.make(container, ClassScope.make(container));
Reifier reify = Reifier.make(factory);
typeSig.accept(reify);
Type result = reify.getResult();
return toClass(result);
}
static Class<?> toClass(Type o) {
if (o instanceof GenericArrayType)
return Array.newInstance(toClass(((GenericArrayType)o).getGenericComponentType()),
0)
.getClass();
return (Class)o;
}
/**
* Parses the enum constant member value at the current position in the
* specified byte buffer, resolving constant references in the specified
* constant pool. The cursor of the byte buffer must point to a
* "enum_const_value structure" as described in the
* RuntimeVisibleAnnotations_attribute:
*
* {
* u2 type_name_index;
* u2 const_name_index;
* } enum_const_value;
*/
@SuppressWarnings({"rawtypes", "unchecked"})
private static Object parseEnumValue(Class<? extends Enum> enumType, ByteBuffer buf,
ConstantPool constPool,
Class<?> container) {
int typeNameIndex = buf.getShort() & 0xFFFF;
String typeName = constPool.getUTF8At(typeNameIndex);
int constNameIndex = buf.getShort() & 0xFFFF;
String constName = constPool.getUTF8At(constNameIndex);
if (!typeName.endsWith(";")) {
// support now-obsolete early jsr175-format class files.
if (!enumType.getName().equals(typeName))
return new AnnotationTypeMismatchExceptionProxy(
typeName + "." + constName);
} else if (enumType != parseSig(typeName, container)) {
return new AnnotationTypeMismatchExceptionProxy(
typeName + "." + constName);
}
try {
return Enum.valueOf(enumType, constName);
} catch(IllegalArgumentException e) {
return new EnumConstantNotPresentExceptionProxy(
(Class<? extends Enum<?>>)enumType, constName);
}
}
/**
* Parses the array value at the current position in the specified byte
* buffer, resolving constant references in the specified constant pool.
* The cursor of the byte buffer must point to an array value struct
* as specified in the RuntimeVisibleAnnotations_attribute:
*
* {
* u2 num_values;
* member_value values[num_values];
* } array_value;
*
* If the array values do not match arrayType, an
* AnnotationTypeMismatchExceptionProxy will be returned.
*/
@SuppressWarnings("unchecked")
private static Object parseArray(Class<?> arrayType,
ByteBuffer buf,
ConstantPool constPool,
Class<?> container) {
int length = buf.getShort() & 0xFFFF; // Number of array components
Class<?> componentType = arrayType.getComponentType();
if (componentType == byte.class) {
return parseByteArray(length, buf, constPool);
} else if (componentType == char.class) {
return parseCharArray(length, buf, constPool);
} else if (componentType == double.class) {
return parseDoubleArray(length, buf, constPool);
} else if (componentType == float.class) {
return parseFloatArray(length, buf, constPool);
} else if (componentType == int.class) {
return parseIntArray(length, buf, constPool);
} else if (componentType == long.class) {
return parseLongArray(length, buf, constPool);
} else if (componentType == short.class) {
return parseShortArray(length, buf, constPool);
} else if (componentType == boolean.class) {
return parseBooleanArray(length, buf, constPool);
} else if (componentType == String.class) {
return parseStringArray(length, buf, constPool);
} else if (componentType == Class.class) {
return parseClassArray(length, buf, constPool, container);
} else if (componentType.isEnum()) {
return parseEnumArray(length, (Class<? extends Enum<?>>)componentType, buf,
constPool, container);
} else {
assert componentType.isAnnotation();
return parseAnnotationArray(length, (Class <? extends Annotation>)componentType, buf,
constPool, container);
}
}
private static Object parseByteArray(int length,
ByteBuffer buf, ConstantPool constPool) {
byte[] result = new byte[length];
boolean typeMismatch = false;
int tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == 'B') {
int index = buf.getShort() & 0xFFFF;
result[i] = (byte) constPool.getIntAt(index);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
private static Object parseCharArray(int length,
ByteBuffer buf, ConstantPool constPool) {
char[] result = new char[length];
boolean typeMismatch = false;
byte tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == 'C') {
int index = buf.getShort() & 0xFFFF;
result[i] = (char) constPool.getIntAt(index);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
private static Object parseDoubleArray(int length,
ByteBuffer buf, ConstantPool constPool) {
double[] result = new double[length];
boolean typeMismatch = false;
int tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == 'D') {
int index = buf.getShort() & 0xFFFF;
result[i] = constPool.getDoubleAt(index);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
private static Object parseFloatArray(int length,
ByteBuffer buf, ConstantPool constPool) {
float[] result = new float[length];
boolean typeMismatch = false;
int tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == 'F') {
int index = buf.getShort() & 0xFFFF;
result[i] = constPool.getFloatAt(index);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
private static Object parseIntArray(int length,
ByteBuffer buf, ConstantPool constPool) {
int[] result = new int[length];
boolean typeMismatch = false;
int tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == 'I') {
int index = buf.getShort() & 0xFFFF;
result[i] = constPool.getIntAt(index);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
private static Object parseLongArray(int length,
ByteBuffer buf, ConstantPool constPool) {
long[] result = new long[length];
boolean typeMismatch = false;
int tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == 'J') {
int index = buf.getShort() & 0xFFFF;
result[i] = constPool.getLongAt(index);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
private static Object parseShortArray(int length,
ByteBuffer buf, ConstantPool constPool) {
short[] result = new short[length];
boolean typeMismatch = false;
int tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == 'S') {
int index = buf.getShort() & 0xFFFF;
result[i] = (short) constPool.getIntAt(index);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
private static Object parseBooleanArray(int length,
ByteBuffer buf, ConstantPool constPool) {
boolean[] result = new boolean[length];
boolean typeMismatch = false;
int tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == 'Z') {
int index = buf.getShort() & 0xFFFF;
result[i] = (constPool.getIntAt(index) != 0);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
private static Object parseStringArray(int length,
ByteBuffer buf, ConstantPool constPool) {
String[] result = new String[length];
boolean typeMismatch = false;
int tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == 's') {
int index = buf.getShort() & 0xFFFF;
result[i] = constPool.getUTF8At(index);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
private static Object parseClassArray(int length,
ByteBuffer buf,
ConstantPool constPool,
Class<?> container) {
Object[] result = new Class<?>[length];
boolean typeMismatch = false;
int tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == 'c') {
result[i] = parseClassValue(buf, constPool, container);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
private static Object parseEnumArray(int length, Class<? extends Enum<?>> enumType,
ByteBuffer buf,
ConstantPool constPool,
Class<?> container) {
Object[] result = (Object[]) Array.newInstance(enumType, length);
boolean typeMismatch = false;
int tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == 'e') {
result[i] = parseEnumValue(enumType, buf, constPool, container);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
private static Object parseAnnotationArray(int length,
Class<? extends Annotation> annotationType,
ByteBuffer buf,
ConstantPool constPool,
Class<?> container) {
Object[] result = (Object[]) Array.newInstance(annotationType, length);
boolean typeMismatch = false;
int tag = 0;
for (int i = 0; i < length; i++) {
tag = buf.get();
if (tag == '@') {
result[i] = parseAnnotation(buf, constPool, container, true);
} else {
skipMemberValue(tag, buf);
typeMismatch = true;
}
}
return typeMismatch ? exceptionProxy(tag) : result;
}
/**
* Returns an appropriate exception proxy for a mismatching array
* annotation where the erroneous array has the specified tag.
*/
private static ExceptionProxy exceptionProxy(int tag) {
return new AnnotationTypeMismatchExceptionProxy(
"Array with component tag: " + tag);
}
/**
* Skips the annotation at the current position in the specified
* byte buffer. The cursor of the byte buffer must point to
* an "annotation structure" OR two bytes into an annotation
* structure (i.e., after the type index).
*
* @parameter complete true if the byte buffer points to the beginning
* of an annotation structure (rather than two bytes in).
*/
private static void skipAnnotation(ByteBuffer buf, boolean complete) {
if (complete)
buf.getShort(); // Skip type index
int numMembers = buf.getShort() & 0xFFFF;
for (int i = 0; i < numMembers; i++) {
buf.getShort(); // Skip memberNameIndex
skipMemberValue(buf);
}
}
/**
* Skips the annotation member value at the current position in the
* specified byte buffer. The cursor of the byte buffer must point to a
* "member_value structure."
*/
private static void skipMemberValue(ByteBuffer buf) {
int tag = buf.get();
skipMemberValue(tag, buf);
}
/**
* Skips the annotation member value at the current position in the
* specified byte buffer. The cursor of the byte buffer must point
* immediately after the tag in a "member_value structure."
*/
private static void skipMemberValue(int tag, ByteBuffer buf) {
switch(tag) {
case 'e': // Enum value
buf.getInt(); // (Two shorts, actually.)
break;
case '@':
skipAnnotation(buf, true);
break;
case '[':
skipArray(buf);
break;
default:
// Class, primitive, or String
buf.getShort();
}
}
/**
* Skips the array value at the current position in the specified byte
* buffer. The cursor of the byte buffer must point to an array value
* struct.
*/
private static void skipArray(ByteBuffer buf) {
int length = buf.getShort() & 0xFFFF;
for (int i = 0; i < length; i++)
skipMemberValue(buf);
}
/**
* Searches for given {@code element} in given {@code array} by identity.
* Returns {@code true} if found {@code false} if not.
*/
private static boolean contains(Object[] array, Object element) {
for (Object e : array)
if (e == element)
return true;
return false;
}
/*
* This method converts the annotation map returned by the parseAnnotations()
* method to an array. It is called by Field.getDeclaredAnnotations(),
* Method.getDeclaredAnnotations(), and Constructor.getDeclaredAnnotations().
* This avoids the reflection classes to load the Annotation class until
* it is needed.
*/
private static final Annotation[] EMPTY_ANNOTATION_ARRAY = new Annotation[0];
public static Annotation[] toArray(Map<Class<? extends Annotation>, Annotation> annotations) {
return annotations.values().toArray(EMPTY_ANNOTATION_ARRAY);
}
static Annotation[] getEmptyAnnotationArray() { return EMPTY_ANNOTATION_ARRAY; }
}
| gpl-2.0 |
du-lab/mzmine2 | src/main/java/net/sf/mzmine/modules/rawdatamethods/peakpicking/manual/ManualPickerTask.java | 5084 | /*
* Copyright 2006-2018 The MZmine 2 Development Team
*
* This file is part of MZmine 2.
*
* MZmine 2 is free software; you can redistribute it and/or modify it under the terms of the GNU
* General Public License as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
* even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License along with MZmine 2; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.sf.mzmine.modules.rawdatamethods.peakpicking.manual;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.table.AbstractTableModel;
import net.sf.mzmine.datamodel.DataPoint;
import net.sf.mzmine.datamodel.MZmineProject;
import net.sf.mzmine.datamodel.PeakList;
import net.sf.mzmine.datamodel.PeakListRow;
import net.sf.mzmine.datamodel.RawDataFile;
import net.sf.mzmine.datamodel.Scan;
import net.sf.mzmine.datamodel.impl.SimpleDataPoint;
import net.sf.mzmine.modules.peaklistmethods.qualityparameters.QualityParameters;
import net.sf.mzmine.modules.visualization.peaklisttable.table.PeakListTable;
import net.sf.mzmine.taskcontrol.AbstractTask;
import net.sf.mzmine.taskcontrol.TaskStatus;
import net.sf.mzmine.util.scans.ScanUtils;
import com.google.common.collect.Range;
class ManualPickerTask extends AbstractTask {
private Logger logger = Logger.getLogger(this.getClass().getName());
private int processedScans, totalScans;
private final MZmineProject project;
private final PeakListTable table;
private final PeakList peakList;
private PeakListRow peakListRow;
private RawDataFile dataFiles[];
private Range<Double> rtRange, mzRange;
ManualPickerTask(MZmineProject project, PeakListRow peakListRow, RawDataFile dataFiles[],
ManualPickerParameters parameters, PeakList peakList, PeakListTable table) {
this.project = project;
this.peakListRow = peakListRow;
this.dataFiles = dataFiles;
this.peakList = peakList;
this.table = table;
rtRange = parameters.getParameter(ManualPickerParameters.retentionTimeRange).getValue();
mzRange = parameters.getParameter(ManualPickerParameters.mzRange).getValue();
}
public double getFinishedPercentage() {
if (totalScans == 0)
return 0;
return (double) processedScans / totalScans;
}
public String getTaskDescription() {
return "Manually picking peaks from " + Arrays.toString(dataFiles);
}
public void run() {
setStatus(TaskStatus.PROCESSING);
logger.finest("Starting manual peak picker, RT: " + rtRange + ", m/z: " + mzRange);
// Calculate total number of scans to process
for (RawDataFile dataFile : dataFiles) {
int[] scanNumbers = dataFile.getScanNumbers(1, rtRange);
totalScans += scanNumbers.length;
}
// Find peak in each data file
for (RawDataFile dataFile : dataFiles) {
ManualPeak newPeak = new ManualPeak(dataFile);
boolean dataPointFound = false;
int[] scanNumbers = dataFile.getScanNumbers(1, rtRange);
for (int scanNumber : scanNumbers) {
if (isCanceled())
return;
// Get next scan
Scan scan = dataFile.getScan(scanNumber);
// Find most intense m/z peak
DataPoint basePeak = ScanUtils.findBasePeak(scan, mzRange);
if (basePeak != null) {
if (basePeak.getIntensity() > 0)
dataPointFound = true;
newPeak.addDatapoint(scan.getScanNumber(), basePeak);
} else {
final double mzCenter = (mzRange.lowerEndpoint() + mzRange.upperEndpoint()) / 2.0;
DataPoint fakeDataPoint = new SimpleDataPoint(mzCenter, 0);
newPeak.addDatapoint(scan.getScanNumber(), fakeDataPoint);
}
processedScans++;
}
if (dataPointFound) {
newPeak.finalizePeak();
if (newPeak.getArea() > 0)
peakListRow.addPeak(dataFile, newPeak);
} else {
peakListRow.removePeak(dataFile);
}
}
// Notify the GUI that peaklist contents have changed
if (peakList != null) {
// Check if the feature list row has been added to the feature list, and
// if it has not, add it
List<PeakListRow> rows = Arrays.asList(peakList.getRows());
if (!rows.contains(peakListRow)) {
peakList.addRow(peakListRow);
}
// Add quality parameters to peaks
QualityParameters.calculateQualityParameters(peakList);
project.notifyObjectChanged(peakList, true);
}
if (table != null) {
((AbstractTableModel) table.getModel()).fireTableDataChanged();
}
logger.finest("Finished manual peak picker, " + processedScans + " scans processed");
setStatus(TaskStatus.FINISHED);
}
}
| gpl-2.0 |
Decentrify/GVoD | manager/src/main/java/se/sics/gvod/manager/gson/FileDescriptorAdapter.java | 1821 | ///*
// * Copyright (C) 2009 Swedish Institute of Computer Science (SICS) Copyright (C)
// * 2009 Royal Institute of Technology (KTH)
// *
// * GVoD is free software; you can redistribute it and/or
// * modify it under the terms of the GNU General Public License
// * as published by the Free Software Foundation; either version 2
// * of the License, or (at your option) any later version.
// *
// * This program is distributed in the hope that it will be useful,
// * but WITHOUT ANY WARRANTY; without even the implied warranty of
// * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// * GNU General Public License for more details.
// *
// * You should have received a copy of the GNU General Public License
// * along with this program; if not, write to the Free Software
// * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
// */
//
//package se.sics.gvod.manager.gson;
//
//import com.google.gson.TypeAdapter;
//import com.google.gson.stream.JsonReader;
//import com.google.gson.stream.JsonWriter;
//import java.io.IOException;
//import se.sics.gvod.manager.FileDescriptor;
//
///**
// * @author Alex Ormenisan <aaor@sics.se>
// */
//public class FileDescriptorAdapter extends TypeAdapter<FileDescriptor> {
//
// @Override
// public void write(JsonWriter writer, FileDescriptor file) throws IOException {
// writer.beginObject();
// writer.name("path").value(file.path);
// writer.name("name").value(file.name);
// writer.name("size").value(file.size);
// writer.name("status").value(file.status.toString());
// writer.endObject();
// }
//
// @Override
// public FileDescriptor read(JsonReader reader) throws IOException {
// throw new UnsupportedOperationException("Not supported yet.");
// }
//
//}
| gpl-2.0 |
gnooth/j | src/org/armedbear/lisp/StandardClass.java | 21338 | /*
* StandardClass.java
*
* Copyright (C) 2003-2005 Peter Graves
* $Id: StandardClass.java,v 1.47 2005/12/27 19:46:47 piso Exp $
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
package org.armedbear.lisp;
public class StandardClass extends SlotClass
{
public StandardClass()
{
setClassLayout(new Layout(this, NIL, NIL));
}
public StandardClass(Symbol symbol, LispObject directSuperclasses)
{
super(symbol, directSuperclasses);
setClassLayout(new Layout(this, NIL, NIL));
}
public LispObject typeOf()
{
return Symbol.STANDARD_CLASS;
}
public LispObject classOf()
{
return STANDARD_CLASS;
}
public LispObject typep(LispObject type) throws ConditionThrowable
{
if (type == Symbol.STANDARD_CLASS)
return T;
if (type == STANDARD_CLASS)
return T;
return super.typep(type);
}
public LispObject allocateInstance() throws ConditionThrowable
{
Layout layout = getClassLayout();
if (layout == null)
{
Symbol.ERROR.execute(Symbol.SIMPLE_ERROR,
Keyword.FORMAT_CONTROL,
new SimpleString("No layout for class ~S."),
Keyword.FORMAT_ARGUMENTS,
list1(this));
}
return new StandardObject(this, layout.getLength());
}
public String writeToString() throws ConditionThrowable
{
FastStringBuffer sb =
new FastStringBuffer(Symbol.STANDARD_CLASS.writeToString());
if (symbol != null)
{
sb.append(' ');
sb.append(symbol.writeToString());
}
return unreadableString(sb.toString());
}
private static final StandardClass addStandardClass(Symbol name,
LispObject directSuperclasses)
{
StandardClass c = new StandardClass(name, directSuperclasses);
addClass(name, c);
return c;
}
// At this point, BuiltInClass.java has not been completely loaded yet, and
// BuiltInClass.CLASS_T is null. So we need to call setDirectSuperclass()
// for STANDARD_CLASS and STANDARD_OBJECT in initializeStandardClasses()
// below.
public static final StandardClass STANDARD_CLASS =
addStandardClass(Symbol.STANDARD_CLASS, list1(BuiltInClass.CLASS_T));
public static final StandardClass STANDARD_OBJECT =
addStandardClass(Symbol.STANDARD_OBJECT, list1(BuiltInClass.CLASS_T));
// BuiltInClass.FUNCTION is also null here (see previous comment).
public static final StandardClass GENERIC_FUNCTION =
addStandardClass(Symbol.GENERIC_FUNCTION, list2(BuiltInClass.FUNCTION,
STANDARD_OBJECT));
public static final StandardClass CLASS =
addStandardClass(Symbol.CLASS, list1(STANDARD_OBJECT));
public static final StandardClass BUILT_IN_CLASS =
addStandardClass(Symbol.BUILT_IN_CLASS, list1(CLASS));
public static final StandardClass FORWARD_REFERENCED_CLASS =
addStandardClass(Symbol.FORWARD_REFERENCED_CLASS, list1(CLASS));
public static final StandardClass STRUCTURE_CLASS =
addStandardClass(Symbol.STRUCTURE_CLASS, list1(CLASS));
public static final StandardClass CONDITION =
addStandardClass(Symbol.CONDITION, list1(STANDARD_OBJECT));
public static final StandardClass SIMPLE_CONDITION =
addStandardClass(Symbol.SIMPLE_CONDITION, list1(CONDITION));
public static final StandardClass WARNING =
addStandardClass(Symbol.WARNING, list1(CONDITION));
public static final StandardClass SIMPLE_WARNING =
addStandardClass(Symbol.SIMPLE_WARNING, list2(SIMPLE_CONDITION, WARNING));
public static final StandardClass STYLE_WARNING =
addStandardClass(Symbol.STYLE_WARNING, list1(WARNING));
public static final StandardClass SERIOUS_CONDITION =
addStandardClass(Symbol.SERIOUS_CONDITION, list1(CONDITION));
public static final StandardClass STORAGE_CONDITION =
addStandardClass(Symbol.STORAGE_CONDITION, list1(SERIOUS_CONDITION));
public static final StandardClass ERROR =
addStandardClass(Symbol.ERROR, list1(SERIOUS_CONDITION));
public static final StandardClass ARITHMETIC_ERROR =
addStandardClass(Symbol.ARITHMETIC_ERROR, list1(ERROR));
public static final StandardClass CELL_ERROR =
addStandardClass(Symbol.CELL_ERROR, list1(ERROR));
public static final StandardClass CONTROL_ERROR =
addStandardClass(Symbol.CONTROL_ERROR, list1(ERROR));
public static final StandardClass FILE_ERROR =
addStandardClass(Symbol.FILE_ERROR, list1(ERROR));
public static final StandardClass DIVISION_BY_ZERO =
addStandardClass(Symbol.DIVISION_BY_ZERO, list1(ARITHMETIC_ERROR));
public static final StandardClass FLOATING_POINT_INEXACT =
addStandardClass(Symbol.FLOATING_POINT_INEXACT, list1(ARITHMETIC_ERROR));
public static final StandardClass FLOATING_POINT_INVALID_OPERATION =
addStandardClass(Symbol.FLOATING_POINT_INVALID_OPERATION, list1(ARITHMETIC_ERROR));
public static final StandardClass FLOATING_POINT_OVERFLOW =
addStandardClass(Symbol.FLOATING_POINT_OVERFLOW, list1(ARITHMETIC_ERROR));
public static final StandardClass FLOATING_POINT_UNDERFLOW =
addStandardClass(Symbol.FLOATING_POINT_UNDERFLOW, list1(ARITHMETIC_ERROR));
public static final StandardClass PROGRAM_ERROR =
addStandardClass(Symbol.PROGRAM_ERROR, list1(ERROR));
public static final StandardClass PACKAGE_ERROR =
addStandardClass(Symbol.PACKAGE_ERROR, list1(ERROR));
public static final StandardClass STREAM_ERROR =
addStandardClass(Symbol.STREAM_ERROR, list1(ERROR));
public static final StandardClass PARSE_ERROR =
addStandardClass(Symbol.PARSE_ERROR, list1(ERROR));
public static final StandardClass PRINT_NOT_READABLE =
addStandardClass(Symbol.PRINT_NOT_READABLE, list1(ERROR));
public static final StandardClass READER_ERROR =
addStandardClass(Symbol.READER_ERROR, list2(PARSE_ERROR, STREAM_ERROR));
public static final StandardClass END_OF_FILE =
addStandardClass(Symbol.END_OF_FILE, list1(STREAM_ERROR));
public static final StandardClass SIMPLE_ERROR =
addStandardClass(Symbol.SIMPLE_ERROR, list2(SIMPLE_CONDITION, ERROR));
public static final StandardClass TYPE_ERROR =
addStandardClass(Symbol.TYPE_ERROR, list1(ERROR));
public static final StandardClass SIMPLE_TYPE_ERROR =
addStandardClass(Symbol.SIMPLE_TYPE_ERROR, list2(SIMPLE_CONDITION,
TYPE_ERROR));
public static final StandardClass UNBOUND_SLOT =
addStandardClass(Symbol.UNBOUND_SLOT, list1(CELL_ERROR));
public static final StandardClass UNBOUND_VARIABLE =
addStandardClass(Symbol.UNBOUND_VARIABLE, list1(CELL_ERROR));
public static final StandardClass UNDEFINED_FUNCTION =
addStandardClass(Symbol.UNDEFINED_FUNCTION, list1(CELL_ERROR));
public static final StandardClass COMPILER_ERROR =
addStandardClass(Symbol.COMPILER_ERROR, list1(CONDITION));
public static final StandardClass COMPILER_UNSUPPORTED_FEATURE_ERROR =
addStandardClass(Symbol.COMPILER_UNSUPPORTED_FEATURE_ERROR,
list1(CONDITION));
public static final StandardClass JAVA_EXCEPTION =
addStandardClass(Symbol.JAVA_EXCEPTION, list1(ERROR));
public static final StandardClass METHOD =
addStandardClass(Symbol.METHOD, list1(STANDARD_OBJECT));
public static final StandardClass STANDARD_METHOD =
new StandardMethodClass();
static
{
addClass(Symbol.STANDARD_METHOD, STANDARD_METHOD);
}
public static final StandardClass STANDARD_READER_METHOD =
new StandardReaderMethodClass();
static
{
addClass(Symbol.STANDARD_READER_METHOD, STANDARD_READER_METHOD);
}
public static final StandardClass STANDARD_GENERIC_FUNCTION =
new StandardGenericFunctionClass();
static
{
addClass(Symbol.STANDARD_GENERIC_FUNCTION, STANDARD_GENERIC_FUNCTION);
}
public static final StandardClass SLOT_DEFINITION =
new SlotDefinitionClass();
static
{
addClass(Symbol.SLOT_DEFINITION, SLOT_DEFINITION);
}
public static void initializeStandardClasses() throws ConditionThrowable
{
// We need to call setDirectSuperclass() here for classes that have a
// BuiltInClass as a superclass. See comment above (at first mention of
// STANDARD_OBJECT).
STANDARD_CLASS.setDirectSuperclass(CLASS);
STANDARD_OBJECT.setDirectSuperclass(BuiltInClass.CLASS_T);
GENERIC_FUNCTION.setDirectSuperclasses(list2(BuiltInClass.FUNCTION,
STANDARD_OBJECT));
ARITHMETIC_ERROR.setCPL(ARITHMETIC_ERROR, ERROR, SERIOUS_CONDITION,
CONDITION, STANDARD_OBJECT, BuiltInClass.CLASS_T);
ARITHMETIC_ERROR.setDirectSlotDefinitions(
list2(new SlotDefinition(Symbol.OPERATION,
list1(PACKAGE_CL.intern("ARITHMETIC-ERROR-OPERATION"))),
new SlotDefinition(Symbol.OPERANDS,
list1(PACKAGE_CL.intern("ARITHMETIC-ERROR-OPERANDS")))));
BUILT_IN_CLASS.setCPL(BUILT_IN_CLASS, CLASS, STANDARD_OBJECT,
BuiltInClass.CLASS_T);
CELL_ERROR.setCPL(CELL_ERROR, ERROR, SERIOUS_CONDITION, CONDITION,
STANDARD_OBJECT, BuiltInClass.CLASS_T);
CELL_ERROR.setDirectSlotDefinitions(
list1(new SlotDefinition(Symbol.NAME,
list1(Symbol.CELL_ERROR_NAME))));
CLASS.setCPL(CLASS, STANDARD_OBJECT, BuiltInClass.CLASS_T);
COMPILER_ERROR.setCPL(COMPILER_ERROR, CONDITION, STANDARD_OBJECT,
BuiltInClass.CLASS_T);
COMPILER_UNSUPPORTED_FEATURE_ERROR.setCPL(COMPILER_UNSUPPORTED_FEATURE_ERROR,
CONDITION, STANDARD_OBJECT,
BuiltInClass.CLASS_T);
CONDITION.setCPL(CONDITION, STANDARD_OBJECT, BuiltInClass.CLASS_T);
CONDITION.setDirectSlotDefinitions(
list2(new SlotDefinition(Symbol.FORMAT_CONTROL,
list1(Symbol.SIMPLE_CONDITION_FORMAT_CONTROL)),
new SlotDefinition(Symbol.FORMAT_ARGUMENTS,
list1(Symbol.SIMPLE_CONDITION_FORMAT_ARGUMENTS),
NIL)));
CONDITION.setDirectDefaultInitargs(list2(Keyword.FORMAT_ARGUMENTS,
// FIXME
new Closure(list3(Symbol.LAMBDA, NIL, NIL),
new Environment())));
CONTROL_ERROR.setCPL(CONTROL_ERROR, ERROR, SERIOUS_CONDITION, CONDITION,
STANDARD_OBJECT, BuiltInClass.CLASS_T);
DIVISION_BY_ZERO.setCPL(DIVISION_BY_ZERO, ARITHMETIC_ERROR, ERROR,
SERIOUS_CONDITION, CONDITION, STANDARD_OBJECT,
BuiltInClass.CLASS_T);
END_OF_FILE.setCPL(END_OF_FILE, STREAM_ERROR, ERROR, SERIOUS_CONDITION,
CONDITION, STANDARD_OBJECT, BuiltInClass.CLASS_T);
ERROR.setCPL(ERROR, SERIOUS_CONDITION, CONDITION, STANDARD_OBJECT,
BuiltInClass.CLASS_T);
FILE_ERROR.setCPL(FILE_ERROR, ERROR, SERIOUS_CONDITION, CONDITION,
STANDARD_OBJECT, BuiltInClass.CLASS_T);
FILE_ERROR.setDirectSlotDefinitions(
list1(new SlotDefinition(Symbol.PATHNAME,
list1(PACKAGE_CL.intern("FILE-ERROR-PATHNAME")))));
FLOATING_POINT_INEXACT.setCPL(FLOATING_POINT_INEXACT, ARITHMETIC_ERROR,
ERROR, SERIOUS_CONDITION, CONDITION,
STANDARD_OBJECT, BuiltInClass.CLASS_T);
FLOATING_POINT_INVALID_OPERATION.setCPL(FLOATING_POINT_INVALID_OPERATION,
ARITHMETIC_ERROR, ERROR,
SERIOUS_CONDITION, CONDITION,
STANDARD_OBJECT, BuiltInClass.CLASS_T);
FLOATING_POINT_OVERFLOW.setCPL(FLOATING_POINT_OVERFLOW, ARITHMETIC_ERROR,
ERROR, SERIOUS_CONDITION, CONDITION,
STANDARD_OBJECT, BuiltInClass.CLASS_T);
FLOATING_POINT_UNDERFLOW.setCPL(FLOATING_POINT_UNDERFLOW, ARITHMETIC_ERROR,
ERROR, SERIOUS_CONDITION, CONDITION,
STANDARD_OBJECT, BuiltInClass.CLASS_T);
FORWARD_REFERENCED_CLASS.setCPL(FORWARD_REFERENCED_CLASS, CLASS,
BuiltInClass.CLASS_T);
GENERIC_FUNCTION.setCPL(GENERIC_FUNCTION, STANDARD_OBJECT,
BuiltInClass.FUNCTION,
BuiltInClass.CLASS_T);
JAVA_EXCEPTION.setCPL(JAVA_EXCEPTION, ERROR, SERIOUS_CONDITION, CONDITION,
STANDARD_OBJECT, BuiltInClass.CLASS_T);
JAVA_EXCEPTION.setDirectSlotDefinitions(
list1(new SlotDefinition(Symbol.CAUSE, list1(Symbol.JAVA_EXCEPTION_CAUSE))));
METHOD.setCPL(METHOD, STANDARD_OBJECT, BuiltInClass.CLASS_T);
PACKAGE_ERROR.setCPL(PACKAGE_ERROR, ERROR, SERIOUS_CONDITION, CONDITION,
STANDARD_OBJECT, BuiltInClass.CLASS_T);
PACKAGE_ERROR.setDirectSlotDefinitions(
list1(new SlotDefinition(Symbol.PACKAGE,
list1(PACKAGE_CL.intern("PACKAGE-ERROR-PACKAGE")))));
PARSE_ERROR.setCPL(PARSE_ERROR, ERROR, SERIOUS_CONDITION, CONDITION,
STANDARD_OBJECT, BuiltInClass.CLASS_T);
PRINT_NOT_READABLE.setCPL(PRINT_NOT_READABLE, ERROR, SERIOUS_CONDITION,
CONDITION, STANDARD_OBJECT, BuiltInClass.CLASS_T);
PRINT_NOT_READABLE.setDirectSlotDefinitions(
list1(new SlotDefinition(Symbol.OBJECT,
list1(PACKAGE_CL.intern("PRINT-NOT-READABLE-OBJECT")))));
PROGRAM_ERROR.setCPL(PROGRAM_ERROR, ERROR, SERIOUS_CONDITION, CONDITION,
STANDARD_OBJECT, BuiltInClass.CLASS_T);
READER_ERROR.setCPL(READER_ERROR, PARSE_ERROR, STREAM_ERROR, ERROR,
SERIOUS_CONDITION, CONDITION, STANDARD_OBJECT,
BuiltInClass.CLASS_T);
SERIOUS_CONDITION.setCPL(SERIOUS_CONDITION, CONDITION, STANDARD_OBJECT,
BuiltInClass.CLASS_T);
SIMPLE_CONDITION.setCPL(SIMPLE_CONDITION, CONDITION, STANDARD_OBJECT,
BuiltInClass.CLASS_T);
SIMPLE_ERROR.setCPL(SIMPLE_ERROR, SIMPLE_CONDITION, ERROR,
SERIOUS_CONDITION, CONDITION, STANDARD_OBJECT,
BuiltInClass.CLASS_T);
SIMPLE_TYPE_ERROR.setDirectSuperclasses(list2(SIMPLE_CONDITION,
TYPE_ERROR));
SIMPLE_TYPE_ERROR.setCPL(SIMPLE_TYPE_ERROR, SIMPLE_CONDITION,
TYPE_ERROR, ERROR, SERIOUS_CONDITION,
CONDITION, STANDARD_OBJECT, BuiltInClass.CLASS_T);
SIMPLE_WARNING.setDirectSuperclasses(list2(SIMPLE_CONDITION, WARNING));
SIMPLE_WARNING.setCPL(SIMPLE_WARNING, SIMPLE_CONDITION, WARNING,
CONDITION, STANDARD_OBJECT, BuiltInClass.CLASS_T);
STANDARD_CLASS.setCPL(STANDARD_CLASS, CLASS,
STANDARD_OBJECT, BuiltInClass.CLASS_T);
STANDARD_OBJECT.setCPL(STANDARD_OBJECT, BuiltInClass.CLASS_T);
STORAGE_CONDITION.setCPL(STORAGE_CONDITION, SERIOUS_CONDITION, CONDITION,
STANDARD_OBJECT, BuiltInClass.CLASS_T);
STREAM_ERROR.setCPL(STREAM_ERROR, ERROR, SERIOUS_CONDITION, CONDITION,
STANDARD_OBJECT, BuiltInClass.CLASS_T);
STREAM_ERROR.setDirectSlotDefinitions(
list1(new SlotDefinition(Symbol.STREAM,
list1(PACKAGE_CL.intern("STREAM-ERROR-STREAM")))));
STRUCTURE_CLASS.setCPL(STRUCTURE_CLASS, CLASS, STANDARD_OBJECT,
BuiltInClass.CLASS_T);
STYLE_WARNING.setCPL(STYLE_WARNING, WARNING, CONDITION, STANDARD_OBJECT,
BuiltInClass.CLASS_T);
TYPE_ERROR.setCPL(TYPE_ERROR, ERROR, SERIOUS_CONDITION, CONDITION,
STANDARD_OBJECT, BuiltInClass.CLASS_T);
TYPE_ERROR.setDirectSlotDefinitions(
list2(new SlotDefinition(Symbol.DATUM,
list1(PACKAGE_CL.intern("TYPE-ERROR-DATUM"))),
new SlotDefinition(Symbol.EXPECTED_TYPE,
list1(PACKAGE_CL.intern("TYPE-ERROR-EXPECTED-TYPE")))));
UNBOUND_SLOT.setCPL(UNBOUND_SLOT, CELL_ERROR, ERROR, SERIOUS_CONDITION,
CONDITION, STANDARD_OBJECT, BuiltInClass.CLASS_T);
UNBOUND_SLOT.setDirectSlotDefinitions(
list1(new SlotDefinition(Symbol.INSTANCE,
list1(PACKAGE_CL.intern("UNBOUND-SLOT-INSTANCE")))));
UNBOUND_VARIABLE.setCPL(UNBOUND_VARIABLE, CELL_ERROR, ERROR,
SERIOUS_CONDITION, CONDITION, STANDARD_OBJECT,
BuiltInClass.CLASS_T);
UNDEFINED_FUNCTION.setCPL(UNDEFINED_FUNCTION, CELL_ERROR, ERROR,
SERIOUS_CONDITION, CONDITION, STANDARD_OBJECT,
BuiltInClass.CLASS_T);
WARNING.setCPL(WARNING, CONDITION, STANDARD_OBJECT, BuiltInClass.CLASS_T);
// Condition classes.
ARITHMETIC_ERROR.finalizeClass();
CELL_ERROR.finalizeClass();
COMPILER_ERROR.finalizeClass();
COMPILER_UNSUPPORTED_FEATURE_ERROR.finalizeClass();
CONDITION.finalizeClass();
CONTROL_ERROR.finalizeClass();
DIVISION_BY_ZERO.finalizeClass();
END_OF_FILE.finalizeClass();
ERROR.finalizeClass();
FILE_ERROR.finalizeClass();
FLOATING_POINT_INEXACT.finalizeClass();
FLOATING_POINT_INVALID_OPERATION.finalizeClass();
FLOATING_POINT_OVERFLOW.finalizeClass();
FLOATING_POINT_UNDERFLOW.finalizeClass();
JAVA_EXCEPTION.finalizeClass();
PACKAGE_ERROR.finalizeClass();
PARSE_ERROR.finalizeClass();
PRINT_NOT_READABLE.finalizeClass();
PROGRAM_ERROR.finalizeClass();
READER_ERROR.finalizeClass();
SERIOUS_CONDITION.finalizeClass();
SIMPLE_CONDITION.finalizeClass();
SIMPLE_ERROR.finalizeClass();
SIMPLE_TYPE_ERROR.finalizeClass();
SIMPLE_WARNING.finalizeClass();
STORAGE_CONDITION.finalizeClass();
STREAM_ERROR.finalizeClass();
STYLE_WARNING.finalizeClass();
TYPE_ERROR.finalizeClass();
UNBOUND_SLOT.finalizeClass();
UNBOUND_VARIABLE.finalizeClass();
UNDEFINED_FUNCTION.finalizeClass();
WARNING.finalizeClass();
// SYS:SLOT-DEFINITION is constructed and finalized in
// SlotDefinitionClass.java, but we need to fill in a few things here.
Debug.assertTrue(SLOT_DEFINITION.isFinalized());
SLOT_DEFINITION.setCPL(SLOT_DEFINITION, STANDARD_OBJECT,
BuiltInClass.CLASS_T);
SLOT_DEFINITION.setDirectSlotDefinitions(SLOT_DEFINITION.getClassLayout().generateSlotDefinitions());
// There are no inherited slots.
SLOT_DEFINITION.setSlotDefinitions(SLOT_DEFINITION.getDirectSlotDefinitions());
// STANDARD-METHOD
Debug.assertTrue(STANDARD_METHOD.isFinalized());
STANDARD_METHOD.setCPL(STANDARD_METHOD, METHOD, STANDARD_OBJECT,
BuiltInClass.CLASS_T);
STANDARD_METHOD.setDirectSlotDefinitions(STANDARD_METHOD.getClassLayout().generateSlotDefinitions());
// There are no inherited slots.
STANDARD_METHOD.setSlotDefinitions(STANDARD_METHOD.getDirectSlotDefinitions());
// STANDARD-READER-METHOD
Debug.assertTrue(STANDARD_READER_METHOD.isFinalized());
STANDARD_READER_METHOD.setCPL(STANDARD_READER_METHOD, STANDARD_METHOD,
METHOD, STANDARD_OBJECT, BuiltInClass.CLASS_T);
STANDARD_READER_METHOD.setSlotDefinitions(STANDARD_READER_METHOD.getClassLayout().generateSlotDefinitions());
// All but the last slot are inherited.
STANDARD_READER_METHOD.setDirectSlotDefinitions(list1(STANDARD_READER_METHOD.getSlotDefinitions().reverse().car()));
// STANDARD-GENERIC-FUNCTION
Debug.assertTrue(STANDARD_GENERIC_FUNCTION.isFinalized());
STANDARD_GENERIC_FUNCTION.setCPL(STANDARD_GENERIC_FUNCTION,
GENERIC_FUNCTION, STANDARD_OBJECT,
BuiltInClass.FUNCTION,
BuiltInClass.CLASS_T);
STANDARD_GENERIC_FUNCTION.setDirectSlotDefinitions(STANDARD_GENERIC_FUNCTION.getClassLayout().generateSlotDefinitions());
// There are no inherited slots.
STANDARD_GENERIC_FUNCTION.setSlotDefinitions(STANDARD_GENERIC_FUNCTION.getDirectSlotDefinitions());
}
}
| gpl-2.0 |
jinsedeyuzhou/Financial | refresh-layout/src/main/java/com/scwang/smartrefresh/layout/constant/DimensionStatus.java | 1681 | package com.scwang.smartrefresh.layout.constant;
/**
* 尺寸值的定义状态,用于在值覆盖的时候决定优先级
* 越往下优先级越高
*/
public enum DimensionStatus {
DefaultUnNotify(false),//默认值,但是还没通知确认
Default(true),//默认值
XmlWrap(true),//Xml计算
XmlExact(true),//Xml 的view 指定
XmlLayoutUnNotify(false),//Xml 的layout 中指定,但是还没通知确认
XmlLayout(true),//Xml 的layout 中指定
CodeExactUnNotify(false),//代码指定,但是还没通知确认
CodeExact(true),//代码指定
DeadLockUnNotify(false),//锁死,但是还没通知确认
DeadLock(true);//锁死
public final boolean notifyed;
DimensionStatus(boolean notifyed) {
this.notifyed = notifyed;
}
/**
* 转换为未通知状态
*/
public DimensionStatus unNotify() {
if (notifyed) {
DimensionStatus prev = values()[ordinal() - 1];
if (!prev.notifyed) {
return prev;
}
return DefaultUnNotify;
}
return this;
}
/**
* 转换为通知状态
*/
public DimensionStatus notifyed() {
if (!notifyed) {
return values()[ordinal() + 1];
}
return this;
}
/**
* 小于等于
*/
public boolean canReplaceWith(DimensionStatus status) {
return ordinal() < status.ordinal() || ((!notifyed || CodeExact == this) && ordinal() == status.ordinal());
}
/**
* 大于等于
*/
public boolean gteReplaceWith(DimensionStatus status) {
return ordinal() >= status.ordinal();
}
} | gpl-2.0 |
COPELABS-SITI/USENSE | app/src/main/java/cs/usense/utilities/DateUtils.java | 2439 | /**
* @version 2.0
* COPYRIGHTS COPELABS/ULHT, LGPLv3.0, 16-11-2015
* Class is part of the NSense application.
* This class provides a couple of date utilities
* @author Miguel Tavares (COPELABS/ULHT)
*/
package cs.usense.utilities;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public abstract class DateUtils {
private static final SimpleDateFormat SDF_DAY_MONTH = new SimpleDateFormat("dd/MM");
private static final SimpleDateFormat SDF_DATE = new SimpleDateFormat("dd/MM/yyyy");
private static final SimpleDateFormat SDF_TIME_SECOND = new SimpleDateFormat("dd/MM - HH:mm:ss");
private static final SimpleDateFormat SDF_TIME = new SimpleDateFormat("dd/MM - HH:mm");
private static final SimpleDateFormat SDF_TIME_2 = new SimpleDateFormat("dd-MM - HH:mm");
private static final SimpleDateFormat TIME_SERIES_ANALYSIS = new SimpleDateFormat("ddMMMyy:HH:mm:ss");
public static String getTodaysDayOfMonth() {
return SDF_DAY_MONTH.format(Calendar.getInstance().getTime());
}
public static String getTodaysDate() {
return SDF_DATE.format(Calendar.getInstance().getTime());
}
public static String getTimeNowAsStringSecond() {
return SDF_TIME_SECOND.format(Calendar.getInstance().getTime());
}
public static String getTimeNowAsString() {
return SDF_TIME.format(Calendar.getInstance().getTime());
}
public static String getTimeNowFileNameFormatted() {
return SDF_TIME_2.format(Calendar.getInstance().getTime());
}
public static String getTimeNowTimeSeriesFormat() {
return TIME_SERIES_ANALYSIS.format(Calendar.getInstance().getTime());
}
public static long getTimeNowAsLong() {
return Calendar.getInstance().getTime().getTime();
}
public static boolean isMidNight() {
Date date = new Date();
return (date.getHours() == 0 && date.getMinutes() == 0);
}
public static boolean isEndOfWeek() {
Date date = new Date();
int dayOfWeek = Calendar.getInstance().get(Calendar.DAY_OF_WEEK);
return (date.getHours() == 12 && date.getMinutes() == 0 && dayOfWeek == Calendar.FRIDAY);
}
/**
* Provides the current time slot
* @return currentTimeSlot The actual time slot
*/
public static int getTimeSlot(){
return Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
}
}
| gpl-2.0 |