repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
Juffik/JavaRush-1 | src/com/javarush/test/level17/lesson10/bonus03/Restaurant.java | 787 | package com.javarush.test.level17.lesson10.bonus03;
/* Ресторан
1.Разберись, что делает программа. Официант почему-то не относит приготовленные блюда назад к столам :(
2.Исправь ошибку.
Подсказка: это одна строчка
*/
public class Restaurant {
public static void main(String[] args) throws Exception {
Waiter waiterTarget = new Waiter();
Thread waiter = new Thread(waiterTarget);
Cook cookTarget = new Cook();
Thread cook = new Thread(cookTarget);
waiter.start();
cook.start();
Thread.sleep(2000);
waiterTarget.continueWorking = false;
cookTarget.continueWorking = false;
}
}
| mit |
Weisses/Ebonheart-Mods | ViesCraft/Archived/zzz - PreCapabilities - src/main/java/com/viesis/viescraft/common/entity/airshipcolors/v2/EntityAirshipV2Green.java | 1227 | package com.viesis.viescraft.common.entity.airshipcolors.v2;
import net.minecraft.item.Item;
import net.minecraft.world.World;
import com.viesis.viescraft.common.entity.airshipcolors.EntityAirshipV2Core;
import com.viesis.viescraft.configs.ViesCraftConfig;
import com.viesis.viescraft.init.InitItemsVC;
public class EntityAirshipV2Green extends EntityAirshipV2Core {
public EntityAirshipV2Green(World worldIn)
{
super(worldIn);
this.ignoreFrustumCheck = true;
this.preventEntitySpawning = true;
this.setSize(1.0F, 0.35F);
}
public EntityAirshipV2Green(World worldIn, double x, double y, double z)
{
this(worldIn);
this.setPosition(x, y, z);
this.motionX = 0.0D;
this.motionY = 0.0D;
this.motionZ = 0.0D;
this.prevPosX = x;
this.prevPosY = y;
this.prevPosZ = z;
}
/**
* Main entity item drop.
*/
@Override
public Item getItemBoat()
{
return InitItemsVC.item_airship_v2_green;
}
/**
* Custom name for Waila.
*/
@Override
public String getName() {
return this.hasCustomName() ? this.customName : "Green " + ViesCraftConfig.v2AirshipName;
}
}
| mit |
diedertimmers/oxAuth | Server/src/main/java/org/xdi/oxauth/service/ApplicationFactory.java | 2331 | /*
* oxAuth is available under the MIT License (2008). See http://opensource.org/licenses/MIT for full text.
*
* Copyright (c) 2014, Gluu
*/
package org.xdi.oxauth.service;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Factory;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Logger;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.Startup;
import org.jboss.seam.log.Log;
import org.xdi.model.SmtpConfiguration;
import org.xdi.oxauth.crypto.random.RandomChallengeGenerator;
import org.xdi.oxauth.crypto.signature.BouncyCastleSignatureVerification;
import org.xdi.oxauth.model.appliance.GluuAppliance;
import org.xdi.util.StringHelper;
import org.xdi.util.security.StringEncrypter.EncryptionException;
/**
* Holds factoryt methods to create services
*
* @author Yuriy Movchan Date: 05/22/2015
*/
@Scope(ScopeType.APPLICATION)
@Name("applicationFactory")
@Startup
public class ApplicationFactory {
@In
private ApplianceService applianceService;
@Logger
private Log log;
@Factory(value = "randomChallengeGenerator", scope = ScopeType.APPLICATION, autoCreate = true)
public RandomChallengeGenerator createRandomChallengeGenerator() {
return new RandomChallengeGenerator();
}
@Factory(value = "bouncyCastleSignatureVerification", scope = ScopeType.APPLICATION, autoCreate = true)
public BouncyCastleSignatureVerification createBouncyCastleSignatureVerification() {
return new BouncyCastleSignatureVerification();
}
@Factory(value = "smtpConfiguration", scope = ScopeType.APPLICATION, autoCreate = true)
public SmtpConfiguration createSmtpConfiguration() {
GluuAppliance appliance = applianceService.getAppliance();
SmtpConfiguration smtpConfiguration = appliance.getSmtpConfiguration();
if (smtpConfiguration == null) {
return null;
}
String password = smtpConfiguration.getPassword();
if (StringHelper.isNotEmpty(password)) {
try {
EncryptionService securityService = EncryptionService.instance();
smtpConfiguration.setPasswordDecrypted(securityService.decrypt(password));
} catch (EncryptionException ex) {
log.error("Failed to decript SMTP user password", ex);
}
}
return smtpConfiguration;
}
} | mit |
zhaopei0418/maintain | src/main/java/online/zhaopei/myproject/domain/ecssent/InvtDeliveryComparison.java | 2714 | package online.zhaopei.myproject.domain.ecssent;
import online.zhaopei.myproject.domain.BaseDomain;
public class InvtDeliveryComparison extends BaseDomain {
/**
* serialVersionUID
*/
private static final long serialVersionUID = -7562709963950329434L;
private String deliveryHeadGuid;
private String invtHeadGuid;
private String deliveryVoyageNo;
private String invtVoyageNo;
private String deliveryBillNo;
private String invtBillNo;
private String deliveryTrafMode;
private String invtTrafMode;
private String deliveryTrafNo;
private String invtTrafNo;
private String logisticsCode;
private String logisticsNo;
private String copNo;
public String getDeliveryHeadGuid() {
return deliveryHeadGuid;
}
public void setDeliveryHeadGuid(String deliveryHeadGuid) {
this.deliveryHeadGuid = deliveryHeadGuid;
}
public String getInvtHeadGuid() {
return invtHeadGuid;
}
public void setInvtHeadGuid(String invtHeadGuid) {
this.invtHeadGuid = invtHeadGuid;
}
public String getDeliveryVoyageNo() {
return deliveryVoyageNo;
}
public void setDeliveryVoyageNo(String deliveryVoyageNo) {
this.deliveryVoyageNo = deliveryVoyageNo;
}
public String getInvtVoyageNo() {
return invtVoyageNo;
}
public void setInvtVoyageNo(String invtVoyageNo) {
this.invtVoyageNo = invtVoyageNo;
}
public String getDeliveryBillNo() {
return deliveryBillNo;
}
public void setDeliveryBillNo(String deliveryBillNo) {
this.deliveryBillNo = deliveryBillNo;
}
public String getInvtBillNo() {
return invtBillNo;
}
public void setInvtBillNo(String invtBillNo) {
this.invtBillNo = invtBillNo;
}
public String getDeliveryTrafMode() {
return deliveryTrafMode;
}
public void setDeliveryTrafMode(String deliveryTrafMode) {
this.deliveryTrafMode = deliveryTrafMode;
}
public String getInvtTrafMode() {
return invtTrafMode;
}
public void setInvtTrafMode(String invtTrafMode) {
this.invtTrafMode = invtTrafMode;
}
public String getDeliveryTrafNo() {
return deliveryTrafNo;
}
public void setDeliveryTrafNo(String deliveryTrafNo) {
this.deliveryTrafNo = deliveryTrafNo;
}
public String getInvtTrafNo() {
return invtTrafNo;
}
public void setInvtTrafNo(String invtTrafNo) {
this.invtTrafNo = invtTrafNo;
}
public String getLogisticsCode() {
return logisticsCode;
}
public void setLogisticsCode(String logisticsCode) {
this.logisticsCode = logisticsCode;
}
public String getLogisticsNo() {
return logisticsNo;
}
public void setLogisticsNo(String logisticsNo) {
this.logisticsNo = logisticsNo;
}
public String getCopNo() {
return copNo;
}
public void setCopNo(String copNo) {
this.copNo = copNo;
}
}
| mit |
FUDCo/Elko | ServerCore/java/org/elkoserver/foundation/actor/JSONHTTPFramer.java | 6162 | package org.elkoserver.foundation.actor;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Iterator;
import org.elkoserver.foundation.net.HTTPFramer;
import org.elkoserver.foundation.net.NetworkManager;
import org.elkoserver.json.JSONLiteral;
import org.elkoserver.json.JSONObject;
import org.elkoserver.json.Parser;
import org.elkoserver.json.SyntaxError;
import org.elkoserver.util.trace.Trace;
/**
* HTTP message framer for JSON messages transported via HTTP.
*
* <p>This class treats the content of each HTTP POST to the /xmit/ URL as a
* bundle of one or more JSON messages to be handled.
*/
public class JSONHTTPFramer extends HTTPFramer {
/**
* Constructor.
*/
public JSONHTTPFramer(Trace appTrace) {
super(appTrace);
}
/**
* Produce the HTTP for responding to an HTTP GET of the /select/ URL by
* sending a message to the client.
*
* <p>The actual HTTP reply body sent is constructed by concatenating the
* results of one or more coordinated calls to this method, one call for
* each message that is to be sent. In the first of these calls, the
* 'start' flag must be true. In the last, the 'end' flag must be true.
* (If only one message is being sent, this method should be called exactly
* once with both 'start' and 'end' set to true.)
*
* @param message The message to be sent.
* @param seqNumber The sequence number for the next select request.
* @param start true if this message is the first in a batch of messages.
* @param end true if this message is the last in a batch of messages.
*
* @return an appropriate HTTP reply body string for responding to a
* /select/ GET, delivering 'message' to the client.
*/
public String makeSelectReplySegment(Object message, int seqNumber,
boolean start, boolean end)
{
String messageString;
if (message instanceof JSONLiteral) {
messageString = ((JSONLiteral) message).sendableString();
} else if (message instanceof JSONObject) {
messageString = ((JSONObject) message).sendableString();
} else if (message instanceof String) {
messageString = "\"" + ((String) message) + "\"";
} else {
messageString = null;
}
return super.makeSelectReplySegment(messageString, seqNumber,
start, end);
}
/**
* Get an iterator that can extract the JSON message or messages (if any)
* from the body of an HTTP message.
*
* @param body The HTTP message body in question.
*
* @return an iterator that can be called upon to return the JSON
* message(s) contained within 'body'.
*/
public Iterator postBodyUnpacker(String body) {
return new JSONBodyUnpacker(body);
}
/**
* Post body unpacker for a bundle of JSON messages. In this case, the
* HTTP POST body contains one or more JSON messages.
*/
private class JSONBodyUnpacker implements Iterator {
/** Current JSON parser. */
private Parser myParser;
/** Last JSON message parsed. This will be the next JSON message to be
returned because the framer always parses one JSON message ahead,
in order to be able to see the end of the HTTP message string. */
private Object myLastMessageParsed;
/**
* Constructor. Strip the form variable name and parse the rest as
* JSON.
*
* @param postBody The HTTP message body was POSTed.
*/
public JSONBodyUnpacker(String postBody) {
Trace.comm.debugm("unpacker for: /" + postBody + "/");
int junkMark = postBody.indexOf('=');
if (junkMark >= 0) {
// XXX Temporary hack to decode POSTs from Safari
if (postBody.length() > junkMark &&
postBody.charAt(junkMark+1) == '%') {
try {
postBody = URLDecoder.decode(postBody, "UTF-8");
} catch (UnsupportedEncodingException e) {
/* This should never happen. */
Trace.comm.errorm("bogus " + e);
}
}
int startOfMessageMark = postBody.indexOf('{');
if (startOfMessageMark > junkMark) {
postBody = postBody.substring(junkMark + 1);
}
}
myParser = new Parser(postBody);
myLastMessageParsed = parseNextMessage();
}
/**
* Test if there are more messages.
*
* Since the framer always parse one message ahead, just look to see if
* there is a message sitting there.
*/
public boolean hasNext() {
return myLastMessageParsed != null;
}
/**
* Get the next message.
*
* Return the last message parsed, then parse the next message for the
* next time this is called (the parser will return null after it has
* parsed the last actual messge).
*/
public Object next() {
Object result = myLastMessageParsed;
myLastMessageParsed = parseNextMessage();
return result;
}
/**
* Helper routine to actually do the message parsing.
*/
private Object parseNextMessage() {
try {
return myParser.parseObjectLiteral();
} catch (SyntaxError e) {
if (NetworkManager.TheDebugReplyFlag) {
return e;
}
if (Trace.comm.warning && Trace.ON) {
Trace.comm.warningm("syntax error in JSON message: " +
e.getMessage());
}
return null;
}
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}
| mit |
codylieu/slogo | src/commands/mathCommands/RemainderMathCommand.java | 268 | package commands.mathCommands;
import commands.MathCommand;
public class RemainderMathCommand extends MathCommand {
public RemainderMathCommand() {
super(2);
}
@Override
public double execute(Object o) {
return parameters.get(0) % parameters.get(1);
}
}
| mit |
javaseeds/java-design-patterns | unit-of-work/src/main/java/com/iluwatar/unitofwork/StudentRepository.java | 4287 | /*
* The MIT License
* Copyright © 2014-2019 Ilkka Seppälä
*
* 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.iluwatar.unitofwork;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* {@link StudentRepository} Student database repository. supports unit of work for student data.
*/
public class StudentRepository implements IUnitOfWork<Student> {
private static final Logger LOGGER = LoggerFactory.getLogger(StudentRepository.class);
private final Map<String, List<Student>> context;
private final StudentDatabase studentDatabase;
/**
* Constructor.
*
* @param context set of operations to be perform during commit.
* @param studentDatabase Database for student records.
*/
public StudentRepository(Map<String, List<Student>> context, StudentDatabase studentDatabase) {
this.context = context;
this.studentDatabase = studentDatabase;
}
@Override
public void registerNew(Student student) {
LOGGER.info("Registering {} for insert in context.", student.getName());
register(student, UnitActions.INSERT.getActionValue());
}
@Override
public void registerModified(Student student) {
LOGGER.info("Registering {} for modify in context.", student.getName());
register(student, UnitActions.MODIFY.getActionValue());
}
@Override
public void registerDeleted(Student student) {
LOGGER.info("Registering {} for delete in context.", student.getName());
register(student, UnitActions.DELETE.getActionValue());
}
private void register(Student student, String operation) {
var studentsToOperate = context.get(operation);
if (studentsToOperate == null) {
studentsToOperate = new ArrayList<>();
}
studentsToOperate.add(student);
context.put(operation, studentsToOperate);
}
/**
* All UnitOfWork operations are batched and executed together on commit only.
*/
@Override
public void commit() {
if (context == null || context.size() == 0) {
return;
}
LOGGER.info("Commit started");
if (context.containsKey(UnitActions.INSERT.getActionValue())) {
commitInsert();
}
if (context.containsKey(UnitActions.MODIFY.getActionValue())) {
commitModify();
}
if (context.containsKey(UnitActions.DELETE.getActionValue())) {
commitDelete();
}
LOGGER.info("Commit finished.");
}
private void commitInsert() {
var studentsToBeInserted = context.get(UnitActions.INSERT.getActionValue());
for (var student : studentsToBeInserted) {
LOGGER.info("Saving {} to database.", student.getName());
studentDatabase.insert(student);
}
}
private void commitModify() {
var modifiedStudents = context.get(UnitActions.MODIFY.getActionValue());
for (var student : modifiedStudents) {
LOGGER.info("Modifying {} to database.", student.getName());
studentDatabase.modify(student);
}
}
private void commitDelete() {
var deletedStudents = context.get(UnitActions.DELETE.getActionValue());
for (var student : deletedStudents) {
LOGGER.info("Deleting {} to database.", student.getName());
studentDatabase.delete(student);
}
}
}
| mit |
WhiteHsu/Open-LaTeX-Studio | OpenLaTeXStudio/Editor/src/main/java/latexstudio/editor/remote/ConnectDropbox.java | 6531 | /*
* Copyright (c) 2015 Sebastian Brudzinski
*
* See the file LICENSE for copying permission.
*/
package latexstudio.editor.remote;
import com.dropbox.core.DbxAccountInfo;
import com.dropbox.core.DbxAppInfo;
import com.dropbox.core.DbxAuthFinish;
import com.dropbox.core.DbxClient;
import com.dropbox.core.DbxException;
import com.dropbox.core.DbxWebAuthNoRedirect;
import java.awt.Desktop;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import latexstudio.editor.ApplicationLogger;
import latexstudio.editor.settings.ApplicationSettings;
import latexstudio.editor.util.ApplicationUtils;
import latexstudio.editor.util.PropertyService;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.awt.ActionRegistration;
import org.openide.util.Exceptions;
import org.openide.util.NbBundle.Messages;
@ActionID(
category = "Remote",
id = "latexstudio.editor.remote.ConnectDropbox"
)
@ActionRegistration(
displayName = "#CTL_ConnectDropbox"
)
@ActionReference(path = "Menu/Remote", position = 3333, separatorAfter = 3383)
@Messages("CTL_ConnectDropbox=Connect to Dropbox")
public final class ConnectDropbox implements ActionListener {
private static final String PROPERTIES = "dropbox.properties";
private static final String APP_KEY = PropertyService.
readProperties(PROPERTIES).getProperty("dropbox.appKey");
private static final String APP_SECRET = PropertyService.
readProperties(PROPERTIES).getProperty("dropbox.appSecret");
private static final ApplicationLogger LOGGER = new ApplicationLogger("Cloud Support");
@Override
public void actionPerformed(ActionEvent e) {
Cloud.Status currentCloudStatus = Cloud.getInstance().getStatus();
Cloud.getInstance().setStatus(Cloud.Status.CONNECTING);
DbxAppInfo appInfo;
try {
appInfo = new DbxAppInfo(APP_KEY, APP_SECRET);
} catch (IllegalArgumentException ex) {
JOptionPane.showMessageDialog(null,
"You are using the development version of the application and have not provided the necessary properties.\n"
+ "In order to develop Dropbox features, create Dropbox developer account and fill in the necessary fields in dropbox.properties file.\n"
+ "You can also contact us at open-latex-studio@googlegroups.com in case of any troubles.",
"Development version",
JOptionPane.WARNING_MESSAGE);
Cloud.getInstance().setStatus(Cloud.Status.DISCONNECTED);
return;
}
DbxWebAuthNoRedirect webAuth = new DbxWebAuthNoRedirect(DbxUtil.getDbxConfig(), appInfo);
final String authorizeUrl = webAuth.start();
class OpenUrlAction implements ActionListener {
@Override public void actionPerformed(ActionEvent e) {
try {
open(new URI(authorizeUrl));
} catch (URISyntaxException ex) {
Exceptions.printStackTrace(ex);
}
}
}
JButton button = new JButton();
button.setText("Connect to Dropbox");
button.setToolTipText(authorizeUrl);
button.addActionListener(new OpenUrlAction());
String userToken = JOptionPane.showInputDialog(
null,
button,
"Authentication token required",
JOptionPane.INFORMATION_MESSAGE
);
if (userToken != null && !userToken.isEmpty()) {
try {
DbxAuthFinish authFinish = webAuth.finish(userToken);
userToken = authFinish.accessToken;
ApplicationSettings.Setting.DROPBOX_TOKEN.setValue(userToken);
ApplicationSettings.INSTANCE.save();
// getting dbx client displayName
DbxClient client = DbxUtil.getDbxClient();
DbxAccountInfo info = null;
String additional = "";
if(client != null) {
info = client.getAccountInfo();
additional = " (" + info.displayName + ")";
}
LOGGER.log("Successfully connected application with Dropbox account.");
Cloud.getInstance().setStatus(Cloud.Status.DBX_CONNECTED, additional);
} catch (DbxException ex) {
JOptionPane.showMessageDialog(null,
"Invalid access token! Open LaTeX Studio has NOT been connected with Dropbox.\n Please try again and provide correct access token.",
"Invalid token",
JOptionPane.ERROR_MESSAGE);
Cloud.getInstance().setStatus(Cloud.Status.DISCONNECTED);
}
} else {
Cloud.getInstance().setStatus(currentCloudStatus);
}
}
private static void open(URI uri) {
try {
if (Desktop.isDesktopSupported() && Desktop.getDesktop().isSupported(Desktop.Action.BROWSE)) {
Desktop.getDesktop().browse(uri);
} else {
// Desktop API does not support various platforms - try different approach
runtimeCommandOpen(uri);
}
} catch (IOException e) {
Exceptions.printStackTrace(e);
}
}
private static void runtimeCommandOpen(URI uri) {
Runtime rt = Runtime.getRuntime();
try {
if (ApplicationUtils.isWindows()) {
rt.exec("rundll32 url.dll,FileProtocolHandler " + uri.toString());
} else {
String[] browsers = { "epiphany", "firefox", "mozilla", "konqueror",
"netscape", "opera", "links", "lynx" };
StringBuilder cmd = new StringBuilder();
for (int i = 0 ; i < browsers.length; i++) {
cmd.append((i == 0 ? "" : " || ")).append(browsers[i]).append(" \"").append(uri.toString()).append("\" ");
}
rt.exec(new String[] { "sh", "-c", cmd.toString() });
}
} catch (IOException e) {
Exceptions.printStackTrace(e);
}
}
}
| mit |
hpe-idol/java-hod-spring-caching | src/test/java/com/hp/autonomy/hod/caching/HodPerUserCacheResolverTest.java | 796 | package com.hp.autonomy.hod.caching;
import java.util.Collection;
import static org.hamcrest.Matchers.hasItems;
import static org.junit.Assert.assertThat;
public class HodPerUserCacheResolverTest extends AbstractHodCacheResolverTest {
@Override
protected AbstractHodCacheResolver constructCacheResolver() {
return new HodPerUserCacheResolver(new HodCacheNameResolverImpl());
}
@Override
protected void validateCacheNames(final Collection<String> resolvedNames) {
final String userId = userUuid.toString();
assertThat(resolvedNames, hasItems(
"DOMAIN:APPLICATION:" + userId + ":cacheName",
"DOMAIN:APPLICATION:" + userId + ":fooCache",
"DOMAIN:APPLICATION:" + userId + ":barCache"
));
}
}
| mit |
HexogenDev/Hexogen-API | src/main/java/net/hexogendev/hexogen/api/Side.java | 189 | package net.hexogendev.hexogen.api;
public enum Side {
CLIENT, SERVER;
public boolean isServer() {
return !isClient();
}
public boolean isClient() {
return this == CLIENT;
}
}
| mit |
zkmake520/Android_Search | indextank-engine-master/embedded-api/com/flaptor/indextank/api/util/QueryHelper.java | 931 | /*
* Copyright (c) 2011 LinkedIn, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.flaptor.indextank.api.util;
public class QueryHelper {
public static int parseIntParam(String param, int defaultValue) {
try {
if(param != null && !param.isEmpty())
return Integer.parseInt(param);
} catch(Exception e) {
}
return defaultValue;
}
}
| mit |
asegner/skinnywar-maven-plugin | src/test/java/net/segner/maven/plugins/communal/weblogic/WeblogicApplicationXmlTest.java | 1776 | package net.segner.maven.plugins.communal.weblogic;
import net.segner.maven.plugins.communal.module.EarModule;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.internal.util.reflection.Whitebox;
import org.mockito.runners.MockitoJUnitRunner;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsNull.notNullValue;
import static org.hamcrest.core.IsNull.nullValue;
@RunWith(MockitoJUnitRunner.class)
public class WeblogicApplicationXmlTest {
WeblogicApplicationXml weblogicApplicationXml;
@Mock
EarModule earModule;
@Before
public void before() {
weblogicApplicationXml = new WeblogicApplicationXml(earModule);
}
@Test
public void findClassloaderStructure_NotExisting() throws Exception {
// test
WeblogicClassloaderStructure classloaderStructure = weblogicApplicationXml.findClassloaderStructure();
// validate
assertThat("Classloader structure is null if none exists in the document",
classloaderStructure, nullValue());
}
@Test
public void createClassloaderStructure() throws Exception {
// test
WeblogicClassloaderStructure classloaderStructure = weblogicApplicationXml.createClassloaderStructure();
// validate
assertThat("Create classloader structure created something",
classloaderStructure, notNullValue(WeblogicClassloaderStructure.class));
assertThat("Classloader structure has a relationship with provided weblogicApplicationXml",
Whitebox.getInternalState(classloaderStructure, "applicationXml"), is(weblogicApplicationXml));
}
} | mit |
chocolateBlack/LearningSpark | src/main/java/dataframe/JavaFromRowsAndSchema.java | 2316 | package dataframe;
import org.apache.spark.sql.*;
import org.apache.spark.sql.types.DataTypes;
import org.apache.spark.sql.types.StructField;
import org.apache.spark.sql.types.StructType;
import static org.apache.spark.sql.functions.col;
import java.util.Arrays;
import java.util.List;
//
// Note that conceptually a DataFrame is a DataSet<Row>, bot the Java API
// doesn't actually have a definition of DataFrame.
//
// Create a Spark Dataset<Row> from a list of Row instances and a schema
// constructed explicitly. Query it.
//
// This example is fundamental for Dataset<Row> as the chema is created
// explicitly instead of being inferred via an Encoder like in the Dataset
// examples.
//
public class JavaFromRowsAndSchema {
public static void main(String[] args) {
SparkSession spark = SparkSession
.builder()
.appName("DataFrame-Jave-FromRowsAndSchema")
.master("local[4]")
.getOrCreate();
List<Row> customerRows = Arrays.asList(
RowFactory.create(1, "Widget Co", 120000.00, 0.00, "AZ"),
RowFactory.create(2, "Acme Widgets", 410500.00, 500.00, "CA"),
RowFactory.create(3, "Widgetry", 410500.00, 200.00, "CA"),
RowFactory.create(4, "Widgets R Us", 410500.00, 0.0, "CA"),
RowFactory.create(5, "Ye Olde Widgete", 500.00, 0.0, "MA")
);
List<StructField> fields = Arrays.asList(
DataTypes.createStructField("id", DataTypes.IntegerType, true),
DataTypes.createStructField("name", DataTypes.StringType, true),
DataTypes.createStructField("sales", DataTypes.DoubleType, true),
DataTypes.createStructField("discount", DataTypes.DoubleType, true),
DataTypes.createStructField("state", DataTypes.StringType, true)
);
StructType customerSchema = DataTypes.createStructType(fields);
Dataset<Row> customerDF =
spark.createDataFrame(customerRows, customerSchema);
System.out.println("*** the schema created");
customerDF.printSchema();
System.out.println("*** the data");
customerDF.show();
System.out.println("*** just the rows from CA");
customerDF.filter(col("state").equalTo("CA")).show();
spark.stop();
}
}
| mit |
keefe/categorizeus | core/src/main/java/us/categorize/communication/creation/attachment/S3AttachmentHandler.java | 2131 | package us.categorize.communication.creation.attachment;
import java.io.InputStream;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.model.PutObjectResult;
import us.categorize.communication.creation.MessageAssertionAttachment;
public class S3AttachmentHandler implements AttachmentHandler {
private String bucket;
private String region;
private String attachmentURLPrefix;
public S3AttachmentHandler(String bucket, String region, String attachmentURLPrefix){
this.bucket = bucket;
this.region = region;
this.attachmentURLPrefix = attachmentURLPrefix;
}
public String storeAttachment(String label, MessageAssertionAttachment attachmentAssertion, InputStream stream) {
AmazonS3 s3client = new AmazonS3Client(new ProfileCredentialsProvider());
Region currentRegion = Region.getRegion(Regions.fromName(region));//TODO this is working but uh what do I need to do here?
String contentType = attachmentAssertion.getType().toLowerCase();
String fileExtension = "dat";
if(contentType.contains("png")){
fileExtension = "png";
}else if(contentType.contains("jpg") || contentType.contains("jpeg")){
fileExtension = "jpg";
}else if(contentType.contains("gif")){
fileExtension = "gif";
}
String fname = label+"."+fileExtension;
ObjectMetadata s3Metadata = new ObjectMetadata();//TODO deal with specifying content length, per docs
s3Metadata.setContentLength(Integer.parseInt(attachmentAssertion.getSize()));
s3Metadata.setContentType(attachmentAssertion.getType());
PutObjectRequest por = new PutObjectRequest(bucket, fname, stream, s3Metadata);
por.setCannedAcl(CannedAccessControlList.PublicRead);
PutObjectResult result = s3client.putObject(por);
return attachmentURLPrefix+fname;
}
}
| mit |
sreeusha/javarepo | src/main/java/com/zvidia/pomelo/protobuf/MessageOption.java | 266 | package com.zvidia.pomelo.protobuf;
/**
* Created with IntelliJ IDEA.
* User: jiangzm
* Date: 13-8-7
* Time: 下午8:52
* To change this template use File | Settings | File Templates.
*/
public enum MessageOption {
required, optional, repeated, message
}
| mit |
georghinkel/ttc2017smartGrids | solutions/eMoflon/rgse.ttc17.metamodels.src/src/gluemodel/CIM/IEC61970/Informative/MarketOperations/impl/ProductBidClearingImpl.java | 6435 | /**
*/
package gluemodel.CIM.IEC61970.Informative.MarketOperations.impl;
import gluemodel.CIM.IEC61970.Informative.MarketOperations.MarketOperationsPackage;
import gluemodel.CIM.IEC61970.Informative.MarketOperations.ProductBid;
import gluemodel.CIM.IEC61970.Informative.MarketOperations.ProductBidClearing;
import java.util.Collection;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.impl.ENotificationImpl;
import org.eclipse.emf.ecore.util.EObjectWithInverseResolvingEList;
import org.eclipse.emf.ecore.util.InternalEList;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Product Bid Clearing</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* </p>
* <ul>
* <li>{@link gluemodel.CIM.IEC61970.Informative.MarketOperations.impl.ProductBidClearingImpl#getClearedMW <em>Cleared MW</em>}</li>
* <li>{@link gluemodel.CIM.IEC61970.Informative.MarketOperations.impl.ProductBidClearingImpl#getProductBids <em>Product Bids</em>}</li>
* </ul>
*
* @generated
*/
public class ProductBidClearingImpl extends MarketFactorsImpl implements ProductBidClearing {
/**
* The default value of the '{@link #getClearedMW() <em>Cleared MW</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getClearedMW()
* @generated
* @ordered
*/
protected static final float CLEARED_MW_EDEFAULT = 0.0F;
/**
* The cached value of the '{@link #getClearedMW() <em>Cleared MW</em>}' attribute.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getClearedMW()
* @generated
* @ordered
*/
protected float clearedMW = CLEARED_MW_EDEFAULT;
/**
* The cached value of the '{@link #getProductBids() <em>Product Bids</em>}' reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getProductBids()
* @generated
* @ordered
*/
protected EList<ProductBid> productBids;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected ProductBidClearingImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return MarketOperationsPackage.Literals.PRODUCT_BID_CLEARING;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public float getClearedMW() {
return clearedMW;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public void setClearedMW(float newClearedMW) {
float oldClearedMW = clearedMW;
clearedMW = newClearedMW;
if (eNotificationRequired())
eNotify(new ENotificationImpl(this, Notification.SET, MarketOperationsPackage.PRODUCT_BID_CLEARING__CLEARED_MW, oldClearedMW, clearedMW));
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<ProductBid> getProductBids() {
if (productBids == null) {
productBids = new EObjectWithInverseResolvingEList<ProductBid>(ProductBid.class, this, MarketOperationsPackage.PRODUCT_BID_CLEARING__PRODUCT_BIDS, MarketOperationsPackage.PRODUCT_BID__PRODUCT_BID_CLEARING);
}
return productBids;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case MarketOperationsPackage.PRODUCT_BID_CLEARING__PRODUCT_BIDS:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getProductBids()).basicAdd(otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case MarketOperationsPackage.PRODUCT_BID_CLEARING__PRODUCT_BIDS:
return ((InternalEList<?>)getProductBids()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case MarketOperationsPackage.PRODUCT_BID_CLEARING__CLEARED_MW:
return getClearedMW();
case MarketOperationsPackage.PRODUCT_BID_CLEARING__PRODUCT_BIDS:
return getProductBids();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case MarketOperationsPackage.PRODUCT_BID_CLEARING__CLEARED_MW:
setClearedMW((Float)newValue);
return;
case MarketOperationsPackage.PRODUCT_BID_CLEARING__PRODUCT_BIDS:
getProductBids().clear();
getProductBids().addAll((Collection<? extends ProductBid>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case MarketOperationsPackage.PRODUCT_BID_CLEARING__CLEARED_MW:
setClearedMW(CLEARED_MW_EDEFAULT);
return;
case MarketOperationsPackage.PRODUCT_BID_CLEARING__PRODUCT_BIDS:
getProductBids().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case MarketOperationsPackage.PRODUCT_BID_CLEARING__CLEARED_MW:
return clearedMW != CLEARED_MW_EDEFAULT;
case MarketOperationsPackage.PRODUCT_BID_CLEARING__PRODUCT_BIDS:
return productBids != null && !productBids.isEmpty();
}
return super.eIsSet(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public String toString() {
if (eIsProxy()) return super.toString();
StringBuffer result = new StringBuffer(super.toString());
result.append(" (clearedMW: ");
result.append(clearedMW);
result.append(')');
return result.toString();
}
} //ProductBidClearingImpl
| mit |
bilelz/phonegap-system-notification-plugin | android-statusbar-notificaion/SystemNotification.java | 3263 | package com.your_package_name;
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import com.phonegap.api.Plugin;
import com.phonegap.api.PluginResult;
import org.json.JSONArray;
public class SystemNotification extends Plugin {
final int notif_ID = 1234;
NotificationManager notificationManager;
Notification note;
PendingIntent contentIntent;
@Override
public PluginResult execute(String action, JSONArray args, String callbackId)
{
PluginResult.Status status = PluginResult.Status.OK;
String result = "";
try {
if (action.equals("createStatusBarNotification")) {
this.createStatusBarNotification(args.getString(0), args.getString(1), args.getString(2));
}
else if (action.equals("updateNotification")) {
this.updateNotification(args.getString(0), args.getString(1), args.getInt(2));
}
else if (action.equals("cancelNotification")) {
this.cancelNotification();
}
else if (action.equals("showTickerText")) {
this.showTickerText(args.getString(0));
}
return new PluginResult(status, result);
} catch(JSONException e) {
return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
}
}
private void updateNotification(String contentTitle, String contentText, int number)
{
note.setLatestEventInfo(this.ctx, contentTitle, contentText, contentIntent);
note.number = number;
notificationManager.notify(notif_ID,note);
}
private void createStatusBarNotification(String contentTitle, String contentText, String tickerText)
{
notificationManager = (NotificationManager) this.ctx.getSystemService(Context.NOTIFICATION_SERVICE);
note = new Notification(android.R.drawable.btn_star_big_on, tickerText, System.currentTimeMillis() );
//change the icon
Intent notificationIntent = new Intent(this.ctx, myActivityClass.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent = notificationIntent.setFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
contentIntent = PendingIntent.getActivity(this.ctx, 0, notificationIntent, 0);
note.setLatestEventInfo(this.ctx, contentTitle, contentText, contentIntent);
note.number = 1; //Just created notification so number=1. Remove this line if you dont want numbers
notificationManager.notify(notif_ID,note);
}
private void cancelNotification()
{
notificationManager.cancel(notif_ID);
}
private void showTickerText(String tickerText)
{
note.tickerText = tickerText;
notificationManager.notify(notif_ID,note);
}
@Override
public void onPause()
{
super.webView.loadUrl("javascript:navigator.systemNotification.onBackground();");
}
@Override
public void onResume()
{
super.webView.loadUrl("javascript:navigator.systemNotification.onForeground();");
}
}
| mit |
0x90sled/droidtowers | main/source/com/happydroids/droidtowers/achievements/RequirementType.java | 261 | /*
* Copyright (c) 2012. HappyDroids LLC, All rights reserved.
*/
package com.happydroids.droidtowers.achievements;
public enum RequirementType {
POPULATION,
EMPLOYMENT,
DESIRABILITY,
BUILD,
HIRE,
UNLOCK,
HAPPYDROIDS_CONNECT,
ADD_NEIGHBOR
}
| mit |
JunhuaLyu/Nxt-Client-For-Android | src/org/nextcoin/nxtclient/ToolsPage.java | 5600 | package org.nextcoin.nxtclient;
import org.nextcoin.alias.AliasAssignActivity;
import org.nextcoin.alias.AliasCheck;
import org.nextcoin.service.NxtBackgroudService;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Spinner;
public class ToolsPage {
private Context mContext;
private CheckBox mCheckBoxShowPrice;
private CheckBox mCheckBoxNotification;
private View mViewNotification;
private CheckBox mCheckBoxNotificationVibrate;
private Spinner mSpinnerInterval;
public ToolsPage(View page){
mContext = page.getContext();
// real-time price
mCheckBoxShowPrice = (CheckBox)page.findViewById(R.id.check_show_price);
mCheckBoxShowPrice.setChecked(Settings.sharedInstance().isShowingPrice(mContext));
mCheckBoxShowPrice.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Settings.sharedInstance().setShowingPrice(mContext, isChecked);
}});
// transaction notification
mCheckBoxNotification = (CheckBox)page.findViewById(R.id.check_notification);
mCheckBoxNotification.setChecked(Settings.sharedInstance().isNotificationEnable(mContext));
mCheckBoxNotification.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Settings.sharedInstance().setNotificationEnable(mContext, isChecked);
updateStatus();
}});
// notification vibrate
mCheckBoxNotificationVibrate = (CheckBox)page.findViewById(R.id.check_vibrate);
mCheckBoxNotificationVibrate.setChecked(Settings.sharedInstance().isNotificationVibrateEnable(mContext));
mCheckBoxNotificationVibrate.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Settings.sharedInstance().setNotificationVibrateEnable(mContext, isChecked);
}});
// transactions refresh interval
String options[] = new String[3];
options[0] = "5" + (String)mContext.getText(R.string.minute);
options[1] = "10" + (String)mContext.getText(R.string.minute);
options[2] = "30" + (String)mContext.getText(R.string.minute);
ArrayAdapter<String> spinnerAdapter =
new ArrayAdapter<String>(mContext,android.R.layout.simple_spinner_item, options);
spinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinnerInterval = (Spinner)page.findViewById(R.id.spinner_interval);
mSpinnerInterval.setAdapter(spinnerAdapter);
int index = Settings.sharedInstance().getNotificationInterval(mContext);
mSpinnerInterval.setSelection(index);
mSpinnerInterval.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
Settings.sharedInstance().setNotificationInterval(mContext, arg2);
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
}});
mViewNotification = page.findViewById(R.id.layout_interval);
Button btnAliasCheck = (Button)page.findViewById(R.id.btn_alias_check);
btnAliasCheck.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new AliasCheck().open(mContext);
}
});
Button btnAliasAssign = (Button)page.findViewById(R.id.btn_alias_assign);
btnAliasAssign.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mContext.startActivity(new Intent(mContext, AliasAssignActivity.class));
}
});
updateStatus();
}
static public int getRefreshInterval(Context context){
int index = Settings.sharedInstance().getNotificationInterval(context);
if ( 0 == index )
return 5;
else if ( 2 == index )
return 30;
else
return 10;
}
public void updateStatus(){
if ( Settings.sharedInstance().isNotificationEnable(mContext) ){
mViewNotification.setVisibility(View.VISIBLE);
mCheckBoxNotificationVibrate.setVisibility(View.VISIBLE);
Intent serviceIntent = new Intent(mContext, NxtBackgroudService.class);
mContext.startService(serviceIntent);
}else{
mViewNotification.setVisibility(View.GONE);
mCheckBoxNotificationVibrate.setVisibility(View.GONE);
Intent serviceIntent = new Intent(mContext, NxtBackgroudService.class);
mContext.stopService(serviceIntent);
}
}
public void update(){
}
public void release(){
}
}
| mit |
InMobi/api-monetization | java/src/main/java/com/inmobi/monetization/api/request/ad/Slot.java | 2150 | package main.java.com.inmobi.monetization.api.request.ad;
import main.java.com.inmobi.monetization.api.request.utils.Validator;
import main.java.com.inmobi.monetization.api.utils.InternalUtil;
/**
* This class represents the "banner" object, required under the "imp" object to
* describe the type of ad requested.</br>
*
* <p>
* <b>Note:</b>
* </p>
* It is a must to provide a valid ad-slot if you're requesting
* Banner/Interstitial ads. If in case you have not provided a valid value, the
* back end system would choose a default value.
*
* @author rishabhchowdhary
*
*/
public class Slot implements Validator {
private int adSize = 0;
private String position = null;
/**
*
* @return The int value corresponding to the slot size.
*
*/
public int getAdSize() {
return adSize;
}
/**
* Use this setter to provide an ad-size.
*
* @param adSize
* The integer value to represent the requested ad-size.</br>
* <b>Note:</b> Must be greater than zero.
*/
public void setAdSize(int adSize) {
if (adSize > 0) {
this.adSize = adSize;
}
}
/**
*
* @return Returns the String value of the position specified.
*/
public String getPosition() {
return position;
}
/**
*
* @param position
* The position in your app where the banner is placed.</br>
* <b>Example:</b> "top", "center", "bottom", etc.
*/
public void setPosition(String position) {
if (!InternalUtil.isBlank(position)) {
this.position = position;
}
}
public Slot(int adSize, String position) {
setAdSize(adSize);
setPosition(position);
}
public Slot() {
}
/**
* Use this method to check if this object has all the required parameters
* present, to be used to construct a JSON request. The required parameters
* would be specific to an ad-format.
*
* @param type
* The AdRequestType - one of Banner,Interstitial or Native.
* @return If the mandatory params are present, then true, otherwise false.
*/
public boolean isValid() {
boolean isValid = true;
if (adSize <= 0) {
isValid = false;
}
return isValid;
}
}
| mit |
i386/app-store-demo | src/test/java/appstore/TestThisWillFailAbunch.java | 1759 | package appstore;
import static org.junit.Assert.*;
import org.junit.Ignore;
import org.junit.Test;
public class TestThisWillFailAbunch {
@Test
public void aFailingTest() {
assertTrue("I expected this to pass!", true);
}
@Ignore
@Test
public void aFailingTest2() {
// doSomething();
assertTrue("I expected this to pass!", true);
}
@Ignore
@Test
public void aFailingTest3() {
// doSomething();
assertTrue("I expected this to pass!", true);
}
//@Ignore
@Test
public void aFailingTest4() {
// doSomething();
assertTrue("I expected this to pass!", true);
}
@Ignore
@Test
public void aNewFailingTest31() {
// doSomething();
assertTrue("I expected this to pass!", true);
}
@Test
public void aNotherNewFailingTest4() {
// doSomething();
assertTrue("I expected this to pass!", true);
}
@Test
public void aFailingTest5() {
// doSomething();
assertTrue("I expected this to pass!", true);
}
@Test
public void aFailingTest6() {
// doSomething();
assertTrue("I expected this to pass!", true);
}
@Test
public void aPassingTest3() {
assertTrue("Success!", true);
}
@Test
public void aPassingTest4() {
assertTrue("Success!", true);
}
private void doSomething() {
interesting();
}
private void interesting() {
RubeGoldburgMachine machine = new RubeGoldburgMachine();
machine.processPayment();
}
private class RubeGoldburgMachine {
void processPayment() {
throw new IllegalStateException("bad payment code");
}
}
}
| mit |
napstr/FredBoat | FredBoat/src/main/java/fredboat/util/rest/Weather.java | 706 | package fredboat.util.rest;
import fredboat.util.rest.models.weather.RetrievedWeather;
import javax.annotation.Nonnull;
/**
* Interface for the command class to call the model to get different
* implementation(s) of weather provider.
* <p>
* To add other provider, just implement this interface for their data model.
*/
public interface Weather {
/**
* Get current weather by the city.
*
* @param query Query for querying the weather.
* @return Weather object that contains information from the query.
* @throws APILimitException If the API rate has been exceeded.
*/
RetrievedWeather getCurrentWeatherByCity(@Nonnull String query) throws APILimitException;
}
| mit |
GraphWalker/graphwalker-project | graphwalker-websocket/src/test/java/org/graphwalker/websocket/WebSocketServerTest.java | 4184 | package org.graphwalker.websocket;
/*
* #%L
* GraphWalker As A Service
* %%
* Copyright (C) 2005 - 2014 GraphWalker
* %%
* 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.
* #L%
*/
import static org.hamcrest.CoreMatchers.is;
import java.io.IOException;
import java.nio.file.Paths;
import org.graphwalker.core.generator.SingletonRandomGenerator;
import org.graphwalker.core.machine.ExecutionContext;
import org.graphwalker.java.annotation.BeforeExecution;
import org.graphwalker.java.annotation.GraphWalker;
import org.graphwalker.java.test.TestExecutionException;
import org.graphwalker.java.test.TestExecutor;
import org.java_websocket.WebSocket;
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Created by krikar on 10/10/14.
*/
@GraphWalker(value = "random(edge_coverage(100))", start = "e_Connect")
public class WebSocketServerTest extends ExecutionContext implements WebSocketFlow {
private static final Logger logger = LoggerFactory.getLogger(WebSocketServerTest.class);
private WebSocketClient client = new WebSocketClient();
private WebSocketServer server;
private int numberOfConnections = 0;
private int expectedValue = 54686327;
@BeforeExecution
public void startServer() throws Exception {
SingletonRandomGenerator.setSeed(222930684376058L);
server = new WebSocketServer(8887);
server.start();
}
@Test
public void testRun() throws IOException {
TestExecutor testExecutor = new TestExecutor(getClass());
try {
testExecutor.execute(false);
} catch (TestExecutionException e) {
if (e.hasErrors()) {
for (String error : e.getResult().getErrors()) {
System.err.println(error);
}
Assert.fail("Did not expect any errors");
}
}
}
@Override
public void e_StartMachine() {
client.startMachine(Paths.get("json/SmallModel.json"));
}
@Override
public void e_Connect() {
numberOfConnections = server.getSockets().size();
client.run();
}
@Override
public void v_MachineRunning() {
WebSocket socket = server.getSockets().iterator().next();
Assert.assertNotNull(server.getMachines().get(socket));
}
@Override
public void e_HasNext() {
client.hasNext();
}
@Override
public void v_EmptyMachine() {
Assert.assertThat("Before we connected, we should have no connections", numberOfConnections, is(0));
Assert.assertThat("We should now haw 1 connection", server.getSockets().size(), is(1));
Assert.assertThat(server.getMachines().size(), is(1));
WebSocket socket = server.getSockets().iterator().next();
Assert.assertNull(server.getMachines().get(socket));
}
@Override
public void e_GetData() {
String response = client.getData();
JSONObject jsonObject = new JSONObject(response);
Assert.assertEquals(expectedValue, jsonObject.getInt("value"));
}
@Override
public void e_SetData() {
expectedValue = SingletonRandomGenerator.nextInt();
client.setData("value=" + expectedValue);
}
@Override
public void e_GetNext() {
client.getNext();
}
}
| mit |
kaituo/sedge | trunk/src/org/apache/pig/impl/util/NumValCarrier.java | 2238 | /*
* 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.pig.impl.util;
import java.util.Map;
import java.util.HashMap;
import org.apache.pig.data.DataType;
public class NumValCarrier {
private Map<Byte,ValCarrier> byteToStr = new HashMap<Byte,ValCarrier>(10);
public NumValCarrier() {
ValCarrier valCarrier = new ValCarrier("val");
ValCarrier bagCarrier = new ValCarrier("bag");
ValCarrier tupleCarrier = new ValCarrier("tuple");
ValCarrier mapCarrier = new ValCarrier("map");
ValCarrier nullCarrier = new ValCarrier("null");
byteToStr.put(DataType.BAG,bagCarrier);
byteToStr.put(DataType.CHARARRAY,valCarrier);
byteToStr.put(DataType.BYTEARRAY,valCarrier);
byteToStr.put(DataType.DOUBLE,valCarrier);
byteToStr.put(DataType.FLOAT,valCarrier);
byteToStr.put(DataType.INTEGER,valCarrier);
byteToStr.put(DataType.LONG,valCarrier);
byteToStr.put(DataType.MAP,mapCarrier);
byteToStr.put(DataType.TUPLE,tupleCarrier);
byteToStr.put(DataType.NULL,nullCarrier);
}
public String makeNameFromDataType(byte type) {
return byteToStr.get(type).getNextString();
}
private static class ValCarrier {
private int num=0;
private String str;
public ValCarrier(String str) {
this.str=str;
}
public String getNextString() {
return str+"_"+num++;
}
}
}
| mit |
selvasingh/azure-sdk-for-java | sdk/network/mgmt-v2019_09_01/src/main/java/com/microsoft/azure/management/network/v2019_09_01/ExpressRouteCircuitStats.java | 1123 | /**
* 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_09_01;
import com.microsoft.azure.arm.model.HasInner;
import com.microsoft.azure.arm.resources.models.HasManager;
import com.microsoft.azure.management.network.v2019_09_01.implementation.NetworkManager;
import com.microsoft.azure.management.network.v2019_09_01.implementation.ExpressRouteCircuitStatsInner;
/**
* Type representing ExpressRouteCircuitStats.
*/
public interface ExpressRouteCircuitStats extends HasInner<ExpressRouteCircuitStatsInner>, HasManager<NetworkManager> {
/**
* @return the primarybytesIn value.
*/
Long primarybytesIn();
/**
* @return the primarybytesOut value.
*/
Long primarybytesOut();
/**
* @return the secondarybytesIn value.
*/
Long secondarybytesIn();
/**
* @return the secondarybytesOut value.
*/
Long secondarybytesOut();
}
| mit |
dandeeee/android-course | day-08/1_TicTacToe/app/src/main/java/com/dandeeee/tictactoe/ui/component/ColorPickerView.java | 4923 | package com.dandeeee.tictactoe.ui.component;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.Shader;
import android.graphics.SweepGradient;
import android.view.MotionEvent;
import android.view.View;
public class ColorPickerView extends View {
private Paint mPaint;
private Paint mCenterPaint;
private final int[] mColors;
private OnColorChangedListener mListener;
public ColorPickerView(Context c, OnColorChangedListener l, int color) {
super(c);
mListener = l;
mColors = new int[]{
0xFFFF0000, 0xFFFF00FF, 0xFF0000FF, 0xFF00FFFF, 0xFF00FF00,
0xFFFFFF00, 0xFFFF0000
};
Shader s = new SweepGradient(0, 0, mColors, null);
mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mPaint.setShader(s);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeWidth(32);
mCenterPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
mCenterPaint.setColor(color);
mCenterPaint.setStrokeWidth(5);
}
private boolean mTrackingCenter;
private boolean mHighlightCenter;
@Override
protected void onDraw(Canvas canvas) {
float r = CENTER_X - mPaint.getStrokeWidth() * 0.5f;
canvas.translate(CENTER_X, CENTER_X);
canvas.drawOval(new RectF(-r, -r, r, r), mPaint);
canvas.drawCircle(0, 0, CENTER_RADIUS, mCenterPaint);
if (mTrackingCenter) {
int c = mCenterPaint.getColor();
mCenterPaint.setStyle(Paint.Style.STROKE);
if (mHighlightCenter) {
mCenterPaint.setAlpha(0xFF);
} else {
mCenterPaint.setAlpha(0x80);
}
canvas.drawCircle(0, 0,
CENTER_RADIUS + mCenterPaint.getStrokeWidth(),
mCenterPaint);
mCenterPaint.setStyle(Paint.Style.FILL);
mCenterPaint.setColor(c);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(CENTER_X * 2, CENTER_Y * 2);
}
private static final int CENTER_X = 100;
private static final int CENTER_Y = 100;
private static final int CENTER_RADIUS = 32;
private int ave(int s, int d, float p) {
return s + java.lang.Math.round(p * (d - s));
}
private int interpColor(int colors[], float unit) {
if (unit <= 0) {
return colors[0];
}
if (unit >= 1) {
return colors[colors.length - 1];
}
float p = unit * (colors.length - 1);
int i = (int) p;
p -= i;
// now p is just the fractional part [0...1) and i is the index
int c0 = colors[i];
int c1 = colors[i + 1];
int a = ave(Color.alpha(c0), Color.alpha(c1), p);
int r = ave(Color.red(c0), Color.red(c1), p);
int g = ave(Color.green(c0), Color.green(c1), p);
int b = ave(Color.blue(c0), Color.blue(c1), p);
return Color.argb(a, r, g, b);
}
private static final float PI = 3.1415926f;
@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX() - CENTER_X;
float y = event.getY() - CENTER_Y;
boolean inCenter = java.lang.Math.sqrt(x * x + y * y) <= CENTER_RADIUS;
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mTrackingCenter = inCenter;
if (inCenter) {
mHighlightCenter = true;
invalidate();
break;
}
case MotionEvent.ACTION_MOVE:
if (mTrackingCenter) {
if (mHighlightCenter != inCenter) {
mHighlightCenter = inCenter;
invalidate();
}
} else {
float angle = (float) java.lang.Math.atan2(y, x);
// need to turn angle [-PI ... PI] into unit [0....1]
float unit = angle / (2 * PI);
if (unit < 0) {
unit += 1;
}
mCenterPaint.setColor(interpColor(mColors, unit));
invalidate();
}
break;
case MotionEvent.ACTION_UP:
if (mTrackingCenter) {
if (inCenter) {
mListener.colorChanged(mCenterPaint.getColor());
}
mTrackingCenter = false; // so we draw w/o halo
invalidate();
}
break;
}
return true;
}
public interface OnColorChangedListener {
void colorChanged(int color);
}
} | mit |
selvasingh/azure-sdk-for-java | sdk/apimanagement/mgmt-v2019_01_01/src/main/java/com/microsoft/azure/management/apimanagement/v2019_01_01/SignUpSettings.java | 2748 | /**
* 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.apimanagement.v2019_01_01;
import rx.Completable;
import rx.Observable;
import com.microsoft.azure.management.apimanagement.v2019_01_01.implementation.PortalSignupSettingsInner;
import com.microsoft.azure.management.apimanagement.v2019_01_01.implementation.SignUpSettingsInner;
import com.microsoft.azure.arm.model.HasInner;
/**
* Type representing SignUpSettings.
*/
public interface SignUpSettings extends HasInner<SignUpSettingsInner> {
/**
* Gets the entity state (Etag) version of the SignUpSettings.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Completable getEntityTagAsync(String resourceGroupName, String serviceName);
/**
* Get Sign Up Settings for the Portal.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Observable<PortalSignupSettings> getAsync(String resourceGroupName, String serviceName);
/**
* Update Sign-Up settings.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param parameters Update Sign-Up settings.
* @param ifMatch ETag of the Entity. ETag should match the current entity state from the header response of the GET request or it should be * for unconditional update.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Completable updateAsync(String resourceGroupName, String serviceName, PortalSignupSettingsInner parameters, String ifMatch);
/**
* Create or Update Sign-Up settings.
*
* @param resourceGroupName The name of the resource group.
* @param serviceName The name of the API Management service.
* @param parameters Create or update parameters.
* @throws IllegalArgumentException thrown if parameters fail the validation
* @return the observable for the request
*/
Observable<PortalSignupSettings> createOrUpdateAsync(String resourceGroupName, String serviceName, PortalSignupSettingsInner parameters);
}
| mit |
diku-kmc/repg | bench/re2j/src/Patho2.java | 1507 | import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import com.google.re2j.Matcher;
import com.google.re2j.Pattern;
// RE2/J version of "patho2"
public class Patho2 {
private static String regex = "^(?:([a-z]*a)|([a-z]*b))?(?:\n)?$";
public static void main(String [] args) {
int lno = 0;
long preCompile = System.currentTimeMillis();
Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
Matcher matcher;
BufferedReader bi = new BufferedReader(new InputStreamReader(System.in));
String line;
long start = System.currentTimeMillis();
try {
while((line = bi.readLine()) != null) {
lno++;
matcher = pattern.matcher(line);
if(matcher.matches()) {
System.out.print(String.format("%s\n", matcher.group(2) != null ? matcher.group(2) : ""));
} else {
System.err.print(String.format("match error on line %d\n", lno));
}
}
} catch(IOException e) {
System.err.print(String.format("IOException at line %d\n", lno));
}
long end = System.currentTimeMillis();
long elaps = end - start;
long elapsCompile = start - preCompile;
System.err.print(String.format("\ncompilation (ms): %d\n", elapsCompile));
System.err.print(String.format("matching (ms): %d\n", elaps));
}
}
| mit |
hogeschool/INFDEV-Homework | Solutions to homework/java/chapter2/fuels/Dilithium.java | 318 | package chapter2.fuels;
public class Dilithium implements IFuel {
int amount;
public Dilithium(int amount) {
setAmount(amount);
}
@Override
public int getAmount() {
return amount;
}
@Override
public void setAmount(int amount) {
this.amount = amount;
}
}
| mit |
hpautonomy/java-aci-annotations-processor | src/test/java/com/autonomy/aci/client/annotations/testobjects/bugs/subclass/NewsResultCluster.java | 1832 | /*
* Copyright 2015 Hewlett-Packard Development Company, L.P.
* Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
*/
package com.autonomy.aci.client.annotations.testobjects.bugs.subclass;
import com.autonomy.aci.client.annotations.IdolDocument;
import com.autonomy.aci.client.annotations.IdolField;
import com.autonomy.aci.client.annotations.IdolProcessorField;
import java.util.LinkedList;
import java.util.List;
@IdolDocument("autn:cluster")
public class NewsResultCluster {
private String title;
private String category;
private float score;
private final List<String> terms = new LinkedList<>();
private final List<NewsResultDocument> documents = new LinkedList<>();
public String getCategory() {
return category;
}
public List<NewsResultDocument> getDocuments() {
return documents;
}
public float getScore() {
return score;
}
public List<String> getTerms() {
return terms;
}
public String getTitle() {
return title;
}
@IdolField("autn:title")
public NewsResultCluster setTitle(final String value) {
this.title = value;
return this;
}
public NewsResultCluster setCategory(final String value) {
this.category = value;
return this;
}
@IdolField("autn:score")
public NewsResultCluster setScore(final float value) {
this.score = value;
return this;
}
@IdolField("autn:term")
public NewsResultCluster addTerm(final String value) {
this.terms.add(value);
return this;
}
@IdolProcessorField("autn:doc")
public NewsResultCluster addDocument(final NewsResultDocument value) {
this.documents.add(value);
return this;
}
}
| mit |
MrCreosote/workspace_deluxe | src/us/kbase/workspace/database/ResolvedObjectIDNoVer.java | 3998 | package us.kbase.workspace.database;
import static us.kbase.workspace.database.ObjectIDNoWSNoVer.checkObjectName;
import static us.kbase.workspace.database.Util.nonNull;
/** An object identifier that has been partially resolved against the data store, e.g. the name
* and id are available for the workspace and object, but the version is not available.
*
* The names are resolved *at the time the database was accessed and are not further
* updated*.
*
* The underlying assumption of this class is all object IDs are unique and all
* names are unique at the time of resolution. Therefore a set of
* ResolvedObjectIDs constructed at the same time are all unique in name and id,
* and removing one or the other field would not cause the number of unique
* objects to change (as measured by the unique hashcode count, for example).
*
* This is *not* the case for objects generated from different queries.
*
* @author gaprice@lbl.gov
*
*/
public class ResolvedObjectIDNoVer {
private final ResolvedWorkspaceID rwsi;
private final String name;
private final long id;
private final boolean deleted;
/** Create a resolved object identifier without a version.
* @param rwsi the identifier of the resolved workspace in which the object resides.
* @param id the id of the object.
* @param name the name of the object.
* @param deleted true if the object is deleted, false otherwise.
*/
public ResolvedObjectIDNoVer(
final ResolvedWorkspaceID rwsi,
final long id,
final String name,
final boolean deleted) {
nonNull(rwsi, "rwsi");
if (id < 1) {
throw new IllegalArgumentException("id must be > 0");
}
checkObjectName(name);
this.rwsi = rwsi;
this.name = name;
this.id = id;
this.deleted = deleted;
}
/** Create a resolved object identifier without a version from a fully resolved object
* identifier.
* @param roid a fully resolved object identifier.
*/
public ResolvedObjectIDNoVer(final ResolvedObjectID roid) {
nonNull(roid, "roid");
this.rwsi = roid.getWorkspaceIdentifier();
this.name = roid.getName();
this.id = roid.getId();
this.deleted = roid.isDeleted();
}
/** Get the workspace identifier.
* @return the workspace identifier.
*/
public ResolvedWorkspaceID getWorkspaceIdentifier() {
return rwsi;
}
/** Get the object name.
* @return the name.
*/
public String getName() {
return name;
}
/** Get the object id.
* @return the id.
*/
public long getId() {
return id;
}
/** Get whether the object is deleted.
* @return true if the object is deleted.
*/
public boolean isDeleted() {
return deleted;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("ResolvedObjectIDNoVer [rwsi=");
builder.append(rwsi);
builder.append(", name=");
builder.append(name);
builder.append(", id=");
builder.append(id);
builder.append(", deleted=");
builder.append(deleted);
builder.append("]");
return builder.toString();
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (deleted ? 1231 : 1237);
result = prime * result + (int) (id ^ (id >>> 32));
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((rwsi == null) ? 0 : rwsi.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;
}
ResolvedObjectIDNoVer other = (ResolvedObjectIDNoVer) obj;
if (deleted != other.deleted) {
return false;
}
if (id != other.id) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
if (rwsi == null) {
if (other.rwsi != null) {
return false;
}
} else if (!rwsi.equals(other.rwsi)) {
return false;
}
return true;
}
}
| mit |
Deadrik/jMapGen | src/pythagoras/f/GeometryUtil.java | 19709 | //
// Pythagoras - a collection of geometry classes
// http://github.com/samskivert/pythagoras
package pythagoras.f;
/**
* Various geometry utility methods.
*/
public class GeometryUtil
{
public static final float EPSILON = FloatMath.pow(10, -14);
public static int intersectLinesWithParams (float x1, float y1, float x2, float y2,
float x3, float y3, float x4, float y4,
float[] params) {
float dx = x4 - x3;
float dy = y4 - y3;
float d = dx * (y2 - y1) - dy * (x2 - x1);
// float comparison
if (Math.abs(d) < EPSILON) {
return 0;
}
params[0] = (-dx * (y1 - y3) + dy * (x1 - x3)) / d;
if (dx != 0) {
params[1] = (line(params[0], x1, x2) - x3) / dx;
} else if (dy != 0) {
params[1] = (line(params[0], y1, y2) - y3) / dy;
} else {
params[1] = 0f;
}
if (params[0] >= 0 && params[0] <= 1 && params[1] >= 0 && params[1] <= 1) {
return 1;
}
return 0;
}
/**
* Checks whether line (x1, y1) - (x2, y2) and line (x3, y3) - (x4, y4) intersect. If lines
* intersect then the result parameters are saved to point array. The size of {@code point}
* must be at least 2.
*
* @return 1 if two lines intersect in the defined interval, otherwise 0.
*/
public static int intersectLines (float x1, float y1, float x2, float y2, float x3, float y3,
float x4, float y4, float[] point) {
float A1 = -(y2 - y1);
float B1 = (x2 - x1);
float C1 = x1 * y2 - x2 * y1;
float A2 = -(y4 - y3);
float B2 = (x4 - x3);
float C2 = x3 * y4 - x4 * y3;
float coefParallel = A1 * B2 - A2 * B1;
// float comparison
if (x3 == x4 && y3 == y4 && (A1 * x3 + B1 * y3 + C1 == 0) && (x3 >= Math.min(x1, x2)) &&
(x3 <= Math.max(x1, x2)) && (y3 >= Math.min(y1, y2)) && (y3 <= Math.max(y1, y2))) {
return 1;
}
if (Math.abs(coefParallel) < EPSILON) {
return 0;
}
point[0] = (B1 * C2 - B2 * C1) / coefParallel;
point[1] = (A2 * C1 - A1 * C2) / coefParallel;
if (point[0] >= Math.min(x1, x2) && point[0] >= Math.min(x3, x4) &&
point[0] <= Math.max(x1, x2) && point[0] <= Math.max(x3, x4) &&
point[1] >= Math.min(y1, y2) && point[1] >= Math.min(y3, y4) &&
point[1] <= Math.max(y1, y2) && point[1] <= Math.max(y3, y4)) {
return 1;
}
return 0;
}
/**
* Checks whether there is intersection of the line (x1, y1) - (x2, y2) and the quad curve
* (qx1, qy1) - (qx2, qy2) - (qx3, qy3). The parameters of the intersection area saved to
* {@code params}. Therefore {@code params} must be of length at least 4.
*
* @return the number of roots that lie in the defined interval.
*/
public static int intersectLineAndQuad (float x1, float y1, float x2, float y2,
float qx1, float qy1, float qx2, float qy2,
float qx3, float qy3, float[] params) {
float[] eqn = new float[3];
float[] t = new float[2];
float[] s = new float[2];
float dy = y2 - y1;
float dx = x2 - x1;
int quantity = 0;
int count = 0;
eqn[0] = dy * (qx1 - x1) - dx * (qy1 - y1);
eqn[1] = 2 * dy * (qx2 - qx1) - 2 * dx * (qy2 - qy1);
eqn[2] = dy * (qx1 - 2 * qx2 + qx3) - dx * (qy1 - 2 * qy2 + qy3);
if ((count = Crossing.solveQuad(eqn, t)) == 0) {
return 0;
}
for (int i = 0; i < count; i++) {
if (dx != 0) {
s[i] = (quad(t[i], qx1, qx2, qx3) - x1) / dx;
} else if (dy != 0) {
s[i] = (quad(t[i], qy1, qy2, qy3) - y1) / dy;
} else {
s[i] = 0f;
}
if (t[i] >= 0 && t[i] <= 1 && s[i] >= 0 && s[i] <= 1) {
params[2 * quantity] = t[i];
params[2 * quantity + 1] = s[i];
++quantity;
}
}
return quantity;
}
/**
* Checks whether the line (x1, y1) - (x2, y2) and the cubic curve (cx1, cy1) - (cx2, cy2) -
* (cx3, cy3) - (cx4, cy4) intersect. The points of intersection are saved to {@code points}.
* Therefore {@code points} must be of length at least 6.
*
* @return the numbers of roots that lie in the defined interval.
*/
public static int intersectLineAndCubic (float x1, float y1, float x2, float y2,
float cx1, float cy1, float cx2, float cy2,
float cx3, float cy3, float cx4, float cy4,
float[] params) {
float[] eqn = new float[4];
float[] t = new float[3];
float[] s = new float[3];
float dy = y2 - y1;
float dx = x2 - x1;
int quantity = 0;
int count = 0;
eqn[0] = (cy1 - y1) * dx + (x1 - cx1) * dy;
eqn[1] = -3 * (cy1 - cy2) * dx + 3 * (cx1 - cx2) * dy;
eqn[2] = (3 * cy1 - 6 * cy2 + 3 * cy3) * dx - (3 * cx1 - 6 * cx2 + 3 * cx3) * dy;
eqn[3] = (-3 * cy1 + 3 * cy2 - 3 * cy3 + cy4) * dx +
(3 * cx1 - 3 * cx2 + 3 * cx3 - cx4) * dy;
if ((count = Crossing.solveCubic(eqn, t)) == 0) {
return 0;
}
for (int i = 0; i < count; i++) {
if (dx != 0) {
s[i] = (cubic(t[i], cx1, cx2, cx3, cx4) - x1) / dx;
} else if (dy != 0) {
s[i] = (cubic(t[i], cy1, cy2, cy3, cy4) - y1) / dy;
} else {
s[i] = 0f;
}
if (t[i] >= 0 && t[i] <= 1 && s[i] >= 0 && s[i] <= 1) {
params[2 * quantity] = t[i];
params[2 * quantity + 1] = s[i];
++quantity;
}
}
return quantity;
}
/**
* Checks whether two quads (x1, y1) - (x2, y2) - (x3, y3) and (qx1, qy1) - (qx2, qy2) - (qx3,
* qy3) intersect. The result is saved to {@code params}. Thus {@code params} must be of length
* at least 4.
*
* @return the number of roots that lie in the interval.
*/
public static int intersectQuads (float x1, float y1, float x2, float y2, float x3, float y3,
float qx1, float qy1, float qx2, float qy2, float qx3,
float qy3, float[] params) {
float[] initParams = new float[2];
float[] xCoefs1 = new float[3];
float[] yCoefs1 = new float[3];
float[] xCoefs2 = new float[3];
float[] yCoefs2 = new float[3];
int quantity = 0;
xCoefs1[0] = x1 - 2 * x2 + x3;
xCoefs1[1] = -2 * x1 + 2 * x2;
xCoefs1[2] = x1;
yCoefs1[0] = y1 - 2 * y2 + y3;
yCoefs1[1] = -2 * y1 + 2 * y2;
yCoefs1[2] = y1;
xCoefs2[0] = qx1 - 2 * qx2 + qx3;
xCoefs2[1] = -2 * qx1 + 2 * qx2;
xCoefs2[2] = qx1;
yCoefs2[0] = qy1 - 2 * qy2 + qy3;
yCoefs2[1] = -2 * qy1 + 2 * qy2;
yCoefs2[2] = qy1;
// initialize params[0] and params[1]
params[0] = params[1] = 0.25f;
quadNewton(xCoefs1, yCoefs1, xCoefs2, yCoefs2, initParams);
if (initParams[0] <= 1 && initParams[0] >= 0 && initParams[1] >= 0 && initParams[1] <= 1) {
params[2 * quantity] = initParams[0];
params[2 * quantity + 1] = initParams[1];
++quantity;
}
// initialize params
params[0] = params[1] = 0.75f;
quadNewton(xCoefs1, yCoefs1, xCoefs2, yCoefs2, params);
if (initParams[0] <= 1 && initParams[0] >= 0 && initParams[1] >= 0 && initParams[1] <= 1) {
params[2 * quantity] = initParams[0];
params[2 * quantity + 1] = initParams[1];
++quantity;
}
return quantity;
}
/**
* Checks whether the quad (x1, y1) - (x2, y2) - (x3, y3) and the cubic (cx1, cy1) - (cx2, cy2)
* - (cx3, cy3) - (cx4, cy4) curves intersect. The points of the intersection are saved to
* {@code params}. Thus {@code params} must be of length at least 6.
*
* @return the number of intersection points that lie in the interval.
*/
public static int intersectQuadAndCubic (float qx1, float qy1, float qx2, float qy2,
float qx3, float qy3, float cx1, float cy1,
float cx2, float cy2, float cx3, float cy3,
float cx4, float cy4, float[] params) {
int quantity = 0;
float[] initParams = new float[3];
float[] xCoefs1 = new float[3];
float[] yCoefs1 = new float[3];
float[] xCoefs2 = new float[4];
float[] yCoefs2 = new float[4];
xCoefs1[0] = qx1 - 2 * qx2 + qx3;
xCoefs1[1] = 2 * qx2 - 2 * qx1;
xCoefs1[2] = qx1;
yCoefs1[0] = qy1 - 2 * qy2 + qy3;
yCoefs1[1] = 2 * qy2 - 2 * qy1;
yCoefs1[2] = qy1;
xCoefs2[0] = -cx1 + 3 * cx2 - 3 * cx3 + cx4;
xCoefs2[1] = 3 * cx1 - 6 * cx2 + 3 * cx3;
xCoefs2[2] = -3 * cx1 + 3 * cx2;
xCoefs2[3] = cx1;
yCoefs2[0] = -cy1 + 3 * cy2 - 3 * cy3 + cy4;
yCoefs2[1] = 3 * cy1 - 6 * cy2 + 3 * cy3;
yCoefs2[2] = -3 * cy1 + 3 * cy2;
yCoefs2[3] = cy1;
// initialize params[0] and params[1]
params[0] = params[1] = 0.25f;
quadAndCubicNewton(xCoefs1, yCoefs1, xCoefs2, yCoefs2, initParams);
if (initParams[0] <= 1 && initParams[0] >= 0 && initParams[1] >= 0 && initParams[1] <= 1) {
params[2 * quantity] = initParams[0];
params[2 * quantity + 1] = initParams[1];
++quantity;
}
// initialize params
params[0] = params[1] = 0.5f;
quadAndCubicNewton(xCoefs1, yCoefs1, xCoefs2, yCoefs2, params);
if (initParams[0] <= 1 && initParams[0] >= 0 && initParams[1] >= 0 && initParams[1] <= 1) {
params[2 * quantity] = initParams[0];
params[2 * quantity + 1] = initParams[1];
++quantity;
}
params[0] = params[1] = 0.75f;
quadAndCubicNewton(xCoefs1, yCoefs1, xCoefs2, yCoefs2, params);
if (initParams[0] <= 1 && initParams[0] >= 0 && initParams[1] >= 0 && initParams[1] <= 1) {
params[2 * quantity] = initParams[0];
params[2 * quantity + 1] = initParams[1];
++quantity;
}
return quantity;
}
/**
* Checks whether two cubic curves (x1, y1) - (x2, y2) - (x3, y3) - (x4, y4) and (cx1, cy1) -
* (cx2, cy2) - (cx3, cy3) - (cx4, cy4) intersect. The result is saved to {@code params}. Thus
* {@code params} must be of length at least 6.
*
* @return the number of intersection points that lie in the interval.
*/
public static int intersectCubics (float x1, float y1, float x2, float y2, float x3, float y3,
float x4, float y4, float cx1, float cy1,
float cx2, float cy2, float cx3, float cy3,
float cx4, float cy4, float[] params) {
int quantity = 0;
float[] initParams = new float[3];
float[] xCoefs1 = new float[4];
float[] yCoefs1 = new float[4];
float[] xCoefs2 = new float[4];
float[] yCoefs2 = new float[4];
xCoefs1[0] = -x1 + 3 * x2 - 3 * x3 + x4;
xCoefs1[1] = 3 * x1 - 6 * x2 + 3 * x3;
xCoefs1[2] = -3 * x1 + 3 * x2;
xCoefs1[3] = x1;
yCoefs1[0] = -y1 + 3 * y2 - 3 * y3 + y4;
yCoefs1[1] = 3 * y1 - 6 * y2 + 3 * y3;
yCoefs1[2] = -3 * y1 + 3 * y2;
yCoefs1[3] = y1;
xCoefs2[0] = -cx1 + 3 * cx2 - 3 * cx3 + cx4;
xCoefs2[1] = 3 * cx1 - 6 * cx2 + 3 * cx3;
xCoefs2[2] = -3 * cx1 + 3 * cx2;
xCoefs2[3] = cx1;
yCoefs2[0] = -cy1 + 3 * cy2 - 3 * cy3 + cy4;
yCoefs2[1] = 3 * cy1 - 6 * cy2 + 3 * cy3;
yCoefs2[2] = -3 * cy1 + 3 * cy2;
yCoefs2[3] = cy1;
// TODO
params[0] = params[1] = 0.25f;
cubicNewton(xCoefs1, yCoefs1, xCoefs2, yCoefs2, initParams);
if (initParams[0] <= 1 && initParams[0] >= 0 && initParams[1] >= 0 && initParams[1] <= 1) {
params[2 * quantity] = initParams[0];
params[2 * quantity + 1] = initParams[1];
++quantity;
}
params[0] = params[1] = 0.5f;
cubicNewton(xCoefs1, yCoefs1, xCoefs2, yCoefs2, params);
if (initParams[0] <= 1 && initParams[0] >= 0 && initParams[1] >= 0 && initParams[1] <= 1) {
params[2 * quantity] = initParams[0];
params[2 * quantity + 1] = initParams[1];
++quantity;
}
params[0] = params[1] = 0.75f;
cubicNewton(xCoefs1, yCoefs1, xCoefs2, yCoefs2, params);
if (initParams[0] <= 1 && initParams[0] >= 0 && initParams[1] >= 0 && initParams[1] <= 1) {
params[2 * quantity] = initParams[0];
params[2 * quantity + 1] = initParams[1];
++quantity;
}
return quantity;
}
public static float line (float t, float x1, float x2) {
return x1 * (1f - t) + x2 * t;
}
public static float quad (float t, float x1, float x2, float x3) {
return x1 * (1f - t) * (1f - t) + 2f * x2 * t * (1f - t) + x3 * t * t;
}
public static float cubic (float t, float x1, float x2, float x3, float x4) {
return x1 * (1f - t) * (1f - t) * (1f - t) + 3f * x2 * (1f - t) * (1f - t) * t + 3f * x3 *
(1f - t) * t * t + x4 * t * t * t;
}
// x, y - the coordinates of new vertex
// t0 - ?
public static void subQuad (float[] coef, float t0, boolean left) {
if (left) {
coef[2] = (1 - t0) * coef[0] + t0 * coef[2];
coef[3] = (1 - t0) * coef[1] + t0 * coef[3];
} else {
coef[2] = (1 - t0) * coef[2] + t0 * coef[4];
coef[3] = (1 - t0) * coef[3] + t0 * coef[5];
}
}
public static void subCubic (float[] coef, float t0, boolean left) {
if (left) {
coef[2] = (1 - t0) * coef[0] + t0 * coef[2];
coef[3] = (1 - t0) * coef[1] + t0 * coef[3];
} else {
coef[4] = (1 - t0) * coef[4] + t0 * coef[6];
coef[5] = (1 - t0) * coef[5] + t0 * coef[7];
}
}
private static void cubicNewton (float[] xCoefs1, float[] yCoefs1,
float[] xCoefs2, float[] yCoefs2, float[] params) {
float t = 0f, s = 0f;
float t1 = params[0];
float s1 = params[1];
float d, dt, ds;
while (Math.sqrt((t - t1) * (t - t1) + (s - s1) * (s - s1)) > EPSILON) {
d = -(3 * t * t * xCoefs1[0] + 2 * t * xCoefs1[1] + xCoefs1[2]) *
(3 * s * s * yCoefs2[0] + 2 * s * yCoefs2[1] + yCoefs2[2]) +
(3 * t * t * yCoefs1[0] + 2 * t * yCoefs1[1] + yCoefs1[2]) *
(3 * s * s * xCoefs2[0] + 2 * s * xCoefs2[1] + xCoefs2[2]);
dt = (t * t * t * xCoefs1[0] + t * t * xCoefs1[1] + t * xCoefs1[2] + xCoefs1[3] -
s * s * s * xCoefs2[0] - s * s * xCoefs2[1] - s * xCoefs2[2] - xCoefs2[3]) *
(-3 * s * s * yCoefs2[0] - 2 * s * yCoefs2[1] - yCoefs2[2]) +
(t * t * t * yCoefs1[0] + t * t * yCoefs1[1] + t * yCoefs1[2] + yCoefs1[3] -
s * s * s * yCoefs2[0] - s * s * yCoefs2[1] - s * yCoefs2[2] - yCoefs2[3]) *
(3 * s * s * xCoefs2[0] + 2 * s * xCoefs2[1] + xCoefs2[2]);
ds = (3 * t * t * xCoefs1[0] + 2 * t * xCoefs1[1] + xCoefs1[2]) *
(t * t * t * yCoefs1[0] + t * t * yCoefs1[1] + t * yCoefs1[2] + yCoefs1[3] -
s * s * s * yCoefs2[0] - s * s * yCoefs2[1] - s * yCoefs2[2] - yCoefs2[3]) -
(3 * t * t * yCoefs1[0] + 2 * t * yCoefs1[1] + yCoefs1[2]) *
(t * t * t * xCoefs1[0] + t * t * xCoefs1[1] + t * xCoefs1[2] + xCoefs1[3] -
s * s * s * xCoefs2[0] - s * s * xCoefs2[1] - s * xCoefs2[2] - xCoefs2[3]);
t1 = t - dt / d;
s1 = s - ds / d;
}
params[0] = t1;
params[1] = s1;
}
private static void quadAndCubicNewton (float xCoefs1[], float yCoefs1[],
float xCoefs2[], float yCoefs2[], float[] params) {
float t = 0f, s = 0f;
float t1 = params[0];
float s1 = params[1];
float d, dt, ds;
while (Math.sqrt((t - t1) * (t - t1) + (s - s1) * (s - s1)) > EPSILON) {
d = -(2 * t * xCoefs1[0] + xCoefs1[1]) *
(3 * s * s * yCoefs2[0] + 2 * s * yCoefs2[1] + yCoefs2[2]) +
(2 * t * yCoefs1[0] + yCoefs1[1]) *
(3 * s * s * xCoefs2[0] + 2 * s * xCoefs2[1] + xCoefs2[2]);
dt = (t * t * xCoefs1[0] + t * xCoefs1[1] + xCoefs1[2] + -s * s * s * xCoefs2[0] -
s * s * xCoefs2[1] - s * xCoefs2[2] - xCoefs2[3]) *
(-3 * s * s * yCoefs2[0] - 2 * s * yCoefs2[1] - yCoefs2[2]) +
(t * t * yCoefs1[0] + t * yCoefs1[1] + yCoefs1[2] - s * s * s * yCoefs2[0] -
s * s * yCoefs2[1] - s * yCoefs2[2] - yCoefs2[3]) *
(3 * s * s * xCoefs2[0] + 2 * s * xCoefs2[1] + xCoefs2[2]);
ds = (2 * t * xCoefs1[0] + xCoefs1[1]) *
(t * t * yCoefs1[0] + t * yCoefs1[1] + yCoefs1[2] - s * s * s * yCoefs2[0] -
s * s * yCoefs2[1] - s * yCoefs2[2] - yCoefs2[3]) -
(2 * t * yCoefs1[0] + yCoefs1[1]) *
(t * t * xCoefs1[0] + t * xCoefs1[1] + xCoefs1[2] - s * s * s * xCoefs2[0] -
s * s * xCoefs2[1] - s * xCoefs2[2] - xCoefs2[3]);
t1 = t - dt / d;
s1 = s - ds / d;
}
params[0] = t1;
params[1] = s1;
}
private static void quadNewton (float xCoefs1[], float yCoefs1[],
float xCoefs2[], float yCoefs2[], float params[]) {
float t = 0f, s = 0f;
float t1 = params[0];
float s1 = params[1];
float d, dt, ds;
while (Math.sqrt((t - t1) * (t - t1) + (s - s1) * (s - s1)) > EPSILON) {
t = t1;
s = s1;
d = -(2 * t * xCoefs1[0] + xCoefs1[1]) * (2 * s * yCoefs2[0] + yCoefs2[1]) +
(2 * s * xCoefs2[0] + xCoefs2[1]) * (2 * t * yCoefs1[0] + yCoefs1[1]);
dt = -(t * t * xCoefs1[0] + t * xCoefs1[1] + xCoefs1[1] - s * s * xCoefs2[0] -
s * xCoefs2[1] - xCoefs2[2]) * (2 * s * yCoefs2[0] + yCoefs2[1]) +
(2 * s * xCoefs2[0] + xCoefs2[1]) *
(t * t * yCoefs1[0] + t * yCoefs1[1] + yCoefs1[2] - s * s * yCoefs2[0] -
s * yCoefs2[1] - yCoefs2[2]);
ds = (2 * t * xCoefs1[0] + xCoefs1[1]) *
(t * t * yCoefs1[0] + t * yCoefs1[1] + yCoefs1[2] - s * s * yCoefs2[0] -
s * yCoefs2[1] - yCoefs2[2]) - (2 * t * yCoefs1[0] + yCoefs1[1]) *
(t * t * xCoefs1[0] + t * xCoefs1[1] + xCoefs1[2] - s * s * xCoefs2[0] -
s * xCoefs2[1] - xCoefs2[2]);
t1 = t - dt / d;
s1 = s - ds / d;
}
params[0] = t1;
params[1] = s1;
}
}
| mit |
kasperdokter/Reo-compiler | examples/Sung/thesis/npb/bt/RHSCompute.java | 31229 | /*
!-------------------------------------------------------------------------!
! !
! N A S P A R A L L E L B E N C H M A R K S 3.0 !
! !
! J A V A V E R S I O N !
! !
! R H S C o m p u t e !
! !
!-------------------------------------------------------------------------!
! !
! RHSCompute implements thread for rhs_compute subroutine of !
! the BT benchmark. !
! !
! Permission to use, copy, distribute and modify this software !
! for any purpose with or without fee is hereby granted. We !
! request, however, that all derived work reference the NAS !
! Parallel Benchmarks 3.0. This software is provided "as is" !
! without express or implied warranty. !
! !
! Information on NPB 3.0, including the Technical Report NAS-02-008 !
! "Implementation of the NAS Parallel Benchmarks in Java", !
! original specifications, source code, results and information !
! on how to submit new results, is available at: !
! !
! http://www.nas.nasa.gov/Software/NPB/ !
! !
! Send comments or suggestions to npb@nas.nasa.gov !
! !
! NAS Parallel Benchmarks Group !
! NASA Ames Research Center !
! Mail Stop: T27A-1 !
! Moffett Field, CA 94035-1000 !
! !
! E-mail: npb@nas.nasa.gov !
! Fax: (650) 604-3957 !
! !
!-------------------------------------------------------------------------!
! Translation to Java and to MultiThreaded Code: !
! Michael A. Frumkin !
! Mathew Schultz !
!-------------------------------------------------------------------------!
*/
package nl.cwi.pr.runtime.examples.thesis.npb.bt;
import nl.cwi.pr.runtime.api.InputPort;
import nl.cwi.pr.runtime.api.OutputPort;
public class RHSCompute extends BTBase {
// ------------------------------------------------------------------------
private InputPort doInputPort;
private OutputPort doneOutputPort;
public static class Init {
BT bt;
int low1, high1, low2, high2, id;
public Init(BT bt, int low1, int high1, int low2, int high2, int id) {
this.bt = bt;
this.low1 = low1;
this.high1 = high1;
this.low2 = low2;
this.high2 = high2;
this.id = id;
}
}
public static class Work {
boolean exit = false;
public Work() {
this.exit = true;
}
}
public RHSCompute(InputPort initInputPort, InputPort doInputPort,
OutputPort doneOutputPort) {
this.doInputPort = doInputPort;
this.doneOutputPort = doneOutputPort;
Init init = (Init) initInputPort.getUninterruptibly();
RHSComputeConstructor(init.bt, init.low1, init.high1, init.low2,
init.high2);
this.id = init.id;
}
// ------------------------------------------------------------------------
public int id;
// public boolean done = true;
// private arrays and data
int lower_bound1;
int upper_bound1;
int lower_bound2;
int upper_bound2;
int state;
double rho_inv, uijk, up1, um1, vijk, vp1, vm1, wijk, wp1, wm1;
public void RHSComputeConstructor(BT bt, int low1, int high1, int low2,
int high2) {
// public RHSCompute(BT bt, int low1, int high1, int low2, int high2) {
Init(bt);
lower_bound1 = low1;
upper_bound1 = high1;
lower_bound2 = low2;
upper_bound2 = high2;
state = 1;
setPriority(Thread.MAX_PRIORITY);
setDaemon(true);
master = bt;
}
void Init(BT bt) {
// initialize shared data
IMAX = bt.IMAX;
JMAX = bt.JMAX;
KMAX = bt.KMAX;
problem_size = bt.problem_size;
grid_points = bt.grid_points;
niter_default = bt.niter_default;
dt_default = bt.dt_default;
u = bt.u;
rhs = bt.rhs;
forcing = bt.forcing;
cv = bt.cv;
q = bt.q;
cuf = bt.cuf;
isize2 = bt.isize2;
jsize2 = bt.jsize2;
ksize2 = bt.ksize2;
us = bt.us;
vs = bt.vs;
ws = bt.ws;
qs = bt.qs;
rho_i = bt.rho_i;
square = bt.square;
jsize1 = bt.jsize1;
ksize1 = bt.ksize1;
ue = bt.ue;
buf = bt.buf;
jsize3 = bt.jsize3;
}
public void run() {
Object signal = new Object();
for (;;) {
// synchronized (this) {
// while (done == true) {
// try {
// wait();
// synchronized (master) {
// master.notify();
// }
// } catch (InterruptedException ie) {
// }
// }
Object object = doInputPort.getUninterruptibly();
if (object instanceof Work)
return;
step();
// synchronized (master) {
// done = true;
// master.notify();
// }
doneOutputPort.putUninterruptibly(signal);
// }
}
}
public void step() {
int i, j, k, m;
switch (state) {
case 1:
// ---------------------------------------------------------------------
// compute the reciprocal of density, and the kinetic energy,
// and the speed of sound.
// ---------------------------------------------------------------------
for (k = lower_bound1; k <= upper_bound1; k++) {
for (j = 0; j <= grid_points[1] - 1; j++) {
for (i = 0; i <= grid_points[0] - 1; i++) {
rho_inv = 1.0 / u[0 + i * isize2 + j * jsize2 + k
* ksize2];
rho_i[i + j * jsize1 + k * ksize1] = rho_inv;
us[i + j * jsize1 + k * ksize1] = u[1 + i * isize2 + j
* jsize2 + k * ksize2]
* rho_inv;
vs[i + j * jsize1 + k * ksize1] = u[2 + i * isize2 + j
* jsize2 + k * ksize2]
* rho_inv;
ws[i + j * jsize1 + k * ksize1] = u[3 + i * isize2 + j
* jsize2 + k * ksize2]
* rho_inv;
square[i + j * jsize1 + k * ksize1] = 0.5
* (u[1 + i * isize2 + j * jsize2 + k * ksize2]
* u[1 + i * isize2 + j * jsize2 + k
* ksize2]
+ u[2 + i * isize2 + j * jsize2 + k
* ksize2]
* u[2 + i * isize2 + j * jsize2 + k
* ksize2] + u[3 + i * isize2
+ j * jsize2 + k * ksize2]
* u[3 + i * isize2 + j * jsize2 + k
* ksize2]) * rho_inv;
qs[i + j * jsize1 + k * ksize1] = square[i + j * jsize1
+ k * ksize1]
* rho_inv;
}
}
}
// ---------------------------------------------------------------------
// copy the exact forcing term to the right hand side; because
// this forcing term is known, we can store it on the whole grid
// including the boundary
// ---------------------------------------------------------------------
for (k = lower_bound1; k <= upper_bound1; k++) {
for (j = 0; j <= grid_points[1] - 1; j++) {
for (i = 0; i <= grid_points[0] - 1; i++) {
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = forcing[m
+ i * isize2 + j * jsize2 + k * ksize2];
}
}
}
}
break;
case 2:
// ---------------------------------------------------------------------
// compute xi-direction fluxes
// ---------------------------------------------------------------------
for (k = lower_bound2; k <= upper_bound2; k++) {
for (j = 1; j <= grid_points[1] - 2; j++) {
for (i = 1; i <= grid_points[0] - 2; i++) {
uijk = us[i + j * jsize1 + k * ksize1];
up1 = us[(i + 1) + j * jsize1 + k * ksize1];
um1 = us[(i - 1) + j * jsize1 + k * ksize1];
rhs[0 + i * isize2 + j * jsize2 + k * ksize2] = rhs[0
+ i * isize2 + j * jsize2 + k * ksize2]
+ dx1tx1
* (u[0 + (i + 1) * isize2 + j * jsize2 + k
* ksize2]
- 2.0
* u[0 + i * isize2 + j * jsize2 + k
* ksize2] + u[0 + (i - 1)
* isize2 + j * jsize2 + k * ksize2])
- tx2
* (u[1 + (i + 1) * isize2 + j * jsize2 + k
* ksize2] - u[1 + (i - 1) * isize2 + j
* jsize2 + k * ksize2]);
rhs[1 + i * isize2 + j * jsize2 + k * ksize2] = rhs[1
+ i * isize2 + j * jsize2 + k * ksize2]
+ dx2tx1
* (u[1 + (i + 1) * isize2 + j * jsize2 + k
* ksize2]
- 2.0
* u[1 + i * isize2 + j * jsize2 + k
* ksize2] + u[1 + (i - 1)
* isize2 + j * jsize2 + k * ksize2])
+ xxcon2
* con43
* (up1 - 2.0 * uijk + um1)
- tx2
* (u[1 + (i + 1) * isize2 + j * jsize2 + k
* ksize2]
* up1
- u[1 + (i - 1) * isize2 + j * jsize2
+ k * ksize2] * um1 + (u[4
+ (i + 1) * isize2 + j * jsize2 + k
* ksize2]
- square[(i + 1) + j * jsize1 + k
* ksize1]
- u[4 + (i - 1) * isize2 + j * jsize2
+ k * ksize2] + square[(i - 1)
+ j * jsize1 + k * ksize1])
* c2);
rhs[2 + i * isize2 + j * jsize2 + k * ksize2] = rhs[2
+ i * isize2 + j * jsize2 + k * ksize2]
+ dx3tx1
* (u[2 + (i + 1) * isize2 + j * jsize2 + k
* ksize2]
- 2.0
* u[2 + i * isize2 + j * jsize2 + k
* ksize2] + u[2 + (i - 1)
* isize2 + j * jsize2 + k * ksize2])
+ xxcon2
* (vs[(i + 1) + j * jsize1 + k * ksize1] - 2.0
* vs[i + j * jsize1 + k * ksize1] + vs[(i - 1)
+ j * jsize1 + k * ksize1])
- tx2
* (u[2 + (i + 1) * isize2 + j * jsize2 + k
* ksize2]
* up1 - u[2 + (i - 1) * isize2 + j
* jsize2 + k * ksize2]
* um1);
rhs[3 + i * isize2 + j * jsize2 + k * ksize2] = rhs[3
+ i * isize2 + j * jsize2 + k * ksize2]
+ dx4tx1
* (u[3 + (i + 1) * isize2 + j * jsize2 + k
* ksize2]
- 2.0
* u[3 + i * isize2 + j * jsize2 + k
* ksize2] + u[3 + (i - 1)
* isize2 + j * jsize2 + k * ksize2])
+ xxcon2
* (ws[(i + 1) + j * jsize1 + k * ksize1] - 2.0
* ws[i + j * jsize1 + k * ksize1] + ws[(i - 1)
+ j * jsize1 + k * ksize1])
- tx2
* (u[3 + (i + 1) * isize2 + j * jsize2 + k
* ksize2]
* up1 - u[3 + (i - 1) * isize2 + j
* jsize2 + k * ksize2]
* um1);
rhs[4 + i * isize2 + j * jsize2 + k * ksize2] = rhs[4
+ i * isize2 + j * jsize2 + k * ksize2]
+ dx5tx1
* (u[4 + (i + 1) * isize2 + j * jsize2 + k
* ksize2]
- 2.0
* u[4 + i * isize2 + j * jsize2 + k
* ksize2] + u[4 + (i - 1)
* isize2 + j * jsize2 + k * ksize2])
+ xxcon3
* (qs[(i + 1) + j * jsize1 + k * ksize1] - 2.0
* qs[i + j * jsize1 + k * ksize1] + qs[(i - 1)
+ j * jsize1 + k * ksize1])
+ xxcon4
* (up1 * up1 - 2.0 * uijk * uijk + um1 * um1)
+ xxcon5
* (u[4 + (i + 1) * isize2 + j * jsize2 + k
* ksize2]
* rho_i[(i + 1) + j * jsize1 + k
* ksize1]
- 2.0
* u[4 + i * isize2 + j * jsize2 + k
* ksize2]
* rho_i[i + j * jsize1 + k * ksize1] + u[4
+ (i - 1)
* isize2
+ j
* jsize2
+ k
* ksize2]
* rho_i[(i - 1) + j * jsize1 + k
* ksize1])
- tx2
* ((c1
* u[4 + (i + 1) * isize2 + j * jsize2
+ k * ksize2] - c2
* square[(i + 1) + j * jsize1 + k
* ksize1])
* up1 - (c1
* u[4 + (i - 1) * isize2 + j * jsize2
+ k * ksize2] - c2
* square[(i - 1) + j * jsize1 + k
* ksize1])
* um1);
}
}
// ---------------------------------------------------------------------
// add fourth order xi-direction dissipation
// ---------------------------------------------------------------------
for (j = 1; j <= grid_points[1] - 2; j++) {
i = 1;
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
- dssp
* (5.0
* u[m + i * isize2 + j * jsize2 + k
* ksize2]
- 4.0
* u[m + (i + 1) * isize2 + j * jsize2
+ k * ksize2] + u[m + (i + 2)
* isize2 + j * jsize2 + k * ksize2]);
}
i = 2;
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
- dssp
* (-4.0
* u[m + (i - 1) * isize2 + j * jsize2
+ k * ksize2]
+ 6.0
* u[m + i * isize2 + j * jsize2 + k
* ksize2]
- 4.0
* u[m + (i + 1) * isize2 + j * jsize2
+ k * ksize2] + u[m + (i + 2)
* isize2 + j * jsize2 + k * ksize2]);
}
for (m = 0; m <= 4; m++) {
for (i = 3; i <= grid_points[0] - 4; i++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
- dssp
* (u[m + (i - 2) * isize2 + j * jsize2 + k
* ksize2]
- 4.0
* u[m + (i - 1) * isize2 + j
* jsize2 + k * ksize2]
+ 6.0
* u[m + i * isize2 + j * jsize2 + k
* ksize2]
- 4.0
* u[m + (i + 1) * isize2 + j
* jsize2 + k * ksize2] + u[m
+ (i + 2)
* isize2
+ j
* jsize2
+ k
* ksize2]);
}
}
i = grid_points[0] - 3;
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
- dssp
* (u[m + (i - 2) * isize2 + j * jsize2 + k
* ksize2]
- 4.0
* u[m + (i - 1) * isize2 + j * jsize2
+ k * ksize2]
+ 6.0
* u[m + i * isize2 + j * jsize2 + k
* ksize2] - 4.0 * u[m + (i + 1)
* isize2 + j * jsize2 + k * ksize2]);
}
i = grid_points[0] - 2;
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
- dssp
* (u[m + (i - 2) * isize2 + j * jsize2 + k
* ksize2]
- 4.
* u[m + (i - 1) * isize2 + j * jsize2
+ k * ksize2] + 5. * u[m + i
* isize2 + j * jsize2 + k * ksize2]);
}
}
}
break;
case 3:
// ---------------------------------------------------------------------
// compute eta-direction fluxes
// ---------------------------------------------------------------------
for (k = lower_bound2; k <= upper_bound2; k++) {
for (j = 1; j <= grid_points[1] - 2; j++) {
for (i = 1; i <= grid_points[0] - 2; i++) {
vijk = vs[i + j * jsize1 + k * ksize1];
vp1 = vs[i + (j + 1) * jsize1 + k * ksize1];
vm1 = vs[i + (j - 1) * jsize1 + k * ksize1];
rhs[0 + i * isize2 + j * jsize2 + k * ksize2] = rhs[0
+ i * isize2 + j * jsize2 + k * ksize2]
+ dy1ty1
* (u[0 + i * isize2 + (j + 1) * jsize2 + k
* ksize2]
- 2.0
* u[0 + i * isize2 + j * jsize2 + k
* ksize2] + u[0 + i * isize2
+ (j - 1) * jsize2 + k * ksize2])
- ty2
* (u[2 + i * isize2 + (j + 1) * jsize2 + k
* ksize2] - u[2 + i * isize2 + (j - 1)
* jsize2 + k * ksize2]);
rhs[1 + i * isize2 + j * jsize2 + k * ksize2] = rhs[1
+ i * isize2 + j * jsize2 + k * ksize2]
+ dy2ty1
* (u[1 + i * isize2 + (j + 1) * jsize2 + k
* ksize2]
- 2.0
* u[1 + i * isize2 + j * jsize2 + k
* ksize2] + u[1 + i * isize2
+ (j - 1) * jsize2 + k * ksize2])
+ yycon2
* (us[i + (j + 1) * jsize1 + k * ksize1] - 2.0
* us[i + j * jsize1 + k * ksize1] + us[i
+ (j - 1) * jsize1 + k * ksize1])
- ty2
* (u[1 + i * isize2 + (j + 1) * jsize2 + k
* ksize2]
* vp1 - u[1 + i * isize2 + (j - 1)
* jsize2 + k * ksize2]
* vm1);
rhs[2 + i * isize2 + j * jsize2 + k * ksize2] = rhs[2
+ i * isize2 + j * jsize2 + k * ksize2]
+ dy3ty1
* (u[2 + i * isize2 + (j + 1) * jsize2 + k
* ksize2]
- 2.0
* u[2 + i * isize2 + j * jsize2 + k
* ksize2] + u[2 + i * isize2
+ (j - 1) * jsize2 + k * ksize2])
+ yycon2
* con43
* (vp1 - 2.0 * vijk + vm1)
- ty2
* (u[2 + i * isize2 + (j + 1) * jsize2 + k
* ksize2]
* vp1
- u[2 + i * isize2 + (j - 1) * jsize2
+ k * ksize2] * vm1 + (u[4 + i
* isize2 + (j + 1) * jsize2 + k
* ksize2]
- square[i + (j + 1) * jsize1 + k
* ksize1]
- u[4 + i * isize2 + (j - 1) * jsize2
+ k * ksize2] + square[i
+ (j - 1) * jsize1 + k * ksize1])
* c2);
rhs[3 + i * isize2 + j * jsize2 + k * ksize2] = rhs[3
+ i * isize2 + j * jsize2 + k * ksize2]
+ dy4ty1
* (u[3 + i * isize2 + (j + 1) * jsize2 + k
* ksize2]
- 2.0
* u[3 + i * isize2 + j * jsize2 + k
* ksize2] + u[3 + i * isize2
+ (j - 1) * jsize2 + k * ksize2])
+ yycon2
* (ws[i + (j + 1) * jsize1 + k * ksize1] - 2.0
* ws[i + j * jsize1 + k * ksize1] + ws[i
+ (j - 1) * jsize1 + k * ksize1])
- ty2
* (u[3 + i * isize2 + (j + 1) * jsize2 + k
* ksize2]
* vp1 - u[3 + i * isize2 + (j - 1)
* jsize2 + k * ksize2]
* vm1);
rhs[4 + i * isize2 + j * jsize2 + k * ksize2] = rhs[4
+ i * isize2 + j * jsize2 + k * ksize2]
+ dy5ty1
* (u[4 + i * isize2 + (j + 1) * jsize2 + k
* ksize2]
- 2.0
* u[4 + i * isize2 + j * jsize2 + k
* ksize2] + u[4 + i * isize2
+ (j - 1) * jsize2 + k * ksize2])
+ yycon3
* (qs[i + (j + 1) * jsize1 + k * ksize1] - 2.0
* qs[i + j * jsize1 + k * ksize1] + qs[i
+ (j - 1) * jsize1 + k * ksize1])
+ yycon4
* (vp1 * vp1 - 2.0 * vijk * vijk + vm1 * vm1)
+ yycon5
* (u[4 + i * isize2 + (j + 1) * jsize2 + k
* ksize2]
* rho_i[i + (j + 1) * jsize1 + k
* ksize1]
- 2.0
* u[4 + i * isize2 + j * jsize2 + k
* ksize2]
* rho_i[i + j * jsize1 + k * ksize1] + u[4
+ i
* isize2
+ (j - 1)
* jsize2
+ k
* ksize2]
* rho_i[i + (j - 1) * jsize1 + k
* ksize1])
- ty2
* ((c1
* u[4 + i * isize2 + (j + 1) * jsize2
+ k * ksize2] - c2
* square[i + (j + 1) * jsize1 + k
* ksize1])
* vp1 - (c1
* u[4 + i * isize2 + (j - 1) * jsize2
+ k * ksize2] - c2
* square[i + (j - 1) * jsize1 + k
* ksize1])
* vm1);
}
}
// ---------------------------------------------------------------------
// add fourth order eta-direction dissipation
// ---------------------------------------------------------------------
for (i = 1; i <= grid_points[0] - 2; i++) {
j = 1;
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
- dssp
* (5.0
* u[m + i * isize2 + j * jsize2 + k
* ksize2]
- 4.0
* u[m + i * isize2 + (j + 1) * jsize2
+ k * ksize2] + u[m + i
* isize2 + (j + 2) * jsize2 + k
* ksize2]);
}
j = 2;
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
- dssp
* (-4.0
* u[m + i * isize2 + (j - 1) * jsize2
+ k * ksize2]
+ 6.0
* u[m + i * isize2 + j * jsize2 + k
* ksize2]
- 4.0
* u[m + i * isize2 + (j + 1) * jsize2
+ k * ksize2] + u[m + i
* isize2 + (j + 2) * jsize2 + k
* ksize2]);
}
}
for (j = 3; j <= grid_points[1] - 4; j++) {
for (i = 1; i <= grid_points[0] - 2; i++) {
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
- dssp
* (u[m + i * isize2 + (j - 2) * jsize2 + k
* ksize2]
- 4.0
* u[m + i * isize2 + (j - 1)
* jsize2 + k * ksize2]
+ 6.0
* u[m + i * isize2 + j * jsize2 + k
* ksize2]
- 4.0
* u[m + i * isize2 + (j + 1)
* jsize2 + k * ksize2] + u[m
+ i
* isize2
+ (j + 2)
* jsize2
+ k
* ksize2]);
}
}
}
for (i = 1; i <= grid_points[0] - 2; i++) {
j = grid_points[1] - 3;
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
- dssp
* (u[m + i * isize2 + (j - 2) * jsize2 + k
* ksize2]
- 4.0
* u[m + i * isize2 + (j - 1) * jsize2
+ k * ksize2]
+ 6.0
* u[m + i * isize2 + j * jsize2 + k
* ksize2] - 4.0 * u[m + i
* isize2 + (j + 1) * jsize2 + k
* ksize2]);
}
j = grid_points[1] - 2;
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
- dssp
* (u[m + i * isize2 + (j - 2) * jsize2 + k
* ksize2]
- 4.
* u[m + i * isize2 + (j - 1) * jsize2
+ k * ksize2] + 5. * u[m + i
* isize2 + j * jsize2 + k * ksize2]);
}
}
}
break;
case 4:
// ---------------------------------------------------------------------
// compute zeta-direction fluxes
// ---------------------------------------------------------------------
for (j = lower_bound2; j <= upper_bound2; j++) {
for (k = 1; k <= grid_points[1] - 2; k++) {
for (i = 1; i <= grid_points[0] - 2; i++) {
wijk = ws[i + j * jsize1 + k * ksize1];
wp1 = ws[i + j * jsize1 + (k + 1) * ksize1];
wm1 = ws[i + j * jsize1 + (k - 1) * ksize1];
rhs[0 + i * isize2 + j * jsize2 + k * ksize2] = rhs[0
+ i * isize2 + j * jsize2 + k * ksize2]
+ dz1tz1
* (u[0 + i * isize2 + j * jsize2 + (k + 1)
* ksize2]
- 2.0
* u[0 + i * isize2 + j * jsize2 + k
* ksize2] + u[0 + i * isize2
+ j * jsize2 + (k - 1) * ksize2])
- tz2
* (u[3 + i * isize2 + j * jsize2 + (k + 1)
* ksize2] - u[3 + i * isize2 + j
* jsize2 + (k - 1) * ksize2]);
rhs[1 + i * isize2 + j * jsize2 + k * ksize2] = rhs[1
+ i * isize2 + j * jsize2 + k * ksize2]
+ dz2tz1
* (u[1 + i * isize2 + j * jsize2 + (k + 1)
* ksize2]
- 2.0
* u[1 + i * isize2 + j * jsize2 + k
* ksize2] + u[1 + i * isize2
+ j * jsize2 + (k - 1) * ksize2])
+ zzcon2
* (us[i + j * jsize1 + (k + 1) * ksize1] - 2.0
* us[i + j * jsize1 + k * ksize1] + us[i
+ j * jsize1 + (k - 1) * ksize1])
- tz2
* (u[1 + i * isize2 + j * jsize2 + (k + 1)
* ksize2]
* wp1 - u[1 + i * isize2 + j * jsize2
+ (k - 1) * ksize2]
* wm1);
rhs[2 + i * isize2 + j * jsize2 + k * ksize2] = rhs[2
+ i * isize2 + j * jsize2 + k * ksize2]
+ dz3tz1
* (u[2 + i * isize2 + j * jsize2 + (k + 1)
* ksize2]
- 2.0
* u[2 + i * isize2 + j * jsize2 + k
* ksize2] + u[2 + i * isize2
+ j * jsize2 + (k - 1) * ksize2])
+ zzcon2
* (vs[i + j * jsize1 + (k + 1) * ksize1] - 2.0
* vs[i + j * jsize1 + k * ksize1] + vs[i
+ j * jsize1 + (k - 1) * ksize1])
- tz2
* (u[2 + i * isize2 + j * jsize2 + (k + 1)
* ksize2]
* wp1 - u[2 + i * isize2 + j * jsize2
+ (k - 1) * ksize2]
* wm1);
rhs[3 + i * isize2 + j * jsize2 + k * ksize2] = rhs[3
+ i * isize2 + j * jsize2 + k * ksize2]
+ dz4tz1
* (u[3 + i * isize2 + j * jsize2 + (k + 1)
* ksize2]
- 2.0
* u[3 + i * isize2 + j * jsize2 + k
* ksize2] + u[3 + i * isize2
+ j * jsize2 + (k - 1) * ksize2])
+ zzcon2
* con43
* (wp1 - 2.0 * wijk + wm1)
- tz2
* (u[3 + i * isize2 + j * jsize2 + (k + 1)
* ksize2]
* wp1
- u[3 + i * isize2 + j * jsize2
+ (k - 1) * ksize2] * wm1 + (u[4
+ i
* isize2
+ j
* jsize2
+ (k + 1)
* ksize2]
- square[i + j * jsize1 + (k + 1)
* ksize1]
- u[4 + i * isize2 + j * jsize2
+ (k - 1) * ksize2] + square[i
+ j * jsize1 + (k - 1) * ksize1])
* c2);
rhs[4 + i * isize2 + j * jsize2 + k * ksize2] = rhs[4
+ i * isize2 + j * jsize2 + k * ksize2]
+ dz5tz1
* (u[4 + i * isize2 + j * jsize2 + (k + 1)
* ksize2]
- 2.0
* u[4 + i * isize2 + j * jsize2 + k
* ksize2] + u[4 + i * isize2
+ j * jsize2 + (k - 1) * ksize2])
+ zzcon3
* (qs[i + j * jsize1 + (k + 1) * ksize1] - 2.0
* qs[i + j * jsize1 + k * ksize1] + qs[i
+ j * jsize1 + (k - 1) * ksize1])
+ zzcon4
* (wp1 * wp1 - 2.0 * wijk * wijk + wm1 * wm1)
+ zzcon5
* (u[4 + i * isize2 + j * jsize2 + (k + 1)
* ksize2]
* rho_i[i + j * jsize1 + (k + 1)
* ksize1]
- 2.0
* u[4 + i * isize2 + j * jsize2 + k
* ksize2]
* rho_i[i + j * jsize1 + k * ksize1] + u[4
+ i
* isize2
+ j
* jsize2
+ (k - 1)
* ksize2]
* rho_i[i + j * jsize1 + (k - 1)
* ksize1])
- tz2
* ((c1
* u[4 + i * isize2 + j * jsize2
+ (k + 1) * ksize2] - c2
* square[i + j * jsize1 + (k + 1)
* ksize1])
* wp1 - (c1
* u[4 + i * isize2 + j * jsize2
+ (k - 1) * ksize2] - c2
* square[i + j * jsize1 + (k - 1)
* ksize1])
* wm1);
}
}
// ---------------------------------------------------------------------
// add fourth order zeta-direction dissipation
// ---------------------------------------------------------------------
for (i = 1; i <= grid_points[0] - 2; i++) {
k = 1;
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
- dssp
* (5.0
* u[m + i * isize2 + j * jsize2 + k
* ksize2]
- 4.0
* u[m + i * isize2 + j * jsize2
+ (k + 1) * ksize2] + u[m + i
* isize2 + j * jsize2 + (k + 2)
* ksize2]);
}
k = 2;
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
- dssp
* (-4.0
* u[m + i * isize2 + j * jsize2
+ (k - 1) * ksize2]
+ 6.0
* u[m + i * isize2 + j * jsize2 + k
* ksize2]
- 4.0
* u[m + i * isize2 + j * jsize2
+ (k + 1) * ksize2] + u[m + i
* isize2 + j * jsize2 + (k + 2)
* ksize2]);
}
}
for (k = 3; k <= grid_points[2] - 4; k++) {
for (i = 1; i <= grid_points[0] - 2; i++) {
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
- dssp
* (u[m + i * isize2 + j * jsize2 + (k - 2)
* ksize2]
- 4.0
* u[m + i * isize2 + j * jsize2
+ (k - 1) * ksize2]
+ 6.0
* u[m + i * isize2 + j * jsize2 + k
* ksize2]
- 4.0
* u[m + i * isize2 + j * jsize2
+ (k + 1) * ksize2] + u[m
+ i * isize2 + j * jsize2 + (k + 2)
* ksize2]);
}
}
}
for (i = 1; i <= grid_points[0] - 2; i++) {
k = grid_points[2] - 3;
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
- dssp
* (u[m + i * isize2 + j * jsize2 + (k - 2)
* ksize2]
- 4.0
* u[m + i * isize2 + j * jsize2
+ (k - 1) * ksize2]
+ 6.0
* u[m + i * isize2 + j * jsize2 + k
* ksize2] - 4.0 * u[m + i
* isize2 + j * jsize2 + (k + 1)
* ksize2]);
}
k = grid_points[2] - 2;
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
- dssp
* (u[m + i * isize2 + j * jsize2 + (k - 2)
* ksize2]
- 4.
* u[m + i * isize2 + j * jsize2
+ (k - 1) * ksize2] + 5.0 * u[m
+ i * isize2 + j * jsize2 + k * ksize2]);
}
}
}
break;
case 5:
for (k = lower_bound2; k <= upper_bound2; k++) {
for (j = 1; j <= grid_points[1] - 2; j++) {
for (i = 1; i <= grid_points[0] - 2; i++) {
for (m = 0; m <= 4; m++) {
rhs[m + i * isize2 + j * jsize2 + k * ksize2] = rhs[m
+ i * isize2 + j * jsize2 + k * ksize2]
* dt;
}
}
}
}
break;
}
state++;
if (state == 6)
state = 1;
}
public void print_arrays() {
double rhs_density = 0, rhs_x_momentum = 0, rhs_y_momentum = 0, rhs_z_momentum = 0, rhs_energy = 0;
for (int i = 0; i < grid_points[2]; i++) {
for (int j = 0; j < grid_points[1]; j++) {
for (int k = 0; k < grid_points[0]; k++) {
rhs_density += u[0 + i * isize2 + j * jsize2 + k * ksize2]
+ rhs[0 + i * isize2 + j * jsize2 + k * ksize2];
rhs_x_momentum += u[1 + i * isize2 + j * jsize2 + k
* ksize2]
+ rhs[1 + i * isize2 + j * jsize2 + k * ksize2];
rhs_y_momentum += u[2 + i * isize2 + j * jsize2 + k
* ksize2]
+ rhs[2 + i * isize2 + j * jsize2 + k * ksize2];
rhs_z_momentum += u[3 + i * isize2 + j * jsize2 + k
* ksize2]
+ rhs[3 + i * isize2 + j * jsize2 + k * ksize2];
rhs_energy += u[4 + i * isize2 + j * jsize2 + k * ksize2]
+ rhs[4 + i * isize2 + j * jsize2 + k * ksize2];
}
}
}
System.out.println(" density: " + rhs_density);
System.out.println(" x_momentum: " + rhs_x_momentum);
System.out.println(" y_momentum: " + rhs_y_momentum);
System.out.println(" z_momentum: " + rhs_z_momentum);
System.out.println(" energy: " + rhs_energy);
}
}
| mit |
patbos/jenkins | core/src/test/java/hudson/util/ArgumentListBuilderTest.java | 11899 | /*
* The MIT License
*
* Copyright (c) 2004-2010, Sun Microsystems, Inc., Kohsuke Kawaguchi, Yahoo! Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.util;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;
import org.junit.Ignore;
import org.junit.Test;
import org.jvnet.hudson.test.Issue;
public class ArgumentListBuilderTest {
@Test
public void assertEmptyMask() {
ArgumentListBuilder builder = new ArgumentListBuilder();
builder.add("arg");
builder.add("other", "arguments");
assertFalse("There should not be any masked arguments", builder.hasMaskedArguments());
boolean[] array = builder.toMaskArray();
assertNotNull("The mask array should not be null", array);
assertThat("The mask array was incorrect", array, is(new boolean[] { false, false, false }));
}
@Test
public void assertLastArgumentIsMasked() {
ArgumentListBuilder builder = new ArgumentListBuilder();
builder.add("arg");
builder.addMasked("ismasked");
assertTrue("There should be masked arguments", builder.hasMaskedArguments());
boolean[] array = builder.toMaskArray();
assertNotNull("The mask array should not be null", array);
assertThat("The mask array was incorrect", array, is(new boolean[] { false, true }));
}
@Test
public void assertSeveralMaskedArguments() {
ArgumentListBuilder builder = new ArgumentListBuilder();
builder.add("arg");
builder.addMasked("ismasked");
builder.add("non masked arg");
builder.addMasked("ismasked2");
assertTrue("There should be masked arguments", builder.hasMaskedArguments());
boolean[] array = builder.toMaskArray();
assertNotNull("The mask array should not be null", array);
assertThat("The mask array was incorrect", array, is(new boolean[] { false, true, false, true }));
}
@Test
public void assertPrependAfterAddingMasked() {
ArgumentListBuilder builder = new ArgumentListBuilder();
builder.addMasked("ismasked");
builder.add("arg");
builder.prepend("first", "second");
assertTrue("There should be masked arguments", builder.hasMaskedArguments());
boolean[] array = builder.toMaskArray();
assertNotNull("The mask array should not be null", array);
assertThat("The mask array was incorrect", array, is(new boolean[] { false, false, true, false }));
}
@Test
public void assertPrependBeforeAddingMasked() {
ArgumentListBuilder builder = new ArgumentListBuilder();
builder.prepend("first", "second");
builder.addMasked("ismasked");
builder.add("arg");
assertTrue("There should be masked arguments", builder.hasMaskedArguments());
boolean[] array = builder.toMaskArray();
assertNotNull("The mask array should not be null", array);
assertThat("The mask array was incorrect", array, is(new boolean[] { false, false, true, false }));
}
@Test
public void testToWindowsCommand() {
ArgumentListBuilder builder = new ArgumentListBuilder().
add("ant.bat").add("-Dfoo1=abc"). // nothing special, no quotes
add("-Dfoo2=foo bar").add("-Dfoo3=/u*r").add("-Dfoo4=/us?"). // add quotes
add("-Dfoo10=bar,baz").
add("-Dfoo5=foo;bar^baz").add("-Dfoo6=<xml>&here;</xml>"). // add quotes
add("-Dfoo7=foo|bar\"baz"). // add quotes and "" for "
add("-Dfoo8=% %QED% %comspec% %-%(%.%"). // add quotes, and extra quotes for %Q and %c
add("-Dfoo9=%'''%%@%"); // no quotes as none of the % are followed by a letter
// By default, does not escape %VAR%
assertThat(builder.toWindowsCommand().toCommandArray(), is(new String[] { "cmd.exe", "/C",
"\"ant.bat", "-Dfoo1=abc", "\"-Dfoo2=foo bar\"", "\"-Dfoo3=/u*r\"", "\"-Dfoo4=/us?\"",
"\"-Dfoo10=bar,baz\"", "\"-Dfoo5=foo;bar^baz\"", "\"-Dfoo6=<xml>&here;</xml>\"",
"\"-Dfoo7=foo|bar\"\"baz\"", "\"-Dfoo8=% %QED% %comspec% %-%(%.%\"",
"-Dfoo9=%'''%%@%", "&&", "exit", "%%ERRORLEVEL%%\"" }));
// Pass flag to escape %VAR%
assertThat(builder.toWindowsCommand(true).toCommandArray(), is(new String[] { "cmd.exe", "/C",
"\"ant.bat", "-Dfoo1=abc", "\"-Dfoo2=foo bar\"", "\"-Dfoo3=/u*r\"", "\"-Dfoo4=/us?\"",
"\"-Dfoo10=bar,baz\"", "\"-Dfoo5=foo;bar^baz\"", "\"-Dfoo6=<xml>&here;</xml>\"",
"\"-Dfoo7=foo|bar\"\"baz\"", "\"-Dfoo8=% %\"Q\"ED% %\"c\"omspec% %-%(%.%\"",
"-Dfoo9=%'''%%@%", "&&", "exit", "%%ERRORLEVEL%%\"" }));
// Try to hide password
builder.add("-Dpassword=hidden", true);
// By default, does not escape %VAR%
assertThat(builder.toWindowsCommand().toString(), is("cmd.exe /C \"ant.bat -Dfoo1=abc \"\"-Dfoo2=foo bar\"\" \"-Dfoo3=/u*r\" \"-Dfoo4=/us?\" \"-Dfoo10=bar,baz\" \"-Dfoo5=foo;bar^baz\" \"-Dfoo6=<xml>&here;</xml>\" \"-Dfoo7=foo|bar\"\"baz\" \"\"-Dfoo8=% %QED% %comspec% %-%(%.%\"\" -Dfoo9=%'''%%@% ****** && exit %%ERRORLEVEL%%\"" ));
// Pass flag to escape %VAR%
assertThat(builder.toWindowsCommand(true).toString(), is("cmd.exe /C \"ant.bat -Dfoo1=abc \"\"-Dfoo2=foo bar\"\" \"-Dfoo3=/u*r\" \"-Dfoo4=/us?\" \"-Dfoo10=bar,baz\" \"-Dfoo5=foo;bar^baz\" \"-Dfoo6=<xml>&here;</xml>\" \"-Dfoo7=foo|bar\"\"baz\" \"\"-Dfoo8=% %\"Q\"ED% %\"c\"omspec% %-%(%.%\"\" -Dfoo9=%'''%%@% ****** && exit %%ERRORLEVEL%%\""));
}
@Test
@Ignore("It's only for reproduce JENKINS-28790 issue. It's added to testToWindowsCommand")
@Issue("JENKINS-28790")
public void testToWindowsCommandMasked() {
ArgumentListBuilder builder = new ArgumentListBuilder().
add("ant.bat").add("-Dfoo1=abc"). // nothing special, no quotes
add("-Dfoo2=foo bar").add("-Dfoo3=/u*r").add("-Dfoo4=/us?"). // add quotes
add("-Dfoo10=bar,baz").
add("-Dfoo5=foo;bar^baz").add("-Dfoo6=<xml>&here;</xml>"). // add quotes
add("-Dfoo7=foo|bar\"baz"). // add quotes and "" for "
add("-Dfoo8=% %QED% %comspec% %-%(%.%"). // add quotes, and extra quotes for %Q and %c
add("-Dfoo9=%'''%%@%"). // no quotes as none of the % are followed by a letter
add("-Dpassword=hidden", true);
// By default, does not escape %VAR%
assertThat(builder.toWindowsCommand().toString(), is("cmd.exe /C \"ant.bat -Dfoo1=abc \"\"-Dfoo2=foo bar\"\" \"-Dfoo3=/u*r\" \"-Dfoo4=/us?\" \"-Dfoo10=bar,baz\" \"-Dfoo5=foo;bar^baz\" \"-Dfoo6=<xml>&here;</xml>\" \"-Dfoo7=foo|bar\"\"baz\" \"\"-Dfoo8=% %QED% %comspec% %-%(%.%\"\" -Dfoo9=%'''%%@% ****** && exit %%ERRORLEVEL%%\"" ));
// Pass flag to escape %VAR%
assertThat(builder.toWindowsCommand(true).toString(), is("cmd.exe /C \"ant.bat -Dfoo1=abc \"\"-Dfoo2=foo bar\"\" \"-Dfoo3=/u*r\" \"-Dfoo4=/us?\" \"-Dfoo10=bar,baz\" \"-Dfoo5=foo;bar^baz\" \"-Dfoo6=<xml>&here;</xml>\" \"-Dfoo7=foo|bar\"\"baz\" \"\"-Dfoo8=% %\"Q\"ED% %\"c\"omspec% %-%(%.%\"\" -Dfoo9=%'''%%@% ****** && exit %%ERRORLEVEL%%\""));
}
@Test
public void assertMaskOnClone() {
ArgumentListBuilder builder = new ArgumentListBuilder();
builder.add("arg1");
builder.addMasked("masked1");
builder.add("arg2");
ArgumentListBuilder clone = builder.clone();
assertTrue("There should be masked arguments", clone.hasMaskedArguments());
boolean[] array = clone.toMaskArray();
assertNotNull("The mask array should not be null", array);
assertThat("The mask array was incorrect", array, is(builder.toMaskArray()));
}
private static final Map<String, String> KEY_VALUES = new LinkedHashMap<String, String>() {{
put("key1", "value1");
put("key2", "value2");
put("key3", "value3");
}};
private static final Set<String> MASKS = new HashSet<String>() {{
add("key2");
}};
@Test
public void assertKeyValuePairsWithMask() {
ArgumentListBuilder builder = new ArgumentListBuilder();
builder.addKeyValuePairs(null, KEY_VALUES, MASKS);
assertTrue("There should be masked arguments", builder.hasMaskedArguments());
boolean[] array = builder.toMaskArray();
assertNotNull("The mask array should not be null", array);
assertThat("The mask array was incorrect", array, is(new boolean[] { false, true, false }));
}
@Test
public void assertKeyValuePairs() {
ArgumentListBuilder builder = new ArgumentListBuilder();
builder.addKeyValuePairs(null, KEY_VALUES);
assertFalse("There should not be any masked arguments", builder.hasMaskedArguments());
boolean[] array = builder.toMaskArray();
assertNotNull("The mask array should not be null", array);
assertThat("The mask array was incorrect", array, is(new boolean[] { false, false, false }));
}
@Test
public void addKeyValuePairsFromPropertyString() throws IOException {
final Map<String, String> map = new HashMap<>();
map.put("PATH", "C:\\Windows");
final VariableResolver<String> resolver = new VariableResolver.ByMap<>(map);
final String properties = "my.path=$PATH";
ArgumentListBuilder builder = new ArgumentListBuilder();
builder.addKeyValuePairsFromPropertyString("", properties, resolver);
assertEquals("my.path=C:\\Windows", builder.toString());
builder = new ArgumentListBuilder();
builder.addKeyValuePairsFromPropertyString("", properties, resolver, null);
assertEquals("my.path=C:\\Windows", builder.toString());
}
@Test
public void numberOfBackslashesInPropertiesShouldBePreservedAfterMacroExpansion() throws IOException {
final Map<String, String> map = new HashMap<>();
map.put("ONE", "one\\backslash");
map.put("TWO", "two\\\\backslashes");
map.put("FOUR", "four\\\\\\\\backslashes");
final String properties = "one=$ONE\n" +
"two=$TWO\n" +
"four=$FOUR\n"
;
final String args = new ArgumentListBuilder()
.addKeyValuePairsFromPropertyString("", properties, new VariableResolver.ByMap<>(map))
.toString()
;
assertThat(args, containsString("one=one\\backslash"));
assertThat(args, containsString("two=two\\\\backslashes"));
assertThat(args, containsString("four=four\\\\\\\\backslashes"));
}
}
| mit |
boggad/jdk9-sample | sample-catalog/src/main/spring.context/org/springframework/cache/interceptor/CacheOperationInvoker.java | 1796 | /*
* Copyright 2002-2016 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.cache.interceptor;
/**
* Abstract the invocation of a cache operation.
*
* <p>Does not provide a way to transmit checked exceptions but
* provide a special exception that should be used to wrap any
* exception that was thrown by the underlying invocation.
* Callers are expected to handle this issue type specifically.
*
* @author Stephane Nicoll
* @since 4.1
*/
@FunctionalInterface
public interface CacheOperationInvoker {
/**
* Invoke the cache operation defined by this instance. Wraps any exception
* that is thrown during the invocation in a {@link ThrowableWrapper}.
* @return the result of the operation
* @throws ThrowableWrapper if an error occurred while invoking the operation
*/
Object invoke() throws ThrowableWrapper;
/**
* Wrap any exception thrown while invoking {@link #invoke()}.
*/
@SuppressWarnings("serial")
class ThrowableWrapper extends RuntimeException {
private final Throwable original;
public ThrowableWrapper(Throwable original) {
super(original.getMessage(), original);
this.original = original;
}
public Throwable getOriginal() {
return this.original;
}
}
}
| mit |
Deepak345/al-go-rithms | sort/quick_sort/java/QuickSort.java | 2032 | class QuickSort
{
/* This function takes last element as pivot,
places the pivot element at its correct
position in sorted array, and places all
smaller (smaller than pivot) to left of
pivot and all greater elements to right
of pivot */
int partition(int arr[], int low, int high)
{
int pivot = arr[high];
int i = (low-1); // index of smaller element
for (int j=low; j<high; j++)
{
// If current element is smaller than or
// equal to pivot
if (arr[j] <= pivot)
{
i++;
// swap arr[i] and arr[j]
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// swap arr[i+1] and arr[high] (or pivot)
int temp = arr[i+1];
arr[i+1] = arr[high];
arr[high] = temp;
return i+1;
}
/* The main function that implements QuickSort()
arr[] --> Array to be sorted,
low --> Starting index,
high --> Ending index */
void sort(int arr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[pi] is
now at right place */
int pi = partition(arr, low, high);
// Recursively sort elements before
// partition and after partition
sort(arr, low, pi-1);
sort(arr, pi+1, high);
}
}
/* A utility function to print array of size n */
static void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
// Driver program
public static void main(String args[])
{
int arr[] = {10, 7, 8, 9, 1, 5};
int n = arr.length;
QuickSort ob = new QuickSort();
ob.sort(arr, 0, n-1);
System.out.println("sorted array");
printArray(arr);
}
} | mit |
gorelikov/testcontainers-java | core/src/test/java/org/testcontainers/junit/DockerComposeOverrideTest.java | 2301 | package org.testcontainers.junit;
import com.google.common.util.concurrent.Uninterruptibles;
import org.junit.Assume;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.Test;
import org.rnorth.ducttape.unreliables.Unreliables;
import org.testcontainers.containers.DockerComposeContainer;
import org.testcontainers.utility.TestEnvironment;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.concurrent.TimeUnit;
import static org.rnorth.visibleassertions.VisibleAssertions.info;
import static org.rnorth.visibleassertions.VisibleAssertions.pass;
import static org.testcontainers.junit.DockerComposeDoNotOverrideTest.*;
/**
* Created by rnorth on 11/06/2016.
*/
public class DockerComposeOverrideTest {
@Rule
public DockerComposeContainer compose =
new DockerComposeContainer(
new File(DOCKER_COMPOSE_OVERRIDE_TEST_BASE_YML),
new File(DOCKER_COMPOSE_OVERRIDE_TEST_OVERRIDE_YML))
.withExposedService("alpine_1", 3000);
@BeforeClass
public static void checkVersion() {
Assume.assumeTrue(TestEnvironment.dockerApiAtLeast("1.22"));
}
@Test(timeout = 30_000)
public void testEnvVar() throws IOException {
BufferedReader br = Unreliables.retryUntilSuccess(10, TimeUnit.SECONDS, () -> {
Uninterruptibles.sleepUninterruptibly(1, TimeUnit.SECONDS);
Socket socket = new Socket(compose.getServiceHost("alpine_1", 3000), compose.getServicePort("alpine_1", 3000));
return new BufferedReader(new InputStreamReader(socket.getInputStream()));
});
Unreliables.retryUntilTrue(10, TimeUnit.SECONDS, () -> {
while (br.ready()) {
String line = br.readLine();
if (line.contains(DOCKER_COMPOSE_OVERRIDE_TEST_OVERRIDE_ENV)) {
pass("Mapped environment variable was found");
return true;
}
}
info("Mapped environment variable was not found yet - process probably not ready");
Uninterruptibles.sleepUninterruptibly(100, TimeUnit.MILLISECONDS);
return false;
});
}
}
| mit |
Weisses/Ebonheart-Mods | ViesCraft/Archived/zzz - PreCapabilities - src/main/java/com/viesis/viescraft/common/items/airshipitems/v3/ItemAirshipV3Admin.java | 2123 | package com.viesis.viescraft.common.items.airshipitems.v3;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.init.SoundEvents;
import net.minecraft.item.ItemStack;
import net.minecraft.stats.StatList;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.text.translation.I18n;
import net.minecraft.world.World;
import com.viesis.viescraft.ViesCraft;
import com.viesis.viescraft.common.entity.airshipitems.v3.EntityItemAirshipV3Admin;
import com.viesis.viescraft.common.items.ItemHelper;
import com.viesis.viescraft.common.items.airshipitems.ItemAirshipCore;
import com.viesis.viescraft.configs.ViesCraftConfig;
public class ItemAirshipV3Admin extends ItemAirshipCore {
public ItemAirshipV3Admin()
{
ItemHelper.setItemName(this, "item_airship_v3_admin");
this.setCreativeTab(ViesCraft.tabViesCraftAirships);
}
@Override
public ActionResult<ItemStack> onItemRightClick(ItemStack itemStackIn, World worldIn, EntityPlayer playerIn, EnumHand hand)
{
if(playerIn.isSneaking())
{
if (!playerIn.capabilities.isCreativeMode)
{
--itemStackIn.stackSize;
}
worldIn.playSound((EntityPlayer)null, playerIn.posX, playerIn.posY, playerIn.posZ, SoundEvents.ENTITY_EXPERIENCE_BOTTLE_THROW, SoundCategory.NEUTRAL, 0.5F, 0.4F / (itemRand.nextFloat() * 0.4F + 0.8F));
if (!worldIn.isRemote)
{
EntityItemAirshipV3Admin entityairship = new EntityItemAirshipV3Admin(worldIn, playerIn);
entityairship.setHeadingFromThrower(playerIn, playerIn.rotationPitch, playerIn.rotationYaw, -20.0F, 0.7F, 1.0F);
worldIn.spawnEntityInWorld(entityairship);
}
playerIn.addStat(StatList.getObjectUseStats(this));
return new ActionResult(EnumActionResult.SUCCESS, itemStackIn);
}
return new ActionResult(EnumActionResult.SUCCESS, itemStackIn);
}
@Override
public String getItemStackDisplayName(ItemStack stack)
{
return ("" + I18n.translateToLocal("Admin " + ViesCraftConfig.v3AirshipName)).trim();
}
}
| mit |
RentTheRunway/alchemy | alchemy-api/src/main/java/io/rtr/alchemy/dto/requests/AllocationRequest.java | 2174 | package io.rtr.alchemy.dto.requests;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.JsonTypeName;
import javax.validation.constraints.NotNull;
/**
* Represents requests for multiple allocation actions
*/
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "action")
@JsonSubTypes({
@Type(AllocationRequest.Reallocate.class),
@Type(AllocationRequest.Allocate.class),
@Type(AllocationRequest.Deallocate.class)
})
public abstract class AllocationRequest {
@NotNull
private final String treatment;
@NotNull
private final Integer size;
public AllocationRequest(String treatment,
Integer size) {
this.treatment = treatment;
this.size = size;
}
public String getTreatment() {
return treatment;
}
public Integer getSize() {
return size;
}
@JsonTypeName("allocate")
public static class Allocate extends AllocationRequest {
public Allocate(@JsonProperty("treatment") String treatment,
@JsonProperty("size") Integer size) {
super(treatment, size);
}
}
@JsonTypeName("deallocate")
public static class Deallocate extends AllocationRequest {
public Deallocate(@JsonProperty("treatment") String treatment,
@JsonProperty("size") Integer size) {
super(treatment, size);
}
}
@JsonTypeName("reallocate")
public static class Reallocate extends AllocationRequest {
@NotNull
private final String target;
public Reallocate(@JsonProperty("treatment") String treatment,
@JsonProperty("size") Integer size,
@JsonProperty("target") String target) {
super(treatment, size);
this.target = target;
}
public String getTarget() {
return target;
}
}
}
| mit |
navalev/azure-sdk-for-java | sdk/sql/mgmt-v2015_05_01_preview/src/main/java/com/microsoft/azure/management/sql/v2015_05_01_preview/implementation/SqlManager.java | 10665 | /**
* 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.sql.v2015_05_01_preview.implementation;
import com.microsoft.azure.AzureEnvironment;
import com.microsoft.azure.AzureResponseBuilder;
import com.microsoft.azure.credentials.AzureTokenCredentials;
import com.microsoft.azure.management.apigeneration.Beta;
import com.microsoft.azure.management.apigeneration.Beta.SinceVersion;
import com.microsoft.azure.arm.resources.AzureConfigurable;
import com.microsoft.azure.serializer.AzureJacksonAdapter;
import com.microsoft.rest.RestClient;
import com.microsoft.azure.management.sql.v2015_05_01_preview.DatabaseAdvisors;
import com.microsoft.azure.management.sql.v2015_05_01_preview.DatabaseRecommendedActions;
import com.microsoft.azure.management.sql.v2015_05_01_preview.ServerAdvisors;
import com.microsoft.azure.management.sql.v2015_05_01_preview.DatabaseBlobAuditingPolicies;
import com.microsoft.azure.management.sql.v2015_05_01_preview.DatabaseAutomaticTunings;
import com.microsoft.azure.management.sql.v2015_05_01_preview.EncryptionProtectors;
import com.microsoft.azure.management.sql.v2015_05_01_preview.FailoverGroups;
import com.microsoft.azure.management.sql.v2015_05_01_preview.FirewallRules;
import com.microsoft.azure.management.sql.v2015_05_01_preview.ManagedInstances;
import com.microsoft.azure.management.sql.v2015_05_01_preview.Operations;
import com.microsoft.azure.management.sql.v2015_05_01_preview.ServerKeys;
import com.microsoft.azure.management.sql.v2015_05_01_preview.Servers;
import com.microsoft.azure.management.sql.v2015_05_01_preview.SyncAgents;
import com.microsoft.azure.management.sql.v2015_05_01_preview.SyncGroups;
import com.microsoft.azure.management.sql.v2015_05_01_preview.SyncMembers;
import com.microsoft.azure.management.sql.v2015_05_01_preview.SubscriptionUsages;
import com.microsoft.azure.management.sql.v2015_05_01_preview.VirtualNetworkRules;
import com.microsoft.azure.arm.resources.implementation.AzureConfigurableCoreImpl;
import com.microsoft.azure.arm.resources.implementation.ManagerCore;
/**
* Entry point to Azure Sql resource management.
*/
public final class SqlManager extends ManagerCore<SqlManager, SqlManagementClientImpl> {
private DatabaseAdvisors databaseAdvisors;
private DatabaseRecommendedActions databaseRecommendedActions;
private ServerAdvisors serverAdvisors;
private DatabaseBlobAuditingPolicies databaseBlobAuditingPolicies;
private DatabaseAutomaticTunings databaseAutomaticTunings;
private EncryptionProtectors encryptionProtectors;
private FailoverGroups failoverGroups;
private FirewallRules firewallRules;
private ManagedInstances managedInstances;
private Operations operations;
private ServerKeys serverKeys;
private Servers servers;
private SyncAgents syncAgents;
private SyncGroups syncGroups;
private SyncMembers syncMembers;
private SubscriptionUsages subscriptionUsages;
private VirtualNetworkRules virtualNetworkRules;
/**
* Get a Configurable instance that can be used to create SqlManager with optional configuration.
*
* @return the instance allowing configurations
*/
public static Configurable configure() {
return new SqlManager.ConfigurableImpl();
}
/**
* Creates an instance of SqlManager that exposes Sql resource management API entry points.
*
* @param credentials the credentials to use
* @param subscriptionId the subscription UUID
* @return the SqlManager
*/
public static SqlManager authenticate(AzureTokenCredentials credentials, String subscriptionId) {
return new SqlManager(new RestClient.Builder()
.withBaseUrl(credentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER)
.withCredentials(credentials)
.withSerializerAdapter(new AzureJacksonAdapter())
.withResponseBuilderFactory(new AzureResponseBuilder.Factory())
.build(), subscriptionId);
}
/**
* Creates an instance of SqlManager that exposes Sql resource management API entry points.
*
* @param restClient the RestClient to be used for API calls.
* @param subscriptionId the subscription UUID
* @return the SqlManager
*/
public static SqlManager authenticate(RestClient restClient, String subscriptionId) {
return new SqlManager(restClient, subscriptionId);
}
/**
* The interface allowing configurations to be set.
*/
public interface Configurable extends AzureConfigurable<Configurable> {
/**
* Creates an instance of SqlManager that exposes Sql management API entry points.
*
* @param credentials the credentials to use
* @param subscriptionId the subscription UUID
* @return the interface exposing Sql management API entry points that work across subscriptions
*/
SqlManager authenticate(AzureTokenCredentials credentials, String subscriptionId);
}
/**
* @return Entry point to manage DatabaseAdvisors.
*/
public DatabaseAdvisors databaseAdvisors() {
if (this.databaseAdvisors == null) {
this.databaseAdvisors = new DatabaseAdvisorsImpl(this);
}
return this.databaseAdvisors;
}
/**
* @return Entry point to manage DatabaseRecommendedActions.
*/
public DatabaseRecommendedActions databaseRecommendedActions() {
if (this.databaseRecommendedActions == null) {
this.databaseRecommendedActions = new DatabaseRecommendedActionsImpl(this);
}
return this.databaseRecommendedActions;
}
/**
* @return Entry point to manage ServerAdvisors.
*/
public ServerAdvisors serverAdvisors() {
if (this.serverAdvisors == null) {
this.serverAdvisors = new ServerAdvisorsImpl(this);
}
return this.serverAdvisors;
}
/**
* @return Entry point to manage DatabaseBlobAuditingPolicies.
*/
public DatabaseBlobAuditingPolicies databaseBlobAuditingPolicies() {
if (this.databaseBlobAuditingPolicies == null) {
this.databaseBlobAuditingPolicies = new DatabaseBlobAuditingPoliciesImpl(this);
}
return this.databaseBlobAuditingPolicies;
}
/**
* @return Entry point to manage DatabaseAutomaticTunings.
*/
public DatabaseAutomaticTunings databaseAutomaticTunings() {
if (this.databaseAutomaticTunings == null) {
this.databaseAutomaticTunings = new DatabaseAutomaticTuningsImpl(this);
}
return this.databaseAutomaticTunings;
}
/**
* @return Entry point to manage EncryptionProtectors.
*/
public EncryptionProtectors encryptionProtectors() {
if (this.encryptionProtectors == null) {
this.encryptionProtectors = new EncryptionProtectorsImpl(this);
}
return this.encryptionProtectors;
}
/**
* @return Entry point to manage FailoverGroups.
*/
public FailoverGroups failoverGroups() {
if (this.failoverGroups == null) {
this.failoverGroups = new FailoverGroupsImpl(this);
}
return this.failoverGroups;
}
/**
* @return Entry point to manage FirewallRules.
*/
public FirewallRules firewallRules() {
if (this.firewallRules == null) {
this.firewallRules = new FirewallRulesImpl(this);
}
return this.firewallRules;
}
/**
* @return Entry point to manage ManagedInstances.
*/
public ManagedInstances managedInstances() {
if (this.managedInstances == null) {
this.managedInstances = new ManagedInstancesImpl(this);
}
return this.managedInstances;
}
/**
* @return Entry point to manage Operations.
*/
public Operations operations() {
if (this.operations == null) {
this.operations = new OperationsImpl(this);
}
return this.operations;
}
/**
* @return Entry point to manage ServerKeys.
*/
public ServerKeys serverKeys() {
if (this.serverKeys == null) {
this.serverKeys = new ServerKeysImpl(this);
}
return this.serverKeys;
}
/**
* @return Entry point to manage Servers.
*/
public Servers servers() {
if (this.servers == null) {
this.servers = new ServersImpl(this);
}
return this.servers;
}
/**
* @return Entry point to manage SyncAgents.
*/
public SyncAgents syncAgents() {
if (this.syncAgents == null) {
this.syncAgents = new SyncAgentsImpl(this);
}
return this.syncAgents;
}
/**
* @return Entry point to manage SyncGroups.
*/
public SyncGroups syncGroups() {
if (this.syncGroups == null) {
this.syncGroups = new SyncGroupsImpl(this);
}
return this.syncGroups;
}
/**
* @return Entry point to manage SyncMembers.
*/
public SyncMembers syncMembers() {
if (this.syncMembers == null) {
this.syncMembers = new SyncMembersImpl(this);
}
return this.syncMembers;
}
/**
* @return Entry point to manage SubscriptionUsages.
*/
public SubscriptionUsages subscriptionUsages() {
if (this.subscriptionUsages == null) {
this.subscriptionUsages = new SubscriptionUsagesImpl(this);
}
return this.subscriptionUsages;
}
/**
* @return Entry point to manage VirtualNetworkRules.
*/
public VirtualNetworkRules virtualNetworkRules() {
if (this.virtualNetworkRules == null) {
this.virtualNetworkRules = new VirtualNetworkRulesImpl(this);
}
return this.virtualNetworkRules;
}
/**
* The implementation for Configurable interface.
*/
private static final class ConfigurableImpl extends AzureConfigurableCoreImpl<Configurable> implements Configurable {
public SqlManager authenticate(AzureTokenCredentials credentials, String subscriptionId) {
return SqlManager.authenticate(buildRestClient(credentials), subscriptionId);
}
}
private SqlManager(RestClient restClient, String subscriptionId) {
super(
restClient,
subscriptionId,
new SqlManagementClientImpl(restClient).withSubscriptionId(subscriptionId));
}
}
| mit |
openhab/openhab2 | bundles/org.openhab.binding.velux/src/main/java/org/openhab/binding/velux/internal/things/VeluxProduct.java | 13516 | /**
* 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.velux.internal.things;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* <B>Velux</B> product representation.
* <P>
* Combined set of information describing a single Velux product.
*
* @author Guenther Schreiner - initial contribution.
*/
@NonNullByDefault
public class VeluxProduct {
private final Logger logger = LoggerFactory.getLogger(VeluxProduct.class);
// Public definition
public static final VeluxProduct UNKNOWN = new VeluxProduct();
// Type definitions
public static class ProductBridgeIndex {
// Public definition
public static final ProductBridgeIndex UNKNOWN = new ProductBridgeIndex(0);
// Class internal
private int id;
// Constructor
public ProductBridgeIndex(int id) {
this.id = id;
}
// Class access methods
public int toInt() {
return id;
}
@Override
public String toString() {
return Integer.toString(id);
}
}
// State (of movement) of an actuator
public static enum State {
NON_EXECUTING(0),
ERROR(1),
NOT_USED(2),
WAITING_FOR_POWER(3),
EXECUTING(4),
DONE(5),
MANUAL_OVERRIDE(0x80),
UNKNOWN(0xFF);
public final int value;
private State(int value) {
this.value = value;
}
}
// Class internal
private VeluxProductName name;
private VeluxProductType typeId;
private ProductBridgeIndex bridgeProductIndex;
private boolean v2 = false;
private int order = 0;
private int placement = 0;
private int velocity = 0;
private int variation = 0;
private int powerMode = 0;
private String serialNumber = VeluxProductSerialNo.UNKNOWN;
private int state = State.UNKNOWN.value;
private int currentPosition = 0;
private int targetPosition = 0;
private int remainingTime = 0;
private int timeStamp = 0;
// Constructor
/**
* Constructor
*
* just for the dummy VeluxProduct.
*/
public VeluxProduct() {
logger.trace("VeluxProduct() created.");
this.name = VeluxProductName.UNKNOWN;
this.typeId = VeluxProductType.UNDEFTYPE;
this.bridgeProductIndex = ProductBridgeIndex.UNKNOWN;
}
/**
* Constructor
*
* @param name This field Name holds the name of the actuator, ex. “Window 1”. This field is 64 bytes
* long, formatted as UTF-8 characters.
* @param typeId This field indicates the node type, ex. Window, Roller shutter, Light etc.
* @param bridgeProductIndex NodeID is an Actuator index in the system table, to get information from. It must be a
* value from 0 to 199.
*/
public VeluxProduct(VeluxProductName name, VeluxProductType typeId, ProductBridgeIndex bridgeProductIndex) {
logger.trace("VeluxProduct(v1,name={}) created.", name.toString());
this.name = name;
this.typeId = typeId;
this.bridgeProductIndex = bridgeProductIndex;
}
/**
* Constructor
*
* @param name This field Name holds the name of the actuator, ex. “Window 1”. This field is 64 bytes
* long, formatted as UTF-8 characters.
* @param typeId This field indicates the node type, ex. Window, Roller shutter, Light etc.
* @param bridgeProductIndex NodeID is an Actuator index in the system table, to get information from. It must be a
* value from 0 to 199.
* @param order Order can be used to store a sort order. The sort order is used in client end, when
* presenting a list of nodes for the user.
* @param placement Placement can be used to store a room group index or house group index number.
* @param velocity This field indicates what velocity the node is operation with.
* @param variation More detail information like top hung, kip, flat roof or sky light window.
* @param powerMode This field indicates the power mode of the node (ALWAYS_ALIVE/LOW_POWER_MODE).
* @param serialNumber This field tells the serial number of the node. This field is 8 bytes.
* @param state This field indicates the operating state of the node.
* @param currentPosition This field indicates the current position of the node.
* @param target This field indicates the target position of the current operation.
* @param remainingTime This field indicates the remaining time for a node activation in seconds.
* @param timeStamp UTC time stamp for last known position.
*/
public VeluxProduct(VeluxProductName name, VeluxProductType typeId, ProductBridgeIndex bridgeProductIndex,
int order, int placement, int velocity, int variation, int powerMode, String serialNumber, int state,
int currentPosition, int target, int remainingTime, int timeStamp) {
logger.trace("VeluxProduct(v2,name={}) created.", name.toString());
this.name = name;
this.typeId = typeId;
this.bridgeProductIndex = bridgeProductIndex;
this.v2 = true;
this.order = order;
this.placement = placement;
this.velocity = velocity;
this.variation = variation;
this.powerMode = powerMode;
this.serialNumber = serialNumber;
this.state = state;
this.currentPosition = currentPosition;
this.targetPosition = target;
this.remainingTime = remainingTime;
this.timeStamp = timeStamp;
}
// Utility methods
@Override
public VeluxProduct clone() {
if (this.v2) {
return new VeluxProduct(this.name, this.typeId, this.bridgeProductIndex, this.order, this.placement,
this.velocity, this.variation, this.powerMode, this.serialNumber, this.state, this.currentPosition,
this.targetPosition, this.remainingTime, this.timeStamp);
} else {
return new VeluxProduct(this.name, this.typeId, this.bridgeProductIndex);
}
}
// Class access methods
/**
* Returns the name of the current product (aka actuator) for convenience as type-specific class.
*
* @return nameOfThisProduct as type {@link VeluxProductName}.
*/
public VeluxProductName getProductName() {
return this.name;
}
/**
* Returns the type of the current product (aka actuator) for convenience as type-specific class.
*
* @return typeOfThisProduct as type {@link VeluxProductType}.
*/
public VeluxProductType getProductType() {
return this.typeId;
}
public ProductBridgeIndex getBridgeProductIndex() {
return this.bridgeProductIndex;
}
@Override
public String toString() {
if (this.v2) {
return String.format("Product \"%s\" / %s (bridgeIndex=%d,serial=%s,position=%04X)", this.name, this.typeId,
this.bridgeProductIndex.toInt(), this.serialNumber, this.currentPosition);
} else {
return String.format("Product \"%s\" / %s (bridgeIndex %d)", this.name, this.typeId,
this.bridgeProductIndex.toInt());
}
}
// Class helper methods
public String getProductUniqueIndex() {
if (!v2 || serialNumber.startsWith(VeluxProductSerialNo.UNKNOWN)) {
return name.toString();
}
return VeluxProductSerialNo.cleaned(serialNumber);
}
// Getter and Setter methods
/**
* @return <b>v2</b> as type boolean signals the availability of firmware version two (product) details.
*/
public boolean isV2() {
return v2;
}
/**
* @return <b>order</b> as type int describes the user-oriented sort-order.
*/
public int getOrder() {
return order;
}
/**
* @return <B>placement</B> as type int is used to describe a group index or house group index number.
*/
public int getPlacement() {
return placement;
}
/**
* @return <B>velocity</B> as type int describes what velocity the node is operation with
*/
public int getVelocity() {
return velocity;
}
/**
* @return <B>variation</B> as type int describes detail information like top hung, kip, flat roof or sky light
* window.
*/
public int getVariation() {
return variation;
}
/**
* @return <B>powerMode</B> as type int is used to show the power mode of the node (ALWAYS_ALIVE/LOW_POWER_MODE).
*/
public int getPowerMode() {
return powerMode;
}
/**
* @return <B>serialNumber</B> as type String is the serial number of 8 bytes length of the node.
*/
public String getSerialNumber() {
return serialNumber;
}
/**
* @return <B>state</B> as type int is used to operating state of the node.
*/
public int getState() {
return state;
}
/**
* @param newState Update the operating state of the node.
* @return <B>modified</B> as type boolean to signal a real modification.
*/
public boolean setState(int newState) {
if (this.state == newState) {
return false;
} else {
logger.trace("setState(name={},index={}) state {} replaced by {}.", name.toString(),
bridgeProductIndex.toInt(), this.state, newState);
this.state = newState;
return true;
}
}
/**
* @return <B>currentPosition</B> as type int signals the current position of the node.
*/
public int getCurrentPosition() {
return currentPosition;
}
/**
* @param newCurrentPosition Update the current position of the node.
* @return <B>modified</B> as boolean to signal a real modification.
*/
public boolean setCurrentPosition(int newCurrentPosition) {
if (this.currentPosition == newCurrentPosition) {
return false;
} else {
logger.trace("setCurrentPosition(name={},index={}) currentPosition {} replaced by {}.", name.toString(),
bridgeProductIndex.toInt(), this.currentPosition, newCurrentPosition);
this.currentPosition = newCurrentPosition;
return true;
}
}
/**
* @return <b>target</b> as type int shows the target position of the current operation.
*/
public int getTarget() {
return targetPosition;
}
/**
* @param newTarget Update the target position of the current operation.
* @return <b>modified</b> as boolean to signal a real modification.
*/
public boolean setTarget(int newTarget) {
if (this.targetPosition == newTarget) {
return false;
} else {
logger.trace("setCurrentPosition(name={},index={}) target {} replaced by {}.", name.toString(),
bridgeProductIndex.toInt(), this.targetPosition, newTarget);
this.targetPosition = newTarget;
return true;
}
}
/**
* @return <b>remainingTime</b> as type int describes the intended remaining time of current operation.
*/
public int getRemainingTime() {
return remainingTime;
}
/**
* @return <b>timeStamp</b> as type int describes the current time.
*/
public int getTimeStamp() {
return timeStamp;
}
/**
* Returns the display position of the actuator.
* <li>As a general rule it returns <b>currentPosition</b>, except as follows..
* <li>If the actuator is in a motion state it returns <b>targetPosition</b>
* <li>If the motion state is 'done' but the currentPosition is invalid it returns <b>targetPosition</b>
* <li>If the manual override flag is set it returns the <b>unknown</b> position value
*
* @return The display position of the actuator
*/
public int getDisplayPosition() {
// manual override flag set: position is 'unknown'
if ((state & State.MANUAL_OVERRIDE.value) != 0) {
return VeluxProductPosition.VPP_VELUX_UNKNOWN;
}
// only check other conditions if targetPosition is valid and differs from currentPosition
if ((targetPosition != currentPosition) && (targetPosition <= VeluxProductPosition.VPP_VELUX_MAX)
&& (targetPosition >= VeluxProductPosition.VPP_VELUX_MIN)) {
int state = this.state & 0xf;
// actuator is in motion: for quicker UI update, return targetPosition
if ((state > State.ERROR.value) && (state < State.DONE.value)) {
return targetPosition;
}
// motion complete but currentPosition is not valid: return targetPosition
if ((state == State.DONE.value) && ((currentPosition > VeluxProductPosition.VPP_VELUX_MAX)
|| (currentPosition < VeluxProductPosition.VPP_VELUX_MIN))) {
return targetPosition;
}
}
return currentPosition;
}
}
| epl-1.0 |
kgibm/open-liberty | dev/com.ibm.ws.jsf.2.3_fat/test-applications/ELImplicitObjectsViaCDI.war/src/com/ibm/ws/jsf23/fat/elimplicit/cdi/beans/ELImplicitObjectBean.java | 6676 | /*******************************************************************************
* Copyright (c) 2017, 2020 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.jsf23.fat.elimplicit.cdi.beans;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.enterprise.context.RequestScoped;
import javax.faces.annotation.ApplicationMap;
import javax.faces.annotation.FacesConfig;
import javax.faces.annotation.FlowMap;
import javax.faces.annotation.HeaderMap;
import javax.faces.annotation.HeaderValuesMap;
import javax.faces.annotation.InitParameterMap;
import javax.faces.annotation.RequestCookieMap;
import javax.faces.annotation.RequestMap;
import javax.faces.annotation.RequestParameterMap;
import javax.faces.annotation.RequestParameterValuesMap;
import javax.faces.annotation.SessionMap;
import javax.faces.annotation.ViewMap;
import javax.faces.application.FacesMessage;
import javax.faces.application.ResourceHandler;
import javax.faces.component.UIViewRoot;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.faces.context.Flash;
import javax.inject.Inject;
import javax.inject.Named;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
/**
* Bean that tests if EL implicit objects are injectable
*/
@Named("elImplicitObjectBean")
@RequestScoped
@FacesConfig
public class ELImplicitObjectBean implements Serializable {
/** */
private static final long serialVersionUID = 1L;
private static Logger LOGGER = Logger.getLogger(ELImplicitObjectBean.class.getName());
@Inject
private FacesContext facesContext; // #{facesContext}
@Inject
private ExternalContext externalContext; // #{externalContext}
@Inject
private UIViewRoot viewRoot; // #{view}
@Inject
private ServletContext servletContext; // #{application}
@Inject
private Flash flash; // #{flash}
@Inject
private HttpSession httpSession; // #{session}
@Inject
@ApplicationMap
private Map<String, Object> applicationMap; // #{applicationScope}
@Inject
@SessionMap
private Map<String, Object> sessionMap; // #{sessionScope}
@Inject
@ViewMap
private Map<String, Object> viewMap; // #{viewScope}
@Inject
@RequestMap
private Map<String, Object> requestMap; // #{requestScope}
@Inject
@FlowMap
private Map<Object, Object> flowMap; // #{flowScope}
@Inject
@HeaderMap
private Map<String, String> headerMap; // #{header}
@Inject
@RequestCookieMap
private Map<String, Object> cookieMap; // #{cookie}
@Inject
@InitParameterMap
private Map<String, String> initParameterMap; // #{initParam}
@Inject
@RequestParameterMap
private Map<String, String> requestParameterMap; // #{param}
@Inject
@RequestParameterValuesMap
private Map<String, String[]> requestParameterValuesMap; // #{paramValues}
@Inject
@HeaderValuesMap
private Map<String, String[]> headerValuesMap; // #{headerValues}
@Inject
private ResourceHandler resourceHandler; // #{"resource"}
public void execute() {
if (facesContext == null) {
LOGGER.log(Level.INFO, "FacesContext was not initialized -> {0}", facesContext);
} else {
facesContext.addMessage(null, new FacesMessage("FacesContext project stage: " + facesContext.getApplication().getProjectStage()));
facesContext.addMessage(null, new FacesMessage("ServletContext context path: " + servletContext.getContextPath()));
facesContext.addMessage(null, new FacesMessage("ExternalContext app context path: " + externalContext.getApplicationContextPath()));
facesContext.addMessage(null, new FacesMessage("UIViewRoot viewId: " + viewRoot.getViewId()));
facesContext.addMessage(null, new FacesMessage("Flash isRedirect: " + flash.isRedirect()));
facesContext.addMessage(null, new FacesMessage("HttpSession isNew: " + httpSession.isNew()));
facesContext.addMessage(null, new FacesMessage("Application name from ApplicationMap: " + applicationMap.get("com.ibm.websphere.servlet.enterprise.application.name")));
// handle jakarta/javax namespace switch
Object charset = sessionMap.get("javax.faces.request.charset");
// handle jakarta/javax namespace switch
if(charset == null){
charset = sessionMap.get("jakarta.faces.request.charset");
}
facesContext.addMessage(null, new FacesMessage("Char set from SessionMap: " + charset ));
facesContext.addMessage(null, new FacesMessage("ViewMap isEmpty: " + viewMap.isEmpty()));
facesContext.addMessage(null, new FacesMessage("URI from RequestMap: " + requestMap.get("com.ibm.websphere.servlet.uri_non_decoded")));
try {
facesContext.addMessage(null, new FacesMessage("Flow map isEmpty: " + flowMap.isEmpty()));
} catch (Exception e) {
facesContext.addMessage(null, new FacesMessage("Flow map object is null: Exception: " + e.getMessage()));
}
facesContext.addMessage(null, new FacesMessage("Message from HeaderMap: " + headerMap.get("headerMessage")));
facesContext.addMessage(null, new FacesMessage("Cookie object from CookieMap: " + cookieMap.get("JSESSIONID")));
facesContext.addMessage(null, new FacesMessage("WELD_CONTEXT_ID_KEY from InitParameterMap: " + initParameterMap.get("WELD_CONTEXT_ID_KEY")));
facesContext.addMessage(null, new FacesMessage("Message from RequestParameterMap: " + requestParameterMap.get("message")));
facesContext.addMessage(null, new FacesMessage("Message from RequestParameterValuesMap: " + Arrays.toString(requestParameterValuesMap.get("message"))));
facesContext.addMessage(null, new FacesMessage("Message from HeaderValuesMap: " + Arrays.toString(headerValuesMap.get("headerMessage"))));
facesContext.addMessage(null, new FacesMessage("Resource handler JSF_SCRIPT_LIBRARY_NAME constant: " + resourceHandler.JSF_SCRIPT_LIBRARY_NAME));
}
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ssl/test/com/ibm/ws/ssl/internal/KeystoreConfigurationFactoryTest.java | 4832 | /*******************************************************************************
* Copyright (c) 2012 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.ssl.internal;
import static org.junit.Assert.assertEquals;
import java.io.File;
import java.util.Dictionary;
import java.util.Hashtable;
import org.jmock.Expectations;
import org.jmock.Mockery;
import org.jmock.integration.junit4.JUnit4Mockery;
import org.jmock.lib.legacy.ClassImposteriser;
import org.junit.After;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TestRule;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceReference;
import org.osgi.service.component.ComponentContext;
import com.ibm.wsspi.kernel.service.location.WsLocationAdmin;
import test.common.SharedOutputManager;
/**
*
*/
@SuppressWarnings("unchecked")
public class KeystoreConfigurationFactoryTest {
private static SharedOutputManager outputMgr = SharedOutputManager.getInstance();
/**
* Using the test rule will drive capture/restore and will dump on error..
* Notice this is not a static variable, though it is being assigned a value we
* allocated statically. -- the normal-variable-ness is for before/after processing
*/
@Rule
public TestRule managerRule = outputMgr;
private final Mockery mock = new JUnit4Mockery() {
{
setImposteriser(ClassImposteriser.INSTANCE);
}
};
private final ComponentContext cc = mock.mock(ComponentContext.class);
private final BundleContext bc = mock.mock(BundleContext.class);
private final ServiceReference<WsLocationAdmin> locSvcRef = mock.mock(ServiceReference.class);
private final WsLocationAdmin locSvc = mock.mock(WsLocationAdmin.class);
private final Dictionary props = new Hashtable();
private KeystoreConfigurationFactory ksConfigFactory;
@Before
public void setUp() {
final String defaultKeyStore = LibertyConstants.DEFAULT_OUTPUT_LOCATION + LibertyConstants.DEFAULT_FALLBACK_KEY_STORE_FILE;
final File defaultKeyStoreJKS = new File(defaultKeyStore);
mock.checking(new Expectations() {
{
allowing(cc).getBundleContext();
will(returnValue(bc));
allowing(cc).locateService("locMgr", locSvcRef);
will(returnValue(locSvc));
allowing(cc).locateService("LocMgr", locSvcRef);
will(returnValue(locSvc));
allowing(locSvc).resolveString(defaultKeyStore);
will(returnValue(defaultKeyStoreJKS.getAbsoluteFile()));
}
});
ksConfigFactory = new KeystoreConfigurationFactory();
ksConfigFactory.setLocMgr(locSvcRef);
ksConfigFactory.activate(cc);
}
@After
public void tearDown() {
ksConfigFactory.unsetLocMgr(locSvcRef);
ksConfigFactory.deactivate(cc, 0);
mock.assertIsSatisfied();
}
/**
* Test method for {@link com.ibm.ws.ssl.internal.KeystoreConfigurationFactory#updated(java.lang.String, java.util.Dictionary)}.
* b
*/
@Test
public void updated_noId() throws Exception {
ksConfigFactory.updated("registeredPid", props);
}
/**
* Test method for {@link com.ibm.ws.ssl.internal.KeystoreConfigurationFactory#updated(java.lang.String, java.util.Dictionary)}.
*/
@Test
public void updated() throws Exception {
props.put("id", "myId");
ksConfigFactory.updated("registeredPid", props);
}
/**
* Test method for {@link com.ibm.ws.ssl.internal.KeystoreConfigurationFactory#deleted(java.lang.String)}.
*/
@Test
public void deleted_notRegistered() {
ksConfigFactory.deleted("unregisteredPid");
}
/**
* Test method for {@link com.ibm.ws.ssl.internal.KeystoreConfigurationFactory#deleted(java.lang.String)}.
*/
@Test
public void deleted_registered() throws Exception {
props.put("id", "myId");
ksConfigFactory.updated("registeredPid", props);
ksConfigFactory.deleted("registeredPid");
}
/**
* Test method for {@link com.ibm.ws.ssl.internal.KeystoreConfigurationFactory#getName()}.
*/
@Test
public void getName() {
assertEquals("Did not receive expected name",
"Keystore configuration", ksConfigFactory.getName());
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jsp/src/com/ibm/ws/jsp/translator/utils/SDEInstaller.java | 9431 | /*******************************************************************************
* Copyright (c) 1997, 2004 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
*******************************************************************************/
//APARS:
//PI89577 hmpadill 11/16/17 JSPs containg Java 8 specific syntaxes might fail to compile
package com.ibm.ws.jsp.translator.utils;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
public class SDEInstaller {
private static final boolean verbose = false;
static final String nameSDE = "SourceDebugExtension";
byte[] orig;
byte[] sdeAttr;
byte[] gen;
int origPos = 0;
int genPos = 0;
int sdeIndex;
static void install(File inOutClassFile, SmapGenerator smapGenerator) throws IOException {
File tmpFile = new File(inOutClassFile.getPath() + "tmp");
new SDEInstaller(inOutClassFile, smapGenerator, tmpFile);
if (!inOutClassFile.delete()) {
throw new IOException("inOutClassFile.delete() failed");
}
if (!tmpFile.renameTo(inOutClassFile)) {
throw new IOException("tmpFile.renameTo(inOutClassFile) failed");
}
}
SDEInstaller(File inClassFile, SmapGenerator smapGenerator, File outClassFile) throws IOException {
if (!inClassFile.exists()) {
throw new FileNotFoundException("no such file: " + inClassFile);
}
// get the bytes
orig = readWhole(inClassFile);
sdeAttr = smapGenerator.toString().getBytes("UTF-8");
gen = new byte[orig.length + sdeAttr.length + 100];
// do it
addSDE();
// write result
FileOutputStream outStream = new FileOutputStream(outClassFile);
outStream.write(gen, 0, genPos);
outStream.close();
}
static byte[] readWhole(File input) throws IOException {
FileInputStream inStream = new FileInputStream(input);
int len = (int) input.length();
byte[] bytes = new byte[len];
if (inStream.read(bytes, 0, len) != len) {
throw new IOException("expected size: " + len);
}
inStream.close();
return bytes;
}
void addSDE() throws UnsupportedEncodingException, IOException {
int i;
copy(4 + 2 + 2); // magic min/maj version
int constantPoolCountPos = genPos;
int constantPoolCount = readU2();
if (verbose) {
System.out.println("constant pool count: " + constantPoolCount);
}
writeU2(constantPoolCount);
// copy old constant pool return index of SDE symbol, if found
sdeIndex = copyConstantPool(constantPoolCount);
if (sdeIndex < 0) {
// if "SourceDebugExtension" symbol not there add it
writeUtf8ForSDE();
// increment the countantPoolCount
sdeIndex = constantPoolCount;
++constantPoolCount;
randomAccessWriteU2(constantPoolCountPos, constantPoolCount);
if (verbose) {
System.out.println("SourceDebugExtension not found, installed at: " + sdeIndex);
}
}
else {
if (verbose) {
System.out.println("SourceDebugExtension found at: " + sdeIndex);
}
}
copy(2 + 2 + 2); // access, this, super
int interfaceCount = readU2();
writeU2(interfaceCount);
if (verbose) {
System.out.println("interfaceCount: " + interfaceCount);
}
copy(interfaceCount * 2);
copyMembers(); // fields
copyMembers(); // methods
int attrCountPos = genPos;
int attrCount = readU2();
writeU2(attrCount);
if (verbose) {
System.out.println("class attrCount: " + attrCount);
}
// copy the class attributes, return true if SDE attr found (not copied)
if (!copyAttrs(attrCount)) {
// we will be adding SDE and it isn't already counted
++attrCount;
randomAccessWriteU2(attrCountPos, attrCount);
if (verbose) {
System.out.println("class attrCount incremented");
}
}
writeAttrForSDE(sdeIndex);
}
void copyMembers() {
int count = readU2();
writeU2(count);
if (verbose) {
System.out.println("members count: " + count);
}
for (int i = 0; i < count; ++i) {
copy(6); // access, name, descriptor
int attrCount = readU2();
writeU2(attrCount);
if (verbose) {
System.out.println("member attr count: " + attrCount);
}
copyAttrs(attrCount);
}
}
boolean copyAttrs(int attrCount) {
boolean sdeFound = false;
for (int i = 0; i < attrCount; ++i) {
int nameIndex = readU2();
// don't write old SDE
if (nameIndex == sdeIndex) {
sdeFound = true;
if (verbose) {
System.out.println("SDE attr found");
}
}
else {
writeU2(nameIndex); // name
int len = readU4();
writeU4(len);
copy(len);
if (verbose) {
System.out.println("attr len: " + len);
}
}
}
return sdeFound;
}
void writeAttrForSDE(int index) {
writeU2(index);
writeU4(sdeAttr.length);
for (int i = 0; i < sdeAttr.length; ++i) {
writeU1(sdeAttr[i]);
}
}
void randomAccessWriteU2(int pos, int val) {
int savePos = genPos;
genPos = pos;
writeU2(val);
genPos = savePos;
}
int readU1() {
return ((int) orig[origPos++]) & 0xFF;
}
int readU2() {
int res = readU1();
return (res << 8) + readU1();
}
int readU4() {
int res = readU2();
return (res << 16) + readU2();
}
void writeU1(int val) {
gen[genPos++] = (byte) val;
}
void writeU2(int val) {
writeU1(val >> 8);
writeU1(val & 0xFF);
}
void writeU4(int val) {
writeU2(val >> 16);
writeU2(val & 0xFFFF);
}
void copy(int count) {
for (int i = 0; i < count; ++i) {
gen[genPos++] = orig[origPos++];
}
}
byte[] readBytes(int count) {
byte[] bytes = new byte[count];
for (int i = 0; i < count; ++i) {
bytes[i] = orig[origPos++];
}
return bytes;
}
void writeBytes(byte[] bytes) {
for (int i = 0; i < bytes.length; ++i) {
gen[genPos++] = bytes[i];
}
}
int copyConstantPool(int constantPoolCount) throws UnsupportedEncodingException, IOException {
int sdeIndex = -1;
// copy const pool index zero not in class file
for (int i = 1; i < constantPoolCount; ++i) {
int tag = readU1();
writeU1(tag);
switch (tag) {
case 7 : // Class
case 8 : // String
if (verbose) {
System.out.println(i + " copying 2 bytes");
}
copy(2);
break;
case 9 : // Field
case 10 : // Method
case 11 : // InterfaceMethod
case 3 : // Integer
case 4 : // Float
case 12 : // NameAndType
case 18 : // InvokeDynamic PI89577
if (verbose) {
System.out.println(i + " copying 4 bytes");
}
copy(4);
break;
case 5 : // Long
case 6 : // Double
if (verbose) {
System.out.println(i + " copying 8 bytes");
}
copy(8);
i++;
break;
case 1 : // Utf8
int len = readU2();
writeU2(len);
byte[] utf8 = readBytes(len);
String str = new String(utf8, "UTF-8");
if (verbose) {
System.out.println(i + " read class attr -- '" + str + "'");
}
if (str.equals(nameSDE)) {
sdeIndex = i;
}
writeBytes(utf8);
break;
default :
throw new IOException("unexpected tag: " + tag);
}
}
return sdeIndex;
}
void writeUtf8ForSDE() {
int len = nameSDE.length();
writeU1(1); // Utf8 tag
writeU2(len);
for (int i = 0; i < len; ++i) {
writeU1(nameSDE.charAt(i));
}
}
}
| epl-1.0 |
tht-krisztian/EMF-IncQuery-Examples | school/school.incquery/src-gen/school/util/SchoolsProcessor.java | 717 | package school.util;
import org.eclipse.incquery.runtime.api.IMatchProcessor;
import school.School;
import school.SchoolsMatch;
/**
* A match processor tailored for the school.schools pattern.
*
* Clients should derive an (anonymous) class that implements the abstract process().
*
*/
@SuppressWarnings("all")
public abstract class SchoolsProcessor implements IMatchProcessor<SchoolsMatch> {
/**
* Defines the action that is to be executed on each match.
* @param pSch the value of pattern parameter Sch in the currently processed match
*
*/
public abstract void process(final School pSch);
@Override
public void process(final SchoolsMatch match) {
process(match.getSch());
}
}
| epl-1.0 |
MikeJMajor/openhab2-addons-dlinksmarthome | bundles/org.openhab.binding.kodi/src/main/java/org/openhab/binding/kodi/internal/config/KodiConfig.java | 2320 | /**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.kodi.internal.config;
/**
* Thing configuration from openHAB.
*
* @author Christoph Weitkamp - Initial contribution
* @author Christoph Weitkamp - Improvements for playing audio notifications
*/
public class KodiConfig {
private String ipAddress;
private Integer port;
private Integer httpPort;
private String httpUser;
private String httpPassword;
private Integer refreshInterval;
private Integer notificationTimeout;
private Integer notificationVolume;
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public Integer getPort() {
return port;
}
public void setPort(Integer port) {
this.port = port;
}
public Integer getHttpPort() {
return httpPort;
}
public void setHttpPort(Integer httpPort) {
this.httpPort = httpPort;
}
public String getHttpUser() {
return httpUser;
}
public void setHttpUser(String httpUser) {
this.httpUser = httpUser;
}
public String getHttpPassword() {
return httpPassword;
}
public void setHttpPassword(String httpPassword) {
this.httpPassword = httpPassword;
}
public Integer getRefreshInterval() {
return refreshInterval;
}
public void setRefreshInterval(Integer refreshInterval) {
this.refreshInterval = refreshInterval;
}
public Integer getNotificationTimeout() {
return notificationTimeout;
}
public void setNotificationTimeout(Integer notificationTimeout) {
this.notificationTimeout = notificationTimeout;
}
public Integer getNotificationVolume() {
return notificationVolume;
}
public void setNotificationVolume(Integer notificationVolume) {
this.notificationVolume = notificationVolume;
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.cdi.internal/src/com/ibm/ws/cdi/internal/archive/liberty/RuntimeFactory.java | 5446 | /*******************************************************************************
* Copyright (c) 2015, 2016 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.cdi.internal.archive.liberty;
import java.io.File;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import org.osgi.framework.Bundle;
import org.osgi.framework.wiring.BundleWiring;
import com.ibm.ws.cdi.CDIException;
import com.ibm.ws.cdi.CDIServiceUtils;
import com.ibm.ws.cdi.internal.interfaces.Application;
import com.ibm.ws.cdi.internal.interfaces.ArchiveType;
import com.ibm.ws.cdi.internal.interfaces.CDIArchive;
import com.ibm.ws.cdi.internal.interfaces.ExtensionArchive;
import com.ibm.ws.container.service.app.deploy.ApplicationInfo;
import com.ibm.ws.container.service.app.deploy.ContainerInfo;
import com.ibm.wsspi.adaptable.module.Container;
import com.ibm.wsspi.artifact.ArtifactContainer;
import com.ibm.wsspi.kernel.service.utils.FileUtils;
/**
*
*/
public class RuntimeFactory {
private final CDILibertyRuntime services;
private final ConcurrentHashMap<ApplicationInfo, Application> applications = new ConcurrentHashMap<ApplicationInfo, Application>();
/**
* @param services
*/
public RuntimeFactory(CDILibertyRuntime services) {
this.services = services;
}
private Container getContainerForBundle(Bundle bundle) {
//for a bundle, we can use the bundles own private data storage as the cache..
File cacheDir = bundle.getDataFile("cache");
if (!FileUtils.ensureDirExists(cacheDir)) {
return null;
}
File cacheDirAdapt = bundle.getDataFile("cacheAdapt");
if (!FileUtils.ensureDirExists(cacheDirAdapt)) {
return null;
}
File cacheDirOverlay = bundle.getDataFile("cacheOverlay");
if (!FileUtils.ensureDirExists(cacheDirOverlay)) {
return null;
}
// Create an artifact API and adaptable Container implementation for the bundle
ArtifactContainer artifactContainer = getServices().getArtifactContainerFactory().getContainer(cacheDir, bundle);
Container container = getServices().getAdaptableModuleFactory().getContainer(cacheDirAdapt, cacheDirOverlay, artifactContainer);
return container;
}
/**
* @param appInfo
* @return
* @throws CDIException
*/
public Application newApplication(ApplicationInfo appInfo) throws CDIException {
Application application = this.applications.get(appInfo);
if (application == null) {
application = new ApplicationImpl(appInfo, this);
Application oldApplication = this.applications.putIfAbsent(appInfo, application);
if (oldApplication != null) {
application = oldApplication;
}
}
return application;
}
public Application removeApplication(ApplicationInfo appInfo) {
return this.applications.remove(appInfo);
}
public CDIArchive newArchive(ApplicationImpl application,
ContainerInfo containerInfo,
ArchiveType archiveType,
ClassLoader classLoader) {
CDIArchive archive = new CDIArchiveImpl(application, containerInfo, archiveType, classLoader, this);
return archive;
}
/**
* {@inheritDoc}
*
* @param extraExtensions
*
* @throws CDIException
*/
public ExtensionArchive getExtensionArchiveForBundle(Bundle bundle,
Set<String> extraClasses,
Set<String> extraAnnotations,
boolean applicationBDAsVisible,
boolean extClassesOnly, Set<String> extraExtensionClasses) throws CDIException {
ExtensionArchive extensionArchive = null;
Container container = getContainerForBundle(bundle);
//get hold of bundle classloader
BundleWiring bundleWiring = bundle.adapt(BundleWiring.class);
ClassLoader loader = bundleWiring.getClassLoader();
if (container != null) {
ExtensionContainerInfo containerInfo = new ExtensionContainerInfo(container, loader, CDIServiceUtils.getSymbolicNameWithoutMinorOrMicroVersionPart(bundle.getSymbolicName())
+ "_"
+ CDIServiceUtils.getOSGIVersionForBndName(bundle.getVersion()), extraClasses, extraAnnotations, applicationBDAsVisible, extClassesOnly);
extensionArchive = new ExtensionArchiveImpl(containerInfo, this, extraExtensionClasses);
}
return extensionArchive;
}
/**
* @return
*/
public CDILibertyRuntime getServices() {
return services;
}
}
| epl-1.0 |
paulianttila/openhab2 | bundles/org.openhab.binding.smartmeter/src/main/java/org/openhab/binding/smartmeter/internal/sml/SmlUnitConversion.java | 6951 | /**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.smartmeter.internal.sml;
import javax.measure.Quantity;
import javax.measure.Unit;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.openhab.core.library.unit.SIUnits;
import org.openhab.core.library.unit.Units;
import org.openmuc.jsml.EUnit;
/**
* Converts a {@link EUnit} to an {@link Unit}.
*
* @author Matthias Steigenberger - Initial contribution
*
*/
@NonNullByDefault
public class SmlUnitConversion {
@SuppressWarnings("unchecked")
public static @Nullable <Q extends Quantity<Q>> Unit<Q> getUnit(EUnit unit) {
Unit<?> javaUnit = null;
switch (unit) {
case AMPERE:
javaUnit = Units.AMPERE;
break;
case AMPERE_HOUR:
javaUnit = Units.AMPERE.divide(Units.HOUR);
break;
case AMPERE_PER_METRE:
javaUnit = Units.AMPERE.multiply(SIUnits.METRE);
break;
case AMPERE_SQUARED_HOURS:
javaUnit = Units.AMPERE.pow(2).multiply(Units.HOUR);
break;
case BAR:
javaUnit = SIUnits.PASCAL.multiply(100000);
break;
case COULOMB:
javaUnit = Units.COULOMB;
break;
case CUBIC_METRE:
case CUBIC_METRE_CORRECTED:
javaUnit = SIUnits.CUBIC_METRE;
break;
case CUBIC_METRE_PER_DAY:
case CUBIC_METRE_PER_DAY_CORRECTED:
javaUnit = SIUnits.CUBIC_METRE.divide(Units.DAY);
break;
case CUBIC_METRE_PER_HOUR:
case CUBIC_METRE_PER_HOUR_CORRECTED:
javaUnit = SIUnits.CUBIC_METRE.divide(Units.HOUR);
break;
case DAY:
javaUnit = Units.DAY;
break;
case DEGREE:
javaUnit = Units.DEGREE_ANGLE;
break;
case DEGREE_CELSIUS:
javaUnit = SIUnits.CELSIUS;
break;
case FARAD:
javaUnit = Units.FARAD;
break;
case HENRY:
javaUnit = Units.HENRY;
break;
case HERTZ:
javaUnit = Units.HERTZ;
break;
case HOUR:
javaUnit = Units.HOUR;
break;
case JOULE:
javaUnit = Units.JOULE;
break;
case JOULE_PER_HOUR:
javaUnit = Units.JOULE.divide(Units.HOUR);
break;
case KELVIN:
javaUnit = Units.KELVIN;
break;
case KILOGRAM:
javaUnit = SIUnits.KILOGRAM;
case KILOGRAM_PER_SECOND:
javaUnit = SIUnits.KILOGRAM.divide(Units.SECOND);
break;
case LITRE:
javaUnit = Units.LITRE;
break;
case MASS_DENSITY:
break;
case METER_CONSTANT_OR_PULSE_VALUE:
break;
case METRE:
javaUnit = SIUnits.METRE;
break;
case METRE_PER_SECOND:
javaUnit = Units.METRE_PER_SECOND;
break;
case MOLE_PERCENT:
javaUnit = Units.MOLE;
break;
case MONTH:
javaUnit = Units.YEAR.divide(12);
break;
case NEWTON:
javaUnit = Units.NEWTON;
case NEWTONMETER:
javaUnit = Units.NEWTON.multiply(SIUnits.METRE);
break;
case OHM:
javaUnit = Units.OHM;
break;
case OHM_METRE:
javaUnit = Units.OHM.multiply(SIUnits.METRE);
break;
case PASCAL:
javaUnit = SIUnits.PASCAL;
break;
case PASCAL_SECOND:
javaUnit = SIUnits.PASCAL.multiply(Units.SECOND);
break;
case PERCENTAGE:
javaUnit = Units.PERCENT;
break;
case SECOND:
javaUnit = Units.SECOND;
break;
case TESLA:
javaUnit = Units.TESLA;
break;
case VAR:
javaUnit = Units.WATT.alternate("Var");
break;
case VAR_HOUR:
javaUnit = Units.WATT.alternate("Var").multiply(Units.HOUR);
break;
case VOLT:
javaUnit = Units.VOLT;
break;
case VOLT_AMPERE:
javaUnit = Units.VOLT.multiply(Units.AMPERE);
break;
case VOLT_AMPERE_HOUR:
javaUnit = Units.VOLT.multiply(Units.AMPERE).multiply(Units.HOUR);
break;
case VOLT_PER_METRE:
javaUnit = Units.WATT.divide(SIUnits.METRE);
break;
case VOLT_SQUARED_HOURS:
javaUnit = Units.VOLT.pow(2).multiply(Units.HOUR);
break;
case WATT:
javaUnit = Units.WATT;
break;
case WATT_HOUR:
javaUnit = Units.WATT.multiply(Units.HOUR);
break;
case WEBER:
javaUnit = Units.WEBER;
break;
case WEEK:
javaUnit = Units.WEEK;
break;
case YEAR:
javaUnit = Units.YEAR;
break;
// not clearly defined yet:
case VOLT_SQUARED_HOUR_METER_CONSTANT_OR_PULSE_VALUE:
break;
case REACTIVE_ENERGY_METER_CONSTANT_OR_PULSE_VALUE:
break;
case ACTIVE_ENERGY_METER_CONSTANT_OR_PULSE_VALUE:
break;
case AMPERE_SQUARED_HOUR_METER_CONSTANT_OR_PULSE_VALUE:
break;
case APPARENT_ENERGY_METER_CONSTANT_OR_PULSE_VALUE:
break;
case ENERGY_PER_VOLUME:
break;
case CALORIFIC_VALUE:
break;
// no unit possible:
case MIN:
case OTHER_UNIT:
case RESERVED:
case COUNT:
case CURRENCY:
case EMPTY:
break;
default:
break;
}
return (Unit<Q>) javaUnit;
}
}
| epl-1.0 |
cbaerikebc/kapua | service/api/src/main/java/org/eclipse/kapua/KapuaIllegalStateException.java | 1033 | /*******************************************************************************
* Copyright (c) 2011, 2016 Eurotech and/or its affiliates 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:
* Eurotech - initial API and implementation
*
*******************************************************************************/
package org.eclipse.kapua;
/**
* KapuaIllegalStateException is thrown when the the user session is inconsistent.
*
* @since 1.0
*
*/
public class KapuaIllegalStateException extends KapuaRuntimeException
{
private static final long serialVersionUID = -912672615903975466L;
/**
* Constructor
*
* @param message
*/
public KapuaIllegalStateException(String message)
{
super(KapuaErrorCodes.ILLEGAL_STATE, null, message);
}
}
| epl-1.0 |
paulianttila/openhab2 | bundles/org.openhab.binding.enocean/src/main/java/org/openhab/binding/enocean/internal/eep/A5_10/A5_10_09.java | 675 | /**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.enocean.internal.eep.A5_10;
import org.openhab.binding.enocean.internal.messages.ERP1Message;
/**
*
* @author Daniel Weber - Initial contribution
*/
public class A5_10_09 extends A5_10 {
public A5_10_09(ERP1Message packet) {
super(packet);
}
}
| epl-1.0 |
eclipse/eavp | org.eclipse.eavp.viz.modeling/src/org/eclipse/eavp/viz/modeling/base/EntityMapEntry.java | 2669 | /*******************************************************************************
* Copyright (c) 2016 UT-Battelle, LLC.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Robert Smith
*******************************************************************************/
package org.eclipse.eavp.viz.modeling.base;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.eclipse.eavp.viz.modeling.properties.IMeshCategory;
/**
* A class which contains an array list of IControllers associated with an
* IMeshCategory. This class is meant to hold an IMesh's entities map in a
* piecewise manner, in a class with JAXB support so that the information in the
* HashMap can be persisted.
*
* @author Robert Smith
*
*/
@XmlRootElement(name = "EntityMapEntry")
@XmlAccessorType(XmlAccessType.FIELD)
public class EntityMapEntry {
/**
* The map category this entry represents.
*/
@XmlAnyElement
private IMeshCategory category;
/**
* The list of entities within the given category.
*/
@XmlAnyElement
private ArrayList<IController> values;
/**
* The nullary constructor.
*/
public EntityMapEntry() {
category = null;
values = null;
}
/**
* The default constructor.
*
* @param category
* The category for this entry.
* @param values
* The entities under that category in the map.
*/
public EntityMapEntry(IMeshCategory category,
ArrayList<IController> values) {
this.category = category;
this.values = values;
}
/**
* Getter method for the category.
*
* @return The entry's category
*/
public IMeshCategory getCategory() {
return category;
}
/**
* Getter method for the values.
*
* @return The entry's values.
*/
public ArrayList<IController> getValues() {
return values;
}
/**
* Setter method for the category.
*
* @param category
* The entry's new category
*/
public void setCategory(IMeshCategory category) {
this.category = category;
}
/**
* Setter method for the values.
*
* @param values
* The entry's new values.
*/
public void setValues(ArrayList<IController> values) {
this.values = values;
}
}
| epl-1.0 |
ghillairet/emfjson | src/main/java/org/emfjson/jackson/databind/deser/EcoreReferenceDeserializer.java | 1836 | /*
* Copyright (c) 2019 Guillaume Hillairet and others.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* https://www.eclipse.org/legal/epl-2.0, or the MIT License which is
* available at https://opensource.org/licenses/MIT.
*
* SPDX-License-Identifier: EPL-2.0 OR MIT
*
*/
package org.emfjson.jackson.databind.deser;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EReference;
import org.emfjson.jackson.annotations.EcoreReferenceInfo;
import org.emfjson.jackson.annotations.EcoreTypeInfo;
import org.emfjson.jackson.databind.EMFContext;
import java.io.IOException;
public class EcoreReferenceDeserializer extends JsonDeserializer<ReferenceEntry> {
private final EcoreReferenceInfo info;
private final EcoreTypeInfo typeInfo;
public EcoreReferenceDeserializer(EcoreReferenceInfo info, EcoreTypeInfo typeInfo) {
this.typeInfo = typeInfo;
this.info = info;
}
@Override
public ReferenceEntry deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException {
EObject parent = EMFContext.getParent(ctxt);
EReference reference = EMFContext.getReference(ctxt);
String id = null;
String type = null;
while (jp.nextToken() != JsonToken.END_OBJECT) {
final String field = jp.getCurrentName();
if (field.equalsIgnoreCase(info.getProperty())) {
id = jp.nextTextValue();
} else if (field.equalsIgnoreCase(typeInfo.getProperty())) {
type = jp.nextTextValue();
}
}
return id != null ? new ReferenceEntry.Base(parent, reference, id, type): null;
}
}
| epl-1.0 |
dvanherbergen/openhab2 | addons/binding/org.openhab.binding.zwave/src/main/java/org/openhab/binding/zwave/internal/protocol/commandclass/ZWaveTimeParametersCommandClass.java | 6800 | /**
* Copyright (c) 2014-2016 by the respective copyright holders.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.openhab.binding.zwave.internal.protocol.commandclass;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import org.openhab.binding.zwave.internal.protocol.SerialMessage;
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.ZWaveController;
import org.openhab.binding.zwave.internal.protocol.ZWaveEndpoint;
import org.openhab.binding.zwave.internal.protocol.ZWaveNode;
import org.openhab.binding.zwave.internal.protocol.ZWaveSerialMessageException;
import org.openhab.binding.zwave.internal.protocol.event.ZWaveCommandClassValueEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamOmitField;
/**
* Handles the time parameters command class.
*
* @author Jorg de Jong
* @author Chris Jackson
*/
@XStreamAlias("timeParametersCommandClass")
public class ZWaveTimeParametersCommandClass extends ZWaveCommandClass
implements ZWaveGetCommands, ZWaveCommandClassDynamicState {
@XStreamOmitField
private static final Logger logger = LoggerFactory.getLogger(ZWaveTimeParametersCommandClass.class);
private static final int TIME_SET = 1;
private static final int TIME_GET = 2;
private static final int TIME_REPORT = 3;
/**
* Creates a new instance of the ZWaveTimeParametersCommandClass class.
*
* @param node the node this command class belongs to
* @param controller the controller to use
* @param endpoint the endpoint this Command class belongs to
*/
public ZWaveTimeParametersCommandClass(ZWaveNode node, ZWaveController controller, ZWaveEndpoint endpoint) {
super(node, controller, endpoint);
}
/**
* {@inheritDoc}
*/
@Override
public CommandClass getCommandClass() {
return CommandClass.TIME_PARAMETERS;
}
/**
* Gets a SerialMessage with the TIME_GET command
*
* @return the serial message.
*/
@Override
public SerialMessage getValueMessage() {
logger.debug("NODE {}: Creating new message for command TIME_GET", getNode().getNodeId());
SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData,
SerialMessageType.Request, SerialMessageClass.ApplicationCommandHandler, SerialMessagePriority.Get);
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(getNode().getNodeId());
outputData.write(2);
outputData.write(getCommandClass().getKey());
outputData.write(TIME_GET);
result.setMessagePayload(outputData.toByteArray());
return result;
}
/**
* Gets a SerialMessage with the TIME_SET command
*
* @return the serial message.
*/
public SerialMessage getSetMessage(Date date) {
logger.debug("NODE {}: Creating new message for command TIME_SET", getNode().getNodeId());
Calendar cal = Calendar.getInstance();
cal.setTime(date);
SerialMessage result = new SerialMessage(getNode().getNodeId(), SerialMessageClass.SendData,
SerialMessageType.Request, SerialMessageClass.SendData, SerialMessagePriority.RealTime);
ByteArrayOutputStream outputData = new ByteArrayOutputStream();
outputData.write(getNode().getNodeId());
outputData.write(9);
outputData.write(getCommandClass().getKey());
outputData.write(TIME_SET);
outputData.write((cal.get(Calendar.YEAR) & 0xff00) >> 8);
outputData.write((cal.get(Calendar.YEAR) & 0xff));
outputData.write(cal.get(Calendar.MONTH) + 1);
outputData.write(cal.get(Calendar.DAY_OF_MONTH));
outputData.write(cal.get(Calendar.HOUR_OF_DAY));
outputData.write(cal.get(Calendar.MINUTE));
outputData.write(cal.get(Calendar.SECOND));
result.setMessagePayload(outputData.toByteArray());
return result;
}
/**
* {@inheritDoc}
*
* @throws ZWaveSerialMessageException
*/
@Override
public void handleApplicationCommandRequest(SerialMessage serialMessage, int offset, int endpoint)
throws ZWaveSerialMessageException {
logger.debug("NODE {}: Received TIME_PARAMETERS command V{}", getNode().getNodeId(), getVersion());
int command = serialMessage.getMessagePayloadByte(offset);
switch (command) {
case TIME_REPORT:
int year = (serialMessage.getMessagePayloadByte(offset + 1) << 8
| serialMessage.getMessagePayloadByte(offset + 2));
int month = serialMessage.getMessagePayloadByte(offset + 3);
int day = serialMessage.getMessagePayloadByte(offset + 4);
int hour = serialMessage.getMessagePayloadByte(offset + 5);
int minute = serialMessage.getMessagePayloadByte(offset + 6);
int second = serialMessage.getMessagePayloadByte(offset + 7);
Calendar cal = Calendar.getInstance();
cal.clear();
cal.set(year, month - 1, day, hour, minute, second);
logger.debug("NODE {}: Received time report: {}", getNode().getNodeId(), cal.getTime());
Date nodeTime = cal.getTime();
ZWaveCommandClassValueEvent zEvent = new ZWaveCommandClassValueEvent(getNode().getNodeId(), endpoint,
getCommandClass(), nodeTime);
getController().notifyEventListeners(zEvent);
break;
default:
logger.warn(String.format("NODE %d: Unsupported Command %d for command class %s (0x%02X).",
getNode().getNodeId(), command, getCommandClass().getLabel(), getCommandClass().getKey()));
break;
}
}
@Override
public Collection<SerialMessage> getDynamicValues(boolean refresh) {
ArrayList<SerialMessage> result = new ArrayList<SerialMessage>();
if (refresh == true && getEndpoint() == null) {
result.add(getValueMessage());
}
return result;
}
}
| epl-1.0 |
a434413631/huloomobile | huloomobile/src/com/poqop/document/PageTreeNode.java | 8894 | package com.poqop.document;
import android.graphics.*;
import java.lang.ref.SoftReference;
class PageTreeNode {
private static final int SLICE_SIZE = 65535;
private Bitmap bitmap;
private SoftReference<Bitmap> bitmapWeakReference;
private boolean decodingNow;
private final RectF pageSliceBounds;
private final Page page;
private PageTreeNode[] children;
private final int treeNodeDepthLevel;
private Matrix matrix = new Matrix();
private final Paint bitmapPaint = new Paint();
private DocumentView documentView;
private boolean invalidateFlag;
private Rect targetRect;
private RectF targetRectF;
PageTreeNode(DocumentView documentView, RectF localPageSliceBounds, Page page, int treeNodeDepthLevel, PageTreeNode parent) {
this.documentView = documentView;
this.pageSliceBounds = evaluatePageSliceBounds(localPageSliceBounds, parent);
this.page = page;
this.treeNodeDepthLevel = treeNodeDepthLevel;
}
public void updateVisibility() {
invalidateChildren();
if (children != null) {
for (PageTreeNode child : children) {
child.updateVisibility();
}
}
if (isVisible()) {
if (!thresholdHit()) {
if (getBitmap() != null && !invalidateFlag) {
restoreBitmapReference();
} else {
decodePageTreeNode();
}
}
}
if (!isVisibleAndNotHiddenByChildren()) {
stopDecodingThisNode();
setBitmap(null);
}
}
public void invalidate() {
invalidateChildren();
invalidateRecursive();
updateVisibility();
}
private void invalidateRecursive() {
invalidateFlag = true;
if (children != null) {
for (PageTreeNode child : children) {
child.invalidateRecursive();
}
}
stopDecodingThisNode();
}
void invalidateNodeBounds() {
targetRect = null;
targetRectF = null;
if (children != null) {
for (PageTreeNode child : children) {
child.invalidateNodeBounds();
}
}
}
void draw(Canvas canvas) {
if (getBitmap() != null) {
canvas.drawBitmap(getBitmap(), new Rect(0, 0, getBitmap().getWidth(), getBitmap().getHeight()), getTargetRect(), bitmapPaint);
}
if (children == null) {
return;
}
for (PageTreeNode child : children) {
child.draw(canvas);
}
}
private boolean isVisible() {
return RectF.intersects(documentView.getViewRect(), getTargetRectF());
}
private RectF getTargetRectF() {
if (targetRectF == null) {
targetRectF = new RectF(getTargetRect());
}
return targetRectF;
}
private void invalidateChildren() {
if (thresholdHit() && children == null && isVisible()) {
final int newThreshold = treeNodeDepthLevel * 2;
children = new PageTreeNode[]
{
new PageTreeNode(documentView, new RectF(0, 0, 1.0f, 1.0f), page, newThreshold, this),
new PageTreeNode(documentView, new RectF(0.5f, 0, 1.0f, 0.5f), page, newThreshold, this),
new PageTreeNode(documentView, new RectF(0, 0.5f, 0.5f, 1.0f), page, newThreshold, this),
new PageTreeNode(documentView, new RectF(0.5f, 0.5f, 1.0f, 1.0f), page, newThreshold, this)
};
}
if (!thresholdHit() && getBitmap() != null || !isVisible()) {
recycleChildren();
}
}
private boolean thresholdHit() {
float zoom = documentView.zoomModel.getZoom();
int mainWidth = documentView.getWidth();
float height = page.getPageHeight(mainWidth, zoom);
return (mainWidth * zoom * height) / (treeNodeDepthLevel * treeNodeDepthLevel) > SLICE_SIZE;
}
public Bitmap getBitmap() {
return bitmapWeakReference != null ? bitmapWeakReference.get() : null;
}
private void restoreBitmapReference() {
setBitmap(getBitmap());
}
private void decodePageTreeNode() {
if (isDecodingNow()) {
return;
}
setDecodingNow(true);
documentView.decodeService.decodePage(this, page.index, new DecodeService.DecodeCallback() {
public void decodeComplete(final Bitmap bitmap) {
documentView.post(new Runnable() {
public void run() {
setBitmap(bitmap);
invalidateFlag = false;
setDecodingNow(false);
page.setAspectRatio(documentView.decodeService.getPageWidth(page.index), documentView.decodeService.getPageHeight(page.index));
invalidateChildren();
}
});
}
}, documentView.zoomModel.getZoom(), pageSliceBounds);
}
private RectF evaluatePageSliceBounds(RectF localPageSliceBounds, PageTreeNode parent) {
if (parent == null) {
return localPageSliceBounds;
}
final Matrix matrix = new Matrix();
matrix.postScale(parent.pageSliceBounds.width(), parent.pageSliceBounds.height());
matrix.postTranslate(parent.pageSliceBounds.left, parent.pageSliceBounds.top);
final RectF sliceBounds = new RectF();
matrix.mapRect(sliceBounds, localPageSliceBounds);
return sliceBounds;
}
private void setBitmap(Bitmap bitmap) {
if (bitmap != null && bitmap.getWidth() == -1 && bitmap.getHeight() == -1) {
return;
}
if (this.bitmap != bitmap) {
if (bitmap != null) {
if (this.bitmap != null) {
this.bitmap.recycle();
}
bitmapWeakReference = new SoftReference<Bitmap>(bitmap);
documentView.postInvalidate();
}
this.bitmap = bitmap;
}
}
private boolean isDecodingNow() {
return decodingNow;
}
private void setDecodingNow(boolean decodingNow) {
if (this.decodingNow != decodingNow) {
this.decodingNow = decodingNow;
if (decodingNow) {
documentView.progressModel.increase();
} else {
documentView.progressModel.decrease();
}
}
}
private Rect getTargetRect() {
if (targetRect == null) {
matrix.reset();
matrix.postScale(page.bounds.width(), page.bounds.height());
matrix.postTranslate(page.bounds.left, page.bounds.top);
RectF targetRectF = new RectF();
matrix.mapRect(targetRectF, pageSliceBounds);
targetRect = new Rect((int) targetRectF.left, (int) targetRectF.top, (int) targetRectF.right, (int) targetRectF.bottom);
}
return targetRect;
}
private void stopDecodingThisNode() {
if (!isDecodingNow()) {
return;
}
documentView.decodeService.stopDecoding(this);
setDecodingNow(false);
}
private boolean isHiddenByChildren() {
if (children == null) {
return false;
}
for (PageTreeNode child : children) {
if (child.getBitmap() == null) {
return false;
}
}
return true;
}
private void recycleChildren() {
if (children == null) {
return;
}
for (PageTreeNode child : children) {
child.recycle();
}
if (!childrenContainBitmaps()) {
children = null;
}
}
private boolean containsBitmaps() {
return getBitmap() != null || childrenContainBitmaps();
}
private boolean childrenContainBitmaps() {
if (children == null) {
return false;
}
for (PageTreeNode child : children) {
if (child.containsBitmaps()) {
return true;
}
}
return false;
}
private void recycle() {
stopDecodingThisNode();
setBitmap(null);
if (children != null) {
for (PageTreeNode child : children) {
child.recycle();
}
}
}
private boolean isVisibleAndNotHiddenByChildren() {
return isVisible() && !isHiddenByChildren();
}
}
| epl-1.0 |
cwi-swat/pdb.values | src/org/eclipse/imp/pdb/facts/exceptions/UnexpectedResultTypeException.java | 452 | package org.eclipse.imp.pdb.facts.exceptions;
import org.eclipse.imp.pdb.facts.type.Type;
public class UnexpectedResultTypeException extends FactTypeUseException {
private static final long serialVersionUID = 1551922923060851569L;
private Type result;
public UnexpectedResultTypeException(Type result, Throwable cause) {
super("Unexpected result " + result, cause);
this.result = result;
}
public Type getResult() {
return result;
}
}
| epl-1.0 |
McGill-DP-Group/seg.jUCMNav | src/seg/jUCMNav/actions/concerns/ApplyConcernAction.java | 13158 | package seg.jUCMNav.actions.concerns;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.eclipse.gef.commands.Command;
import org.eclipse.gef.commands.CompoundCommand;
import org.eclipse.gef.commands.UnexecutableCommand;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import seg.jUCMNav.JUCMNavPlugin;
import seg.jUCMNav.Messages;
import seg.jUCMNav.actions.SelectionHelper;
import seg.jUCMNav.actions.URNSelectionAction;
import seg.jUCMNav.aourn.composer.AspectMarkerMappings;
import seg.jUCMNav.aourn.composer.UCMAspectComposer;
import seg.jUCMNav.aourn.composer.exceptions.CompositionNotRequired;
import seg.jUCMNav.aourn.composer.exceptions.MalformedAspectMap;
import seg.jUCMNav.aourn.matcher.Mapping;
import seg.jUCMNav.aourn.matcher.Match;
import seg.jUCMNav.aourn.matcher.MatchList;
import seg.jUCMNav.aourn.matcher.MatchableElementFactory;
import seg.jUCMNav.aourn.matcher.PointcutMatcher;
import seg.jUCMNav.aourn.matcher.exceptions.MatchingFailedException;
import seg.jUCMNav.model.commands.concerns.AddAspectStubsCommand;
import seg.jUCMNav.views.preferences.DisplayPreferences;
import ucm.map.InBinding;
import ucm.map.NodeConnection;
import ucm.map.OutBinding;
import ucm.map.PathNode;
import ucm.map.PluginBinding;
import ucm.map.PointcutKind;
import ucm.map.Stub;
import ucm.map.UCMmap;
import urn.URNspec;
import urncore.URNmodelElement;
/**
* Action related to applying a concern to the model
*
* @author gunterm
*
*/
public class ApplyConcernAction extends URNSelectionAction {
public static final String APPLYCONCERN = "seg.jUCMNav.actions.concerns.ApplyConcernAction"; //$NON-NLS-1$
// this is either an aspect map, a pointcut graph, or a concern
private URNmodelElement element;
private URNspec urn;
/**
* @param part
* the workbench part we are working with
*/
public ApplyConcernAction(IWorkbenchPart part) {
super(part);
setId(APPLYCONCERN);
// TODO create a new icon for Apply Concern
setImageDescriptor(JUCMNavPlugin.getImageDescriptor("icons/Concern16.gif")); //$NON-NLS-1$
}
/**
* Returns true if a map, a grl graph, or a concern is selected; false otherwise
*
* @see seg.jUCMNav.actions.URNSelectionAction#calculateEnabled()
*/
protected boolean calculateEnabled() {
if(!DisplayPreferences.getInstance().isAdvancedControlEnabled() || !DisplayPreferences.getInstance().isShowAspect())
return false;
SelectionHelper sel = new SelectionHelper(getSelectedObjects());
element = sel.getURNmodelElement();
switch (sel.getSelectionType()) {
case SelectionHelper.MAP:
// TODO GRL and concerns not yet supported
// case SelectionHelper.GRLGRAPH:
// case SelectionHelper.CONCERN:
urn = sel.getUrnspec();
return true;
default:
return false;
}
}
/**
* @return a {@link AddAspectStubsCommand}
*/
protected Command getCommand() {
boolean showInfoMessages = false;
// TODO only works for UCM right now
HashSet<UCMmap> pointcutMaps = getPointcutExpression(element);
UCMmap pointcutMap = null;
// TODO externalize strings
if (!pointcutMaps.isEmpty()) {
MatchableElementFactory.clearCache();
List<PathNode> joinpoints = MatchableElementFactory.createMatchableElements(urn, element, pointcutMaps);
List<MatchList> matchResultList = new ArrayList<MatchList>();
MatchList matchResult = new MatchList();
String capture = ""; //$NON-NLS-1$
int size = 0;
for (Iterator iterator = pointcutMaps.iterator(); iterator.hasNext();) {
pointcutMap = (UCMmap) iterator.next();
if (showInfoMessages)
MessageDialog.openConfirm(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Result", "Found pointcut expression: " + pointcutMap.getName() + " [" + pointcutMap.getId() + Messages.getString("ApplyConcernAction.CloseBracketJoinPoints") + joinpoints.size() + Messages.getString("ApplyConcernAction.SpacePathNodes")); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$
try {
matchResult = PointcutMatcher.match(pointcutMap, joinpoints);
matchResultList.add(matchResult);
if (matchResult.getMatchList().size() < 20)
capture = capture + capture(matchResult);
size = size + matchResult.getMatchList().size();
} catch (MatchingFailedException e) {
// add an empty list of matches, so that there is the same number of entries in the results array as there are pointcut maps
matchResultList.add(new MatchList());
}
}
if (showInfoMessages)
MessageDialog.openConfirm(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Result", "Found " + size + Messages.getString("ApplyConcernAction.SpaceMatches") + capture); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
else
MessageDialog.openConfirm(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Result", "Found " + size + "matches!"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
// go through all the pointcut maps and compose their match results
int i = 0;
UCMAspectComposer.resetCounter();
List<List<AspectMarkerMappings>> composeResultList = new ArrayList<List<AspectMarkerMappings>>();
boolean compositionSuccessful = false;
for (Iterator iterator = pointcutMaps.iterator(); iterator.hasNext();) {
pointcutMap = (UCMmap) iterator.next();
MatchList mResult = matchResultList.get(i++);
// if there are some matches, continue with the composition
if (mResult.getMatchList().size() > 0) {
List<AspectMarkerMappings> composeResult = new ArrayList<AspectMarkerMappings>();
capture = ""; //$NON-NLS-1$
try {
composeResult = UCMAspectComposer.compose((UCMmap) element, pointcutMap, mResult);
composeResultList.add(composeResult);
if (composeResult.size() < 20)
capture = capture + capture(composeResult);
compositionSuccessful = true;
} catch (MalformedAspectMap e) {
MessageDialog.openConfirm(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", "Malformed aspect map!"); //$NON-NLS-1$ //$NON-NLS-2$
} catch (CompositionNotRequired e) {
MessageDialog.openConfirm(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", "Nothing to compose!"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
}
if (compositionSuccessful) {
size = 0;
for (int j = 0; j < composeResultList.size(); j++) {
size = size + composeResultList.get(j).size();
}
if (showInfoMessages)
MessageDialog.openConfirm(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Result", "Aspect markers to apply: " + size + " " + capture); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
if (size < 250) {
// perform the commands to update the model - one for each aspect marker that is being added
CompoundCommand cmd = new AddAspectStubsCommand(urn, composeResultList);
// dispose of the the temporary matching and composition data
disposeMatchingCompositionInfo();
return cmd;
} else {
MessageDialog.openConfirm(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Info", "Too much work to add so many aspect markers!"); //$NON-NLS-1$ //$NON-NLS-2$
}
}
} else {
MessageDialog.openConfirm(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), "Error", "This map does not contain one or more pointcut stubs with the same pointcut maps and with in/out-bindings for all in/out-paths!"); //$NON-NLS-1$ //$NON-NLS-2$
}
return UnexecutableCommand.INSTANCE;
}
private HashSet<UCMmap> getPointcutExpression(URNmodelElement element) {
// TODO only works for UCM right now
if (element instanceof UCMmap) {
// find all pointcut stubs
List<Stub> pointcutStubs = new ArrayList<Stub>();
for (Iterator iter = ((UCMmap) element).getNodes().iterator(); iter.hasNext();) {
PathNode pathnode = (PathNode) iter.next();
if (pathnode instanceof Stub && !((Stub) pathnode).getAopointcut().equals(PointcutKind.NONE_LITERAL)) {
pointcutStubs.add((Stub) pathnode);
}
}
// check that all pointcuts stubs have the same number of plug-in maps and at least one plug-in map (i.e., pointcut map)
HashSet<UCMmap> pointcutMaps = new HashSet<UCMmap>();
int numberOfPlugins = -1;
for (int i = 0; i < pointcutStubs.size(); i++) {
Stub stub = pointcutStubs.get(i);
int size = stub.getBindings().size();
if (numberOfPlugins == -1)
numberOfPlugins = size;
else if (size != numberOfPlugins) {
numberOfPlugins = -1;
break;
}
for (Iterator iterator = stub.getBindings().iterator(); iterator.hasNext();) {
UCMmap pcMap = ((PluginBinding) iterator.next()).getPlugin();
pointcutMaps.add(pcMap);
}
}
// return empty set if the number of plug-in maps is not the same or is 0 (i.e., it was set to -1 in the previous for loop)
// also check that all plug-in maps are the same for each pointcut stub (i.e., the number of all plug-in maps is the same as numberOfPlugins)
if (numberOfPlugins == -1 || numberOfPlugins != pointcutMaps.size())
return new HashSet<UCMmap>();
// furthermore, all in/out-paths of the pointcut stubs need to have an in/outBinding for all its pointcut maps
for (int i = 0; i < pointcutStubs.size(); i++) {
Stub pcStub = pointcutStubs.get(i);
for (int j = 0; j < pcStub.getBindings().size(); j++) {
List<NodeConnection> ncList = new ArrayList<NodeConnection>();
ncList.addAll(pcStub.getPred());
ncList.addAll(pcStub.getSucc());
PluginBinding pl = (PluginBinding) pcStub.getBindings().get(j);
// look through all the in/outBindings and remove the corresponding in/out-path from the list of in/out-paths
for (int k = 0; k < pl.getIn().size(); k++) {
InBinding in = (InBinding) pl.getIn().get(k);
ncList.remove(in.getStubEntry());
}
for (int k = 0; k < pl.getOut().size(); k++) {
OutBinding out = (OutBinding) pl.getOut().get(k);
ncList.remove(out.getStubExit());
}
// the remaining list of in/out-paths has to be empty if all in/out-paths have bindings
if (!ncList.isEmpty()) {
// return empty set if some in/out-paths do not have bindings
return new HashSet<UCMmap>();
}
}
}
return pointcutMaps;
}
return new HashSet<UCMmap>();
}
private void disposeMatchingCompositionInfo() {
UCMAspectComposer.dispose();
PointcutMatcher.dispose();
}
private String capture(MatchList result) {
String capture = ""; //$NON-NLS-1$
if (result != null) {
for (Iterator iter = result.getMatchList().iterator(); iter.hasNext();) {
Match mappings = (Match) iter.next();
for (Iterator iterator = mappings.getMatch().iterator(); iterator.hasNext();) {
Mapping mapping = (Mapping) iterator.next();
if (mapping.getPointcutElement().getElement() == null)
capture += "null" + " --> " + mapping.getJoinpoint().getName() + "[" + mapping.getJoinpoint().getId() + "] "; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
else
capture += mapping.getPointcutElement().getName() + "[" + mapping.getPointcutElement().getId() + "] --> " + mapping.getJoinpoint().getName() + "[" + mapping.getJoinpoint().getId() + "] "; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$
}
capture += "----- "; //$NON-NLS-1$
}
}
else
capture += Messages.getString("ApplyConcernAction.NoMatch"); //$NON-NLS-1$
return capture;
}
private static String capture(List<AspectMarkerMappings> result) {
String capture = ""; //$NON-NLS-1$
for (int i = 0; i < result.size(); i++) {
PathNode joinpoint = (PathNode) result.get(i).getFirstMapping().get(0);
NodeConnection insertionPoint = (NodeConnection) result.get(i).getInsertionPoint();
capture += joinpoint.getName() + "[" + joinpoint.getId() + Messages.getString("ApplyConcernAction.CloseBracketInsertionPoint") + ((PathNode) insertionPoint.getSource()).getName() + "[" + ((PathNode) insertionPoint.getSource()).getId() + "]<-->" + ((PathNode) insertionPoint.getTarget()).getName() + "[" + ((PathNode) insertionPoint.getTarget()).getId() + "] ----- "; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$
}
return capture;
}
} | epl-1.0 |
zzzzgc/ZGC4Obj | subpackage/src/main/java/com/xinxing/subpackage/core/log/CallBackOrderLogNorm.java | 748 | package com.xinxing.subpackage.core.log;
import org.apache.log4j.Logger;
public class CallBackOrderLogNorm {
public static void requestLog(String orderId,String param,String who,Logger logger) {
logger.info("收到"+who+"回调查询:"+param+"");
}
public static void responseLog(String orderId,String param,String who,Logger log) {
log.info("反馈"+who+"回调查询:"+param+"");
}
public static void resultLog(String orderId, String status, String msg,String who,Logger log) {
log.info(""+who+"回调查询概要,ID:"+orderId+",status:"+status+",msg:"+msg);
}
public static void ExceptionLog(String param, String orderId,String who,Logger log) {
log.info(""+who+"回调查询异常:"+param+",ID:"+orderId);
}
}
| epl-1.0 |
epsilonlabs/epsilon-static-analysis | org.eclipse.epsilon.haetae.eol.type/src/org/eclipse/epsilon/eol/visitor/resolution/type/naive/impl/ReturnStatementTypeResolver.java | 2530 | package org.eclipse.epsilon.eol.visitor.resolution.type.naive.impl;
import org.eclipse.epsilon.eol.metamodel.EOLElement;
import org.eclipse.epsilon.eol.metamodel.OperationDefinition;
import org.eclipse.epsilon.eol.metamodel.ReturnStatement;
import org.eclipse.epsilon.eol.metamodel.TransactionStatement;
import org.eclipse.epsilon.eol.metamodel.Type;
import org.eclipse.epsilon.eol.metamodel.visitor.EolVisitorController;
import org.eclipse.epsilon.eol.metamodel.visitor.ReturnStatementVisitor;
import org.eclipse.epsilon.eol.problem.LogBook;
import org.eclipse.epsilon.eol.problem.imessages.IMessage_TypeResolution;
import org.eclipse.epsilon.eol.visitor.resolution.type.naive.context.TypeResolutionContext;
import org.eclipse.epsilon.eol.visitor.resolution.type.naive.util.TypeUtil;
public class ReturnStatementTypeResolver extends ReturnStatementVisitor<TypeResolutionContext, Object>{
@Override
public Object visit(ReturnStatement returnStatement,
TypeResolutionContext context,
EolVisitorController<TypeResolutionContext, Object> controller) {
controller.visit(returnStatement.getExpression(), context);
EOLElement rawContainer = returnStatement.getContainer(); //get the container
while((!(rawContainer instanceof OperationDefinition) && !(rawContainer instanceof TransactionStatement))&& rawContainer != null) //get all the way to OperationDefinition
{
rawContainer = rawContainer.getContainer();
}
if (rawContainer == null) {
LogBook.getInstance().addError(returnStatement, IMessage_TypeResolution.RETURN_STATEMENT_NOT_IN_OP);
}
else {
OperationDefinition container = (OperationDefinition) rawContainer; //cast
Type returnType = container.getReturnType(); //get return type of the operation
if (returnType == null) {
}
else {
Type returnedType = returnStatement.getExpression().getResolvedType();
if (returnedType == null) {
LogBook.getInstance().addError(returnStatement.getExpression(), IMessage_TypeResolution.EXPRESSION_DOES_NOT_HAVE_A_TYPE);
}
else {
OperationDefinition op = (OperationDefinition) rawContainer;
// if (TypeUtil.getInstance().isInstanceofAnyType(op.getReturnType())) {
// op.setReturnType(EcoreUtil.copy(returnedType));
// }
// else {
if (!TypeUtil.getInstance().isTypeEqualOrGeneric(returnedType, op.getReturnType())) {
LogBook.getInstance().addError(returnStatement.getExpression(), IMessage_TypeResolution.TYPE_MISMATCH);
}
// }
}
}
}
return null;
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/io.openliberty.ws.jaxrs.global.handler.internal_fat/test-applications/rs20ApplicationWithClient/src/com/ibm/samples/jaxrs/HelloRest20ClientServlet.java | 1856 | /*******************************************************************************
* Copyright (c) 2021 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.samples.jaxrs;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Response;
@WebServlet("/HelloRest20ClientServlet")
public class HelloRest20ClientServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter pw = resp.getWriter();
String port = req.getParameter("port");
if (port == null) {
pw.write("Can not get port");
return;
}
StringBuilder sb = new StringBuilder("http://localhost:").append(port).append("/rs20ApplicationWithClient/hello");
ClientBuilder cb = ClientBuilder.newBuilder();
Client c = cb.build();
WebTarget t = c.target(sb.toString());
Response response = t.request().get();
String result = response.readEntity(String.class);
pw.write(result);
}
}
| epl-1.0 |
TypeFox/che | assembly-multiuser/assembly-wsmaster-war/src/main/java/org/eclipse/che/api/deploy/MultiUserCheWsMasterModule.java | 4154 | /*
* 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.api.deploy;
import com.google.inject.AbstractModule;
import com.google.inject.name.Names;
import javax.sql.DataSource;
import org.eclipse.che.api.user.server.jpa.JpaPreferenceDao;
import org.eclipse.che.api.user.server.jpa.JpaUserDao;
import org.eclipse.che.api.user.server.spi.PreferenceDao;
import org.eclipse.che.api.user.server.spi.UserDao;
import org.eclipse.che.inject.DynaModule;
import org.eclipse.che.mail.template.ST.STTemplateProcessorImpl;
import org.eclipse.che.mail.template.TemplateProcessor;
import org.eclipse.che.multiuser.api.permission.server.AdminPermissionInitializer;
import org.eclipse.che.multiuser.api.permission.server.PermissionChecker;
import org.eclipse.che.multiuser.api.permission.server.PermissionCheckerImpl;
import org.eclipse.che.multiuser.keycloak.server.deploy.KeycloakModule;
import org.eclipse.che.multiuser.organization.api.OrganizationApiModule;
import org.eclipse.che.multiuser.organization.api.OrganizationJpaModule;
import org.eclipse.che.multiuser.resource.api.ResourceModule;
import org.eclipse.che.security.PBKDF2PasswordEncryptor;
import org.eclipse.che.security.PasswordEncryptor;
@DynaModule
public class MultiUserCheWsMasterModule extends AbstractModule {
@Override
protected void configure() {
bind(TemplateProcessor.class).to(STTemplateProcessorImpl.class);
bind(DataSource.class).toProvider(org.eclipse.che.core.db.JndiDataSourceProvider.class);
install(new org.eclipse.che.multiuser.api.permission.server.jpa.SystemPermissionsJpaModule());
install(new org.eclipse.che.multiuser.api.permission.server.PermissionsModule());
install(
new org.eclipse.che.multiuser.permission.workspace.server.WorkspaceApiPermissionsModule());
install(
new org.eclipse.che.multiuser.permission.workspace.server.jpa
.MultiuserWorkspaceJpaModule());
//Permission filters
bind(org.eclipse.che.multiuser.permission.system.SystemServicePermissionsFilter.class);
bind(org.eclipse.che.multiuser.permission.user.UserProfileServicePermissionsFilter.class);
bind(org.eclipse.che.multiuser.permission.user.UserServicePermissionsFilter.class);
bind(org.eclipse.che.multiuser.permission.factory.FactoryPermissionsFilter.class);
bind(org.eclipse.che.plugin.activity.ActivityPermissionsFilter.class);
bind(AdminPermissionInitializer.class).asEagerSingleton();
bind(
org.eclipse.che.multiuser.permission.resource.filters.ResourceUsageServicePermissionsFilter
.class);
bind(
org.eclipse.che.multiuser.permission.resource.filters
.FreeResourcesLimitServicePermissionsFilter.class);
install(new ResourceModule());
install(new OrganizationApiModule());
install(new OrganizationJpaModule());
install(new KeycloakModule());
//User and profile - use profile from keycloak and other stuff is JPA
bind(PasswordEncryptor.class).to(PBKDF2PasswordEncryptor.class);
bind(UserDao.class).to(JpaUserDao.class);
bind(PreferenceDao.class).to(JpaPreferenceDao.class);
bind(PermissionChecker.class).to(PermissionCheckerImpl.class);
bindConstant()
.annotatedWith(Names.named("machine.terminal_agent.run_command"))
.to(
"$HOME/che/terminal/che-websocket-terminal "
+ "-addr :4411 "
+ "-cmd ${SHELL_INTERPRETER} "
+ "-enable-auth "
+ "-enable-activity-tracking");
bindConstant()
.annotatedWith(Names.named("machine.exec_agent.run_command"))
.to(
"$HOME/che/exec-agent/che-exec-agent "
+ "-addr :4412 "
+ "-cmd ${SHELL_INTERPRETER} "
+ "-enable-auth "
+ "-logs-dir $HOME/che/exec-agent/logs");
}
}
| epl-1.0 |
kgibm/open-liberty | dev/com.ibm.ws.messaging.common/src/com/ibm/ws/sib/comms/CommsConstants.java | 67708 | /*******************************************************************************
* Copyright (c) 2012, 2021 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.sib.comms;
import com.ibm.ws.sib.utils.RuntimeInfo;
/**
* This class just contains component-wide constants.
* It does not include any constants used by other components.
*/
public class CommsConstants
{
public final static String MSG_GROUP_FAP_FLOW = com.ibm.ws.sib.utils.TraceGroups.TRGRP_COMMS_FAP_FLOW;
public final static String MSG_GROUP = com.ibm.ws.sib.utils.TraceGroups.TRGRP_COMMS;
public final static String MSG_BUNDLE = "com.ibm.ws.sib.comms.CWSICMessages"; // f195445.8 // D217339
protected final static String JS_COMMS_CLIENT_CONNECTION_FACTORY_CLASS =
"com.ibm.ws.sib.comms.client.ClientConnectionFactoryImpl"; // D219803
//F172397
protected final static String JS_COMMS_ME_CONNECTION_FACTORY_CLASS =
"com.ibm.ws.sib.comms.server.mesupport.MEConnectionFactoryImpl"; // D219803
//f183052.2
public final static String JS_COMMS_MQ_LINK_MANAGER_CLASS =
"com.ibm.ws.sib.comms.mq.link.MQLinkManagerImpl";
public final static String JS_COMMS_MQ_UTILITIES_CLASS =
"com.ibm.ws.sib.comms.mq.util.MQUtilitiesImpl";
public final static String SERVER_DIAG_MODULE_CLASS =
"com.ibm.ws.sib.comms.client.ServerCommsDiagnosticModule";
// **** Runtime configuration constants ****//
// These constants are configuration properties that can be altered at runtime. These properties
// are designed to be tweaked if needed, but should not need to be.
// Start D235891
private final static String SIBPF = RuntimeInfo.SIB_PROPERTY_PREFIX +
"comms" +
RuntimeInfo.SIB_PROPERTY_SEPARATOR;
private static final String CLIENTPF = RuntimeInfo.SIB_PROPERTY_PREFIX +
"client" +
RuntimeInfo.SIB_PROPERTY_SEPARATOR;
public final static String ASYNC_THREADPOOL_CONF_KEY = SIBPF + "AsyncThreadPoolSize"; // f192215
public final static String ASYNC_THREADPOOL_SIZE = "10"; // f192215
public final static String INLINE_ASYNC_CBACKS_KEY = SIBPF + "InlineAsyncCBacks"; // f192654
public final static String INLINE_ASYNC_CBACKS = Boolean.toString(true); // D271523
public final static String EXCHANGE_TX_SEND_KEY = SIBPF + "ForceTransactedSendExchange"; // f192829
public final static String EXCHANGE_TX_SEND = "false"; // f192829
public final static String EXCHANGE_EXPRESS_END_KEY = SIBPF + "ForceExpressSendExchange"; // f192829
public final static String EXCHANGE_EXPRESS_SEND = "false"; // f192829
public final static String FLUSH_RH_RECV_WAIT_KEY = SIBPF + "ForceRHRecvWithWaitFlush"; // f192829
public final static String FLUSH_RH_RECV_WAIT = "false"; // f192829
// When set to true - "optimized" transactions (i.e. don't send a start transaction flow and
// don't start or end global transaction branches) will be disabled.
public final static String DISABLE_OPTIMIZED_TX_KEY = SIBPF + "DisableOptimizedTransactions";
public final static String DISABLE_OPTIMIZED_TX = "false";
// These can be used to allow the sib.properties file to override the default heartbeat settings
// that the client will negotiate with the server.
// Note that heartbeats are negotiated upwards (to whoever has the highest value) so if you
// want to set them to very low values you will need to ensure they are also set to low values
// on the server
public final static String HEARTBEAT_INTERVAL_KEY = SIBPF + "HeartbeatInterval";
public final static String HEARTBEAT_TIMEOUT_KEY = SIBPF + "HeartbeatTimeout";
// Start D214620
// These parameters are needed to tune the read ahead algorithm. More information is
// available in the ReadAheadQueue javadoc or on the JetStream Teamroom
public final static String RA_HIGH_QUEUE_BYTES_KEY = SIBPF + "RAHighQueueBytes"; // f192759.2
public final static String RA_HIGH_QUEUE_BYTES = "102400"; // f192759.2
public final static String RA_LOW_QUEUE_BYTES_FACTOR_KEY = SIBPF + "RALowQueueBytesFactor";
public final static String RA_LOW_QUEUE_BYTES_FACTOR = "0.5";
public final static String RA_HIGH_QUEUE_THRESH_KEY = SIBPF + "RAHighQueueBytesThreshold";
public final static String RA_HIGH_QUEUE_THRESH = "0";
public final static String RA_HIGH_QUEUE_BYTES_MAX_KEY = SIBPF + "RAHighQueueBytesMax";
public final static String RA_HIGH_QUEUE_BYTES_MAX = "10240000";
public final static String RA_HIGH_QUEUE_BYTES_TO_KEY = SIBPF + "RAHighQueueBytesTimeOut";
public final static String RA_HIGH_QUEUE_BYTES_TO = "2000";
// End D214620
// These SIB properties allow the modification of the capabilities that we inform our peer
// about during our initial handshake phase.
public static final String CAPABILITIY_REQUIRES_NONJAVA_BOOTSTRAP_KEY = CLIENTPF + "NonJavaBootstrap";
public static final String CAPABILITIY_REQUIRES_NONJAVA_BOOTSTRAP_DEF = Boolean.toString(false);
public static final String CAPABILITIY_REQUIRES_JMS_MESSAGES_KEY = CLIENTPF + "JMFOnly";
public static final String CAPABILITIY_REQUIRES_JMS_MESSAGES_DEF = Boolean.toString(false);
public static final String CAPABILITIY_REQUIRES_JMF_ENCODING_KEY = CLIENTPF + "JMSOnly";
public static final String CAPABILITIY_REQUIRES_JMF_ENCODING_DEF = Boolean.toString(false);
// These can be used to allow the sib.properties file to override the FAP version we support.
// Different values can be specified for both the client and the server.
public final static String SERVER_FAP_LEVEL_KEY = SIBPF + "ServerFapLevel";
public final static String CLIENT_FAP_LEVEL_KEY = SIBPF + "ClientFapLevel";
// Strict ordering of message redelivery (for JMS spec compliance in Session.recover)
public final static String STRICT_REDELIVERY_KEY = SIBPF + "StrictRedeliveryOrdering";
public final static String STRICT_REDELIVERY_DEFAULT = "false";
public static final int SEG_REQUEST_SCHEMA = 0x6E; // F247845
// Start D217374
/**
* The FAP Version of this client - please consider incrementing this in steps of
* more than one. See description of SUPPORTED_FAP_VERSIONS for justification
* Note that the supported fap versions table needs to be updated too...
*/
// Venu Liberty COMMS
// directly assigning value .. to separate JFapChannelConstants
//updated version for shared non durable
public static final short CURRENT_FAP_VERSION = 20;
/**
* FAP versions supported. It may appear a little odd that we have both a current fap version
* and a set of supported versions. This came about because of a problem that occured during
* version 6.1 development where a 6.0.1 APAR fix could have required a change to the FAP.
* Fortunately an alternative solution was found - however, this could have been a real problem.
* This is because the 6.0.1 FAP level was 1 - and the APAR fix would have needed to bump the
* FAP level up to 2. However 6.0.2 had already been shipped with a FAP level of 2 - so there
* would be no way to determine if a FAP level of 2 meant support for 6.0.2 features or
* support for the 6.0.1 APAR fix.
* <p>
* As of FAP version 3 (which ironically was a version reserved for service...) the party
* wishing to establish a connection must send all the FAP versions it supports as part of
* the handshake (this takes the form of a big-endian bitmap). The receipient will then
* select the highest
*/
private static final boolean SUPPORTED_FAP_VERSIONS[] =
{
true, // 1: supported (WAS 6.0)
true, // 2: supported (WAS 6.0.2)
true, // 3: supported (WAS 6.0.2.11)
false, // 4: not supported (reserved for future 602 service)
true, // 5: supported (WAS 6.1)
true, // 6: supported (WAS 6.1.0.2)
true, // 7: supported (WAS 6.1.0.23, PK73713)
false, // 8: not supported (reserved for future 61 service)
true, // 9: supported (WAS 7.0)
true, //10: supported (WAS 7.0.0.3)
false, //11: not supported (reserved for future 7* service)
false, //12: not supported (reserved for future 7* service)
true, //13: supported (WAS 8)
true, //14: supported (WAS 8.0.0.2)
true, //15: supported (WAS 8.0.0.4)
false, //16: not supported (reserved for future 8* service)
false,//17: not supported (reserved for future 8.5.5* service)
false,//18: not supported (reserved for future 8.5.5* service)
false, //19: not supported (reserved for future 8.5.5* service)
true //20: supported (WAS 9)
};
public static final boolean isFapLevelSupported(int level)
{
boolean result = false;
if ((level > 0) && (level <= SUPPORTED_FAP_VERSIONS.length))
result = SUPPORTED_FAP_VERSIONS[level - 1];
return result;
}
// The first bit that comes in the handshake flow to indicate what we are
public static final byte HANDSHAKE_CLIENT = 0x01;
public static final byte HANDSHAKE_ME = 0x02;
// Handshake paramters
public static final short FIELDID_PRODUCT_VERSION = 0x0001;
public static final short FIELDID_FAP_LEVEL = 0x0002;
public static final short FIELDID_MAX_MESSAGE_SIZE = 0x0003;
public static final short FIELDID_MAX_TRANSMISSION_SIZE = 0x0004;
public static final short FIELDID_HEARTBEAT_INTERVAL = 0x0005;
public static final short FIELDID_SOURCE_ME_NAME = 0x0006; // Not used
public static final short FIELDID_CAPABILITIES = 0x0007;
public static final short FIELDID_CONNECTION_OBJECT_ID = 0x0008; // Not used
public static final short FIELDID_USERID = 0x0009; // Not used
public static final short FIELDID_PASSWORD = 0x000A; // Not used
public static final short FIELDID_PRODUCT_ID = 0x000B;
public static final short FIELDID_SUPORTED_FAPS = 0x000C;
public static final short FIELDID_HEARTBEAT_TIMEOUT = 0x000D;
/**
* Used to indicate how the conversation which performs the
* handshake is to be used.
*/
public static final short FIELDID_CONVERSATION_USAGE_TYPE = 0x000E;
public static final short FIELDID_CELL_NAME = 0x000F;
public static final short FIELDID_NODE_NAME = 0x0010;
public static final short FIELDID_SERVER_NAME = 0x0011;
public static final short FIELDID_CLUSTER_NAME = 0x0012;
// begin F247975
/** Bit mask for reserved capability bits */
public static final short CAPABILITIY_RESERVED_MASK = (short) 0xFF80;
/** Capability bit - supports transactions */
public static final short CAPABILITIY_SUPPORTS_TRANSACTIONS = (short) 0x0001;
/** Capability bit - supports reliable messages */
public static final short CAPABILITIY_SUPPORTS_RELIABLE_MSGS = (short) 0x0002;
/** Capability bit - supports assured messages */
public static final short CAPABILITIY_SUPPORTS_ASSURED_MSG = (short) 0x0004;
/**
* Capability bit - requires non-Java bootstrap. When this capabilities bit is set, the
* client requires that no Java specific functionality (for example Java serialisation)
* is used during the bootstrap process.
*/
public static final short CAPABILITIY_REQUIRES_NONJAVA_BOOTSTRAP = (short) 0x0008;
/**
* Capability bit - requires JMS formatted messages. When this is set we must assume
* that our peer cannot process messages that are not JMS messages. Thus we may need
* to take the appropriate action to convert / not deliver non-JMS messages
*/
public static final short CAPABILITIY_REQUIRES_JMS_MESSAGES = (short) 0x0010;
/**
* Capability bit - requires JMF encoded messages. When this bit is set we must assume
* that our peer cannot process messages that are not encoded using JMF encoding. Thus
* we may need to re-encode any messages transfered.
*/
public static final short CAPABILITIY_REQUIRES_JMF_ENCODING = (short) 0x0020;
// end F247975
/**
* Capability bit - requires optimized transactions. When this bit is set we must
* assume that out peer will encode the start of a transaction with the first unit
* of work, and in the case of XA transactions not send start and end flows.
* This changes the format of any transmission that carries transactional data.
*/
public static final short CAPABILITIY_REQUIRES_OPTIMIZED_TX = (short) 0x0040;
/**
* The value that we would describe as 'default' capabilities for this client.
*/
public static final short CAPABILITIES_DEFAULT =
CommsConstants.CAPABILITIY_SUPPORTS_TRANSACTIONS | // Supports transactions (always the case)
CommsConstants.CAPABILITIY_SUPPORTS_RELIABLE_MSGS | // Supports reliable messages (always the case)
CommsConstants.CAPABILITIY_SUPPORTS_ASSURED_MSG | // Supports assured messages (always the case)
CommsConstants.CAPABILITIY_REQUIRES_OPTIMIZED_TX; // Requires optimized transactions (FAP 4 and up)
/**
* Not currently used - used on handshake to indicate the maximum message size that can be
* accepted.
*/
public static final long MAX_MESSAGE_SIZE = 10000;
/**
* Not currently used - used on handshake to indicate the maximum transmission size that can be
* used.
*/
public static final int MAX_TRANSMISSION_SIZE = 10000;
// Product ID's flowed in the handshake
public static final short PRODUCT_ID_JETSTREAM = 0x0001;
public static final short PRODUCT_ID_XMS = 0x0002;
public static final short PRODUCT_ID_DOTNET = 0x0003;
// Event ID's that are asynchronously sent to us by the server code
public static final short EVENTID_CONNECTION_QUIESCING = 0x0001;
public static final short EVENTID_ME_QUIESCING = 0x0002;
public static final short EVENTID_ME_TERMINATED = 0x0003;
public static final short EVENTID_ASYNC_EXCEPTION = 0x0004;
// Browser flags used when creating a browser SIB0113.comms.1
// NOTE: When you add a flag - don't forget to update the BF_MAX_VALID
// value to ensure we are always checking for legals values
public static final short BF_ALLOW_GATHERING = 0x0001;
public static final short BF_MAX_VALID = 0x0001;
// Consumer flags used when creating a consumer
// NOTE: When you add a flag - don't forget to update the CF_MAX_VALID
// value to ensure we are always checking for legals values
public static final short CF_READAHEAD = 0x0001;
public static final short CF_NO_LOCAL = 0x0002;
public static final short CF_MULTI_CONSUMER = 0x0004;
public static final short CF_UNICAST = 0x0008;
public static final short CF_MULTICAST = 0x0010;
public static final short CF_RELIABLE_MULTICAST = 0x0020;
public static final short CF_BIFURCATABLE = 0x0040; // F219476.2
public static final short CF_IGNORE_INITIAL_INDOUBTS = 0x0080; // D351339.comms
public static final short CF_ALLOW_GATHERING = 0x0100; //SIB0113.comms.1
public static final short CF_MAX_VALID = 0x01FF; //D237047,SIB0113.comms.1
// Producer flags used when creating a browser SIB0113.comms.1
// NOTE: When you add a flag - don't forget to update the PF_MAX_VALID
// value to ensure we are always checking for legals values
public static final short PF_BIND_TO_QUEUE_POINT = 0x0001;
public static final short PF_PREFER_LOCAL_QUEUE_POINT = 0x0002;
public static final short PF_MAX_VALID = 0x0003;
public static final byte DESTADDR_ISFROMMEDIATION = 1; // D255694
// Exception constants
public static final short SI_NO_EXCEPTION = 0x0000;
public static final short SI_EXCEPTION = 0x0001;
public static final short SI_INCORRECT_CALL_EXCEPTION = 0x0002;
public static final short SI_INVALID_DESTINATION_PREFIX_EXCEPTION = 0x0003;
public static final short SI_DISCRIMINATOR_SYNTAX_EXCEPTION = 0x0004;
public static final short SI_SELECTOR_SYNTAX_EXCEPTION = 0x0005;
public static final short SI_INSUFFICIENT_DATA_FOR_FACT_EXCEPTION = 0x0006;
public static final short SI_AUTHENTICATION_EXCEPTION = 0x0007;
public static final short SI_NOT_POSSIBLE_IN_CUR_CONFIG_EXCEPTION = 0x0008;
public static final short SI_NOT_AUTHORISED_EXCEPTION = 0x0009;
public static final short SI_SESSION_UNAVAILABLE_EXCEPTION = 0x000A;
public static final short SI_SESSION_DROPPED_EXCEPTION = 0x000B;
public static final short SI_DURSUB_ALREADY_EXISTS_EXCEPTION = 0x000C;
public static final short SI_DURSUB_MISMATCH_EXCEPTION = 0x000D;
public static final short SI_DURSUB_NOT_FOUND_EXCEPTION = 0x000E;
public static final short SI_CONNECTION_UNAVAILABLE_EXCEPTION = 0x000F;
public static final short SI_CONNECTION_DROPPED_EXCEPTION = 0x0010;
public static final short SI_DATAGRAPH_FORMAT_MISMATCH_EXCEPTION = 0x0011;
public static final short SI_DATAGRAPH_SCHEMA_NOT_FOUND_EXCEPTION = 0x0012;
public static final short SI_DESTINATION_LOCKED_EXCEPTION = 0x0013;
public static final short SI_TEMPORARY_DEST_NOT_FOUND_EXCEPTION = 0x0014;
public static final short SI_MESSAGE_EXCEPTION = 0x0015;
public static final short SI_RESOURCE_EXCEPTION = 0x0016;
public static final short SI_LIMIT_EXCEEDED_EXCEPTION = 0x0017;
public static final short SI_CONNECTION_LOST_EXCEPTION = 0x0018;
public static final short SI_ROLLBACK_EXCEPTION = 0x0019;
public static final short SI_NOT_SUPPORTED_EXCEPTION = 0x001A;
public static final short SI_MSG_DOMAIN_NOT_SUPPORTED_EXCEPTION = 0x001B;
public static final short SI_DATAGRAPH_EXCEPTION = 0x001C;
public static final short SI_ERROR_EXCEPTION = 0x001D;
public static final short SI_COMMAND_INVOCATION_FAILED_EXCEPTION = 0x001E; // SIB0009.comms.1
public static final short SI_MESSAGE_NOT_LOCKED_EXCEPTION = 0x001F;
public static final short EXCEPTION_INTERNAL_ERROR = 0x0100;
public static final short EXCEPTION_XAEXCEPTION = 0x0101;
public static final short DATAID_EXCEPTION_PROBEID = 0x0001;
public static final short DATAID_EXCEPTION_MESSAGE = 0x0002;
public static final short DATAID_EXCEPTION_REASON = 0x0003;
/** This is flown across the wire when there is no transaction present */
public static final int NO_TRANSACTION = 0;
/** This is flown across the wire when there is no order context present */
public static final short NO_ORDER_CONTEXT = 0;
/** This is flown across the wire when there is no destination type */
public static final short NO_DEST_TYPE = -1;
// End D217372
public static final short NO_DEST_AVAIL = -1; //SIB0137.comms.2
////////////////////////////////////////////////////////////////////////
//// Bits used in the flags field of an optimized transaction flow
// Transacted bit - when this bit is set the operation is transacted.
// If this bit is clear then the client specified a null transaction.
public static final int OPTIMIZED_TX_FLAGS_TRANSACTED_BIT = 0x00000001;
// Local transaction - the optimized transaction is a local (uncoordinated)
// transaction when this bit it set. When this bit is cleared the
// transaction is a global (XA) transaction.
public static final int OPTIMIZED_TX_FLAGS_LOCAL_BIT = 0x00000002;
// Create transaction - when set a new transaction should be created
// before performing the operation. When cleared - the operation is
// being performed in the scope of an existing transaction.
public static final int OPTIMIZED_TX_FLAGS_CREATE_BIT = 0x00000004;
// End previous transaction - when set the current XA transaction should
// be ended before performing the operation.
public static final int OPTIMIZED_TX_END_PREVIOUS_BIT = 0x00000008;
// Local transaction allows subordinates flag - when set the creation
// of a local transaction will supply the "allow subordinates" flag.
public static final int OPTIMIZED_TX_FLAGS_SUBORDINATES_ALLOWED = 0x00000010;
////////////////////////////////////////////////////////////////////////
/** This constant is used in ME-ME messages to denote a normal JsMessage */
public static final byte MEME_JSMESSAGE = (byte) 0x00;
/** This constant is used in ME-ME messages to denote a ControlMessage */
public static final byte MEME_CONTROLMESSAGE = (byte) 0x01;
// These constants are used by the async consumer
public static final short ASYNC_START_OR_MID_BATCH = 0x0000;
public static final short ASYNC_LAST_IN_BATCH = 0x0001;
// These flags are used when sending messages in chunks
public static final byte CHUNKED_MESSAGE_FIRST = (byte) 0x01;
public static final byte CHUNKED_MESSAGE_MIDDLE = (byte) 0x02;
public static final byte CHUNKED_MESSAGE_LAST = (byte) 0x04;
/** The minimum size of a message that is sent in chunks (1Mb) */
public static final int MINIMUM_MESSAGE_SIZE_FOR_CHUNKING = 1024000;
// **** FFDC Probe ID Constants **** //
// The following constants are to be used in the FFDC probe ID field.
// Everytime a FFDC is thrown, it should use a constant in it's probe ID
// field that is defined here. That way, even if code line number change
// it can still be easily identified where the FFDC is being generated
// from.
// Probe Id's should follow the numbering convention that is:
// <component>-<unique id for class>-<unique id for probe>
// The components are:
// 1 - Client
// 2 - Client proxy queues
// 3 - Server
// 4 - ME->ME
// 5 - Common (used across more than one above component)
// Probe Id' should also remain unique across releases.
// ***** Client side ***** //
// public static final String CLIENTSIDECONNECTION_CONNECT_01 = "1-001-0001";
public static final String CLIENTSIDECONNECTION_CONNECT_02 = "1-001-0002";
public static final String CLIENTSIDECONNECTION_CONNECT_03 = "1-001-0003";
public static final String CLIENTSIDECONNECTION_CONNECT_04 = "1-001-0004";
public static final String CLIENTSIDECONNECTION_CONNECT_05 = "1-001-0005";
public static final String CLIENTSIDECONNECTION_CONNECT_06 = "1-001-0006";
public static final String CLIENTSIDECONNECTION_CLOSE_01 = "1-001-0007";
public static final String CLIENTSIDECONNECTION_TRMHANDSHAKEEXCHANGE_01 = "1-001-0008";
public static final String CLIENTSIDECONNECTION_SETSICONN_01 = "1-001-0009";
public static final String CLIENTSIDECONNECTION_SENDMFPSCHEMA_01 = "1-001-0010";//D234369
public static final String CLIENTSIDECONNECTION_REQUESTMFPSCHEMA_01 = "1-001-0011";//F247845
// public static final String CONNECTIONPROXY_SEND_01 = "1-002-0001";
// public static final String CONNECTIONPROXY_SENDTOEXCEPTIONDEST_01 = "1-002-0002";
public static final String CONNECTIONPROXY_STATICINIT_01 = "1-002-0003";
// public static final String CONNECTIONPROXY_RECEIVEWITHWAIT_01 = "1-002-0004";
public static final String CONNECTIONPROXY_GETDESTINATIONDEF_01 = "1-002-0005";
public static final String CONNECTIONPROXY_INVOKECMD_01 = "1-002-0006";// SIB0009.comms.1
public static final String CONNECTIONPROXY_INVOKECMD_02 = "1-002-0007";// SIB0009.comms.1
public static final String CONNECTIONPROXY_SENDCHUNKED_01 = "1-002-0008";
public static final String CONNECTIONPROXY_SENDCHUNKEDEXCEPTION_01 = "1-002-0009";
public static final String CONNECTIONPROXY_STATICINIT_02 = "1-002-0010";
public static final String CONSUMERSESSIONPROXY_RCVNOWAIT_01 = "1-003-0001";
public static final String CONSUMERSESSIONPROXY_RCVWITHWAIT_01 = "1-003-0002";
public static final String CONSUMERSESSIONPROXY_STATICINIT_01 = "1-003-0003";
public static final String CONSUMERSESSIONPROXY_REGASYNC_01 = "1-003-0004";
// public static final String CONSUMERSESSIONPROXY_PERFORMRCV_01 = "1-003-0005";
public static final String CONSUMERSESSIONPROXY_PERFORMRCV_02 = "1-003-0006";
public static final String CONSUMERSESSIONPROXY_LOCKMSG_01 = "1-003-0007";
// public static final String CONSUMERSESSIONPROXY_UNLOCKMSG_01 = "1-003-0008";
public static final String CONSUMERSESSIONPROXY_SESSION_STOPPED_01 = "1-003-0009";
public static final String CONSUMERSESSIONPROXY_SESSION_STOPPED_02 = "1-003-0010";
public static final String CONSUMERSESSIONPROXY_SESSION_STOPPED_03 = "1-003-0011";
public static final String CONSUMERSESSIONPROXY_INCALLBACKACT_01 = "1-003-0012";
// public static final String PRODUCERSESSIONPROXY_SEND_01 = "1-004-0001";
public static final String PRODUCERSESSIONPROXY_STATICINIT_01 = "1-004-0002";
public static final String PRODUCERSESSIONPROXY_SENDCHUNKED_01 = "1-004-0003";
public static final String BROWSERSESSION_NEXT_01 = "1-005-0001";
// public static final String BIFCONSUMERSESSION_GETJMOFROMBUFFER_01 = "1-006-0001";
public static final String SIXARESOURCEPROXY_COMMIT_01 = "1-007-0001";
public static final String SIXARESOURCEPROXY_END_01 = "1-007-0002";
public static final String SIXARESOURCEPROXY_FORGET_01 = "1-007-0003";
public static final String SIXARESOURCEPROXY_GETTXTIMEOUT_01 = "1-007-0004";
public static final String SIXARESOURCEPROXY_PREPARE_01 = "1-007-0005";
public static final String SIXARESOURCEPROXY_RECOVER_01 = "1-007-0006";
public static final String SIXARESOURCEPROXY_ROLLBACK_01 = "1-007-0007";
public static final String SIXARESOURCEPROXY_SETTXTIMEOUT_01 = "1-007-0008";
public static final String SIXARESOURCEPROXY_START_01 = "1-007-0009";
public static final String PROXYRECEIVELISTENER_DATARCVD_01 = "1-008-0001";
public static final String PROXYRECEIVELISTENER_DATARCVD_02 = "1-008-0002";
public static final String PROXYRECEIVELISTENER_PROCESSMSG_01 = "1-008-0003";
public static final String PROXYRECEIVELISTENER_PROCESSMSG_02 = "1-008-0004";
public static final String PROXYRECEIVELISTENER_PROCESSEVENT_01 = "1-008-0005";
public static final String PROXYRECEIVELISTENER_PROCESSEVENT_02 = "1-008-0006";
public static final String PROXYRECEIVELISTENER_PROCESSEVENT_03 = "1-008-0007";
public static final String PROXYRECEIVELISTENER_PROCESSSCHEMA_01 = "1-008-0008";
public static final String PROXYRECEIVELISTENER_DESTLIST_CALLBACK_02 = "1-008-0010"; //SIB0137.comms.3
public static final String PROXYRECEIVELISTENER_SESSION_STOPPED_01 = "1-008-0011"; //SIB0115d.comms
public static final String PROXYRECEIVELISTENER_SESSION_STOPPED_02 = "1-008-0012"; //SIB0115d.comms
public static final String PROXYRECEIVELISTENER_CONSUMERMON_CALLBACK_01 = "1-008-0013"; //F011127
public static final String CONNECTIONPROPS_GETWLMEP_01 = "1-009-0001";
public static final String CONNECTIONPROPS_GETEP_01 = "1-009-0002";
public static final String CONNECTIONPROPS_GETCHAIN_01 = "1-009-0003";
public static final String PROXY_GETPROXYID_01 = "1-010-0001";
public static final String PROXY_GETCONNECTIONPROXY_01 = "1-010-0002";
public static final String COMMS_ADMIN_START_01 = "1-011-0001";// D225856
public static final String ORDERCONTEXTPROXY_CREATE_01 = "1-012-0001";// D241156
public static final String ORDERCONTEXTPROXY_CLOSE_01 = "1-012-0002";// D241156
public static final String OPTRESOURCEPROXY_COMMIT_01 = "1-013-0001";
public static final String OPTRESOURCEPROXY_SETENDNOTREQUIRED_01 = "1-013-0002";
public static final String OPTRESOURCEPROXY_GETENDFLAGS_01 = "1-013-0003";
public static final String OPTUNCOORDPROXY_GETXID_01 = "1-014-00001";
public static final String OPTUNCOORDPROXY_ISENDREQUIRED_01 = "1-014-00002";
public static final String OPTUNCOORDPROXY_SETENDNOTREQUIRED_01 = "1-014-00003";
public static final String OPTUNCOORDPROXY_GETENDFLAGS_01 = "1-014-00004";
public static final String CLIENTASYNCHEVENTTHREADPOOL_INVOKE_01 = "1-015-00001";
public static final String DESTINATIONLISTENERTHREAD_RUN_01 = "1-015-00002";
public static final String SUSPENDABLEXARESOURCE_START_01 = "1-016-0001";
public static final String ASYNC_CON_THREADPOOL_SCHQ_RUN_01 = "1-017-0001"; //PM12356
public static final String ASYNC_CON_THREADPOOL_SCHQ_RUN_02 = "1-017-0002"; //PM12356
public static final String ASYNC_CON_THREADPOOL_SCHQ_RUN_03 = "1-017-0003"; //PM12356
public static final String CONSUMERSETCHANGECALLBACKTHREAD_RUN_01 = "1-018-00001"; //F011127
// ***** Proxy-queue related ***** //
public static final String ORDEREDPROXYQUEUEIMPL_CLOSE_01 = "2-001-0001";
public static final String PROXYQUEUECONVGROUPIMPL_CLOSE_01 = "2-002-0001";
public static final String PROXYQUEUECONVGROUPIMPL_NOTIFYCLOSE_01 = "2-002-0002";
public static final String ASYNC_THREADPOOL_HASCAPACITY_01 = "2-003-0001";
public static final String ASYNC_DISPATCHER_DELIVERMSGS_01 = "2-004-0001";
public static final String ASYNC_DISPATCHER_DELIVERMSGS_02 = "2-004-0002";
public static final String CONVERSATIONHELPERIMPL_01 = "2-005-0001";
public static final String CONVERSATIONHELPERIMPL_02 = "2-005-0002";
public static final String CONVERSATIONHELPERIMPL_03 = "2-005-0003";
public static final String CONVERSATIONHELPERIMPL_04 = "2-005-0004";
public static final String CONVERSATIONHELPERIMPL_05 = "2-005-0005";
public static final String CONVERSATIONHELPERIMPL_06 = "2-005-0006";
public static final String CONVERSATIONHELPERIMPL_07 = "2-005-0007";
public static final String CONVERSATIONHELPERIMPL_08 = "2-005-0008";
public static final String CONVERSATIONHELPERIMPL_09 = "2-005-0009";
public static final String CONVERSATIONHELPERIMPL_10 = "2-005-0010";
public static final String CONVERSATIONHELPERIMPL_11 = "2-005-0011";
public static final String CONVERSATIONHELPERIMPL_12 = "2-005-0012";
public static final String CONVERSATIONHELPERIMPL_13 = "2-005-0013";
public static final String CONVERSATIONHELPERIMPL_14 = "2-005-0014";
public static final String CONVERSATIONHELPERIMPL_15 = "2-005-0015";//D234369
public static final String CONVERSATIONHELPERIMPL_16 = "2-005-0016";//D234369
public static final String CONVERSATIONHELPERIMPL_17 = "2-005-0017";//D234369
public static final String CONVERSATIONHELPERIMPL_18 = "2-005-0018";//D234369
public static final String CONVERSATIONHELPERIMPL_19 = "2-005-0019";//D234369
public static final String CONVERSATIONHELPERIMPL_20 = "2-005-0020";//F013661
public static final String ASYNCHPQIMPL_SETCONSUMERSESS_01 = "2-006-0001";
public static final String ASYNCHPQIMPL_SETCONSUMERSESS_02 = "2-006-0002";
public static final String ASYNCHPQIMPL_PROCESSEXCEPTIONS_01 = "2-006-0003";// D225856
public static final String ASYNCHPQIMPL_SETASYNCCALLBACK_01 = "2-006-0004";// D225856
public static final String ASYNCHPQ_PUT_01 = "2-007-0001";
public static final String ASYNCHPQ_GET_01 = "2-007-0002";
public static final String ASYNCHPQ_GETBATCH_01 = "2-007-0003";
public static final String ASYNCHPQ_GETBATCH_02 = "2-007-0004";
public static final String ASYNCHPQ_DELIVER_01 = "2-007-0005";//D249096
public static final String ASYNCHPQ_DELIVER_02 = "2-007-0006";//D249096
public static final String ASYNCHPQ_DELIVER_03 = "2-007-0007";//D249096
public static final String ASYNCHPQ_DELIVER_04 = "2-007-0008";//D249096
public static final String ASYNCHPQ_DELIVER_05 = "2-007-0009";//D249096
public static final String BROWSERPQ_SETBROWSERSESS_01 = "2-008-0001";
public static final String BROWSERPQ_SETBROWSERSESS_02 = "2-008-0002";
public static final String ORDEREDPQ_GET_01 = "2-009-0001";
public static final String ORDEREDPQ_GETBATCH_01 = "2-009-0002";
public static final String ORDEREDPQ_GETBATCH_02 = "2-009-0003";
public static final String ORDEREDPQ_GETDESCRIPTOR_01 = "2-009-0004";
public static final String PQCONVGRPFACTIMPL_CREATE_01 = "2-010-0001";
public static final String RHPQIMPL_SETCONSUMERSESS_01 = "2-011-0001";
public static final String RHPQIMPL_SETCONSUMERSESS_02 = "2-011-0002";
public static final String RHPQIMPL_PROCESSEXCEPTIONS_01 = "2-011-0003";// D225856
public static final String RHPQIMPL_DELIVERMESSAGES_01 = "2-011-0004";
public static final String RHPQ_WAITNONEMPTY_01 = "2-012-0001";
public static final String RHPQ_GET_01 = "2-012-0002";// D220088
public static final String RHPQ_WAITNONEMPTY_02 = "2-012-0003";// D218324
public static final String RHPQ_DELIVER_01 = "2-012-0004";//D249096
public static final String RHPQ_DELIVER_02 = "2-012-0005";//D249096
public static final String RHPQ_DELIVER_03 = "2-012-0006";//D249096
public static final String RHPQ_DELIVER_04 = "2-012-0007";//D249096
public static final String RHPQ_DELIVER_05 = "2-012-0008";//D249096
public static final String RHPQ_DELIVER_06 = "2-012-0009";//PM12356
public static final String RHPQ_DELIVER_07 = "2-012-0010";//PM12356
public static final String SHORTIDALLOCATOR_INIT_01 = "2-013-0001";
// public static final String BASEQ_CLINIT_01 = "2-014-0001";// D225856
public static final String MULTICASTRHPROXYQUEUE_CLOSED_01 = "2-015-0001";
public static final String RHSESSPQIMPL_RECEIVENOWAIT_01 = "2-016-0001";
public static final String RHSESSPQIMPL_RECEIVEWITHWAIT_01 = "2-016-0002";
public static final String QUEUEDATA_GETMESSAGE_01 = "2-017-0001";
// ***** Server side ***** //
public static final String GENERICTRANSPORTRECEIVELISTENER_ERROR_01 = "3-001-0001";
public static final String COMMONSERVERRECEIVELISTENER_RHSHAKE_01 = "3-031-0001";
public static final String COMMONSERVERRECEIVELISTENER_HSREJCT_01 = "3-031-0002";
public static final String COMMONSERVERRECEIVELISTENER_RHSHAKE_02 = "3-031-0003";
public static final String SERVERSIDECONNECTION_CLOSE_01 = "3-002-0001";
public static final String SERVERSIDECONNECTION_CONNECT_01 = "3-002-0002";
public static final String SERVERSIDECONNECTION_SETSICORECONN_01 = "3-002-0003";
public static final String SERVERSIDECONNECTION_TRMEXCHANGE_01 = "3-002-0004";
public static final String SERVERSIDECONNECTION_MFPEXCHANGE_01 = "3-002-0005";
public static final String SERVERSIDECONNECTION_SENDMFPSCHEMA_01 = "3-002-0006";// D234369
public static final String SERVERSIDECONNECTION_REQUESTMFPSCHEMATA_01 = "3-002-0007";// F247845
public static final String SERVERSIDECONNECTION_EMITNOTIFICATION_01 = "3-002-0008";// F206161.5
public static final String SERVERTRANSPORTFACTORY_INIT_01 = "3-003-0001";
public static final String SERVERTRANSPORTFACTORY_INIT_02 = "3-003-0002";
public static final String SERVERTRANSPORTRECEIVELISTENER_INIT_01 = "3-004-0001";
public static final String SERVERTRANSPORTRECEIVELISTENER_TRMEXCG_01 = "3-004-0003";
public static final String SERVERTRANSPORTRECEIVELISTENER_TRMEXCG_02 = "3-004-0004";
public static final String SERVERTRANSPORTRECEIVELISTENER_CONNGET_01 = "3-004-0005";
public static final String SERVERTRANSPORTRECEIVELISTENER_CONNGET_02 = "3-004-0006";
public static final String SERVERTRANSPORTRECEIVELISTENER_CONNGET_03 = "3-004-0007";
public static final String SERVERTRANSPORTRECEIVELISTENER_CONNGET_04 = "3-004-0008";
public static final String SERVERTRANSPORTRECEIVELISTENER_CONNCLS_01 = "3-004-0009";
public static final String SERVERTRANSPORTRECEIVELISTENER_ERROR_01 = "3-004-0010";
public static final String SERVERTRANSPORTRECEIVELISTENER_ERROR_02 = "3-004-0011";
public static final String SERVERTRANSPORTRECEIVELISTENER_ERROR_03 = "3-004-0012";
public static final String SERVERTRANSPORTRECEIVELISTENER_DATARCV_01 = "3-004-0013";
public static final String SERVERTRANSPORTRECEIVELISTENER_CLOSECONN_01 = "3-004-0016";
public static final String SERVERTRANSPORTRECEIVELISTENER_MFPEXCG_01 = "3-004-0017";
public static final String SERVERTRANSPORTRECEIVELISTENER_MFPEXCG_02 = "3-004-0018";
public static final String SERVERTRANSPORTRECEIVELISTENER_MFPSCHEMA_01 = "3-004-0019";
public static final String SERVERTRANSPORTRECEIVELISTENER_DIRECTCN_01 = "3-004-0020";
public static final String SERVERTRANSPORTRECEIVELISTENER_DIRECTCN_02 = "3-004-0021";
public static final String SERVERTRANSPORTRECEIVELISTENER_DIRECTCN_03 = "3-004-0022";
public static final String SERVERTRANSPORTRECEIVELISTENER_GETTHREAD_01 = "3-004-0023";
public static final String SERVERTRANSPORTRECEIVELISTENER_GETTHREAD_02 = "3-004-0023";// D297060
public static final String SERVERTRANSPORTRECEIVELISTENER_GETTHREAD_03 = "3-004-0023";// D297060
public static final String SERVERTRANSPORTRECEIVELISTENER_GETTHREAD_04 = "3-004-0023";// D297060
public static final String SERVERTRANSPORTRECEIVELISTENER_GETTHREAD_05 = "3-004-0023";// D297060
public static final String SERVERTRANSPORTRECEIVELISTENER_MFPREQSCH_01 = "3-004-0024";// F247845
public static final String SERVERTRANSPORTRECEIVELISTENER_MFPREQSCH_02 = "3-004-0025";// F247845
public static final String SERVERTRANSPORTRECEIVELISTENER_MFPREQSCH_03 = "3-004-0026";// F247845
public static final String SERVERSICORECONNECTIONLISTENER_MEN_01 = "3-005-0001";
public static final String SERVERSICORECONNECTIONLISTENER_MET_01 = "3-005-0002";
public static final String SERVERSICORECONNECTIONLISTENER_ASYNC_01 = "3-005-0003";
public static final String SERVERSICORECONNECTIONLISTENER_COMMS_01 = "3-005-0004";
public static final String SERVERSICORECONNECTIONLISTENER_MEQ_01 = "3-005-0005";
public static final String SERVERSICORECONNECTIONLISTENER_ASYNC_02 = "3-005-0006";
public static final String STATICCATCONNECTION_CONNCLONE_01 = "3-006-0001";
public static final String STATICCATCONNECTION_CONNCLONE_02 = "3-006-0002";
public static final String STATICCATCONNECTION_CONNCLONE_03 = "3-006-0003";
public static final String STATICCATCONNECTION_CONNCLOSE_01 = "3-006-0004";
public static final String STATICCATCONNECTION_CONNCLOSE_02 = "3-006-0005";
public static final String STATICCATCONNECTION_UNIQID_01 = "3-006-0006";
public static final String STATICCATCONNECTION_UNIQID_02 = "3-006-0007";
public static final String STATICCATCONNECTION_CONNCLS_02 = "3-006-0008";
public static final String STATICCATCONNECTION_RCVCONNMSG_01 = "3-006-0009";
public static final String STATICCATCONNECTION_CREATE_OC_01 = "3-006-0010";
public static final String STATICCATCONNECTION_CREATE_OC_02 = "3-006-0011";
public static final String STATICCATCONNECTION_CREATE_OC_03 = "3-006-0012";
public static final String STATICCATCONNECTION_CLOSE_OC_01 = "3-006-0012";
public static final String STATICCATCONNECTION_CHK_MESSAGING_REQ_01 = "3-006-0013"; // LIDB3684.11.1.3
public static final String STATICCATCONNECTION_CHK_MESSAGING_REQ_02 = "3-006-0014"; // LIDB3684.11.1.3
public static final String STATICCATCONNECTION_INVOKECMD_01 = "3-006-0015"; // SIB0009.comms.1
public static final String STATICCATCONNECTION_INVOKECMD_02 = "3-006-0016"; // SIB0009.comms.1
public static final String STATICCATCONNECTION_ADD_DEST_LISTENER_01 = "3-006-0017"; // SIB0137.comms.2
public static final String STATICCATCONNECTION_ADD_DEST_LISTENER_02 = "3-006-0018"; // SIB0137.comms.3
public static final String STATICCATCONNECTION_CONNCLOSE_03 = "3-006-0019";
public static final String STATICCATCONNECTION_REG_SET_CONSUMER_MON_01 = "3-006-0020"; //F011127
public static final String STATICCATCONNECTION_REG_SET_CONSUMER_MON_02 = "3-006-0021"; //F011127
public static final String STATICCATDESTINATION_DESTCREATE_01 = "3-007-0001";
public static final String STATICCATDESTINATION_DESTCREATE_02 = "3-007-0002";
public static final String STATICCATDESTINATION_DESTDELETE_01 = "3-007-0003";
public static final String STATICCATDESTINATION_DESTDELETE_02 = "3-007-0004";
public static final String STATICCATDESTINATION_DESTGET_01 = "3-007-0005";
public static final String STATICCATDESTINATION_DESTGET_02 = "3-007-0006";
public static final String STATICCATDESTINATION_DESTGET_03 = "3-007-0007";
public static final String STATICCATDESTINATION_DESTGET_04 = "3-007-0008";
public static final String STATICCATDESTINATION_DESTGET_05 = "3-007-0009";
public static final String STATICCATDESTINATION_DESTGET_06 = "3-007-0010";
public static final String STATICCATPRODUCER_CREATE_01 = "3-008-0001";
public static final String STATICCATPRODUCER_CREATE_02 = "3-008-0002";
public static final String STATICCATPRODUCER_CREATE_03 = "3-008-0003";
public static final String STATICCATPRODUCER_CLOSE_01 = "3-008-0003";
public static final String STATICCATPRODUCER_CLOSE_02 = "3-008-0004";
public static final String STATICCATPRODUCER_SEND_01 = "3-008-0005";
public static final String STATICCATPRODUCER_SEND_02 = "3-008-0006";
public static final String STATICCATPRODUCER_SEND_03 = "3-008-0007";
public static final String STATICCATPRODUCER_SEND_04 = "3-008-0008";
public static final String STATICCATPRODUCER_CONNSEND_01 = "3-008-0009";
public static final String STATICCATPRODUCER_CONNSEND_02 = "3-008-0010";
public static final String STATICCATPRODUCER_CONNSEND_03 = "3-008-0011";
public static final String STATICCATPRODUCER_CONNSEND_04 = "3-008-0012";
public static final String STATICCATPRODUCER_SENDCHUNKED_01 = "3-008-0013";
public static final String STATICCATPRODUCER_SENDCHUNKED_02 = "3-008-0014";
public static final String STATICCATPRODUCER_SENDCHUNKED_03 = "3-008-0015";
public static final String STATICCATPRODUCER_SENDCHUNKED_04 = "3-008-0016";
public static final String STATICCATPRODUCER_SENDCHUNKED_05 = "3-008-0017";
public static final String STATICCATPRODUCER_SENDCHUNKEDCONN_01 = "3-008-0018";
public static final String STATICCATPRODUCER_SENDCHUNKEDCONN_02 = "3-008-0019";
public static final String STATICCATPRODUCER_SENDCHUNKEDCONN_03 = "3-008-0020";
public static final String STATICCATPRODUCER_SENDCHUNKEDCONN_04 = "3-008-0021";
public static final String STATICCATPRODUCER_SENDCHUNKEDCONN_05 = "3-008-0022";
public static final String STATICCATTRANSACTION_CREATE_01 = "3-009-0001";
public static final String STATICCATTRANSACTION_BEGIN_01 = "3-009-0002";
public static final String STATICCATTRANSACTION_BEGIN_02 = "3-009-0003";
public static final String STATICCATTRANSACTION_PREPARE_01 = "3-009-0004";
public static final String STATICCATTRANSACTION_PREPARE_02 = "3-009-0005";
public static final String STATICCATTRANSACTION_COMMIT_01 = "3-009-0006";
public static final String STATICCATTRANSACTION_COMMIT_02 = "3-009-0007";
public static final String STATICCATTRANSACTION_ROLLBACK_01 = "3-009-0008";
public static final String STATICCATTRANSACTION_ROLLBACK_02 = "3-009-0009";
public static final String STATICCATCONSUMER_CREATE_01 = "3-010-0001";
public static final String STATICCATCONSUMER_CREATE_02 = "3-010-0002";
public static final String STATICCATCONSUMER_CREATE_03 = "3-010-0003";
public static final String STATICCATCONSUMER_CREATE_04 = "3-010-0004";
public static final String STATICCATCONSUMER_CREATEBIF_01 = "3-010-0005";
public static final String STATICCATCONSUMER_CREATEBIF_02 = "3-010-0006";
public static final String STATICCATSUBSCRIPTION_CREATE_01 = "3-011-0001";
public static final String STATICCATSUBSCRIPTION_CREATE_02 = "3-011-0002";
public static final String STATICCATSUBSCRIPTION_CREATE_03 = "3-011-0003";
public static final String STATICCATSUBSCRIPTION_DELETE_01 = "3-011-0004";
public static final String STATICCATSUBSCRIPTION_DELETE_02 = "3-011-0005";
public static final String STATICCATSUBSCRIPTION_CREATECONS_01 = "3-011-0006";
public static final String STATICCATSUBSCRIPTION_CREATECONS_02 = "3-011-0007";
public static final String STATICCATSUBSCRIPTION_CREATECONS_03 = "3-011-0008";
public static final String STATICCATSUBSCRIPTION_CREATECONS_04 = "3-011-0009";
public static final String STATICCATSUBSCRIPTION_CREATECONS_05 = "3-011-0010";
public static final String STATICCATHELPER_SEND_EXCEP_01 = "3-012-0001";
public static final String STATICCATHELPER_SEND_ASEXCEP_01 = "3-012-0002";
public static final String STATICCATHELPER_SENDSESSRESPONSE_01 = "3-012-0003";
public static final String STATICCATHELPER_SENDSESSRESPONSE_02 = "3-012-0004";
public static final String STATICCATHELPER_SENDMCSESSRESPONSE_01 = "3-012-0005";
public static final String STATICCATXATRANSACTION_XAOPEN_01 = "3-013-0001";
public static final String STATICCATXATRANSACTION_XAOPEN_02 = "3-013-0002";
public static final String STATICCATXATRANSACTION_XASTART_01 = "3-013-0003";
public static final String STATICCATXATRANSACTION_XASTART_02 = "3-013-0004";
public static final String STATICCATXATRANSACTION_XASTART_03 = "3-013-0005";
public static final String STATICCATXATRANSACTION_XAEND_01 = "3-013-0006";
public static final String STATICCATXATRANSACTION_XAEND_02 = "3-013-0007";
// public static final String STATICCATXATRANSACTION_XAEND_03 = "3-013-0008";
public static final String STATICCATXATRANSACTION_XAPREPARE_01 = "3-013-0009";
public static final String STATICCATXATRANSACTION_XAPREPARE_02 = "3-013-0010";
// public static final String STATICCATXATRANSACTION_XAPREPARE_03 = "3-013-0011";
public static final String STATICCATXATRANSACTION_XACOMMIT_01 = "3-013-0012";
public static final String STATICCATXATRANSACTION_XACOMMIT_02 = "3-013-0013";
// public static final String STATICCATXATRANSACTION_XACOMMIT_03 = "3-013-0014";
public static final String STATICCATXATRANSACTION_XAROLLBACK_01 = "3-013-0015";
public static final String STATICCATXATRANSACTION_XAROLLBACK_02 = "3-013-0016";
// public static final String STATICCATXATRANSACTION_XAROLLBACK_03 = "3-013-0017";
public static final String STATICCATXATRANSACTION_XARECOVER_01 = "3-013-0018";
public static final String STATICCATXATRANSACTION_XARECOVER_02 = "3-013-0019";
// public static final String STATICCATXATRANSACTION_XARECOVER_03 = "3-013-0020";
public static final String STATICCATXATRANSACTION_XAFORGET_01 = "3-013-0021";
public static final String STATICCATXATRANSACTION_XAFORGET_02 = "3-013-0022";
// public static final String STATICCATXATRANSACTION_XAFORGET_03 = "3-013-0023";
public static final String STATICCATXATRANSACTION_GETTXTIMEOUT_01 = "3-013-0024";
public static final String STATICCATXATRANSACTION_GETTXTIMEOUT_02 = "3-013-0025";
// public static final String STATICCATXATRANSACTION_GETTXTIMEOUT_03 = "3-013-0026";
public static final String STATICCATXATRANSACTION_SETTXTIMEOUT_01 = "3-013-0027";
public static final String STATICCATXATRANSACTION_SETTXTIMEOUT_02 = "3-013-0028";
// public static final String STATICCATXATRANSACTION_SETTXTIMEOUT_03 = "3-013-0029";
public static final String STATICCATXATRANSACTION_XASTART_04 = "3-013-0030";// D297060
public static final String STATICCATXATRANSACTION_XASTART_05 = "3-013-0031";// D297060
public static final String STATICCATXATRANSACTION_GETRESFROMTX_01 = "3-013-0032";// D297060
public static final String STATICCATXATRANSACTION_GETRESFROMTX_02 = "3-013-0033";// D297060
public static final String STATICCATXATRANSACTION_GETRESFROMTX_03 = "3-013-0034";
public static final String STATICCATDESTINATION_GETDESTCONFIG_01 = "3-014-0001";
public static final String STATICCATDESTINATION_GETDESTCONFIG_02 = "3-014-0002";
public static final String STATICCATDESTINATION_GETDESTCONFIG_03 = "3-014-0003";
public static final String STATICCATDESTINATION_SENDTOEXCEP_01 = "3-014-0004";
public static final String STATICCATDESTINATION_SENDTOEXCEP_02 = "3-014-0005";
public static final String STATICCATDESTINATION_SENDTOEXCEP_03 = "3-014-0006";
public static final String STATICCATDESTINATION_SENDCHUNKEDTOEXCEP_01 = "3-014-0007";
public static final String STATICCATDESTINATION_SENDCHUNKEDTOEXCEP_02 = "3-014-0008";
public static final String STATICCATDESTINATION_SENDCHUNKEDTOEXCEP_03 = "3-014-0009";
public static final String STATICCATDESTINATION_SENDCHUNKEDTOEXCEP_04 = "3-014-0010";
public static final String STATICCATBROWSER_RCVCREATEBROWSERSESS_01 = "3-015-0001";
public static final String STATICCATBROWSER_RCVCREATEBROWSERSESS_02 = "3-015-0002";
public static final String STATICCATBROWSER_RCVCREATEBROWSERSESS_03 = "3-015-0003";
public static final String STATICCATBROWSER_RCVRESETBROWSERSESS_01 = "3-015-0004";
public static final String STATICCATBROWSER_RCVRESETBROWSERSESS_02 = "3-015-0005";
public static final String STATICCATBROWSER_RCVRESETBROWSERSESS_03 = "3-015-0006";
public static final String STATICCATBROWSER_RCVRESETBROWSERSESS_04 = "3-015-0007";
public static final String STATICCATBROWSER_RCVCREATEBROWSERSESS_04 = "3-015-0008"; //SIB0113.comms.1
public static final String CATSYNCASYNCHREADER_CONSUME_MSGS_01 = "3-016-0001";
public static final String CATSYNCASYNCHREADER_CONSUME_MSGS_03 = "3-016-0002";
public static final String CATSYNCASYNCHREADER_CONSUME_MSGS_04 = "3-016-0003";
public static final String CATSYNCASYNCHREADER_SEND_MSG_01 = "3-016-0004";
public static final String CATSYNCASYNCHREADER_SEND_MSG_02 = "3-016-0005";
public static final String CATSYNCASYNCHREADER_SEND_EXCEP_01 = "3-016-0006";
public static final String CATSYNCASYNCHREADER_SEND_NO_MSG_01 = "3-016-0007";
public static final String CATSYNCASYNCHREADER_CLOSE_SESS_01 = "3-016-0008";
public static final String CATSYNCASYNCHREADER_ASYNCHEXCEPTION_01 = "3-016-0009";
public static final String CATSYNCASYNCHREADER_COMMSFAILURE_01 = "3-016-0010";
public static final String CATSYNCASYNCHREADER_METERMINATED_01 = "3-016-0011";
public static final String CATSYNCASYNCHREADER_SEND_MSG_03 = "3-016-0012";
public static final String CATSYNCASYNCHREADER_CONSUME_MSGS_05 = "3-016-0013";
public static final String CATTIMER_ALARM_01 = "3-017-0001";
public static final String CATASYNCHCONSUMER_SETCALLBACK_01 = "3-018-0001";
public static final String CATASYNCHCONSUMER_SETCALLBACK_02 = "3-018-0002";
public static final String CATASYNCHCONSUMER_UNLOCKSET_01 = "3-018-0003";
public static final String CATASYNCHCONSUMER_UNLOCKSET_02 = "3-018-0004";
public static final String CATASYNCHCONSUMER_DELETESET_01 = "3-018-0005";
public static final String CATASYNCHCONSUMER_UNLOCKALL_01 = "3-018-0006";
public static final String CATASYNCHCONSUMER_UNLOCKALL_02 = "3-018-0007";
// public static final String CATASYNCHCONSUMER_SENDMESS_01 = "3-018-0008";
public static final String CATASYNCHCONSUMER_CONSUME_MSGS_01 = "3-018-0009";
public static final String CATASYNCHCONSUMER_CONSUME_MSGS_02 = "3-018-0010";
public static final String CATASYNCHCONSUMER_SENDCHUNKEDMESS_01 = "3-018-0011";
public static final String CATASYNCHCONSUMER_SENDENTIREMESS_01 = "3-018-0012";
public static final String CATASYNCHCONSUMER_SENSSION_STOPPED_01 = "3-018-0013"; // SIB0115d.comms
public static final String CATASYNCHCONSUMER_UNLOCKSET_03 = "3-018-0014";
public static final String CATASYNCHCONSUMER_UNLOCKSET_04 = "3-018-0015";
public static final String CATASYNCHCONSUMER_UNLOCKALL_03 = "3-018-0016";//F013661
public static final String CATASYNCHCONSUMER_UNLOCKALL_04 = "3-018-0017";//F013661
public static final String CATCONSUMER_RECEIVE_01 = "3-019-0001";
public static final String CATCONSUMER_CLOSE_01 = "3-019-0002";
public static final String CATCONSUMER_CLOSE_02 = "3-019-0003";
public static final String CATCONSUMER_SETASYNCHCALLBACK_01 = "3-019-0004";
public static final String CATCONSUMER_START_01 = "3-019-0005";
public static final String CATCONSUMER_STOP_01 = "3-019-0006";
public static final String CATCONSUMER_STOP_02 = "3-019-0007";
public static final String CATCONSUMER_UNLOCKSET_01 = "3-019-0008";
public static final String CATCONSUMER_DELETESET_01 = "3-019-0009";
public static final String CATCONSUMER_UNLOCKALL_01 = "3-019-0010";
public static final String CATCONSUMER_REQUESTMSGS_01 = "3-019-0011";
public static final String CATCONSUMER_UNSETASYNCHCALLBACK_01 = "3-019-0012";
public static final String CATCONSUMER_UNSETASYNCHCALLBACK_02 = "3-019-0013";
public static final String CATCONSUMER_FLUSH_01 = "3-019-0014";
public static final String CATCONSUMER_RESET_01 = "3-019-0015";
public static final String CATCONSUMER_READSET_01 = "3-019-0016";
public static final String CATCONSUMER_READANDDELTESET_01 = "3-019-0017";
public static final String CATCONSUMER_START_02 = "3-019-0018";
public static final String CATCONSUMER_UNLOCKSET_02 = "3-019-0019";
public static final String CATCONSUMER_UNLOCKALL_02 = "3-019-0020";
public static final String CATCONSUMER_SETSTATE_01 = "3-019-0021";
public static final String CATSESSSYNCHCONSUMER_RECEIVE_01 = "3-020-0001";
public static final String CATSESSSYNCHCONSUMER_RECEIVE_02 = "3-020-0002";
public static final String CATSESSSYNCHCONSUMER_RECEIVE_03 = "3-020-0003";
public static final String CATSESSSYNCHCONSUMER_CLOSE_01 = "3-020-0004";
public static final String CATSESSSYNCHCONSUMER_START_01 = "3-020-0005";
public static final String CATSESSSYNCHCONSUMER_RECEIVE_04 = "3-020-0006";
public static final String CATPROXYCONSUMER_DELETESET_01 = "3-021-0001";
public static final String CATPROXYCONSUMER_DELETESET_02 = "3-021-0002";
public static final String CATPROXYCONSUMER_UNLOCKSET_01 = "3-021-0003";
public static final String CATPROXYCONSUMER_UNLOCKSET_02 = "3-021-0004";
public static final String CATPROXYCONSUMER_UNLOCKALL_01 = "3-021-0005";
public static final String CATPROXYCONSUMER_UNLOCKALL_02 = "3-021-0006";
public static final String CATPROXYCONSUMER_FLUSH_01 = "3-021-0007";
public static final String CATPROXYCONSUMER_FLUSH_02 = "3-021-0008";
public static final String CATPROXYCONSUMER_SEND_MSG_01 = "3-021-0009";
public static final String CATPROXYCONSUMER_REQUEST_MSGS_01 = "3-021-0010";
public static final String CATPROXYCONSUMER_SEND_CHUNKED_MSG_01 = "3-021-0011";
public static final String CATPROXYCONSUMER_UNLOCKSET_04 = "3-021-0012"; //This way matches up with 6.1.
public static final String CATPROXYCONSUMER_UNLOCKSET_03 = "3-021-0013";
public static final String CATPROXYCONSUMER_UNLOCKALL_03 = "3-021-0014";
public static final String CATPROXYCONSUMER_UNLOCKALL_04 = "3-021-0015";
public static final String CATASYNCHRHREADER_CONSUME_MSGS_01 = "3-022-0001";
public static final String CATASYNCHRHREADER_CONSUME_MSGS_02 = "3-022-0002";
public static final String CATBROWSECONSUMER_SENDMESSAGE_01 = "3-023-0001";
public static final String CATBROWSECONSUMER_SENDMESSAGE_02 = "3-023-0002";
public static final String CATBROWSECONSUMER_GETNEXTMESSAGE_01 = "3-023-0003";
public static final String CATBROWSECONSUMER_FLUSH_01 = "3-023-0004";
public static final String CATBROWSECONSUMER_CLOSE_01 = "3-023-0005";
public static final String CATBROWSECONSUMER_CLOSE_02 = "3-023-0006";
public static final String CATBROWSECONSUMER_SEND_CHUNKED_MSG_01 = "3-023-0007";
public static final String CATBROWSECONSUMER_SEND_CHUNKED_MSG_02 = "3-023-0008";
public static final String CATASYNCHCONSUMER_FLUSH_01 = "3-024-0001";
public static final String CATASYNCHCONSUMER_FLUSH_02 = "3-024-0002";
public static final String CATASYNCHCONSUMER_DELETESET_02 = "3-024-0003";
public static final String CATBIFCONSUMER_DELETESET_01 = "3-025-0001";
public static final String CATBIFCONSUMER_DELETESET_02 = "3-025-0002";
public static final String CATBIFCONSUMER_DELETESET_03 = "3-025-0003";
public static final String CATBIFCONSUMER_DELETESET_04 = "3-025-0004";
public static final String CATBIFCONSUMER_UNLOCKSET_01 = "3-025-0005";
public static final String CATBIFCONSUMER_UNLOCKSET_02 = "3-025-0006";
public static final String CATBIFCONSUMER_READSET_01 = "3-025-0007";
public static final String CATBIFCONSUMER_READSET_02 = "3-025-0008";
public static final String CATBIFCONSUMER_READANDDELTESET_01 = "3-025-0009";
public static final String CATBIFCONSUMER_READANDDELTESET_02 = "3-025-0010";
public static final String CATBIFCONSUMER_ADDSIBMESS_01 = "3-025-0011";
public static final String CATBIFCONSUMER_CLOSE_01 = "3-025-0012";
public static final String CATBIFCONSUMER_CLOSE_02 = "3-025-0013";
public static final String CATBIFCONSUMER_UNLOCKSET_03 = "3-025-0014";
public static final String CATBIFCONSUMER_UNLOCKSET_04 = "3-025-0015";
public static final String MULTICASTCONSUMERSESSION_CONSUMEMSGS_01 = "3-026-0001";
public static final String MULTICASTCONSUMERSESSION_CONSUMEMSGS_02 = "3-026-0002";
public static final String CATMAINCONSUMER_CHECKNOTBROWSER_01 = "3-027-0001";
public static final String CATMAINCONSUMER_CHECKNOTBROWSER_02 = "3-027-0002";
public static final String CATMAINCONSUMER_START_01 = "3-027-0004";
public static final String CATMAINCONSUMER_STOP_01 = "3-027-0005";
public static final String CONVERSATIONSTATE_INIT_01 = "3-028-0001";
public static final String CONVERSATIONSTATE_INIT_02 = "3-028-0002";
public static final String CONVERSATIONSTATE_INIT_03 = "3-028-0003";
public static final String CATTRANSACTION_ROLLBACKINDOUBTTXS_01 = "3-029-0001";// D257768
public static final String IDTOTXTABLE_SELFDESTRUCT_01 = "3-030-0001";
public static final String IDTOTXTABLE_GETTXGLOBALTXBRANCH_01 = "3-030-0002";
public static final String IDTOTXTABLE_GETEXCEPFORROLLBACKLOCALTX_01 = "3-030-0003";
public static final String IDTOTXTABLE_ENDOPTGLOBALTXBRANCH_01 = "3-030-0004";
public static final String IDTOTXTABLE_GETEXPFORROLLBACKONLYGLOBALTX_02 = "3-030-0005";
public static final String IDTOTXTABLE_GETEXPFORROLLBACKONLYGLOBALTX_01 = "3-030-0006";
public static final String IDTOTXTABLE_REMOVELOCALTX_01 = "3-030-0007";
public static final String IDTOTXTABLE_ENDGLOBALTXBRANCH_01 = "3-030-0008";
public static final String IDTOTXTABLE_ISLOCALTXROLLBACKONLY_01 = "3-030-0009";
public static final String IDTOTXTABLE_REMOVEGLOBALTXBRANCH_01 = "3-030-0010";
public static final String IDTOTXTABLE_LOCALTXENTRY_GETEXCEPTION_01 = "3-030-0011";
public static final String IDTOTXTABLE_RMENTRY_ENDCURRENT_01 = "3-030-0012";
public static final String IDTOTXTABLE_RMENTRY_ENDCURRENT_02 = "3-030-0013";
public static final String IDTOTXTABLE_RMENTRY_GETEXCEPTION_01 = "3-030-0014";
public static final String IDTOTXTABLE_RMENTRY_GETEXCEPTION_02 = "3-030-0015";
public static final String IDTOTXTABLE_RMENTRY_GETEXCEPTION_03 = "3-030-0016";
public static final String IDTOTXTABLE_RMENTRY_ISROLLBACKONLY_01 = "3-030-0017";
public static final String IDTOTXTABLE_RMENTRY_COMPLETEXID_01 = "3-030-0018";
public static final String IDTOTXTABLE_RMENTRY_COMPLETEXID_02 = "3-030-0019";
public static final String IDTOTXTABLE_RMENTRY_ENDTXBRANCH_01 = "3-030-0020";
public static final String IDTOTXTABLE_RMENTRY_SETINDOUBT_01 = "3-030-0021";
public static final String IDTOTXTABLE_RMENTRY_SETINDOUBT_02 = "3-030-0022";
public static final String IDTOTXTABLE_RMENTRY_MARKROLLBACKONLY_01 = "3-030-0023";
public static final String IDTOTXTABLE_RMENTRY_ENDCURRENT_03 = "3-030-0024";
public static final String SERVERTRANSPORTACCEPTLISTENER_REMOVEALL_01 = "3-031-0001";
// ***** ME->ME related ***** //
public static final String MECONNECTION_CONNECT_01 = "4-001-0001";
public static final String MECONNECTION_CONNECT_02 = "4-001-0002";
public static final String MECONNECTION_CONNECT_03 = "4-001-0003";
public static final String MECONNECTION_SEND_01 = "4-001-0004";
public static final String MECONNECTION_TRMHANDSHAKEEXCHANGE_01 = "4-001-0005";
public static final String MECONNECTION_TRMHANDSHAKEEXCHANGE_02 = "4-001-0006";
public static final String MECONNECTION_MFPHANDSHAKEEXCHANGE_01 = "4-001-0007";
public static final String MECONNECTION_MFPHANDSHAKEEXCHANGE_02 = "4-001-0008";
public static final String MECONNECTION_SEND_02 = "4-001-0009"; // D215177.2
public static final String MECONNECTION_REQUESTMFPSCHEMATA_01 = "4-001-0010";// F247845
public static final String MECONNECTION_CLOSEREQCOMPLETE_01 = "4-001-0011";
public static final String MECONNECTION_RCVDCLOSEREQ_01 = "4-001-0012";
public static final String MECONNECTION_RCVDCLOSERESP_01 = "4-001-0013";
public static final String MECONNECTION_SENDCLOSERESPONSE_01 = "4-001-0014";
public static final String METRANSPORTRECEIVELISTENER_INIT_01 = "4-002-0001";
public static final String METRANSPORTRECEIVELISTENER_TRMEXCG_01 = "4-002-0002";
public static final String METRANSPORTRECEIVELISTENER_TRMEXCG_02 = "4-002-0003";
public static final String METRANSPORTRECEIVELISTENER_DATARCV_01 = "4-002-0004";
public static final String METRANSPORTRECEIVELISTENER_DATARCV_02 = "4-002-0005";
public static final String METRANSPORTRECEIVELISTENER_ERROR_01 = "4-002-0006";
// public static final String METRANSPORTRECEIVELISTENER_RHSHAKE_01 = "4-002-0007";
public static final String METRANSPORTRECEIVELISTENER_RMESSAGE_01 = "4-002-0008";
public static final String METRANSPORTRECEIVELISTENER_RMESSAGE_02 = "4-002-0009";
// public static final String METRANSPORTRECEIVELISTENER_HSREJCT_01 = "4-002-0010";
// public static final String METRANSPORTRECEIVELISTENER_HSREJCT_02 = "4-002-0011";
// public static final String METRANSPORTRECEIVELISTENER_RCLOSE_01 = "4-002-0012";
// public static final String METRANSPORTRECEIVELISTENER_RCLOSE_02 = "4-002-0013";
public static final String METRANSPORTRECEIVELISTENER_RCVTRMEXCHANGE_01 = "4-002-0014"; // D280276
public static final String METRANSPORTRECEIVELISTENER_OUTBOUNDSETUP_01 = "4-002-0015"; // D280276
public static final String METRANSPORTRECEIVELISTENER_OUTBOUNDSETUP_02 = "4-002-0016"; // D280276
public static final String METRANSPORTRECEIVELISTENER_DATARCV_03 = "4-002-0017"; // D295765
public static final String METRANSPORTRECEIVELISTENER_RCHMESSAGE_01 = "4-002-0018";
public static final String METRANSPORTRECEIVELISTENER_RCHMESSAGE_02 = "4-002-0019";
public static final String MECONNECTIONFACT_CLINIT_01 = "4-003-0001";
// ***** Common ***** //
public static final String JFAPCOMMUNICATOR_EXCHANGE_01 = "5-001-0001";
public static final String JFAPCOMMUNICATOR_SEND_01 = "5-001-0002";
public static final String JFAPCOMMUNICATOR_INITIATEHANDSHAKING_01 = "5-001-0003";
public static final String JFAPCOMMUNICATOR_INITIATEHANDSHAKING_02 = "5-001-0004";
public static final String JFAPCOMMUNICATOR_INITIATEHANDSHAKING_03 = "5-001-0005";
// public static final String JFAPCOMMUNICATOR_GETCMDCOMPLETIONCODE_01 = "5-001-0006";
public static final String JFAPCOMMUNICATOR_VALIDATECSTATE_01 = "5-001-0007";
public static final String JFAPCOMMUNICATOR_VALIDATECSTATE_02 = "5-001-0008";
public static final String JFAPCOMMUNICATOR_VALIDATECSTATE_03 = "5-001-0009";
// public static final String COMMSSTRING_SETSTRING_01 = "5-002-0001";
// public static final String COMMSSTRING_SETBYTES_01 = "5-002-0002";
// public static final String COMMSSTRING_VALIDATE_01 = "5-002-0003";
public static final String COMMSUTILS_GETRUNTIMEINT_01 = "5-003-0001";// D235891
public static final String COMMSUTILS_GETRUNTIMEDOUBLE_01 = "5-003-0002";// D235891
public static final String CONVERSATIONSTATE_EXTENDOBJECTTABLE_01 = "5-004-0001";// D256703
public static final String TRANTODISPATCHMAP_ADDDISPATCHLOCALTX_01 = "5-005-0001";// D297060
public static final String TRANTODISPATCHMAP_ADDENLISTEDGLOBALTX_01 = "5-005-0002";// D297060
public static final String TRANTODISPATCHMAP_MARKNOTENLISTED_01 = "5-005-0003";// D297060
public static final String TRANTODISPATCHMAP_REMOVEFORLOCALTX_01 = "5-005-0004";// D297060
public static final String TRANTODISPATCHMAP_REMOVEFORGLOBALTX_01 = "5-005-0005";// D297060
public static final String TRANTODISPATCHMAP_GETENLISTED_01 = "5-005-0006";// D297060
public static final String TRANTODISPATCHMAP_CREATENEWENLISTED_01 = "5-005-0007";// D297060
public static final String TRANTODISPATCHMAP_GMARKNOTENLISTED_01 = "5-005-0008";// D297060
public static final String TRANTODISPATCHMAP_GMARKNOTENLISTED_02 = "5-005-0009";// D297060
public static final String TRANTODISPATCHMAP_REMOVEDISPATCHABLE_01 = "5-005-0010";// D297060
public static final String COMMSBYTEBUFFER_PUTMESSAGE_01 = "5-006-0001";
public static final String COMMSBYTEBUFFER_GETMESSAGE_01 = "5-006-0002";
public static final String COMMSBYTEBUFFER_PUTSTRING_01 = "5-006-0003";
public static final String COMMSBYTEBUFFER_GETSTRING_01 = "5-006-0004";
public static final String COMMSBYTEBUFFER_PUTCLIENTMSG_01 = "5-006-0005";
public static final String COMMSBYTEBUFFER_PUTCLIENTMSG_02 = "5-006-0006";
public static final String COMMSBYTEBUFFER_PUTCLIENTMSG_03 = "5-006-0007";
public static final String COMMSBYTEBUFFER_PUTCLIENTMSG_04 = "5-006-0008";
public static final String COMMSBYTEBUFFER_SETREASONABLE_01 = "5-006-0009";
public static final String COMMSBYTEBUFFER_SETREASONABLE_02 = "5-006-0010";
public static final String COMMSBYTEBUFFER_CALC_ENC_STRLEN_01 = "5-006-0011";
public static final String COMMSDIAGMODULE_INITIALIZE_01 = "5-005-0001";
public static final String TRANSACTION_INFORMCONSUMERSOFROLLBACK_01 = "5-007-0001";// PK86574
public static final String SERVERDESTINATIONLISTENER_DESTAVAILABLE_01 = "3-032-0001"; //SIB0137.comms.3
public static final String SERVERDESTINATIONLISTENER_DESTAVAILABLE_02 = "3-032-0002"; //SIB0137.comms.3
public static final String SERVERDESTINATIONLISTENER_DESTAVAILABLE_03 = "3-032-0003"; //SIB0137.comms.3
public static final String SERVERCONSUMERMONITORLISTENER_CONSUMERSETCHANGE_01 = "3-033-0001"; //F011127
public static final String SERVERCONSUMERMONITORLISTENER_CONSUMERSETCHANGE_02 = "3-033-0002"; //F011127
//Add byte values for boolean true and false.
public static final byte TRUE_BYTE = 0x00;
public static final byte FALSE_BYTE = 0x01;
}
| epl-1.0 |
Snickermicker/openhab2 | bundles/org.openhab.binding.iaqualink/src/main/java/org/openhab/binding/iaqualink/internal/IAqualinkHandlerFactory.java | 2380 | /**
* Copyright (c) 2010-2019 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.iaqualink.internal;
import static org.openhab.binding.iaqualink.internal.IAqualinkBindingConstants.IAQUALINK_DEVICE_THING_TYPE_UID;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jetty.client.HttpClient;
import org.eclipse.smarthome.core.thing.Thing;
import org.eclipse.smarthome.core.thing.ThingTypeUID;
import org.eclipse.smarthome.core.thing.binding.BaseThingHandlerFactory;
import org.eclipse.smarthome.core.thing.binding.ThingHandler;
import org.eclipse.smarthome.core.thing.binding.ThingHandlerFactory;
import org.eclipse.smarthome.io.net.http.HttpClientFactory;
import org.openhab.binding.iaqualink.internal.handler.IAqualinkHandler;
import org.osgi.service.component.annotations.Component;
import org.osgi.service.component.annotations.Reference;
/**
* The {@link IAqualinkHandlerFactory} is responsible for creating things and
* thing handlers.
*
* @author Dan Cunningham - Initial contribution
*/
@NonNullByDefault
@Component(service = ThingHandlerFactory.class, configurationPid = "binding.iaqualink")
public class IAqualinkHandlerFactory extends BaseThingHandlerFactory {
private @NonNullByDefault({}) HttpClient httpClient;
@Override
public boolean supportsThingType(ThingTypeUID thingTypeUID) {
return IAQUALINK_DEVICE_THING_TYPE_UID.equals(thingTypeUID);
}
@Override
protected @Nullable ThingHandler createHandler(Thing thing) {
ThingTypeUID thingTypeUID = thing.getThingTypeUID();
if (IAQUALINK_DEVICE_THING_TYPE_UID.equals(thingTypeUID)) {
return new IAqualinkHandler(thing, httpClient);
}
return null;
}
@Reference
protected void setHttpClientFactory(HttpClientFactory httpClientFactory) {
this.httpClient = httpClientFactory.getCommonHttpClient();
}
protected void unsetHttpClientFactory(HttpClientFactory httpClientFactory) {
this.httpClient = null;
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.jpa.container.core/src/com/ibm/ws/jpa/JPAVersion.java | 1890 | /*******************************************************************************
* Copyright (c) 2015 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.jpa;
public enum JPAVersion {
UNKNOWN(1, "Unknown"),
JPA20(6, "2.0"),
JPA21(7, "2.1"),
JPA22(8, "2.2"),
JPA30(9, "3.0");
private final int jeeSpecLevel;
private final String versionStr;
private JPAVersion(int jeeSpecLevel, String versionStr) {
this.jeeSpecLevel = jeeSpecLevel;
this.versionStr = versionStr;
}
public int getJeeSpecLevel() {
return jeeSpecLevel;
}
public String getVersionStr() {
return versionStr;
}
public boolean greaterThan(JPAVersion jpaVersionObj) {
if (jpaVersionObj == null) {
return false;
}
return jeeSpecLevel > jpaVersionObj.getJeeSpecLevel();
}
public boolean greaterThanOrEquals(JPAVersion jpaVersionObj) {
if (jpaVersionObj == null) {
return false;
}
return jeeSpecLevel >= jpaVersionObj.getJeeSpecLevel();
}
public boolean lesserThan(JPAVersion jpaVersionObj) {
if (jpaVersionObj == null) {
return false;
}
return jeeSpecLevel < jpaVersionObj.getJeeSpecLevel();
}
public boolean lesserThanOrEquals(JPAVersion jpaVersionObj) {
if (jpaVersionObj == null) {
return false;
}
return jeeSpecLevel <= jpaVersionObj.getJeeSpecLevel();
}
} | epl-1.0 |
eclipse/hawkbit | hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/event/remote/AbstractRemoteEventTest.java | 4192 | /**
* 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.repository.event.remote;
import static org.junit.jupiter.api.Assertions.fail;
import java.util.Map;
import org.eclipse.hawkbit.event.BusProtoStuffMessageConverter;
import org.eclipse.hawkbit.repository.event.TenantAwareEvent;
import org.eclipse.hawkbit.repository.jpa.AbstractJpaIntegrationTest;
import org.junit.jupiter.api.BeforeEach;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.bus.event.RemoteApplicationEvent;
import org.springframework.cloud.bus.jackson.BusJacksonAutoConfiguration;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.integration.support.MutableMessageHeaders;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.converter.AbstractMessageConverter;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.util.ClassUtils;
import org.springframework.util.MimeType;
import org.springframework.util.MimeTypeUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
/**
* Test the remote entity events.
*/
public abstract class AbstractRemoteEventTest extends AbstractJpaIntegrationTest {
@Autowired
private BusProtoStuffMessageConverter busProtoStuffMessageConverter;
private AbstractMessageConverter jacksonMessageConverter;
@BeforeEach
public void setup() throws Exception {
final BusJacksonAutoConfiguration autoConfiguration = new BusJacksonAutoConfiguration();
this.jacksonMessageConverter = autoConfiguration.busJsonConverter(null);
ReflectionTestUtils.setField(jacksonMessageConverter, "packagesToScan",
new String[] { "org.eclipse.hawkbit.repository.event.remote",
ClassUtils.getPackageName(RemoteApplicationEvent.class) });
((InitializingBean) jacksonMessageConverter).afterPropertiesSet();
}
private Message<?> createProtoStuffMessage(final TenantAwareEvent event) {
final Map<String, Object> headers = Maps.newLinkedHashMap();
headers.put(MessageHeaders.CONTENT_TYPE, BusProtoStuffMessageConverter.APPLICATION_BINARY_PROTOSTUFF);
return busProtoStuffMessageConverter.toMessage(event, new MutableMessageHeaders(headers));
}
private Message<String> createJsonMessage(final Object event) {
final Map<String, MimeType> headers = Maps.newLinkedHashMap();
headers.put(MessageHeaders.CONTENT_TYPE, MimeTypeUtils.APPLICATION_JSON);
try {
final String json = new ObjectMapper().writeValueAsString(event);
final Message<String> message = MessageBuilder.withPayload(json).copyHeaders(headers).build();
return message;
} catch (final JsonProcessingException e) {
fail(e.getMessage());
}
return null;
}
protected Message<?> createMessageWithImmutableHeader(final TenantAwareEvent event) {
final Map<String, Object> headers = Maps.newLinkedHashMap();
return busProtoStuffMessageConverter.toMessage(event, new MessageHeaders(headers));
}
@SuppressWarnings("unchecked")
protected <T extends TenantAwareEvent> T createJacksonEvent(final T event) {
final Message<String> message = createJsonMessage(event);
return (T) jacksonMessageConverter.fromMessage(message, event.getClass());
}
@SuppressWarnings("unchecked")
protected <T extends TenantAwareEvent> T createProtoStuffEvent(final T event) {
final Message<?> message = createProtoStuffMessage(event);
return (T) busProtoStuffMessageConverter.fromMessage(message, event.getClass());
}
}
| epl-1.0 |
AnthonyHullDiamond/scanning | org.eclipse.scanning.test/src/org/eclipse/scanning/test/event/queues/QueueTest.java | 4797 | /*-
*******************************************************************************
* Copyright (c) 2011, 2016 Diamond Light Source Ltd.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Matthew Gerring - initial API and implementation and/or initial documentation
*******************************************************************************/
package org.eclipse.scanning.test.event.queues;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import java.net.URI;
import org.eclipse.scanning.api.event.EventException;
import org.eclipse.scanning.api.event.queues.IQueue;
import org.eclipse.scanning.api.event.queues.QueueStatus;
import org.eclipse.scanning.api.event.queues.beans.Queueable;
import org.eclipse.scanning.event.queues.Queue;
import org.eclipse.scanning.event.queues.ServicesHolder;
import org.eclipse.scanning.test.event.queues.dummy.DummyBean;
import org.eclipse.scanning.test.event.queues.mocks.MockConsumer;
import org.eclipse.scanning.test.event.queues.mocks.MockEventService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class QueueTest {
private MockConsumer<DummyBean> mockCons;
private MockEventService mockEvServ;
private String qRoot = "test-queue";
private URI uri;
@Before
public void setUp() throws Exception {
mockEvServ = new MockEventService();
mockCons = new MockConsumer<>();
mockEvServ.setMockConsumer(mockCons);
ServicesHolder.setEventService(mockEvServ);
uri = new URI("file:///foo/bar");
}
@After
public void tearDown() {
uri = null;
mockCons = null;
mockEvServ = null;
ServicesHolder.setEventService(null);
}
/**
* Test the correct instantiation of the Queue object.
* @throws EventException
*/
@Test
public void testQueueConfig() throws EventException {
IQueue<Queueable> testQueue = new Queue<>(qRoot, uri);
assertEquals("Queue has wrong status", QueueStatus.INITIALISED, testQueue.getStatus());
//Test we're setting destination names correctly on construction
assertEquals("Configured & expected submit queue names differ", qRoot+IQueue.SUBMISSION_QUEUE_SUFFIX, testQueue.getSubmissionQueueName());
assertEquals("Configured & expected status set names differ", qRoot+IQueue.STATUS_SET_SUFFIX, testQueue.getStatusSetName());
assertEquals("Configured & expected status topic names differ", qRoot+IQueue.STATUS_TOPIC_SUFFIX, testQueue.getStatusTopicName());
assertEquals("Configured & expected heartbeat topic names differ", qRoot+IQueue.HEARTBEAT_TOPIC_SUFFIX, testQueue.getHeartbeatTopicName());
assertEquals("Configured & expected command set names differ", qRoot+IQueue.COMMAND_SET_SUFFIX, testQueue.getCommandSetName());
assertEquals("Configured & expected command topic names differ", qRoot+IQueue.COMMAND_TOPIC_SUFFIX, testQueue.getCommandTopicName());
//Test the consumer name & ID are being set on construction
assertEquals("Consumer name not set correctly", qRoot, mockCons.getName());
assertEquals("Consumer ID not recorded in Queue", mockCons.getConsumerId(), testQueue.getConsumerID());
}
/**
* Test that queues can be cleared
* @throws EventException
*/
@Test
public void testClearQueues() throws EventException {
IQueue<Queueable> testQueue = new Queue<>(qRoot, uri);
boolean cleared = testQueue.clearQueues();
assertTrue("Status queue not cleared", mockCons.isClearStatQueue());
assertTrue("Submit queue not cleared", mockCons.isClearSubmitQueue());
assertTrue("clearQueues failed to clear", cleared);
}
/**
* Tests starting & stopping the consumer through the Queue
* @throws EventException
*/
@Test
public void testStartStop() throws EventException {
IQueue<Queueable> testQueue = new Queue<>(qRoot, uri);
testQueue.start();
assertTrue("Consumer start has not been called", mockCons.isStarted());
assertEquals("Queue has wrong status", QueueStatus.STARTED, testQueue.getStatus());
testQueue.stop();
assertTrue("Consumer stop has not been called", mockCons.isStopped());
assertEquals("Queue has wrong status", QueueStatus.STOPPED, testQueue.getStatus());
}
/**
* Tests disconnecting the consumer (and heartbeat monitor) through the Queue
* @throws EventException
*/
@Test
public void testDisconnect() throws EventException {
IQueue<Queueable> testQueue = new Queue<>(qRoot, uri);
testQueue.disconnect();
assertTrue("Consumer disconnect has not been called", mockCons.isDisconnected());
assertEquals("Queue has wrong status", QueueStatus.DISPOSED, testQueue.getStatus());
}
}
| epl-1.0 |
mballance/egtkwave | gtkwave/gtkwave-3.3.52/contrib/fst_jni/fstAttrType.java | 1516 | /*
* Copyright (c) 2013 Tony Bybell.
*
* 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.
*/
public class fstAttrType
{
private fstAttrType( ) { }
public static final String [] FST_AT_NAMESTRINGS =
{ "misc", "array", "enum", "class" };
public static final int FST_AT_MIN = 0;
public static final int FST_AT_MISC = 0;
public static final int FST_AT_ARRAY = 1;
public static final int FST_AT_ENUM = 2;
public static final int FST_AT_PACK = 3;
public static final int FST_AT_MAX = 3;
};
| epl-1.0 |
kgibm/open-liberty | dev/com.ibm.ws.microprofile.openapi.1.1.model/src/com/ibm/ws/microprofile/openapi/impl/model/responses/package-info.java | 851 | /*******************************************************************************
* Copyright (c) 2017, 2019 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/**
* @version 1.0
*/
@org.osgi.annotation.versioning.Version("1.0")
@TraceOptions(traceGroup = "MPOPENAPI", messageBundle = "io.openliberty.microprofile.openapi.internal.resources.OpenAPI")
package com.ibm.ws.microprofile.openapi.impl.model.responses;
import com.ibm.websphere.ras.annotation.TraceOptions;
| epl-1.0 |
paulianttila/openhab2 | bundles/org.openhab.binding.solaredge/src/main/java/org/openhab/binding/solaredge/internal/handler/SolarEdgeBaseHandler.java | 5643 | /**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.solaredge.internal.handler;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
import org.eclipse.jetty.client.HttpClient;
import org.openhab.binding.solaredge.internal.AtomicReferenceTrait;
import org.openhab.binding.solaredge.internal.config.SolarEdgeConfiguration;
import org.openhab.binding.solaredge.internal.connector.WebInterface;
import org.openhab.core.thing.Channel;
import org.openhab.core.thing.ChannelUID;
import org.openhab.core.thing.Thing;
import org.openhab.core.thing.ThingStatus;
import org.openhab.core.thing.ThingStatusDetail;
import org.openhab.core.thing.binding.BaseThingHandler;
import org.openhab.core.types.Command;
import org.openhab.core.types.State;
import org.openhab.core.types.UnDefType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The {@link SolarEdgeBaseHandler} is responsible for handling commands, which are
* sent to one of the channels.
*
* @author Alexander Friese - initial contribution
*/
@NonNullByDefault
public abstract class SolarEdgeBaseHandler extends BaseThingHandler implements SolarEdgeHandler, AtomicReferenceTrait {
private final Logger logger = LoggerFactory.getLogger(SolarEdgeBaseHandler.class);
private final long LIVE_POLLING_INITIAL_DELAY = 1;
private final long AGGREGATE_POLLING_INITIAL_DELAY = 2;
/**
* Interface object for querying the Solaredge web interface
*/
private WebInterface webInterface;
/**
* Schedule for polling live data
*/
private final AtomicReference<@Nullable Future<?>> liveDataPollingJobReference;
/**
* Schedule for polling aggregate data
*/
private final AtomicReference<@Nullable Future<?>> aggregateDataPollingJobReference;
public SolarEdgeBaseHandler(Thing thing, HttpClient httpClient) {
super(thing);
this.webInterface = new WebInterface(scheduler, this, httpClient);
this.liveDataPollingJobReference = new AtomicReference<>(null);
this.aggregateDataPollingJobReference = new AtomicReference<>(null);
}
@Override
public void handleCommand(ChannelUID channelUID, Command command) {
logger.debug("command for {}: {}", channelUID, command);
// write access is not supported.
}
@Override
public void initialize() {
logger.debug("About to initialize SolarEdge");
SolarEdgeConfiguration config = getConfiguration();
logger.debug("Solaredge initialized with configuration: {}", config);
startPolling();
webInterface.start();
updateStatus(ThingStatus.UNKNOWN, ThingStatusDetail.NONE, "waiting for web api login");
}
/**
* Start the polling.
*/
private void startPolling() {
updateJobReference(liveDataPollingJobReference,
scheduler.scheduleWithFixedDelay(new SolarEdgeLiveDataPolling(this), LIVE_POLLING_INITIAL_DELAY,
getConfiguration().getLiveDataPollingInterval(), TimeUnit.MINUTES));
updateJobReference(aggregateDataPollingJobReference,
scheduler.scheduleWithFixedDelay(new SolarEdgeAggregateDataPolling(this),
AGGREGATE_POLLING_INITIAL_DELAY, getConfiguration().getAggregateDataPollingInterval(),
TimeUnit.MINUTES));
}
/**
* Disposes the bridge.
*/
@Override
public void dispose() {
logger.debug("Handler disposed.");
cancelJobReference(liveDataPollingJobReference);
cancelJobReference(aggregateDataPollingJobReference);
webInterface.dispose();
}
@Override
public WebInterface getWebInterface() {
return webInterface;
}
/**
* will update all channels provided in the map
*/
@Override
public void updateChannelStatus(Map<Channel, State> values) {
logger.debug("Handling channel update.");
for (Channel channel : values.keySet()) {
if (getChannels().contains(channel)) {
State value = values.get(channel);
if (value != null) {
logger.debug("Channel is to be updated: {}: {}", channel.getUID().getAsString(), value);
updateState(channel.getUID(), value);
} else {
logger.debug("Value is null or not provided by solaredge (channel: {})",
channel.getUID().getAsString());
updateState(channel.getUID(), UnDefType.UNDEF);
}
} else {
logger.debug("Could not identify channel: {} for model {}", channel.getUID().getAsString(),
getThing().getThingTypeUID().getAsString());
}
}
}
@Override
public void setStatusInfo(ThingStatus status, ThingStatusDetail statusDetail, String description) {
super.updateStatus(status, statusDetail, description);
}
@Override
public SolarEdgeConfiguration getConfiguration() {
return this.getConfigAs(SolarEdgeConfiguration.class);
}
}
| epl-1.0 |
OpenLiberty/open-liberty | dev/com.ibm.ws.ejbcontainer.core/src/com/ibm/websphere/cpmi/PMModuleCookie.java | 715 | /*******************************************************************************
* Copyright (c) 2001 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.websphere.cpmi;
/**
* To differentiate multiple installations of same module. Uniquely identifies
* a module "instance".
**/
public interface PMModuleCookie
{}
| epl-1.0 |
Mirage20/che | wsmaster/che-core-api-machine/src/main/java/org/eclipse/che/api/machine/server/recipe/RecipeService.java | 8543 | /*******************************************************************************
* 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.api.machine.server.recipe;
import org.eclipse.che.api.core.ApiException;
import org.eclipse.che.api.core.BadRequestException;
import org.eclipse.che.api.core.rest.Service;
import org.eclipse.che.api.core.rest.annotations.GenerateLink;
import org.eclipse.che.api.core.rest.shared.dto.Link;
import org.eclipse.che.api.core.util.LinksHelper;
import org.eclipse.che.api.machine.server.spi.RecipeDao;
import org.eclipse.che.api.machine.shared.ManagedRecipe;
import org.eclipse.che.api.machine.shared.dto.recipe.NewRecipe;
import org.eclipse.che.api.machine.shared.dto.recipe.RecipeDescriptor;
import org.eclipse.che.api.machine.shared.dto.recipe.RecipeUpdate;
import org.eclipse.che.commons.env.EnvironmentContext;
import org.eclipse.che.commons.lang.NameGenerator;
import org.eclipse.che.dto.server.DtoFactory;
import javax.inject.Inject;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.DefaultValue;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriBuilder;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.stream.Collectors;
import static com.google.common.base.Strings.isNullOrEmpty;
import static java.util.Arrays.asList;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
import static javax.ws.rs.core.MediaType.TEXT_PLAIN;
import static javax.ws.rs.core.Response.Status.CREATED;
import static org.eclipse.che.api.machine.shared.Constants.LINK_REL_CREATE_RECIPE;
import static org.eclipse.che.api.machine.shared.Constants.LINK_REL_GET_RECIPE_SCRIPT;
import static org.eclipse.che.api.machine.shared.Constants.LINK_REL_REMOVE_RECIPE;
import static org.eclipse.che.api.machine.shared.Constants.LINK_REL_SEARCH_RECIPES;
import static org.eclipse.che.api.machine.shared.Constants.LINK_REL_UPDATE_RECIPE;
/**
* Recipe API
*
* @author Eugene Voevodin
*/
@Path("/recipe")
public class RecipeService extends Service {
private final RecipeDao recipeDao;
@Inject
public RecipeService(RecipeDao recipeDao) {
this.recipeDao = recipeDao;
}
@POST
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@GenerateLink(rel = LINK_REL_CREATE_RECIPE)
public Response createRecipe(NewRecipe newRecipe) throws ApiException {
if (newRecipe == null) {
throw new BadRequestException("Recipe required");
}
if (isNullOrEmpty(newRecipe.getType())) {
throw new BadRequestException("Recipe type required");
}
if (isNullOrEmpty(newRecipe.getScript())) {
throw new BadRequestException("Recipe script required");
}
if (isNullOrEmpty(newRecipe.getName())) {
throw new BadRequestException("Recipe name required");
}
String userId = EnvironmentContext.getCurrent().getSubject().getUserId();
final RecipeImpl recipe = new RecipeImpl().withId(NameGenerator.generate("recipe", 16))
.withName(newRecipe.getName())
.withCreator(userId)
.withType(newRecipe.getType())
.withScript(newRecipe.getScript())
.withTags(newRecipe.getTags());
recipeDao.create(recipe);
return Response.status(CREATED)
.entity(asRecipeDescriptor(recipe))
.build();
}
@GET
@Path("/{id}/script")
public Response getRecipeScript(@PathParam("id") String id) throws ApiException, UnsupportedEncodingException {
// Do not remove!
// Docker can not use dockerfile in some cases without content-length header.
final ManagedRecipe recipe = recipeDao.getById(id);
byte[] script = recipe.getScript().getBytes("UTF-8");
return Response.ok(script, MediaType.TEXT_PLAIN)
.header(HttpHeaders.CONTENT_LENGTH, script.length)
.build();
}
@GET
@Path("/{id}")
@Produces(APPLICATION_JSON)
public RecipeDescriptor getRecipe(@PathParam("id") String id) throws ApiException {
return asRecipeDescriptor(recipeDao.getById(id));
}
@GET
@Produces(APPLICATION_JSON)
@GenerateLink(rel = LINK_REL_SEARCH_RECIPES)
public List<RecipeDescriptor> searchRecipes(@QueryParam("tags") List<String> tags,
@QueryParam("type") String type,
@DefaultValue("0") @QueryParam("skipCount") Integer skipCount,
@DefaultValue("30") @QueryParam("maxItems") Integer maxItems) throws ApiException {
final String currentUser = EnvironmentContext.getCurrent().getSubject().getUserId();
return recipeDao.search(currentUser, tags, type, skipCount, maxItems)
.stream()
.map(this::asRecipeDescriptor)
.collect(Collectors.toList());
}
@PUT
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@GenerateLink(rel = LINK_REL_UPDATE_RECIPE)
public RecipeDescriptor updateRecipe(RecipeUpdate update) throws ApiException {
if (update == null) {
throw new BadRequestException("Update required");
}
if (update.getId() == null) {
throw new BadRequestException("Recipe id required");
}
return asRecipeDescriptor(recipeDao.update(new RecipeImpl(update)));
}
@DELETE
@Path("/{id}")
public void removeRecipe(@PathParam("id") String id) throws ApiException {
recipeDao.remove(id);
}
/**
* Transforms {@link ManagedRecipe} to {@link RecipeDescriptor}.
*/
private RecipeDescriptor asRecipeDescriptor(ManagedRecipe recipe) {
final RecipeDescriptor descriptor = DtoFactory.getInstance()
.createDto(RecipeDescriptor.class)
.withId(recipe.getId())
.withName(recipe.getName())
.withType(recipe.getType())
.withScript(recipe.getScript())
.withCreator(recipe.getCreator())
.withTags(recipe.getTags());
final UriBuilder builder = getServiceContext().getServiceUriBuilder();
final Link removeLink = LinksHelper.createLink("DELETE",
builder.clone()
.path(getClass(), "removeRecipe")
.build(recipe.getId())
.toString(),
LINK_REL_REMOVE_RECIPE);
final Link scriptLink = LinksHelper.createLink("GET",
builder.clone()
.path(getClass(), "getRecipeScript")
.build(recipe.getId())
.toString(),
TEXT_PLAIN,
LINK_REL_GET_RECIPE_SCRIPT);
descriptor.setLinks(asList(scriptLink, removeLink));
return descriptor;
}
}
| epl-1.0 |
magiclud/decorator | src/main/java/eu/jpereira/trainings/designpatterns/structural/decorator/SocialPublisher.java | 1829 | /**
* Copyright 2011 Joao Miguel Pereira
*
* 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 eu.jpereira.trainings.designpatterns.structural.decorator;
import java.util.ArrayList;
import java.util.List;
import eu.jpereira.trainings.designpatterns.structural.decorator.channel.SocialChannel;
/**
* @author jpereira
*
*/
public class SocialPublisher {
private List<SocialChannel> channels;
public SocialPublisher() {
this.channels = createSocialChannelList();
}
/**
* @param textMessage
*/
public void publish(String textMessage) {
//For each channels, deliver the message
for (SocialChannel channel : this.channels ) {
channel.deliverMessage(textMessage);
}
}
/**
* @return
*/
public int getSocialChannelsCount() {
return this.channels.size();
}
/**
* @param channel
*/
public void addSocialChannel(SocialChannel channel) {
this.channels.add(channel);
}
/**
* Factory method
*
* @return
*/
protected List<SocialChannel> createSocialChannelList() {
return new ArrayList<SocialChannel>();
}
/**
* @param channel
* @return
*/
public boolean removeChannel(SocialChannel channel) {
boolean removed = false;
if (this.channels.contains(channel)) {
this.channels.remove(channel);
removed = true;
}
return removed;
}
}
| epl-1.0 |
iammyr/Benchmark | src/main/java/org/owasp/benchmark/testcode/BenchmarkTest09665.java | 2402 | /**
* 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("/BenchmarkTest09665")
public class BenchmarkTest09665 extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
@Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String param = "";
java.util.Enumeration<String> headers = request.getHeaders("foo");
if (headers.hasMoreElements()) {
param = headers.nextElement(); // just grab first element
}
String bar = new Test().doSomething(param);
String sql = "SELECT * from USERS where USERNAME=? and PASSWORD='"+ bar +"'";
try {
java.sql.Connection connection = org.owasp.benchmark.helpers.DatabaseHelper.getSqlConnection();
java.sql.PreparedStatement statement = connection.prepareStatement( sql );
statement.setString(1, "foo");
statement.execute();
} catch (java.sql.SQLException e) {
throw new ServletException(e);
}
} // end doPost
private class Test {
public String doSomething(String param) throws ServletException, IOException {
String bar = param;
return bar;
}
} // end innerclass Test
} // end DataflowThruInnerClass
| gpl-2.0 |
ojdkbuild/lookaside_java-1.8.0-openjdk | jdk/src/share/classes/sun/awt/ExtendedKeyCodes.java | 35008 | /*
* Copyright (c) 2009, 2018, 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.awt;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.awt.event.KeyEvent;
public class ExtendedKeyCodes {
/**
* ATTN: These are the readonly hashes with load factor == 1;
* adding a value, please set the inital capacity to exact number of items
* or higher.
*/
// Keycodes declared in KeyEvent.java with corresponding Unicode values.
private final static HashMap<Integer, Integer> regularKeyCodesMap =
new HashMap<Integer,Integer>(98, 1.0f);
// Keycodes derived from Unicode values. Here should be collected codes
// for characters appearing on the primary layer of at least one
// known keyboard layout. For instance, sterling sign is on the primary layer
// of the Mac Italian layout.
private final static HashSet<Integer> extendedKeyCodesSet =
new HashSet<Integer>(501, 1.0f);
final public static int getExtendedKeyCodeForChar( int c ) {
int uc = Character.toUpperCase( c );
int lc = Character.toLowerCase( c );
if (regularKeyCodesMap.containsKey( c )) {
if(regularKeyCodesMap.containsKey(uc)) {
return regularKeyCodesMap.get( uc );
}
return regularKeyCodesMap.get( c );
}
uc += 0x01000000;
lc += 0x01000000;
if (extendedKeyCodesSet.contains( uc )) {
return uc;
}else if (extendedKeyCodesSet.contains( lc )) {
return lc;
}
return KeyEvent.VK_UNDEFINED;
}
static {
regularKeyCodesMap.put(0x08, KeyEvent.VK_BACK_SPACE);
regularKeyCodesMap.put(0x09, KeyEvent.VK_TAB);
regularKeyCodesMap.put(0x0a, KeyEvent.VK_ENTER);
regularKeyCodesMap.put(0x1B, KeyEvent.VK_ESCAPE);
regularKeyCodesMap.put(0x20AC, KeyEvent.VK_EURO_SIGN);
regularKeyCodesMap.put(0x20, KeyEvent.VK_SPACE);
regularKeyCodesMap.put(0x21, KeyEvent.VK_EXCLAMATION_MARK);
regularKeyCodesMap.put(0x22, KeyEvent.VK_QUOTEDBL);
regularKeyCodesMap.put(0x23, KeyEvent.VK_NUMBER_SIGN);
regularKeyCodesMap.put(0x24, KeyEvent.VK_DOLLAR);
regularKeyCodesMap.put(0x26, KeyEvent.VK_AMPERSAND);
regularKeyCodesMap.put(0x27, KeyEvent.VK_QUOTE);
regularKeyCodesMap.put(0x28, KeyEvent.VK_LEFT_PARENTHESIS);
regularKeyCodesMap.put(0x29, KeyEvent.VK_RIGHT_PARENTHESIS);
regularKeyCodesMap.put(0x2A, KeyEvent.VK_ASTERISK);
regularKeyCodesMap.put(0x2B, KeyEvent.VK_PLUS);
regularKeyCodesMap.put(0x2C, KeyEvent.VK_COMMA);
regularKeyCodesMap.put(0x2D, KeyEvent.VK_MINUS);
regularKeyCodesMap.put(0x2E, KeyEvent.VK_PERIOD);
regularKeyCodesMap.put(0x2F, KeyEvent.VK_SLASH);
regularKeyCodesMap.put(0x30, KeyEvent.VK_0);
regularKeyCodesMap.put(0x31, KeyEvent.VK_1);
regularKeyCodesMap.put(0x32, KeyEvent.VK_2);
regularKeyCodesMap.put(0x33, KeyEvent.VK_3);
regularKeyCodesMap.put(0x34, KeyEvent.VK_4);
regularKeyCodesMap.put(0x35, KeyEvent.VK_5);
regularKeyCodesMap.put(0x36, KeyEvent.VK_6);
regularKeyCodesMap.put(0x37, KeyEvent.VK_7);
regularKeyCodesMap.put(0x38, KeyEvent.VK_8);
regularKeyCodesMap.put(0x39, KeyEvent.VK_9);
regularKeyCodesMap.put(0x3A, KeyEvent.VK_COLON);
regularKeyCodesMap.put(0x3B, KeyEvent.VK_SEMICOLON);
regularKeyCodesMap.put(0x3C, KeyEvent.VK_LESS);
regularKeyCodesMap.put(0x3D, KeyEvent.VK_EQUALS);
regularKeyCodesMap.put(0x3E, KeyEvent.VK_GREATER);
regularKeyCodesMap.put(0x40, KeyEvent.VK_AT);
regularKeyCodesMap.put(0x41, KeyEvent.VK_A);
regularKeyCodesMap.put(0x42, KeyEvent.VK_B);
regularKeyCodesMap.put(0x43, KeyEvent.VK_C);
regularKeyCodesMap.put(0x44, KeyEvent.VK_D);
regularKeyCodesMap.put(0x45, KeyEvent.VK_E);
regularKeyCodesMap.put(0x46, KeyEvent.VK_F);
regularKeyCodesMap.put(0x47, KeyEvent.VK_G);
regularKeyCodesMap.put(0x48, KeyEvent.VK_H);
regularKeyCodesMap.put(0x49, KeyEvent.VK_I);
regularKeyCodesMap.put(0x4A, KeyEvent.VK_J);
regularKeyCodesMap.put(0x4B, KeyEvent.VK_K);
regularKeyCodesMap.put(0x4C, KeyEvent.VK_L);
regularKeyCodesMap.put(0x4D, KeyEvent.VK_M);
regularKeyCodesMap.put(0x4E, KeyEvent.VK_N);
regularKeyCodesMap.put(0x4F, KeyEvent.VK_O);
regularKeyCodesMap.put(0x50, KeyEvent.VK_P);
regularKeyCodesMap.put(0x51, KeyEvent.VK_Q);
regularKeyCodesMap.put(0x52, KeyEvent.VK_R);
regularKeyCodesMap.put(0x53, KeyEvent.VK_S);
regularKeyCodesMap.put(0x54, KeyEvent.VK_T);
regularKeyCodesMap.put(0x55, KeyEvent.VK_U);
regularKeyCodesMap.put(0x56, KeyEvent.VK_V);
regularKeyCodesMap.put(0x57, KeyEvent.VK_W);
regularKeyCodesMap.put(0x58, KeyEvent.VK_X);
regularKeyCodesMap.put(0x59, KeyEvent.VK_Y);
regularKeyCodesMap.put(0x5A, KeyEvent.VK_Z);
regularKeyCodesMap.put(0x5B, KeyEvent.VK_OPEN_BRACKET);
regularKeyCodesMap.put(0x5C, KeyEvent.VK_BACK_SLASH);
regularKeyCodesMap.put(0x5D, KeyEvent.VK_CLOSE_BRACKET);
regularKeyCodesMap.put(0x5E, KeyEvent.VK_CIRCUMFLEX);
regularKeyCodesMap.put(0x5F, KeyEvent.VK_UNDERSCORE);
regularKeyCodesMap.put(0x60, KeyEvent.VK_BACK_QUOTE);
regularKeyCodesMap.put(0x61, KeyEvent.VK_A);
regularKeyCodesMap.put(0x62, KeyEvent.VK_B);
regularKeyCodesMap.put(0x63, KeyEvent.VK_C);
regularKeyCodesMap.put(0x64, KeyEvent.VK_D);
regularKeyCodesMap.put(0x65, KeyEvent.VK_E);
regularKeyCodesMap.put(0x66, KeyEvent.VK_F);
regularKeyCodesMap.put(0x67, KeyEvent.VK_G);
regularKeyCodesMap.put(0x68, KeyEvent.VK_H);
regularKeyCodesMap.put(0x69, KeyEvent.VK_I);
regularKeyCodesMap.put(0x6A, KeyEvent.VK_J);
regularKeyCodesMap.put(0x6B, KeyEvent.VK_K);
regularKeyCodesMap.put(0x6C, KeyEvent.VK_L);
regularKeyCodesMap.put(0x6D, KeyEvent.VK_M);
regularKeyCodesMap.put(0x6E, KeyEvent.VK_N);
regularKeyCodesMap.put(0x6F, KeyEvent.VK_O);
regularKeyCodesMap.put(0x70, KeyEvent.VK_P);
regularKeyCodesMap.put(0x71, KeyEvent.VK_Q);
regularKeyCodesMap.put(0x72, KeyEvent.VK_R);
regularKeyCodesMap.put(0x73, KeyEvent.VK_S);
regularKeyCodesMap.put(0x74, KeyEvent.VK_T);
regularKeyCodesMap.put(0x75, KeyEvent.VK_U);
regularKeyCodesMap.put(0x76, KeyEvent.VK_V);
regularKeyCodesMap.put(0x77, KeyEvent.VK_W);
regularKeyCodesMap.put(0x78, KeyEvent.VK_X);
regularKeyCodesMap.put(0x79, KeyEvent.VK_Y);
regularKeyCodesMap.put(0x7A, KeyEvent.VK_Z);
regularKeyCodesMap.put(0x7B, KeyEvent.VK_BRACELEFT);
regularKeyCodesMap.put(0x7D, KeyEvent.VK_BRACERIGHT);
regularKeyCodesMap.put(0x7F, KeyEvent.VK_DELETE);
regularKeyCodesMap.put(0xA1, KeyEvent.VK_INVERTED_EXCLAMATION_MARK);
extendedKeyCodesSet.add(0x01000000+0x0060);
extendedKeyCodesSet.add(0x01000000+0x007C);
extendedKeyCodesSet.add(0x01000000+0x007E);
extendedKeyCodesSet.add(0x01000000+0x00A2);
extendedKeyCodesSet.add(0x01000000+0x00A3);
extendedKeyCodesSet.add(0x01000000+0x00A5);
extendedKeyCodesSet.add(0x01000000+0x00A7);
extendedKeyCodesSet.add(0x01000000+0x00A8);
extendedKeyCodesSet.add(0x01000000+0x00AB);
extendedKeyCodesSet.add(0x01000000+0x00B0);
extendedKeyCodesSet.add(0x01000000+0x00B1);
extendedKeyCodesSet.add(0x01000000+0x00B2);
extendedKeyCodesSet.add(0x01000000+0x00B3);
extendedKeyCodesSet.add(0x01000000+0x00B4);
extendedKeyCodesSet.add(0x01000000+0x00B5);
extendedKeyCodesSet.add(0x01000000+0x00B6);
extendedKeyCodesSet.add(0x01000000+0x00B7);
extendedKeyCodesSet.add(0x01000000+0x00B9);
extendedKeyCodesSet.add(0x01000000+0x00BA);
extendedKeyCodesSet.add(0x01000000+0x00BB);
extendedKeyCodesSet.add(0x01000000+0x00BC);
extendedKeyCodesSet.add(0x01000000+0x00BD);
extendedKeyCodesSet.add(0x01000000+0x00BE);
extendedKeyCodesSet.add(0x01000000+0x00BF);
extendedKeyCodesSet.add(0x01000000+0x00C4);
extendedKeyCodesSet.add(0x01000000+0x00C5);
extendedKeyCodesSet.add(0x01000000+0x00C6);
extendedKeyCodesSet.add(0x01000000+0x00C7);
extendedKeyCodesSet.add(0x01000000+0x00D1);
extendedKeyCodesSet.add(0x01000000+0x00D6);
extendedKeyCodesSet.add(0x01000000+0x00D7);
extendedKeyCodesSet.add(0x01000000+0x00D8);
extendedKeyCodesSet.add(0x01000000+0x00DF);
extendedKeyCodesSet.add(0x01000000+0x00E0);
extendedKeyCodesSet.add(0x01000000+0x00E1);
extendedKeyCodesSet.add(0x01000000+0x00E2);
extendedKeyCodesSet.add(0x01000000+0x00E4);
extendedKeyCodesSet.add(0x01000000+0x00E5);
extendedKeyCodesSet.add(0x01000000+0x00E6);
extendedKeyCodesSet.add(0x01000000+0x00E7);
extendedKeyCodesSet.add(0x01000000+0x00E8);
extendedKeyCodesSet.add(0x01000000+0x00E9);
extendedKeyCodesSet.add(0x01000000+0x00EA);
extendedKeyCodesSet.add(0x01000000+0x00EB);
extendedKeyCodesSet.add(0x01000000+0x00EC);
extendedKeyCodesSet.add(0x01000000+0x00ED);
extendedKeyCodesSet.add(0x01000000+0x00EE);
extendedKeyCodesSet.add(0x01000000+0x00F0);
extendedKeyCodesSet.add(0x01000000+0x00F1);
extendedKeyCodesSet.add(0x01000000+0x00F2);
extendedKeyCodesSet.add(0x01000000+0x00F3);
extendedKeyCodesSet.add(0x01000000+0x00F4);
extendedKeyCodesSet.add(0x01000000+0x00F5);
extendedKeyCodesSet.add(0x01000000+0x00F6);
extendedKeyCodesSet.add(0x01000000+0x00F7);
extendedKeyCodesSet.add(0x01000000+0x00F8);
extendedKeyCodesSet.add(0x01000000+0x00F9);
extendedKeyCodesSet.add(0x01000000+0x00FA);
extendedKeyCodesSet.add(0x01000000+0x00FB);
extendedKeyCodesSet.add(0x01000000+0x00FC);
extendedKeyCodesSet.add(0x01000000+0x00FD);
extendedKeyCodesSet.add(0x01000000+0x00FE);
extendedKeyCodesSet.add(0x01000000+0x0105);
extendedKeyCodesSet.add(0x01000000+0x02DB);
extendedKeyCodesSet.add(0x01000000+0x0142);
extendedKeyCodesSet.add(0x01000000+0x013E);
extendedKeyCodesSet.add(0x01000000+0x015B);
extendedKeyCodesSet.add(0x01000000+0x0161);
extendedKeyCodesSet.add(0x01000000+0x015F);
extendedKeyCodesSet.add(0x01000000+0x0165);
extendedKeyCodesSet.add(0x01000000+0x017E);
extendedKeyCodesSet.add(0x01000000+0x017C);
extendedKeyCodesSet.add(0x01000000+0x0103);
extendedKeyCodesSet.add(0x01000000+0x0107);
extendedKeyCodesSet.add(0x01000000+0x010D);
extendedKeyCodesSet.add(0x01000000+0x0119);
extendedKeyCodesSet.add(0x01000000+0x011B);
extendedKeyCodesSet.add(0x01000000+0x0111);
extendedKeyCodesSet.add(0x01000000+0x0148);
extendedKeyCodesSet.add(0x01000000+0x0151);
extendedKeyCodesSet.add(0x01000000+0x0171);
extendedKeyCodesSet.add(0x01000000+0x0159);
extendedKeyCodesSet.add(0x01000000+0x016F);
extendedKeyCodesSet.add(0x01000000+0x0163);
extendedKeyCodesSet.add(0x01000000+0x02D9);
extendedKeyCodesSet.add(0x01000000+0x0130);
extendedKeyCodesSet.add(0x01000000+0x0127);
extendedKeyCodesSet.add(0x01000000+0x0125);
extendedKeyCodesSet.add(0x01000000+0x0131);
extendedKeyCodesSet.add(0x01000000+0x011F);
extendedKeyCodesSet.add(0x01000000+0x0135);
extendedKeyCodesSet.add(0x01000000+0x010B);
extendedKeyCodesSet.add(0x01000000+0x0109);
extendedKeyCodesSet.add(0x01000000+0x0121);
extendedKeyCodesSet.add(0x01000000+0x011D);
extendedKeyCodesSet.add(0x01000000+0x016D);
extendedKeyCodesSet.add(0x01000000+0x015D);
extendedKeyCodesSet.add(0x01000000+0x0138);
extendedKeyCodesSet.add(0x01000000+0x0157);
extendedKeyCodesSet.add(0x01000000+0x013C);
extendedKeyCodesSet.add(0x01000000+0x0113);
extendedKeyCodesSet.add(0x01000000+0x0123);
extendedKeyCodesSet.add(0x01000000+0x0167);
extendedKeyCodesSet.add(0x01000000+0x014B);
extendedKeyCodesSet.add(0x01000000+0x0101);
extendedKeyCodesSet.add(0x01000000+0x012F);
extendedKeyCodesSet.add(0x01000000+0x0117);
extendedKeyCodesSet.add(0x01000000+0x012B);
extendedKeyCodesSet.add(0x01000000+0x0146);
extendedKeyCodesSet.add(0x01000000+0x014D);
extendedKeyCodesSet.add(0x01000000+0x0137);
extendedKeyCodesSet.add(0x01000000+0x0173);
extendedKeyCodesSet.add(0x01000000+0x016B);
extendedKeyCodesSet.add(0x01000000+0x0153);
extendedKeyCodesSet.add(0x01000000+0x30FC);
extendedKeyCodesSet.add(0x01000000+0x30A2);
extendedKeyCodesSet.add(0x01000000+0x30A4);
extendedKeyCodesSet.add(0x01000000+0x30A6);
extendedKeyCodesSet.add(0x01000000+0x30A8);
extendedKeyCodesSet.add(0x01000000+0x30AA);
extendedKeyCodesSet.add(0x01000000+0x30AB);
extendedKeyCodesSet.add(0x01000000+0x30AD);
extendedKeyCodesSet.add(0x01000000+0x30AF);
extendedKeyCodesSet.add(0x01000000+0x30B1);
extendedKeyCodesSet.add(0x01000000+0x30B3);
extendedKeyCodesSet.add(0x01000000+0x30B5);
extendedKeyCodesSet.add(0x01000000+0x30B7);
extendedKeyCodesSet.add(0x01000000+0x30B9);
extendedKeyCodesSet.add(0x01000000+0x30BB);
extendedKeyCodesSet.add(0x01000000+0x30BD);
extendedKeyCodesSet.add(0x01000000+0x30BF);
extendedKeyCodesSet.add(0x01000000+0x30C1);
extendedKeyCodesSet.add(0x01000000+0x30C4);
extendedKeyCodesSet.add(0x01000000+0x30C6);
extendedKeyCodesSet.add(0x01000000+0x30C8);
extendedKeyCodesSet.add(0x01000000+0x30CA);
extendedKeyCodesSet.add(0x01000000+0x30CB);
extendedKeyCodesSet.add(0x01000000+0x30CC);
extendedKeyCodesSet.add(0x01000000+0x30CD);
extendedKeyCodesSet.add(0x01000000+0x30CE);
extendedKeyCodesSet.add(0x01000000+0x30CF);
extendedKeyCodesSet.add(0x01000000+0x30D2);
extendedKeyCodesSet.add(0x01000000+0x30D5);
extendedKeyCodesSet.add(0x01000000+0x30D8);
extendedKeyCodesSet.add(0x01000000+0x30DB);
extendedKeyCodesSet.add(0x01000000+0x30DE);
extendedKeyCodesSet.add(0x01000000+0x30DF);
extendedKeyCodesSet.add(0x01000000+0x30E0);
extendedKeyCodesSet.add(0x01000000+0x30E1);
extendedKeyCodesSet.add(0x01000000+0x30E2);
extendedKeyCodesSet.add(0x01000000+0x30E4);
extendedKeyCodesSet.add(0x01000000+0x30E6);
extendedKeyCodesSet.add(0x01000000+0x30E8);
extendedKeyCodesSet.add(0x01000000+0x30E9);
extendedKeyCodesSet.add(0x01000000+0x30EA);
extendedKeyCodesSet.add(0x01000000+0x30EB);
extendedKeyCodesSet.add(0x01000000+0x30EC);
extendedKeyCodesSet.add(0x01000000+0x30ED);
extendedKeyCodesSet.add(0x01000000+0x30EF);
extendedKeyCodesSet.add(0x01000000+0x30F3);
extendedKeyCodesSet.add(0x01000000+0x309B);
extendedKeyCodesSet.add(0x01000000+0x309C);
extendedKeyCodesSet.add(0x01000000+0x06F0);
extendedKeyCodesSet.add(0x01000000+0x06F1);
extendedKeyCodesSet.add(0x01000000+0x06F2);
extendedKeyCodesSet.add(0x01000000+0x06F3);
extendedKeyCodesSet.add(0x01000000+0x06F4);
extendedKeyCodesSet.add(0x01000000+0x06F5);
extendedKeyCodesSet.add(0x01000000+0x06F6);
extendedKeyCodesSet.add(0x01000000+0x06F7);
extendedKeyCodesSet.add(0x01000000+0x06F8);
extendedKeyCodesSet.add(0x01000000+0x06F9);
extendedKeyCodesSet.add(0x01000000+0x0670);
extendedKeyCodesSet.add(0x01000000+0x067E);
extendedKeyCodesSet.add(0x01000000+0x0686);
extendedKeyCodesSet.add(0x01000000+0x060C);
extendedKeyCodesSet.add(0x01000000+0x06D4);
extendedKeyCodesSet.add(0x01000000+0x0660);
extendedKeyCodesSet.add(0x01000000+0x0661);
extendedKeyCodesSet.add(0x01000000+0x0662);
extendedKeyCodesSet.add(0x01000000+0x0663);
extendedKeyCodesSet.add(0x01000000+0x0664);
extendedKeyCodesSet.add(0x01000000+0x0665);
extendedKeyCodesSet.add(0x01000000+0x0666);
extendedKeyCodesSet.add(0x01000000+0x0667);
extendedKeyCodesSet.add(0x01000000+0x0668);
extendedKeyCodesSet.add(0x01000000+0x0669);
extendedKeyCodesSet.add(0x01000000+0x061B);
extendedKeyCodesSet.add(0x01000000+0x0621);
extendedKeyCodesSet.add(0x01000000+0x0624);
extendedKeyCodesSet.add(0x01000000+0x0626);
extendedKeyCodesSet.add(0x01000000+0x0627);
extendedKeyCodesSet.add(0x01000000+0x0628);
extendedKeyCodesSet.add(0x01000000+0x0629);
extendedKeyCodesSet.add(0x01000000+0x062A);
extendedKeyCodesSet.add(0x01000000+0x062B);
extendedKeyCodesSet.add(0x01000000+0x062C);
extendedKeyCodesSet.add(0x01000000+0x062D);
extendedKeyCodesSet.add(0x01000000+0x062E);
extendedKeyCodesSet.add(0x01000000+0x062F);
extendedKeyCodesSet.add(0x01000000+0x0630);
extendedKeyCodesSet.add(0x01000000+0x0631);
extendedKeyCodesSet.add(0x01000000+0x0632);
extendedKeyCodesSet.add(0x01000000+0x0633);
extendedKeyCodesSet.add(0x01000000+0x0634);
extendedKeyCodesSet.add(0x01000000+0x0635);
extendedKeyCodesSet.add(0x01000000+0x0636);
extendedKeyCodesSet.add(0x01000000+0x0637);
extendedKeyCodesSet.add(0x01000000+0x0638);
extendedKeyCodesSet.add(0x01000000+0x0639);
extendedKeyCodesSet.add(0x01000000+0x063A);
extendedKeyCodesSet.add(0x01000000+0x0641);
extendedKeyCodesSet.add(0x01000000+0x0642);
extendedKeyCodesSet.add(0x01000000+0x0643);
extendedKeyCodesSet.add(0x01000000+0x0644);
extendedKeyCodesSet.add(0x01000000+0x0645);
extendedKeyCodesSet.add(0x01000000+0x0646);
extendedKeyCodesSet.add(0x01000000+0x0647);
extendedKeyCodesSet.add(0x01000000+0x0648);
extendedKeyCodesSet.add(0x01000000+0x0649);
extendedKeyCodesSet.add(0x01000000+0x064A);
extendedKeyCodesSet.add(0x01000000+0x064E);
extendedKeyCodesSet.add(0x01000000+0x064F);
extendedKeyCodesSet.add(0x01000000+0x0650);
extendedKeyCodesSet.add(0x01000000+0x0652);
extendedKeyCodesSet.add(0x01000000+0x0698);
extendedKeyCodesSet.add(0x01000000+0x06A4);
extendedKeyCodesSet.add(0x01000000+0x06A9);
extendedKeyCodesSet.add(0x01000000+0x06AF);
extendedKeyCodesSet.add(0x01000000+0x06BE);
extendedKeyCodesSet.add(0x01000000+0x06CC);
extendedKeyCodesSet.add(0x01000000+0x06CC);
extendedKeyCodesSet.add(0x01000000+0x06D2);
extendedKeyCodesSet.add(0x01000000+0x0493);
extendedKeyCodesSet.add(0x01000000+0x0497);
extendedKeyCodesSet.add(0x01000000+0x049B);
extendedKeyCodesSet.add(0x01000000+0x049D);
extendedKeyCodesSet.add(0x01000000+0x04A3);
extendedKeyCodesSet.add(0x01000000+0x04AF);
extendedKeyCodesSet.add(0x01000000+0x04B1);
extendedKeyCodesSet.add(0x01000000+0x04B3);
extendedKeyCodesSet.add(0x01000000+0x04B9);
extendedKeyCodesSet.add(0x01000000+0x04BB);
extendedKeyCodesSet.add(0x01000000+0x04D9);
extendedKeyCodesSet.add(0x01000000+0x04E9);
extendedKeyCodesSet.add(0x01000000+0x0452);
extendedKeyCodesSet.add(0x01000000+0x0453);
extendedKeyCodesSet.add(0x01000000+0x0451);
extendedKeyCodesSet.add(0x01000000+0x0454);
extendedKeyCodesSet.add(0x01000000+0x0455);
extendedKeyCodesSet.add(0x01000000+0x0456);
extendedKeyCodesSet.add(0x01000000+0x0457);
extendedKeyCodesSet.add(0x01000000+0x0458);
extendedKeyCodesSet.add(0x01000000+0x0459);
extendedKeyCodesSet.add(0x01000000+0x045A);
extendedKeyCodesSet.add(0x01000000+0x045B);
extendedKeyCodesSet.add(0x01000000+0x045C);
extendedKeyCodesSet.add(0x01000000+0x0491);
extendedKeyCodesSet.add(0x01000000+0x045E);
extendedKeyCodesSet.add(0x01000000+0x045F);
extendedKeyCodesSet.add(0x01000000+0x2116);
extendedKeyCodesSet.add(0x01000000+0x044E);
extendedKeyCodesSet.add(0x01000000+0x0430);
extendedKeyCodesSet.add(0x01000000+0x0431);
extendedKeyCodesSet.add(0x01000000+0x0446);
extendedKeyCodesSet.add(0x01000000+0x0434);
extendedKeyCodesSet.add(0x01000000+0x0435);
extendedKeyCodesSet.add(0x01000000+0x0444);
extendedKeyCodesSet.add(0x01000000+0x0433);
extendedKeyCodesSet.add(0x01000000+0x0445);
extendedKeyCodesSet.add(0x01000000+0x0438);
extendedKeyCodesSet.add(0x01000000+0x0439);
extendedKeyCodesSet.add(0x01000000+0x043A);
extendedKeyCodesSet.add(0x01000000+0x043B);
extendedKeyCodesSet.add(0x01000000+0x043C);
extendedKeyCodesSet.add(0x01000000+0x043D);
extendedKeyCodesSet.add(0x01000000+0x043E);
extendedKeyCodesSet.add(0x01000000+0x043F);
extendedKeyCodesSet.add(0x01000000+0x044F);
extendedKeyCodesSet.add(0x01000000+0x0440);
extendedKeyCodesSet.add(0x01000000+0x0441);
extendedKeyCodesSet.add(0x01000000+0x0442);
extendedKeyCodesSet.add(0x01000000+0x0443);
extendedKeyCodesSet.add(0x01000000+0x0436);
extendedKeyCodesSet.add(0x01000000+0x0432);
extendedKeyCodesSet.add(0x01000000+0x044C);
extendedKeyCodesSet.add(0x01000000+0x044B);
extendedKeyCodesSet.add(0x01000000+0x0437);
extendedKeyCodesSet.add(0x01000000+0x0448);
extendedKeyCodesSet.add(0x01000000+0x044D);
extendedKeyCodesSet.add(0x01000000+0x0449);
extendedKeyCodesSet.add(0x01000000+0x0447);
extendedKeyCodesSet.add(0x01000000+0x044A);
extendedKeyCodesSet.add(0x01000000+0x2015);
extendedKeyCodesSet.add(0x01000000+0x03B1);
extendedKeyCodesSet.add(0x01000000+0x03B2);
extendedKeyCodesSet.add(0x01000000+0x03B3);
extendedKeyCodesSet.add(0x01000000+0x03B4);
extendedKeyCodesSet.add(0x01000000+0x03B5);
extendedKeyCodesSet.add(0x01000000+0x03B6);
extendedKeyCodesSet.add(0x01000000+0x03B7);
extendedKeyCodesSet.add(0x01000000+0x03B8);
extendedKeyCodesSet.add(0x01000000+0x03B9);
extendedKeyCodesSet.add(0x01000000+0x03BA);
extendedKeyCodesSet.add(0x01000000+0x03BB);
extendedKeyCodesSet.add(0x01000000+0x03BC);
extendedKeyCodesSet.add(0x01000000+0x03BD);
extendedKeyCodesSet.add(0x01000000+0x03BE);
extendedKeyCodesSet.add(0x01000000+0x03BF);
extendedKeyCodesSet.add(0x01000000+0x03C0);
extendedKeyCodesSet.add(0x01000000+0x03C1);
extendedKeyCodesSet.add(0x01000000+0x03C3);
extendedKeyCodesSet.add(0x01000000+0x03C2);
extendedKeyCodesSet.add(0x01000000+0x03C4);
extendedKeyCodesSet.add(0x01000000+0x03C5);
extendedKeyCodesSet.add(0x01000000+0x03C6);
extendedKeyCodesSet.add(0x01000000+0x03C7);
extendedKeyCodesSet.add(0x01000000+0x03C8);
extendedKeyCodesSet.add(0x01000000+0x03C9);
extendedKeyCodesSet.add(0x01000000+0x2190);
extendedKeyCodesSet.add(0x01000000+0x2192);
extendedKeyCodesSet.add(0x01000000+0x2193);
extendedKeyCodesSet.add(0x01000000+0x2013);
extendedKeyCodesSet.add(0x01000000+0x201C);
extendedKeyCodesSet.add(0x01000000+0x201D);
extendedKeyCodesSet.add(0x01000000+0x201E);
extendedKeyCodesSet.add(0x01000000+0x05D0);
extendedKeyCodesSet.add(0x01000000+0x05D1);
extendedKeyCodesSet.add(0x01000000+0x05D2);
extendedKeyCodesSet.add(0x01000000+0x05D3);
extendedKeyCodesSet.add(0x01000000+0x05D4);
extendedKeyCodesSet.add(0x01000000+0x05D5);
extendedKeyCodesSet.add(0x01000000+0x05D6);
extendedKeyCodesSet.add(0x01000000+0x05D7);
extendedKeyCodesSet.add(0x01000000+0x05D8);
extendedKeyCodesSet.add(0x01000000+0x05D9);
extendedKeyCodesSet.add(0x01000000+0x05DA);
extendedKeyCodesSet.add(0x01000000+0x05DB);
extendedKeyCodesSet.add(0x01000000+0x05DC);
extendedKeyCodesSet.add(0x01000000+0x05DD);
extendedKeyCodesSet.add(0x01000000+0x05DE);
extendedKeyCodesSet.add(0x01000000+0x05DF);
extendedKeyCodesSet.add(0x01000000+0x05E0);
extendedKeyCodesSet.add(0x01000000+0x05E1);
extendedKeyCodesSet.add(0x01000000+0x05E2);
extendedKeyCodesSet.add(0x01000000+0x05E3);
extendedKeyCodesSet.add(0x01000000+0x05E4);
extendedKeyCodesSet.add(0x01000000+0x05E5);
extendedKeyCodesSet.add(0x01000000+0x05E6);
extendedKeyCodesSet.add(0x01000000+0x05E7);
extendedKeyCodesSet.add(0x01000000+0x05E8);
extendedKeyCodesSet.add(0x01000000+0x05E9);
extendedKeyCodesSet.add(0x01000000+0x05EA);
extendedKeyCodesSet.add(0x01000000+0x0E01);
extendedKeyCodesSet.add(0x01000000+0x0E02);
extendedKeyCodesSet.add(0x01000000+0x0E03);
extendedKeyCodesSet.add(0x01000000+0x0E04);
extendedKeyCodesSet.add(0x01000000+0x0E05);
extendedKeyCodesSet.add(0x01000000+0x0E07);
extendedKeyCodesSet.add(0x01000000+0x0E08);
extendedKeyCodesSet.add(0x01000000+0x0E0A);
extendedKeyCodesSet.add(0x01000000+0x0E0C);
extendedKeyCodesSet.add(0x01000000+0x0E14);
extendedKeyCodesSet.add(0x01000000+0x0E15);
extendedKeyCodesSet.add(0x01000000+0x0E16);
extendedKeyCodesSet.add(0x01000000+0x0E17);
extendedKeyCodesSet.add(0x01000000+0x0E19);
extendedKeyCodesSet.add(0x01000000+0x0E1A);
extendedKeyCodesSet.add(0x01000000+0x0E1B);
extendedKeyCodesSet.add(0x01000000+0x0E1C);
extendedKeyCodesSet.add(0x01000000+0x0E1D);
extendedKeyCodesSet.add(0x01000000+0x0E1E);
extendedKeyCodesSet.add(0x01000000+0x0E1F);
extendedKeyCodesSet.add(0x01000000+0x0E20);
extendedKeyCodesSet.add(0x01000000+0x0E21);
extendedKeyCodesSet.add(0x01000000+0x0E22);
extendedKeyCodesSet.add(0x01000000+0x0E23);
extendedKeyCodesSet.add(0x01000000+0x0E25);
extendedKeyCodesSet.add(0x01000000+0x0E27);
extendedKeyCodesSet.add(0x01000000+0x0E2A);
extendedKeyCodesSet.add(0x01000000+0x0E2B);
extendedKeyCodesSet.add(0x01000000+0x0E2D);
extendedKeyCodesSet.add(0x01000000+0x0E30);
extendedKeyCodesSet.add(0x01000000+0x0E31);
extendedKeyCodesSet.add(0x01000000+0x0E32);
extendedKeyCodesSet.add(0x01000000+0x0E33);
extendedKeyCodesSet.add(0x01000000+0x0E34);
extendedKeyCodesSet.add(0x01000000+0x0E35);
extendedKeyCodesSet.add(0x01000000+0x0E36);
extendedKeyCodesSet.add(0x01000000+0x0E37);
extendedKeyCodesSet.add(0x01000000+0x0E38);
extendedKeyCodesSet.add(0x01000000+0x0E39);
extendedKeyCodesSet.add(0x01000000+0x0E3F);
extendedKeyCodesSet.add(0x01000000+0x0E40);
extendedKeyCodesSet.add(0x01000000+0x0E41);
extendedKeyCodesSet.add(0x01000000+0x0E43);
extendedKeyCodesSet.add(0x01000000+0x0E44);
extendedKeyCodesSet.add(0x01000000+0x0E45);
extendedKeyCodesSet.add(0x01000000+0x0E46);
extendedKeyCodesSet.add(0x01000000+0x0E47);
extendedKeyCodesSet.add(0x01000000+0x0E48);
extendedKeyCodesSet.add(0x01000000+0x0E49);
extendedKeyCodesSet.add(0x01000000+0x0E50);
extendedKeyCodesSet.add(0x01000000+0x0E51);
extendedKeyCodesSet.add(0x01000000+0x0E52);
extendedKeyCodesSet.add(0x01000000+0x0E53);
extendedKeyCodesSet.add(0x01000000+0x0E54);
extendedKeyCodesSet.add(0x01000000+0x0E55);
extendedKeyCodesSet.add(0x01000000+0x0E56);
extendedKeyCodesSet.add(0x01000000+0x0E57);
extendedKeyCodesSet.add(0x01000000+0x0E58);
extendedKeyCodesSet.add(0x01000000+0x0E59);
extendedKeyCodesSet.add(0x01000000+0x0587);
extendedKeyCodesSet.add(0x01000000+0x0589);
extendedKeyCodesSet.add(0x01000000+0x0589);
extendedKeyCodesSet.add(0x01000000+0x055D);
extendedKeyCodesSet.add(0x01000000+0x055D);
extendedKeyCodesSet.add(0x01000000+0x055B);
extendedKeyCodesSet.add(0x01000000+0x055B);
extendedKeyCodesSet.add(0x01000000+0x055E);
extendedKeyCodesSet.add(0x01000000+0x055E);
extendedKeyCodesSet.add(0x01000000+0x0561);
extendedKeyCodesSet.add(0x01000000+0x0562);
extendedKeyCodesSet.add(0x01000000+0x0563);
extendedKeyCodesSet.add(0x01000000+0x0564);
extendedKeyCodesSet.add(0x01000000+0x0565);
extendedKeyCodesSet.add(0x01000000+0x0566);
extendedKeyCodesSet.add(0x01000000+0x0567);
extendedKeyCodesSet.add(0x01000000+0x0568);
extendedKeyCodesSet.add(0x01000000+0x0569);
extendedKeyCodesSet.add(0x01000000+0x056A);
extendedKeyCodesSet.add(0x01000000+0x056B);
extendedKeyCodesSet.add(0x01000000+0x056C);
extendedKeyCodesSet.add(0x01000000+0x056D);
extendedKeyCodesSet.add(0x01000000+0x056E);
extendedKeyCodesSet.add(0x01000000+0x056F);
extendedKeyCodesSet.add(0x01000000+0x0570);
extendedKeyCodesSet.add(0x01000000+0x0571);
extendedKeyCodesSet.add(0x01000000+0x0572);
extendedKeyCodesSet.add(0x01000000+0x0573);
extendedKeyCodesSet.add(0x01000000+0x0574);
extendedKeyCodesSet.add(0x01000000+0x0575);
extendedKeyCodesSet.add(0x01000000+0x0576);
extendedKeyCodesSet.add(0x01000000+0x0577);
extendedKeyCodesSet.add(0x01000000+0x0578);
extendedKeyCodesSet.add(0x01000000+0x0579);
extendedKeyCodesSet.add(0x01000000+0x057A);
extendedKeyCodesSet.add(0x01000000+0x057B);
extendedKeyCodesSet.add(0x01000000+0x057C);
extendedKeyCodesSet.add(0x01000000+0x057D);
extendedKeyCodesSet.add(0x01000000+0x057E);
extendedKeyCodesSet.add(0x01000000+0x057F);
extendedKeyCodesSet.add(0x01000000+0x0580);
extendedKeyCodesSet.add(0x01000000+0x0581);
extendedKeyCodesSet.add(0x01000000+0x0582);
extendedKeyCodesSet.add(0x01000000+0x0583);
extendedKeyCodesSet.add(0x01000000+0x0584);
extendedKeyCodesSet.add(0x01000000+0x0585);
extendedKeyCodesSet.add(0x01000000+0x0586);
extendedKeyCodesSet.add(0x01000000+0x10D0);
extendedKeyCodesSet.add(0x01000000+0x10D1);
extendedKeyCodesSet.add(0x01000000+0x10D2);
extendedKeyCodesSet.add(0x01000000+0x10D3);
extendedKeyCodesSet.add(0x01000000+0x10D4);
extendedKeyCodesSet.add(0x01000000+0x10D5);
extendedKeyCodesSet.add(0x01000000+0x10D6);
extendedKeyCodesSet.add(0x01000000+0x10D7);
extendedKeyCodesSet.add(0x01000000+0x10D8);
extendedKeyCodesSet.add(0x01000000+0x10D9);
extendedKeyCodesSet.add(0x01000000+0x10DA);
extendedKeyCodesSet.add(0x01000000+0x10DB);
extendedKeyCodesSet.add(0x01000000+0x10DC);
extendedKeyCodesSet.add(0x01000000+0x10DD);
extendedKeyCodesSet.add(0x01000000+0x10DE);
extendedKeyCodesSet.add(0x01000000+0x10DF);
extendedKeyCodesSet.add(0x01000000+0x10E0);
extendedKeyCodesSet.add(0x01000000+0x10E1);
extendedKeyCodesSet.add(0x01000000+0x10E2);
extendedKeyCodesSet.add(0x01000000+0x10E3);
extendedKeyCodesSet.add(0x01000000+0x10E4);
extendedKeyCodesSet.add(0x01000000+0x10E5);
extendedKeyCodesSet.add(0x01000000+0x10E6);
extendedKeyCodesSet.add(0x01000000+0x10E7);
extendedKeyCodesSet.add(0x01000000+0x10E8);
extendedKeyCodesSet.add(0x01000000+0x10E9);
extendedKeyCodesSet.add(0x01000000+0x10EA);
extendedKeyCodesSet.add(0x01000000+0x10EB);
extendedKeyCodesSet.add(0x01000000+0x10EC);
extendedKeyCodesSet.add(0x01000000+0x10ED);
extendedKeyCodesSet.add(0x01000000+0x10EE);
extendedKeyCodesSet.add(0x01000000+0x10EF);
extendedKeyCodesSet.add(0x01000000+0x10F0);
extendedKeyCodesSet.add(0x01000000+0x01E7);
extendedKeyCodesSet.add(0x01000000+0x0259);
extendedKeyCodesSet.add(0x01000000+0x1EB9);
extendedKeyCodesSet.add(0x01000000+0x1ECB);
extendedKeyCodesSet.add(0x01000000+0x1ECD);
extendedKeyCodesSet.add(0x01000000+0x1EE5);
extendedKeyCodesSet.add(0x01000000+0x01A1);
extendedKeyCodesSet.add(0x01000000+0x01B0);
extendedKeyCodesSet.add(0x01000000+0x20AB);
}
}
| gpl-2.0 |
universsky/openjdk | jdk/test/java/lang/instrument/NullRedefineClassesTests.java | 3751 | /*
* Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/**
* @test
* @bug 4920005 4882798
* @summary make sure redefineClasses throws NullPointerException in the right places.
* @author Robert Field as modified from the code of Gabriel Adauto, Wily Technology
*
* @modules java.instrument
* @run build NullRedefineClassesTests
* @run shell MakeJAR.sh redefineAgent
* @run main/othervm -javaagent:redefineAgent.jar NullRedefineClassesTests NullRedefineClassesTests
*/
import java.lang.instrument.ClassDefinition;
import java.lang.instrument.UnmodifiableClassException;
public class
NullRedefineClassesTests
extends ASimpleInstrumentationTestCase
{
/**
* Constructor for NullRedefineClassesTests.
* @param name
*/
public NullRedefineClassesTests(String name) {
super(name);
}
public static void
main (String[] args) throws Throwable {
ATestCaseScaffold test = new NullRedefineClassesTests(args[0]);
test.runTest();
}
protected final void
doRunTest() throws ClassNotFoundException, UnmodifiableClassException {
testNullRedefineClasses();
}
public void
testNullRedefineClasses() throws ClassNotFoundException, UnmodifiableClassException {
boolean caught;
// Test that a null argument throws NullPointerException
caught = false;
try {
fInst.redefineClasses(null);
} catch (NullPointerException npe) {
caught = true;
}
assertTrue(caught);
// Test that a null element throws NullPointerException
caught = false;
try {
fInst.redefineClasses(new ClassDefinition[]{ null });
} catch (NullPointerException npe) {
caught = true;
}
assertTrue(caught);
// Test that a null element amonst others throws NullPointerException
caught = false;
ClassDefinition cd = new ClassDefinition(DummyClass.class, new byte[] {1, 2, 3});
try {
fInst.redefineClasses(new ClassDefinition[]{ cd, null });
} catch (NullPointerException npe) {
caught = true;
}
assertTrue(caught);
// Test that a null class throws NullPointerException
caught = false;
try {
new ClassDefinition(null, new byte[] {1, 2, 3});
} catch (NullPointerException npe) {
caught = true;
}
assertTrue(caught);
// Test that a null byte array throws NullPointerException
caught = false;
try {
new ClassDefinition(DummyClass.class, null);
} catch (NullPointerException npe) {
caught = true;
}
assertTrue(caught);
}
}
| gpl-2.0 |
hannesa2/owncloud-android | owncloudApp/src/main/java/com/owncloud/android/ui/activity/ManageAccountsActivity.java | 18776 | /**
* ownCloud Android client application
*
* @author Andy Scherzinger
* @author Christian Schabesberger
* Copyright (C) 2020 ownCloud GmbH.
* <p/>
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
* <p/>
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* <p/>
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.owncloud.android.ui.activity;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.OperationCanceledException;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SyncRequest;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.drawable.DrawableCompat;
import androidx.work.WorkManager;
import com.owncloud.android.MainApp;
import com.owncloud.android.R;
import com.owncloud.android.authentication.AccountUtils;
import com.owncloud.android.datamodel.FileDataStorageManager;
import com.owncloud.android.files.services.FileDownloader;
import com.owncloud.android.files.services.FileUploader;
import com.owncloud.android.presentation.ui.authentication.AuthenticatorConstants;
import com.owncloud.android.presentation.ui.authentication.LoginActivity;
import com.owncloud.android.services.OperationsService;
import com.owncloud.android.ui.adapter.AccountListAdapter;
import com.owncloud.android.ui.adapter.AccountListItem;
import com.owncloud.android.ui.dialog.RemoveAccountDialogFragment;
import com.owncloud.android.ui.dialog.RemoveAccountDialogViewModel;
import com.owncloud.android.ui.helpers.FileOperationsHelper;
import com.owncloud.android.usecases.CancelUploadFromAccountUseCase;
import com.owncloud.android.utils.PreferenceUtils;
import kotlin.Lazy;
import org.jetbrains.annotations.NotNull;
import timber.log.Timber;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import static org.koin.java.KoinJavaComponent.inject;
/**
* An Activity that allows the user to manage accounts.
*/
public class ManageAccountsActivity extends FileActivity
implements
AccountListAdapter.AccountListAdapterListener,
AccountManagerCallback<Boolean>,
ComponentsGetter {
public static final String KEY_ACCOUNT_LIST_CHANGED = "ACCOUNT_LIST_CHANGED";
public static final String KEY_CURRENT_ACCOUNT_CHANGED = "CURRENT_ACCOUNT_CHANGED";
private ListView mListView;
private final Handler mHandler = new Handler();
private String mAccountBeingRemoved;
private AccountListAdapter mAccountListAdapter;
protected FileUploader.FileUploaderBinder mUploaderBinder = null;
protected FileDownloader.FileDownloaderBinder mDownloaderBinder = null;
private ServiceConnection mDownloadServiceConnection, mUploadServiceConnection = null;
Set<String> mOriginalAccounts;
String mOriginalCurrentAccount;
private Drawable mTintedCheck;
private RemoveAccountDialogViewModel mRemoveAccountDialogViewModel = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
@NotNull Lazy<RemoveAccountDialogViewModel> removeAccountDialogViewModelLazy = inject(RemoveAccountDialogViewModel.class);
mRemoveAccountDialogViewModel = removeAccountDialogViewModelLazy.getValue();
mTintedCheck = ContextCompat.getDrawable(this, R.drawable.ic_current_white);
mTintedCheck = DrawableCompat.wrap(mTintedCheck);
int tint = ContextCompat.getColor(this, R.color.actionbar_start_color);
DrawableCompat.setTint(mTintedCheck, tint);
setContentView(R.layout.accounts_layout);
mListView = findViewById(R.id.account_list);
mListView.setFilterTouchesWhenObscured(
PreferenceUtils.shouldDisallowTouchesWithOtherVisibleWindows(getApplicationContext())
);
setupStandardToolbar(getString(R.string.prefs_manage_accounts), true, true, true);
Account[] accountList = AccountManager.get(this).getAccountsByType(MainApp.Companion.getAccountType());
mOriginalAccounts = toAccountNameSet(accountList);
mOriginalCurrentAccount = AccountUtils.getCurrentOwnCloudAccount(this).name;
setAccount(AccountUtils.getCurrentOwnCloudAccount(this));
onAccountSet(false);
initializeComponentGetters();
// added click listener to switch account
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
switchAccount(position);
}
});
}
@Override
protected void onStart() {
super.onStart();
mAccountListAdapter = new AccountListAdapter(this, getAccountListItems(), mTintedCheck);
mListView.setAdapter(mAccountListAdapter);
}
/**
* converts an array of accounts into a set of account names.
*
* @param accountList the account array
* @return set of account names
*/
private Set<String> toAccountNameSet(Account[] accountList) {
Set<String> actualAccounts = new HashSet<String>(accountList.length);
for (Account account : accountList) {
actualAccounts.add(account.name);
}
return actualAccounts;
}
@Override
public void onBackPressed() {
Intent resultIntent = new Intent();
resultIntent.putExtra(KEY_ACCOUNT_LIST_CHANGED, hasAccountListChanged());
resultIntent.putExtra(KEY_CURRENT_ACCOUNT_CHANGED, hasCurrentAccountChanged());
setResult(RESULT_OK, resultIntent);
finish();
super.onBackPressed();
}
/**
* checks the set of actual accounts against the set of original accounts when the activity has been started.
*
* @return <code>true</code> if account list has changed, <code>false</code> if not
*/
private boolean hasAccountListChanged() {
Account[] accountList = AccountManager.get(this).getAccountsByType(MainApp.Companion.getAccountType());
Set<String> actualAccounts = toAccountNameSet(accountList);
return !mOriginalAccounts.equals(actualAccounts);
}
/**
* checks actual current account against current accounts when the activity has been started.
*
* @return <code>true</code> if account list has changed, <code>false</code> if not
*/
private boolean hasCurrentAccountChanged() {
Account currentAccount = AccountUtils.getCurrentOwnCloudAccount(this);
return (currentAccount != null && !mOriginalCurrentAccount.equals(currentAccount.name));
}
/**
* Initialize ComponentsGetters.
*/
private void initializeComponentGetters() {
mDownloadServiceConnection = newTransferenceServiceConnection();
if (mDownloadServiceConnection != null) {
bindService(new Intent(this, FileDownloader.class), mDownloadServiceConnection,
Context.BIND_AUTO_CREATE);
}
mUploadServiceConnection = newTransferenceServiceConnection();
if (mUploadServiceConnection != null) {
bindService(new Intent(this, FileUploader.class), mUploadServiceConnection,
Context.BIND_AUTO_CREATE);
}
}
/**
* creates the account list items list including the add-account action in case multiaccount_support is enabled.
*
* @return list of account list items
*/
private ArrayList<AccountListItem> getAccountListItems() {
Account[] accountList = AccountManager.get(this).getAccountsByType(MainApp.Companion.getAccountType());
ArrayList<AccountListItem> adapterAccountList = new ArrayList<>(accountList.length);
for (Account account : accountList) {
adapterAccountList.add(new AccountListItem(account));
}
// Add Create Account item at the end of account list if multi-account is enabled
if (getResources().getBoolean(R.bool.multiaccount_support)) {
adapterAccountList.add(new AccountListItem());
}
return adapterAccountList;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
boolean retval = true;
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
break;
default:
retval = super.onOptionsItemSelected(item);
}
return retval;
}
@Override
public void removeAccount(Account account) {
mAccountBeingRemoved = account.name;
RemoveAccountDialogFragment dialog = RemoveAccountDialogFragment.newInstance(
account,
mRemoveAccountDialogViewModel.hasCameraUploadsAttached(account.name)
);
dialog.show(getSupportFragmentManager(), RemoveAccountDialogFragment.FTAG_CONFIRMATION);
}
@Override
public void changePasswordOfAccount(Account account) {
Intent updateAccountCredentials = new Intent(ManageAccountsActivity.this, LoginActivity.class);
updateAccountCredentials.putExtra(AuthenticatorConstants.EXTRA_ACCOUNT, account);
updateAccountCredentials.putExtra(AuthenticatorConstants.EXTRA_ACTION,
AuthenticatorConstants.ACTION_UPDATE_TOKEN);
startActivity(updateAccountCredentials);
}
@Override
public void refreshAccount(Account account) {
Timber.d("Got to start sync");
Timber.d("Requesting sync for " + account.name + " at " + MainApp.Companion.getAuthority() + " with new API");
SyncRequest.Builder builder = new SyncRequest.Builder();
builder.setSyncAdapter(account, MainApp.Companion.getAuthority());
builder.setExpedited(true);
builder.setManual(true);
builder.syncOnce();
// Fix bug in Android Lollipop when you click on refresh the whole account
Bundle extras = new Bundle();
builder.setExtras(extras);
SyncRequest request = builder.build();
ContentResolver.requestSync(request);
this.showSnackMessage(getString(R.string.synchronizing_account));
}
@Override
public void createAccount() {
AccountManager am = AccountManager.get(getApplicationContext());
am.addAccount(MainApp.Companion.getAccountType(),
null,
null,
null,
this,
new AccountManagerCallback<Bundle>() {
@Override
public void run(AccountManagerFuture<Bundle> future) {
if (future != null) {
try {
Bundle result = future.getResult();
String name = result.getString(AccountManager.KEY_ACCOUNT_NAME);
AccountUtils.setCurrentOwnCloudAccount(getApplicationContext(), name);
mAccountListAdapter = new AccountListAdapter(
ManageAccountsActivity.this,
getAccountListItems(),
mTintedCheck
);
mListView.setAdapter(mAccountListAdapter);
runOnUiThread(new Runnable() {
@Override
public void run() {
mAccountListAdapter.notifyDataSetChanged();
}
});
} catch (OperationCanceledException e) {
Timber.e(e, "Account creation canceled");
} catch (Exception e) {
Timber.e(e, "Account creation finished in exception");
}
}
}
}, mHandler);
}
/**
* Callback executed after the {@link AccountManager} removed an account
*
* @param future Result of the removal; future.getResult() is true if account was removed correctly.
*/
@Override
public void run(AccountManagerFuture<Boolean> future) {
if (future != null && future.isDone()) {
Account account = new Account(mAccountBeingRemoved, MainApp.Companion.getAccountType());
if (!AccountUtils.exists(account.name, MainApp.Companion.getAppContext())) {
// Cancel transfers of the removed account
if (mUploaderBinder != null) {
mUploaderBinder.cancel(account);
}
if (mDownloaderBinder != null) {
mDownloaderBinder.cancel(account);
}
CancelUploadFromAccountUseCase cancelUploadFromAccountUseCase = new CancelUploadFromAccountUseCase(WorkManager.getInstance(getBaseContext()));
cancelUploadFromAccountUseCase.execute(new CancelUploadFromAccountUseCase.Params(account.name));
}
mAccountListAdapter = new AccountListAdapter(this, getAccountListItems(), mTintedCheck);
mListView.setAdapter(mAccountListAdapter);
AccountManager am = AccountManager.get(this);
if (am.getAccountsByType(MainApp.Companion.getAccountType()).length == 0) {
// Show create account screen if there isn't any account
am.addAccount(
MainApp.Companion.getAccountType(),
null, null, null,
this,
null, null
);
} else { // at least one account left
if (AccountUtils.getCurrentOwnCloudAccount(this) == null) {
// current account was removed - set another as current
String accountName = "";
Account[] accounts = AccountManager.get(this).getAccountsByType(MainApp.Companion.getAccountType());
if (accounts.length != 0) {
accountName = accounts[0].name;
}
AccountUtils.setCurrentOwnCloudAccount(this, accountName);
}
}
}
}
/**
* Switch current account to that contained in the received position of the list adapter.
*
* @param position A position of the account adapter containing an account.
*/
private void switchAccount(int position) {
Account clickedAccount = mAccountListAdapter.getItem(position).getAccount();
if (getAccount().name.equals(clickedAccount.name)) {
// current account selected, just go back
finish();
} else {
// restart list of files with new account
AccountUtils.setCurrentOwnCloudAccount(
ManageAccountsActivity.this,
clickedAccount.name
);
// Refresh dependencies to be used in selected account
MainApp.Companion.initDependencyInjection();
Intent i = new Intent(
ManageAccountsActivity.this,
FileDisplayActivity.class
);
i.putExtra(FileActivity.EXTRA_ACCOUNT, clickedAccount);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
}
@Override
protected void onDestroy() {
if (mDownloadServiceConnection != null) {
unbindService(mDownloadServiceConnection);
mDownloadServiceConnection = null;
}
if (mUploadServiceConnection != null) {
unbindService(mUploadServiceConnection);
mUploadServiceConnection = null;
}
super.onDestroy();
}
// Methods for ComponentsGetter
@Override
public FileDownloader.FileDownloaderBinder getFileDownloaderBinder() {
return mDownloaderBinder;
}
@Override
public FileUploader.FileUploaderBinder getFileUploaderBinder() {
return mUploaderBinder;
}
@Override
public OperationsService.OperationsServiceBinder getOperationsServiceBinder() {
return null;
}
@Override
public FileDataStorageManager getStorageManager() {
return super.getStorageManager();
}
@Override
public FileOperationsHelper getFileOperationsHelper() {
return null;
}
protected ServiceConnection newTransferenceServiceConnection() {
return new ManageAccountsServiceConnection();
}
/**
* Defines callbacks for service binding, passed to bindService()
*/
private class ManageAccountsServiceConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName component, IBinder service) {
if (component.equals(new ComponentName(ManageAccountsActivity.this, FileDownloader.class))) {
mDownloaderBinder = (FileDownloader.FileDownloaderBinder) service;
} else if (component.equals(new ComponentName(ManageAccountsActivity.this, FileUploader.class))) {
Timber.d("Upload service connected");
mUploaderBinder = (FileUploader.FileUploaderBinder) service;
}
}
@Override
public void onServiceDisconnected(ComponentName component) {
if (component.equals(new ComponentName(ManageAccountsActivity.this, FileDownloader.class))) {
Timber.d("Download service suddenly disconnected");
mDownloaderBinder = null;
} else if (component.equals(new ComponentName(ManageAccountsActivity.this, FileUploader.class))) {
Timber.d("Upload service suddenly disconnected");
mUploaderBinder = null;
}
}
}
}
| gpl-2.0 |
visage-lang/visage-compiler | src/share/classes/org/visage/functions/Function7.java | 2088 | /*
* Copyright 2008-2009 Sun Microsystems, Inc. All Rights Reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*/
package org.visage.functions;
import org.visage.runtime.VisageObject;
public class Function7<R, A1, A2, A3, A4, A5, A6, A7> extends Function<R> {
public Function7() {}
public Function7(final VisageObject implementor, final int number) {
super(implementor, number);
}
// Get the implementor to invoke the function.
// Don't override this.
public Object invoke$(Object arg1, Object arg2, Object[] rargs) {
if (implementor != null) {
return implementor.invoke$(number, arg1, arg2, rargs);
} else {
return invoke((A1)arg1, (A2)arg2, (A3)rargs[0], (A4)rargs[1], (A5)rargs[2], (A6)rargs[3], (A7)rargs[4]);
}
}
// Override this
public R invoke(A1 x1, A2 x2, A3 x3, A4 x4, A5 x5, A6 x6, A7 x7) {
if (implementor != null) {
return (R) implementor.invoke$(number, x1, x2, new Object[] { x3, x4, x5, x6, x7 });
} else {
throw new RuntimeException("invoke function missing");
}
}
}
| gpl-2.0 |
yterauchi/primecloud-controller | auto-project/auto-api/src/main/java/jp/primecloud/auto/api/lb/AttachLoadBalancer.java | 4784 | /*
* Copyright 2014 by SCSK Corporation.
*
* This file is part of PrimeCloud Controller(TM).
*
* PrimeCloud Controller(TM) 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.
*
* PrimeCloud Controller(TM) 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 PrimeCloud Controller(TM). If not, see <http://www.gnu.org/licenses/>.
*/
package jp.primecloud.auto.api.lb;
import java.util.ArrayList;
import java.util.List;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;
import javax.ws.rs.core.MediaType;
import jp.primecloud.auto.api.ApiSupport;
import jp.primecloud.auto.api.ApiValidate;
import org.apache.commons.lang.BooleanUtils;
import jp.primecloud.auto.api.response.lb.AttachLoadBalancerResponse;
import jp.primecloud.auto.common.status.InstanceStatus;
import jp.primecloud.auto.entity.crud.ComponentInstance;
import jp.primecloud.auto.entity.crud.Instance;
import jp.primecloud.auto.entity.crud.LoadBalancer;
import jp.primecloud.auto.exception.AutoApplicationException;
@Path("/AttachLoadBalancer")
public class AttachLoadBalancer extends ApiSupport {
/**
*
* ロードバランサ サーバ割り当て有効化
* @param loadBalancerNo ロードバランサ番号
* @param instanceNo インスタンス番号
*
* @return AttachLoadBalancerResponse
*/
@GET
@Produces(MediaType.APPLICATION_JSON)
public AttachLoadBalancerResponse attachLoadBalancer(
@QueryParam(PARAM_NAME_LOAD_BALANCER_NO) String loadBalancerNo,
@QueryParam(PARAM_NAME_INSTANCE_NO) String instanceNo){
AttachLoadBalancerResponse response = new AttachLoadBalancerResponse();
// 入力チェック
// LoadBalancerNo
ApiValidate.validateLoadBalancerNo(loadBalancerNo);
// InstanceNo
ApiValidate.validateInstanceNo(instanceNo);
// ロードバランサ取得
LoadBalancer loadBalancer = getLoadBalancer(Long.parseLong(loadBalancerNo));
// 権限チェック
checkAndGetUser(loadBalancer);
// インスタンス取得
Instance instance = getInstance(Long.parseLong(instanceNo));
if (BooleanUtils.isFalse(instance.getFarmNo().equals(loadBalancer.getFarmNo()))) {
//ファームとインスタンスが一致しない
throw new AutoApplicationException("EAPI-100022", "Instance", loadBalancer.getFarmNo(), PARAM_NAME_INSTANCE_NO, instanceNo);
}
// サーバのステータスチェック
InstanceStatus instanceStatus = InstanceStatus.fromStatus(instance.getStatus());
if (instanceStatus == InstanceStatus.CONFIGURING || instanceStatus == InstanceStatus.WARNING) {
// ステータスが Configuring 及び Warning の場合は割り当て不可
throw new AutoApplicationException("EAPI-100001", loadBalancerNo, instanceNo);
}
// コンポーネントのチェック
List<ComponentInstance> componentInstances = componentInstanceDao.readByComponentNo(loadBalancer.getComponentNo());
boolean isContain = false;
for (ComponentInstance componentInstance : componentInstances) {
if (BooleanUtils.isFalse(componentInstance.getAssociate())) {
continue;
}
if (componentInstance.getInstanceNo().equals(instance.getInstanceNo())) {
isContain = true;
break;
}
}
if (BooleanUtils.isFalse(isContain)) {
// インスタンスがコンポーネントに含まれていない場合
throw new AutoApplicationException("EAPI-100012", Long.parseLong(loadBalancerNo),
loadBalancer.getComponentNo(), Long.parseLong(instanceNo));
}
// ロードバランサ サーバ割り当て有効化設定処理
List<Long> instanceNos = new ArrayList<Long>();
instanceNos.add(Long.parseLong(instanceNo));
loadBalancerService.enableInstances(Long.parseLong(loadBalancerNo), instanceNos);
response.setSuccess(true);
return response;
}
} | gpl-2.0 |
aeng/zanata-sync | server/src/main/java/org/zanata/sync/model/JobProgress.java | 429 | package org.zanata.sync.model;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* @author Alex Eng <a href="aeng@redhat.com">aeng@redhat.com</a>
*/
@AllArgsConstructor
@NoArgsConstructor
@Getter
public class JobProgress implements Serializable {
private double completePercent;
private String description;
private JobStatusType status;
}
| gpl-2.0 |
RasiahT/Ball-of-Duty | src/org/tempuri/QuitGameResponse.java | 2277 | /**
* QuitGameResponse.java
*
* This file was auto-generated from WSDL
* by the Apache Axis 1.4 Apr 22, 2006 (06:55:48 PDT) WSDL2Java emitter.
*/
package org.tempuri;
public class QuitGameResponse implements java.io.Serializable {
public QuitGameResponse() {
}
private java.lang.Object __equalsCalc = null;
public synchronized boolean equals(java.lang.Object obj) {
if (!(obj instanceof QuitGameResponse)) return false;
QuitGameResponse other = (QuitGameResponse) obj;
if (obj == null) return false;
if (this == obj) return true;
if (__equalsCalc != null) {
return (__equalsCalc == obj);
}
__equalsCalc = obj;
boolean _equals;
_equals = true;
__equalsCalc = null;
return _equals;
}
private boolean __hashCodeCalc = false;
public synchronized int hashCode() {
if (__hashCodeCalc) {
return 0;
}
__hashCodeCalc = true;
int _hashCode = 1;
__hashCodeCalc = false;
return _hashCode;
}
// Type metadata
private static org.apache.axis.description.TypeDesc typeDesc =
new org.apache.axis.description.TypeDesc(QuitGameResponse.class, true);
static {
typeDesc.setXmlType(new javax.xml.namespace.QName("http://tempuri.org/", ">QuitGameResponse"));
}
/**
* Return type metadata object
*/
public static org.apache.axis.description.TypeDesc getTypeDesc() {
return typeDesc;
}
/**
* Get Custom Serializer
*/
public static org.apache.axis.encoding.Serializer getSerializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanSerializer(
_javaType, _xmlType, typeDesc);
}
/**
* Get Custom Deserializer
*/
public static org.apache.axis.encoding.Deserializer getDeserializer(
java.lang.String mechType,
java.lang.Class _javaType,
javax.xml.namespace.QName _xmlType) {
return
new org.apache.axis.encoding.ser.BeanDeserializer(
_javaType, _xmlType, typeDesc);
}
}
| gpl-2.0 |
EHJ-52n/SOS | spring/install-controller/src/main/java/org/n52/sos/web/install/InstallIndexController.java | 2178 | /*
* Copyright (C) 2012-2021 52°North Spatial Information Research 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.web.install;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.n52.sos.web.common.ControllerConstants;
import org.n52.sos.web.install.InstallConstants.Step;
/**
* @since 4.0.0
*
*/
@Controller
@RequestMapping({ ControllerConstants.Paths.INSTALL_ROOT, ControllerConstants.Paths.INSTALL_INDEX })
public class InstallIndexController extends AbstractInstallStepController {
@RequestMapping(method = RequestMethod.GET)
public String get(HttpServletRequest req) {
/* create a session */
setComplete(req.getSession(true));
return ControllerConstants.Views.INSTALL_INDEX;
}
@Override
protected Step getStep() {
return Step.WELCOME;
}
}
| gpl-2.0 |
d4span/freemindfx | src/main/java/plugins/collaboration/socket/MindMapMaster.java | 13982 | /*FreeMind - A Program for creating and viewing Mindmaps
*Copyright (C) 2000-2008 Joerg Mueller, Daniel Polansky, Christian Foltin and others.
*
*See COPYING for Details
*
*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.
*
* Created on 28.12.2008
*/
package plugins.collaboration.socket;
import freemind.common.NumberProperty;
import freemind.common.StringProperty;
import freemind.controller.actions.generated.instance.CollaborationGoodbye;
import freemind.controller.actions.generated.instance.CollaborationUserInformation;
import freemind.extensions.DontSaveMarker;
import freemind.extensions.PermanentNodeHook;
import freemind.main.Resources;
import freemind.main.Tools;
import freemind.main.XMLElement;
import freemind.modes.MindMapNode;
import freemind.modes.mindmapmode.MindMapController;
import freemind.view.mindmapview.NodeView;
import javax.swing.*;
import java.io.IOException;
import java.io.Writer;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.Vector;
/**
* @author foltin
*/
public class MindMapMaster extends SocketBasics implements PermanentNodeHook,
DontSaveMarker {
/**
*
*/
public static final int SOCKET_TIMEOUT_IN_MILLIES = 500;
MasterThread mListener = null;
ServerSocket mServer;
Vector mConnections = new Vector();
protected boolean mLockEnabled = false;
private String mLockMutex = "";
private int mPort;
private String mLockId;
private long mLockedAt;
private String mLockUserName;
private boolean mMasterStarted;
private class MasterThread extends TerminateableThread {
private static final long TIME_BETWEEN_USER_INFORMATION_IN_MILLIES = 5000;
private static final long TIME_FOR_ORPHANED_LOCK = 5000;
private long mLastTimeUserInformationSent = 0;
/**
* @param pName
*/
public MasterThread() {
super("Master");
}
/*
* (non-Javadoc)
*
* @see plugins.collaboration.socket.TerminateableThread#processAction()
*/
public boolean processAction() throws Exception {
try {
logger.finest("Waiting for message");
Socket client = mServer.accept();
logger.info("Received new client.");
client.setSoTimeout(SOCKET_TIMEOUT_IN_MILLIES);
ServerCommunication c = new ServerCommunication(
MindMapMaster.this, client, getMindMapController());
c.start();
synchronized (mConnections) {
mConnections.addElement(c);
}
} catch (SocketTimeoutException e) {
}
final long now = System.currentTimeMillis();
if (now - mLastTimeUserInformationSent > TIME_BETWEEN_USER_INFORMATION_IN_MILLIES) {
mLastTimeUserInformationSent = now;
CollaborationUserInformation userInfo = getMasterInformation();
synchronized (mConnections) {
for (int i = 0; i < mConnections.size(); i++) {
try {
final ServerCommunication connection = (ServerCommunication) mConnections
.elementAt(i);
/* to each server, the IP address is chosen that belongs to this connection.
* E.g. if the connection is routed over one of several network interfaces,
* the address of this interface is reported.
*/
userInfo.setMasterIp(connection.getIpToSocket());
connection.send(userInfo);
} catch (Exception e) {
Resources.getInstance().logException(
e);
}
}
}
}
// timeout such that lock can't be held forever
synchronized (mLockMutex) {
if (mLockEnabled && now - mLockedAt > TIME_FOR_ORPHANED_LOCK) {
logger.warning("Release lock " + mLockId + " held by "
+ mLockUserName);
clearLock();
}
}
return true;
}
}
public synchronized void removeConnection(ServerCommunication client) {
synchronized (mConnections) {
mConnections.remove(client);
}
// correct the map title, as we probably don't have clients anymore
setTitle();
}
protected void setTitle() {
getMindMapController().getController().setTitle();
}
public void startupMapHook() {
super.startupMapHook();
// Restart check, as the startup command is given, even if the mindmap
// is changed via
// the tab bar. So, this method must be idempotent...
if (mMasterStarted) {
// we were already here, so
return;
}
MindMapController controller = getMindMapController();
final StringProperty passwordProperty = new StringProperty(
PASSWORD_DESCRIPTION, PASSWORD);
final StringProperty passwordProperty2 = new StringProperty(
PASSWORD_VERIFICATION_DESCRIPTION, PASSWORD_VERIFICATION);
// StringProperty bindProperty = new StringProperty(
// "IP address of the local machine, or 0.0.0.0 if ", "Host");
final NumberProperty portProperty = getPortProperty();
Vector controls = new Vector();
controls.add(passwordProperty);
controls.add(passwordProperty2);
// controls.add(bindProperty);
controls.add(portProperty);
FormDialog dialog = new FormDialog(controller);
dialog.setUp(controls, new FormDialogValidator() {
public boolean isValid() {
logger.finest("Output valid?");
return Tools.safeEquals(passwordProperty.getValue(),
passwordProperty2.getValue());
}
});
if (!dialog.isSuccess()) {
switchMeOff();
return;
}
/* Store port value in preferences. */
setPortProperty(portProperty);
mPassword = passwordProperty.getValue();
// start server:
logger.info("Start server...");
mMasterStarted = true;
try {
mPort = getPortProperty().getIntValue();
mServer = new ServerSocket(mPort);
mServer.setSoTimeout(SOCKET_TIMEOUT_IN_MILLIES);
mListener = new MasterThread();
mListener.start();
} catch (Exception e) {
Resources.getInstance().logException(e);
controller.getController().errorMessage(
Resources.getInstance().format(
SOCKET_CREATION_EXCEPTION_MESSAGE,
new Object[]{portProperty.getValue(),
e.getMessage()}));
switchMeOff();
return;
}
registerFilter();
logger.info("Starting server. Done.");
setTitle();
}
public void switchMeOff() {
final MindMapController mindMapController = getMindMapController();
// this is not nice, but in the starting phase of the hook, it can't be switched off.
SwingUtilities.invokeLater(new Runnable() {
public void run() {
togglePermanentHook(mindMapController, MASTER_HOOK_LABEL);
}
});
}
public void loadFrom(XMLElement pChild) {
// this plugin should not be saved.
}
public void save(XMLElement pXml) {
// this plugin should not be saved.
// nothing to do.
}
public void shutdownMapHook() {
deregisterFilter();
if (mListener != null) {
signalEndOfSession();
mListener.commitSuicide();
}
try {
if (mServer != null) {
mServer.close();
}
} catch (IOException e) {
Resources.getInstance().logException(e);
}
mMasterStarted = false;
super.shutdownMapHook();
}
/**
*
*/
private void signalEndOfSession() {
CollaborationGoodbye goodbye = new CollaborationGoodbye();
goodbye.setUserId(Tools.getUserName());
synchronized (mConnections) {
for (int i = 0; i < mConnections.size(); i++) {
final ServerCommunication serverCommunication = (ServerCommunication) mConnections
.elementAt(i);
try {
serverCommunication.send(goodbye);
serverCommunication.commitSuicide();
serverCommunication.close();
} catch (IOException e) {
Resources.getInstance().logException(e);
}
}
mConnections.clear();
}
}
public void onAddChild(MindMapNode pAddedChildNode) {
}
public void onAddChildren(MindMapNode pAddedChild) {
}
public void onLostFocusNode(NodeView pNodeView) {
}
public void onNewChild(MindMapNode pNewChildNode) {
}
public void onRemoveChild(MindMapNode pOldChildNode) {
}
public void onRemoveChildren(MindMapNode pOldChildNode, MindMapNode pOldDad) {
}
public void onFocusNode(NodeView pNodeView) {
}
public void onUpdateChildrenHook(MindMapNode pUpdatedNode) {
}
public void onUpdateNodeHook() {
}
public void onViewCreatedHook(NodeView pNodeView) {
}
public void onViewRemovedHook(NodeView pNodeView) {
}
public Integer getRole() {
return ROLE_MASTER;
}
/*
* (non-Javadoc)
*
* @see plugins.collaboration.socket.SocketBasics#getPort()
*/
public int getPort() {
return mPort;
}
/*
* (non-Javadoc)
*
* @see plugins.collaboration.socket.SocketBasics#lock()
*/
protected String lock(String pUserName) throws UnableToGetLockException,
InterruptedException {
synchronized (mLockMutex) {
if (mLockEnabled) {
throw new UnableToGetLockException();
}
mLockEnabled = true;
String lockId = "Lock_" + Math.random();
mLockId = lockId;
mLockedAt = System.currentTimeMillis();
mLockUserName = pUserName;
logger.info("New lock " + lockId + " by " + mLockUserName);
return lockId;
}
}
/*
* (non-Javadoc)
*
* @see
* plugins.collaboration.socket.SocketBasics#sendCommand(java.lang.String,
* java.lang.String, java.lang.String)
*/
protected void broadcastCommand(String pDoAction, String pUndoAction,
String pLockId) throws Exception {
synchronized (mConnections) {
for (int i = 0; i < mConnections.size(); i++) {
((ServerCommunication) mConnections.elementAt(i)).sendCommand(
pDoAction, pUndoAction, pLockId);
}
}
}
/*
* (non-Javadoc)
*
* @see plugins.collaboration.socket.SocketBasics#unlock()
*/
protected void unlock() {
synchronized (mLockMutex) {
if (!mLockEnabled) {
throw new IllegalStateException();
}
logger.fine("Release lock " + mLockId + " held by " + mLockUserName);
clearLock();
}
}
public void clearLock() {
mLockEnabled = false;
mLockId = "none";
mLockUserName = null;
}
/*
* (non-Javadoc)
*
* @see plugins.collaboration.socket.SocketBasics#shutdown()
*/
public void shutdown() {
// TODO Auto-generated method stub
}
public String getLockId() {
synchronized (mLockMutex) {
if (!mLockEnabled) {
throw new IllegalStateException();
}
return mLockId;
}
}
/*
* (non-Javadoc)
*
* @see plugins.collaboration.socket.SocketBasics#getUsers()
*/
public String getUsers() {
StringBuffer users = new StringBuffer(Tools.getUserName());
synchronized (mConnections) {
for (int i = 0; i < mConnections.size(); i++) {
users.append(',');
users.append(' ');
users.append(((ServerCommunication) mConnections.elementAt(i))
.getName());
}
}
return users.toString();
}
public CollaborationUserInformation getMasterInformation() {
CollaborationUserInformation userInfo = new CollaborationUserInformation();
userInfo.setUserIds(getUsers());
userInfo.setMasterHostname(Tools.getHostName());
userInfo.setMasterPort(getPort());
userInfo.setMasterIp(Tools.getHostIpAsString());
return userInfo;
}
public void processUnfinishedLinks() {
}
/* (non-Javadoc)
* @see freemind.extensions.PermanentNodeHook#saveHtml(java.io.Writer)
*/
public void saveHtml(Writer pFileout) {
}
}
| gpl-2.0 |
stelfrich/openmicroscopy | components/insight/SRC/org/openmicroscopy/shoola/agents/dataBrowser/layout/PlateLayout.java | 6076 | /*
* org.openmicroscopy.shoola.agents.dataBrowser.layout.PlateLayout
*
*------------------------------------------------------------------------------
* Copyright (C) 2006-2013 University of Dundee. All rights reserved.
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*------------------------------------------------------------------------------
*/
package org.openmicroscopy.shoola.agents.dataBrowser.layout;
//Java imports
import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
//Third-party libraries
import org.apache.commons.collections.CollectionUtils;
//Application-internal dependencies
import org.openmicroscopy.shoola.agents.dataBrowser.browser.CellDisplay;
import org.openmicroscopy.shoola.agents.dataBrowser.browser.ImageDisplay;
import org.openmicroscopy.shoola.agents.dataBrowser.browser.ImageNode;
import org.openmicroscopy.shoola.agents.dataBrowser.browser.ImageSet;
import org.openmicroscopy.shoola.agents.dataBrowser.browser.WellSampleNode;
import pojos.WellSampleData;
/**
* Lays out the plate.
*
* @author Jean-Marie Burel
* <a href="mailto:j.burel@dundee.ac.uk">j.burel@dundee.ac.uk</a>
* @author Donald MacDonald
* <a href="mailto:donald@lifesci.dundee.ac.uk">donald@lifesci.dundee.ac.uk</a>
* @version 3.0
* @since 3.0-Beta3
*/
public class PlateLayout
implements Layout
{
//NOTE: The algorithm for this layout *relies* on the fact that
//visualization trees are visited in a depth-first fashion.
//When we'll implement iterators to visit a tree, then this class
//will ask for a depth-first iterator.
/** Textual description of this layout. */
static final String DESCRIPTION = "Layout the plate.";
/** Collection of nodes previously displayed. */
private Set oldNodes;
/**
* Lays out the wells.
* @see Layout#doLayout()
*/
public void doLayout() {}
/**
* Retrieves the images.
* @see Layout#visit(ImageNode)
*/
public void visit(ImageNode node) {}
/**
* Retrieves the root node.
* @see Layout#visit(ImageSet)
*/
public void visit(ImageSet node)
{
if (node.getParentDisplay() != null) return;
if (CollectionUtils.isEmpty(oldNodes)) {
Collection nodes = node.getChildrenDisplay();
Iterator i = nodes.iterator();
ImageDisplay n;
List<ImageDisplay> l = new ArrayList<ImageDisplay>();
List<ImageDisplay> col = new ArrayList<ImageDisplay>();
List<ImageDisplay> row = new ArrayList<ImageDisplay>();
CellDisplay cell;
while (i.hasNext()) {
n = (ImageDisplay) i.next();
if (n instanceof CellDisplay) {
cell = (CellDisplay) n;
if (cell.getType() == CellDisplay.TYPE_HORIZONTAL)
col.add(cell);
else row.add(cell);
} else {
l.add(n);
}
}
Dimension maxDim = new Dimension(0, 0);
Iterator children = l.iterator();
ImageDisplay child;
WellSampleData wsd;
while (children.hasNext()) {
child = (ImageDisplay) children.next();
wsd = (WellSampleData) child.getHierarchyObject();
if (wsd.getId() >= 0)
maxDim = LayoutUtils.max(maxDim, child.getPreferredSize());
}
//First need to set width and height
Dimension d;
int height = 0;
int width = 0;
i = l.iterator();
WellSampleNode wsNode;
int r, c;
int h = 0;
int hh;
while (i.hasNext()) {
wsNode = (WellSampleNode) i.next();
h = 0;
hh = 0;
r = wsNode.getLayedoutRow();
c = wsNode.getLayedoutColumn();
d = wsNode.getPreferredSize();
if (r > 0) h = wsNode.getTitleHeight();
if (wsNode.getTitleBarType() == ImageNode.NO_BAR) {
h = wsNode.getTitleHeight();
hh = h;
}
wsNode.setBounds(width+c*maxDim.width,
height+r*(maxDim.height+h) + hh, d.width, d.height);
}
}
}
/**
* Implemented as specified by the {@link Layout} interface.
* @see Layout#getDescription()
*/
public String getDescription() { return DESCRIPTION; }
/**
* Implemented as specified by the {@link Layout} interface.
* @see Layout#getIndex()
*/
public int getIndex() { return LayoutFactory.PLATE_LAYOUT; }
/**
* Implemented as specified by the {@link Layout} interface.
* @see Layout#setOldNodes(Set)
*/
public void setOldNodes(Set oldNodes) { this.oldNodes = oldNodes; }
/**
* Implemented as specified by the {@link Layout} interface.
* @see Layout#setImagesPerRow(int)
*/
public void setImagesPerRow(int number) {}
/**
* Implemented as specified by the {@link Layout} interface.
* @see Layout#getImagesPerRow()
*/
public int getImagesPerRow() { return 0; }
}
| gpl-2.0 |
EHJ-52n/SOS | hibernate/datasource/h2/src/main/java/org/n52/sos/ds/datasource/AbstractH2Datasource.java | 5950 | /*
* Copyright (C) 2012-2021 52°North Spatial Information Research 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.ds.datasource;
import java.lang.reflect.Array;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Pattern;
import org.hibernate.dialect.Dialect;
import org.hibernate.mapping.Table;
import org.hibernate.spatial.dialect.h2geodb.GeoDBDialect;
import org.n52.faroe.ConfigurationError;
import org.n52.faroe.SettingDefinition;
import org.n52.hibernate.spatial.dialect.h2geodb.TimestampWithTimeZoneGeoDBDialect;
import org.n52.iceland.ds.DatasourceCallback;
import geodb.GeoDB;
/**
* TODO JavaDoc
*
* @author <a href="mailto:c.autermann@52north.org">Christian Autermann</a>
*
* @since 4.0.0
*/
public abstract class AbstractH2Datasource extends AbstractHibernateDatasource {
protected static final String H2_DRIVER_CLASS = "org.h2.Driver";
protected static final String H2_DIALECT_CLASS = TimestampWithTimeZoneGeoDBDialect.class.getName();
protected static final String DEFAULT_USERNAME = "sa";
protected static final String DEFAULT_PASSWORD = "";
protected static final Pattern CREATE_INDEX_PATTERN =
Pattern.compile("^create index [a-z]* on observation \\(samplingGeometry\\)$", Pattern.CASE_INSENSITIVE);
@Override
protected Dialect createDialect() {
return new TimestampWithTimeZoneGeoDBDialect();
}
@Override
public boolean supportsClear() {
return true;
}
@Override
public String[] createSchema(Map<String, Object> settings) {
String[] createSchema = super.createSchema(settings);
int index = find(createSchema, CREATE_INDEX_PATTERN);
return stripIndex(createSchema, index);
}
@Override
public Set<SettingDefinition<?>> getChangableSettingDefinitions(Properties p) {
return Collections.emptySet();
}
@Override
public void clear(Properties properties) {
Map<String, Object> settings = parseDatasourceProperties(properties);
Connection conn = null;
Statement stmt = null;
try {
conn = openConnection(settings);
Iterator<Table> tables = getMetadata(conn, settings).collectTableMappings().iterator();
stmt = conn.createStatement();
stmt.execute("set referential_integrity false");
while (tables.hasNext()) {
Table table = tables.next();
if (table.isPhysicalTable()) {
stmt.execute("truncate table " + table.getQuotedName(new GeoDBDialect()));
}
}
stmt.execute("set referential_integrity true");
GeoDB.InitGeoDB(conn);
} catch (SQLException ex) {
throw new ConfigurationError(ex);
} finally {
close(stmt);
close(conn);
}
}
@Override
protected String getDriverClass() {
return H2_DRIVER_CLASS;
}
@Override
public DatasourceCallback getCallback() {
return DatasourceCallback.chain(super.getCallback(), new DatasourceCallback() {
@Override
public Properties onInit(Properties props) {
initGeoDB(parseDatasourceProperties(props));
return props;
}
});
}
protected void initGeoDB(Map<String, Object> settings) throws ConfigurationError {
try (Connection cx = openConnection(settings)) {
GeoDB.InitGeoDB(cx);
} catch (SQLException ex) {
throw new ConfigurationError("Could not init GeoDB", ex);
}
}
public static int find(String[] array, Pattern pattern) {
for (int index = 0; index < array.length; ++index) {
if (pattern.matcher(array[index]).matches()) {
return index;
}
}
return -1;
}
public static <T> T[] stripIndex(T[] array, int idx) {
int len = array.length;
if (idx < 0 || len == 0) {
return array;
}
T[] copy = createArray(array.getClass(), len - 1);
if (idx != 0) {
System.arraycopy(array, 0, copy, 0, idx);
}
if (idx != len - 1) {
System.arraycopy(array, idx + 1, copy, idx, len - idx - 1);
}
return copy;
}
@SuppressWarnings("unchecked")
public static <T> T[] createArray(Class<?> type, int length) {
return ((Object) type == (Object) Object[].class) ? (T[]) new Object[length]
: (T[]) Array.newInstance(type.getComponentType(), length);
}
}
| gpl-2.0 |
FauxFaux/jdk9-jdk | test/javax/swing/plaf/metal/MetalIcons/MetalHiDPIIconsTest.java | 4795 | /*
* Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
/*
* @test
* @bug 8160986
* @summary Bad rendering of Swing UI controls with Metal L&F on HiDPI display
* @run main/manual MetalHiDPIIconsTest
*/
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
public class MetalHiDPIIconsTest {
private static volatile boolean testResult = false;
private static volatile CountDownLatch countDownLatch;
private static final String INSTRUCTIONS = "INSTRUCTIONS:\n"
+ "Verify that icons are painted smoothly for standard Swing UI controls.\n\n"
+ "If the display does not support HiDPI mode press PASS.\n\n"
+ "1. Run the SwingSet2 demo on HiDPI Display.\n"
+ "2. Select Metal Look and Feel\n"
+ "3. Check that the icons are painted smoothly on Swing UI controls like:\n"
+ " - JRadioButton\n"
+ " - JCheckBox\n"
+ " - JComboBox\n"
+ " - JScrollPane (vertical and horizontal scroll bars)\n"
+ "and others...\n\n"
+ "If so, press PASS, else press FAIL.\n";
public static void main(String args[]) throws Exception {
countDownLatch = new CountDownLatch(1);
SwingUtilities.invokeLater(MetalHiDPIIconsTest::createUI);
countDownLatch.await(15, TimeUnit.MINUTES);
if (!testResult) {
throw new RuntimeException("Test fails!");
}
}
private static void createUI() {
final JFrame mainFrame = new JFrame("Metal L&F icons test");
GridBagLayout layout = new GridBagLayout();
JPanel mainControlPanel = new JPanel(layout);
JPanel resultButtonPanel = new JPanel(layout);
GridBagConstraints gbc = new GridBagConstraints();
JTextArea instructionTextArea = new JTextArea();
instructionTextArea.setText(INSTRUCTIONS);
instructionTextArea.setEditable(false);
instructionTextArea.setBackground(Color.white);
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.HORIZONTAL;
mainControlPanel.add(instructionTextArea, gbc);
JButton passButton = new JButton("Pass");
passButton.setActionCommand("Pass");
passButton.addActionListener((ActionEvent e) -> {
testResult = true;
mainFrame.dispose();
countDownLatch.countDown();
});
JButton failButton = new JButton("Fail");
failButton.setActionCommand("Fail");
failButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
mainFrame.dispose();
countDownLatch.countDown();
}
});
gbc.gridx = 0;
gbc.gridy = 0;
resultButtonPanel.add(passButton, gbc);
gbc.gridx = 1;
gbc.gridy = 0;
resultButtonPanel.add(failButton, gbc);
gbc.gridx = 0;
gbc.gridy = 1;
mainControlPanel.add(resultButtonPanel, gbc);
mainFrame.add(mainControlPanel);
mainFrame.pack();
mainFrame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
mainFrame.dispose();
countDownLatch.countDown();
}
});
mainFrame.setVisible(true);
}
}
| gpl-2.0 |
jesusaplsoft/FindAllBugs | findbugs/src/gui/edu/umd/cs/findbugs/sourceViewer/NumberedParagraphView.java | 3911 | /*
* FindBugs - Find Bugs in Java programs
* Copyright (C) 2006, University of Maryland
*
* 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 edu.umd.cs.findbugs.sourceViewer;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;
import java.util.WeakHashMap;
import javax.swing.text.Element;
import javax.swing.text.ParagraphView;
import javax.swing.text.View;
import edu.umd.cs.findbugs.gui2.Driver;
// Code inspired by http://www.developer.com/java/other/article.php/3318421
class NumberedParagraphView extends ParagraphView {
public final static int NUMBERS_WIDTH = (int) Driver.getFontSize() * 3 + 9;
HighlightInformation highlight;
public NumberedParagraphView(Element e, HighlightInformation highlight) {
super(e);
this.highlight = highlight;
}
// protected void setInsets(short top, short left, short bottom,
// short right) {super.setInsets
// (top,(short)(left+NUMBERS_WIDTH),
// bottom,right);
// }
@Override
public void paint(Graphics g, Shape allocation) {
Rectangle r = (allocation instanceof Rectangle) ? (Rectangle) allocation : allocation.getBounds();
Color oldColor = g.getColor();
Integer lineNumber = getLineNumber();
Color highlightColor = highlight.getHighlight(lineNumber);
if (highlightColor != null) {
g.setColor(highlightColor);
g.fillRect(r.x, r.y, r.width, r.height);
g.setColor(oldColor);
}
// r.x += NUMBERS_WIDTH;
super.paint(g, r);
FontMetrics metrics = g.getFontMetrics();
g.setColor(Color.GRAY);
String lineNumberString = lineNumber.toString();
int width = metrics.stringWidth(lineNumberString);
int numberX = r.x - width - 9 + NUMBERS_WIDTH;
int numberY = r.y + metrics.getAscent();
g.drawString(lineNumberString, numberX, numberY);
g.setColor(oldColor);
// System.out.println("Drawing line for " + lineNumber + " @ " + numberX
// +"," + numberY);
// r.x -= NUMBERS_WIDTH;
}
public int getPreviousLineCount0() {
int lineCount = 0;
View parent = this.getParent();
int count = parent.getViewCount();
for (int i = 0; i < count; i++) {
if (parent.getView(i) == this) {
break;
} else {
lineCount += parent.getView(i).getViewCount();
}
}
return lineCount;
}
static WeakHashMap<Element, Integer> elementLineNumberCache = new WeakHashMap<Element, Integer>();
public Integer getLineNumber() {
Element element = this.getElement();
Integer result = elementLineNumberCache.get(element);
if (result != null)
return result;
Element parent = element.getParentElement();
int count = parent.getElementCount();
for (int i = 0; i < count; i++) {
elementLineNumberCache.put(parent.getElement(i), i + 1);
}
result = elementLineNumberCache.get(element);
if (result != null)
return result;
return -1;
}
}
| gpl-2.0 |
skyHALud/codenameone | Ports/iOSPort/xmlvm/apache-harmony-6.0-src-r991881/classlib/modules/swing/src/test/api/java.injected/javax/swing/text/PlainViewTest.java | 14439 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @author Alexey A. Ivanov
*/
package javax.swing.text;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.Shape;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingTestCase;
/**
* This class tests PlainView behavior.
*
* <p>This class is initialized with a "real" PlainView that was obtained from
* JTextArea placed in JFrame.
*
*/
public class PlainViewTest extends SwingTestCase {
private JTextArea area;
private Document doc;
private JFrame frame;
private Shape shape;
private PlainView view;
public void testDrawSelectedText() throws BadLocationException {
area.setText("line1\nline2");
Graphics g = view.getGraphics();
FontMetrics m = view.metrics;
g.setFont(m.getFont());
assertEquals(m.charWidth('l'), view.drawSelectedText(g, 0, 0, 0, 1));
assertEquals(m.stringWidth("line1"), view.drawSelectedText(g, 0, 0, 0, 5));
assertEquals(m.stringWidth("line1\nli"), view.drawSelectedText(g, 0, 0, 0, 8));
try {
view.drawSelectedText(g, 0, 0, -1, 1);
fail("BadLocationException expected");
} catch (BadLocationException e) {
}
try {
view.drawUnselectedText(g, 0, 0, 13, 13);
fail("BadLocationException expected");
} catch (BadLocationException e) {
}
try {
view.drawSelectedText(g, 0, 0, 10, 2);
fail("BadLocationException expected");
} catch (BadLocationException e) {
}
}
public void testDrawUnselectedText() throws BadLocationException {
area.setText("line1\nline2");
Graphics g = view.getGraphics();
FontMetrics m = view.metrics;
g.setFont(m.getFont());
assertEquals(m.charWidth('l'), view.drawUnselectedText(g, 0, 0, 0, 1));
assertEquals(5 + m.charWidth('l'), view.drawUnselectedText(g, 5, 0, 0, 1));
assertEquals(m.stringWidth("line1"), view.drawUnselectedText(g, 0, 0, 0, 5));
assertEquals(m.stringWidth("line1\nli"), view.drawUnselectedText(g, 0, 0, 0, 8));
try {
view.drawUnselectedText(g, 0, 0, -1, 1);
fail("BadLocationException expected");
} catch (BadLocationException e) {
}
try {
view.drawUnselectedText(g, 0, 0, 13, 13);
fail("BadLocationException expected");
} catch (BadLocationException e) {
}
try {
view.drawUnselectedText(g, 0, 0, 10, 2);
fail("BadLocationException expected");
} catch (BadLocationException e) {
}
}
public void testGetPreferredSpan() {
area.setText("1: 0\n2: 012345\n3:\n");
assertEquals(view.metrics.stringWidth("2: 012345"), // longest line
view.getPreferredSpan(View.X_AXIS), 0.00001f);
assertEquals(view.metrics.getHeight() * 4, view.getPreferredSpan(View.Y_AXIS), 0.00001f);
area.setText("\ttext\t1");
float length = view.nextTabStop(0, 0);
length += view.metrics.stringWidth("text");
length = view.nextTabStop(length, 0);
length += view.metrics.stringWidth("1");
assertEquals(length, view.getPreferredSpan(View.X_AXIS), 0.00001f);
}
/**
* Generic tests of <code>modelToView(int, Shape, Position.Bias)</code>.
*/
public void testModelToViewintShapeBias01() throws BadLocationException {
area.setText("1: 0\n2: 012345\n3:\n");
// 01234 5678901234 567
assertTrue(view.modelToView(0, shape, Position.Bias.Backward) instanceof Rectangle);
assertEquals(new Rectangle(1, view.metrics.getHeight()), view.modelToView(0, shape,
Position.Bias.Forward));
assertEquals(new Rectangle(1, view.metrics.getHeight()), view.modelToView(0, shape,
Position.Bias.Backward));
assertEquals(
new Rectangle(view.metrics.charWidth('1'), 0, 1, view.metrics.getHeight()),
view.modelToView(1, shape, Position.Bias.Forward));
assertEquals(
new Rectangle(view.metrics.charWidth('1'), 0, 1, view.metrics.getHeight()),
view.modelToView(1, shape, Position.Bias.Backward));
assertEquals(new Rectangle(view.metrics.stringWidth("2: 012"),
view.metrics.getHeight(), 1, view.metrics.getHeight()), view.modelToView(11,
shape, Position.Bias.Forward));
try {
view.modelToView(-1, shape, Position.Bias.Forward);
fail("BadLocationException is expected");
} catch (BadLocationException e) {
}
assertEquals(new Rectangle(view.metrics.charWidth('\n')/*0*/,
view.metrics.getHeight() * 3, 1, view.metrics.getHeight()), view.modelToView(
doc.getLength() + 1, shape, Position.Bias.Forward));
try {
view.modelToView(doc.getLength() + 2, shape, Position.Bias.Forward);
fail("BadLocationException is expected");
} catch (BadLocationException e) {
}
// try {
view.modelToView(0, shape, null);
// isn't thrown
//fail("IllegalArgumentException must be thrown");
// } catch (IllegalArgumentException e) { }
doc.insertString(1, "\t", null);
assertEquals(
new Rectangle(view.metrics.charWidth('1'), 0, 1, view.metrics.getHeight()),
view.modelToView(1, shape, Position.Bias.Forward));
assertEquals(new Rectangle((int) view.nextTabStop(view.metrics.charWidth('1'), 0), 0,
1, view.metrics.getHeight()), view.modelToView(2, shape, Position.Bias.Forward));
assertEquals(new Rectangle((int) view.nextTabStop(view.metrics.charWidth('1'), 0)
+ view.metrics.charWidth(':'), 0, 1, view.metrics.getHeight()), view
.modelToView(3, shape, Position.Bias.Forward));
}
/**
* Tests <code>modelToView(int, Shape, Position.Bias)</code> when
* <code>shape.getBounds().x != 0</code> and/or
* <code>shape.getBounds().y != 0</code>.
*/
public void testModelToViewintShapeBias02() throws BadLocationException {
area.setText("1: 0\n2: 012345\n3:\n");
((Rectangle) shape).setLocation(7, 10);
assertFalse(((Rectangle) shape).x == 0);
assertEquals(new Rectangle(((Rectangle) shape).x, ((Rectangle) shape).y, 1,
view.metrics.getHeight()), view.modelToView(0, shape, Position.Bias.Forward));
}
/**
* Tests <code>modelToView(int, Shape, Position.Bias)</code>
* with zero-length document.
*/
public void testModelToViewintShapeBias03() throws BadLocationException {
area.setText("");
assertEquals(0, view.getDocument().getLength());
assertEquals(new Rectangle(1, view.metrics.getHeight()), view.modelToView(0, shape,
Position.Bias.Forward));
assertEquals(new Rectangle(1, view.metrics.getHeight()), view.modelToView(1, shape,
Position.Bias.Forward));
try {
view.modelToView(-1, shape, Position.Bias.Forward);
fail("BadLocationException is expected");
} catch (BadLocationException e) {
}
try {
view.modelToView(2, shape, Position.Bias.Forward);
fail("BadLocationException is expected");
} catch (BadLocationException e) {
}
}
/**
* Tests nextTabStop method with default tab size of 8.
*/
public void testNextTabStop01() {
float tabPos = view.getTabSize() * view.metrics.charWidth('m');
assertEquals(8, view.getTabSize());
assertEquals(tabPos, view.nextTabStop(0.0f, 0), 0.00001f);
assertEquals(tabPos, view.nextTabStop(10.0f, 0), 0.00001f);
assertEquals(tabPos, view.nextTabStop(tabPos - 1, 0), 0.00001f);
assertEquals(tabPos * 2, view.nextTabStop(tabPos, 0), 0.00001f);
// Setting tab size to 4 has no effect on already initialized view
doc.putProperty(PlainDocument.tabSizeAttribute, new Integer(4));
assertEquals(4, view.getTabSize());
// The change has no effect
assertEquals(tabPos, view.nextTabStop(0.0f, 0), 0.00001f);
// But after metrics have been updated...
view.updateMetrics();
if (isHarmony()) {
// Our implemetation updates tabSize in updateMetrics
tabPos = view.getTabSize() * view.metrics.charWidth('m');
}
assertEquals(tabPos, view.nextTabStop(0.0f, 0), 0.00001f);
assertEquals(tabPos * 2, view.nextTabStop(tabPos, 0), 0.00001f);
}
/*
* int viewToModel(float, float, Shape, Position.Bias[])
*/
public void testViewToModelfloatfloatShapeBiasArray() throws BadLocationException {
area.setText("1: 0\n2: 012345\n3:\n");
// 01234 5678901234 567
int h = view.metrics.getHeight();
int w = view.metrics.charWidth('1');
Position.Bias[] bias = new Position.Bias[1];
assertNull(bias[0]);
assertEquals(0, view.viewToModel(0f, 0f, shape, bias));
assertSame(Position.Bias.Forward, bias[0]);
bias[0] = null;
assertEquals(0, view.viewToModel(w / 4f, h / 4f, shape, bias));
assertSame(Position.Bias.Forward, bias[0]);
bias[0] = null;
assertEquals(1, view.viewToModel(w - 1f, h / 2f, shape, bias));
assertSame(Position.Bias.Forward, bias[0]);
bias[0] = null;
assertEquals(1, view.viewToModel(w - w / 4f, h / 2f, shape, bias));
assertSame(Position.Bias.Forward, bias[0]);
bias[0] = null;
w = view.metrics.charWidth('2');
// Negative coordinates
assertEquals(0, view.viewToModel(-1f, h - 0.1f, shape, bias));
assertSame(Position.Bias.Forward, bias[0]);
bias[0] = null;
assertEquals(5, view.viewToModel(-1f, h, shape, bias));
assertSame(Position.Bias.Forward, bias[0]);
bias[0] = null;
assertEquals(5, view.viewToModel(-1f, h + 0.1f, shape, bias));
assertSame(Position.Bias.Forward, bias[0]);
bias[0] = null;
assertEquals(0, view.viewToModel(1f, -1f, shape, bias));
assertSame(Position.Bias.Forward, bias[0]);
bias[0] = null;
assertEquals(0, view.viewToModel(w + 1f, -1f, shape, bias));
assertSame(Position.Bias.Forward, bias[0]);
bias[0] = null;
// Past last character of line 1
assertEquals(4, view.viewToModel(view.metrics.stringWidth("1: 0") + 1f, h / 2, shape,
bias));
assertEquals(4, view.viewToModel(view.metrics.stringWidth("1: 0") + 1f, h - 0.1f,
shape, bias));
assertSame(Position.Bias.Forward, bias[0]);
bias[0] = null;
assertEquals(9, view.viewToModel(view.metrics.stringWidth("1: 0"), h, shape, bias));
assertSame(Position.Bias.Forward, bias[0]);
bias[0] = null;
assertEquals(9, view.viewToModel(view.metrics.stringWidth("1: 0"), h + 0.1f, shape,
bias));
assertSame(Position.Bias.Forward, bias[0]);
bias[0] = null;
// Below last line
h = (int) view.getPreferredSpan(View.Y_AXIS);
int pos = doc.getLength();
assertEquals(pos, view.viewToModel(0f, h - 0.1f, shape, bias));
assertSame(Position.Bias.Forward, bias[0]);
bias[0] = null;
assertEquals(pos, view.viewToModel(0f, h, shape, bias));
assertSame(Position.Bias.Forward, bias[0]);
bias[0] = null;
assertEquals(pos, view.viewToModel(0f, h + 0.1f, shape, bias));
assertSame(Position.Bias.Forward, bias[0]);
bias[0] = null;
// Test with tab
w = view.metrics.charWidth('1');
doc.insertString(1, "\t", null);
int tab = (int) view.nextTabStop(w, 0);
int tabSize = tab - w;
assertEquals(1, view.viewToModel(w + tabSize / 2f - 0.5f, 0f, shape, bias));
assertEquals(2, view.viewToModel(w + tabSize / 2f + 0.5f, 0f, shape, bias));
assertEquals(2, view.viewToModel(tab - 1f, 0f, shape, bias));
assertEquals(3, view
.viewToModel(tab + view.metrics.charWidth(':') - 1f, 0, shape, bias));
}
/**
* Creates JFrame (<code>frame</code>), puts JTextArea (<code>area</code>)
* into it and initializes <code>doc</code>, <code>root</code>,
* <code>view</code>, and <code>shape</code> using JTextArea methods.
*/
@Override
protected void setUp() throws Exception {
super.setUp();
frame = new JFrame("PlainView Test");
area = new JTextArea(" ");
frame.getContentPane().add(area);
frame.setSize(100, 150);
frame.pack();
doc = area.getDocument();
view = (PlainView) area.getUI().getRootView(area).getView(0);
shape = area.getVisibleRect();
}
/*
* @see TestCase#tearDown()
*/
@Override
protected void tearDown() throws Exception {
super.tearDown();
frame.dispose();
}
// Painting methods are not tested
/*
public void testDrawLine() {
}
public void testPaint() {
}
*/
}
| gpl-2.0 |
GustoniaEagle/Adventurers-Alchemy | src/main/java/com/eagle/adventurersalchemy/api/AdventurersAlchemyAPI.java | 1019 | package com.eagle.adventurersalchemy.api;
import com.eagle.adventurersalchemy.api.recipe.RecipeMortar;
import net.minecraft.item.ItemStack;
import java.util.ArrayList;
import java.util.List;
/**
* This class was created by GustoniaEagle.
* It is distributed under a part of the Adventurer's Alchemy mod.
* https://github.com/GustoniaEagle/
* <p/>
* Adventurer's Alchemy is open source, and available under the
* GNU General Public License Version 2.
* <p/>
* File created @ 21/06/2015, 09:55 GMT.
*/
public final class AdventurersAlchemyAPI
{
public static List<RecipeMortar> mortarRecipes = new ArrayList<RecipeMortar>();
/**
* Registers a Mortar Recipe.
*
* @param input The input.
* @param output The output.
* @return The recipe created.
*/
public static RecipeMortar registerMortarRecipe(ItemStack input, ItemStack output)
{
RecipeMortar recipe = new RecipeMortar(input, output);
mortarRecipes.add(recipe);
return recipe;
}
}
| gpl-2.0 |
headius/jato | test/functional/jvm/SynchronizationTest.java | 3039 | /*
* Copyright (C) 2008 Saeed Siam
*
* This file is released under the GPL version 2 with the following
* clarification and special exception:
*
* Linking this library statically or dynamically with other modules is
* making a combined work based on this library. Thus, the terms and
* conditions of the GNU General Public License cover the whole
* combination.
*
* As a special exception, the copyright holders of this library give you
* permission to link this library with independent modules to produce an
* executable, regardless of the license terms of these independent
* modules, and to copy and distribute the resulting executable under terms
* of your choice, provided that you also meet, for each linked independent
* module, the terms and conditions of the license of that module. An
* independent module is a module which is not derived from or based on
* this library. If you modify this library, you may extend this exception
* to your version of the library, but you are not obligated to do so. If
* you do not wish to do so, delete this exception statement from your
* version.
*
* Please refer to the file LICENSE for details.
*/
package jvm;
/**
* @author Saeed Siam
*/
public class SynchronizationTest extends TestCase {
public static void testMonitorEnterAndExit() {
Object obj = new Object();
synchronized (obj) {
assertNotNull(obj);
}
}
public static synchronized int staticSynchronizedMethod(int x) {
return x;
}
public synchronized int synchronizedMethod(int x) {
return x;
}
public static synchronized void staticSynchronizedExceptingMethod() {
throw new RuntimeException();
}
public synchronized void synchronizedExceptingMethod() {
throw new RuntimeException();
}
public static void testSynchronizedExceptingMethod() {
SynchronizationTest test = new SynchronizationTest();
boolean caught = false;
try {
test.synchronizedExceptingMethod();
} catch (RuntimeException e) {
caught = true;
}
assertTrue(caught);
}
public static void testSynchronizedMethod() {
SynchronizationTest test = new SynchronizationTest();
assertEquals(3, test.synchronizedMethod(3));
}
public static void testStaticSynchronizedExceptingMethod() {
boolean caught = false;
try {
staticSynchronizedExceptingMethod();
} catch (RuntimeException e) {
caught = true;
}
assertTrue(caught);
}
public static void testStaticSynchronizedMethod() {
assertEquals(3, staticSynchronizedMethod(3));
}
public static void main(String[] args) {
testMonitorEnterAndExit();
testStaticSynchronizedMethod();
testSynchronizedMethod();
testStaticSynchronizedExceptingMethod();
testSynchronizedExceptingMethod();
}
}
| gpl-2.0 |
bramalingam/bioformats | components/formats-bsd/src/loci/formats/codec/JPEGTileDecoder.java | 10387 | /*
* #%L
* BSD implementations of Bio-Formats readers and writers
* %%
* Copyright (C) 2005 - 2016 Open Microscopy Environment:
* - Board of Regents of the University of Wisconsin-Madison
* - Glencoe Software, Inc.
* - University of Dundee
* %%
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* #L%
*/
package loci.formats.codec;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.ColorModel;
import java.awt.image.ImageConsumer;
import java.awt.image.ImageProducer;
import java.io.IOException;
import java.io.InputStream;
import java.util.Hashtable;
import loci.common.ByteArrayHandle;
import loci.common.RandomAccessInputStream;
import loci.common.Region;
import loci.formats.FormatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
*/
public class JPEGTileDecoder {
// -- Constants --
protected static final Logger LOGGER =
LoggerFactory.getLogger(JPEGTileDecoder.class);
// -- Fields --
private TileConsumer consumer;
private TileCache tiles;
private RandomAccessInputStream in;
// -- JPEGTileDecoder API methods --
public void initialize(String id, int imageWidth) {
try {
initialize(new RandomAccessInputStream(id), imageWidth);
}
catch (IOException e) {
LOGGER.debug("", e);
}
}
public void initialize(RandomAccessInputStream in, int imageWidth) {
initialize(in, 0, 0, imageWidth);
}
public void initialize(RandomAccessInputStream in, int y, int h,
int imageWidth)
{
this.in = in;
tiles = new TileCache(y, h);
preprocess(this.in);
try {
Toolkit toolkit = Toolkit.getDefaultToolkit();
byte[] data = new byte[this.in.available()];
this.in.readFully(data);
Image image = toolkit.createImage(data);
ImageProducer producer = image.getSource();
consumer = new TileConsumer(producer, y, h);
producer.startProduction(consumer);
while (producer.isConsumer(consumer));
}
catch (IOException e) { }
}
/**
* Pre-process the stream to make sure that the
* image width and height are non-zero. Returns an array containing
* the image width and height.
*/
public int[] preprocess(RandomAccessInputStream in) {
int[] dims = new int[2];
try {
long fp = in.getFilePointer();
boolean littleEndian = in.isLittleEndian();
in.order(false);
while (in.getFilePointer() < in.length() - 1) {
int code = in.readShort() & 0xffff;
int length = in.readShort() & 0xffff;
long pointer = in.getFilePointer();
if (length > 0xff00 || code < 0xff00) {
in.seek(pointer - 3);
continue;
}
if (code == 0xffc0) {
in.skipBytes(1);
int height = in.readShort() & 0xffff;
int width = in.readShort() & 0xffff;
if (height == 0 || width == 0) {
throw new RuntimeException(
"Width or height > 65500 is not supported.");
}
dims[0] = width;
dims[1] = height;
break;
}
else if (pointer + length - 2 < in.length()) {
in.seek(pointer + length - 2);
}
else {
break;
}
}
in.seek(fp);
in.order(littleEndian);
}
catch (IOException e) { }
return dims;
}
public byte[] getScanline(int y) {
try {
return tiles.get(0, y, consumer.getWidth(), 1);
}
catch (FormatException e) {
LOGGER.debug("", e);
}
catch (IOException e) {
LOGGER.debug("", e);
}
return null;
}
public int getWidth() {
return consumer.getWidth();
}
public int getHeight() {
return consumer.getHeight();
}
public void close() {
try {
if (in != null) {
in.close();
}
}
catch (IOException e) {
LOGGER.debug("", e);
}
tiles = null;
consumer = null;
}
// -- Helper classes --
class TileConsumer implements ImageConsumer {
private int width, height;
private ImageProducer producer;
private int yy = 0, hh = 0;
public TileConsumer(ImageProducer producer) {
this.producer = producer;
}
public TileConsumer(ImageProducer producer, int y, int h) {
this(producer);
this.yy = y;
this.hh = h;
}
// -- TileConsumer API methods --
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
// -- ImageConsumer API methods --
@Override
public void imageComplete(int status) {
producer.removeConsumer(this);
}
@Override
public void setDimensions(int width, int height) {
this.width = width;
this.height = height;
if (hh <= 0) hh = height;
}
@Override
public void setPixels(int x, int y, int w, int h, ColorModel model,
byte[] pixels, int off, int scanSize)
{
LOGGER.debug("Storing row {} of {} ({}%)", new Object[] {y, height,
((double) y / height) * 100.0});
if (y >= (yy + hh)) {
imageComplete(0);
return;
}
else if (y < yy) return;
try {
tiles.add(pixels, x, y, w, h);
}
catch (FormatException e) {
LOGGER.debug("", e);
}
catch (IOException e) {
LOGGER.debug("", e);
}
}
@Override
public void setPixels(int x, int y, int w, int h, ColorModel model,
int[] pixels, int off, int scanSize)
{
LOGGER.debug("Storing row {} of {} ({}%)", new Object[] {y, (yy + hh),
((double) y / (yy + hh)) * 100.0});
if (y >= (yy + hh)) {
imageComplete(0);
return;
}
else if (y < yy) return;
try {
tiles.add(pixels, x, y, w, h);
}
catch (FormatException e) {
LOGGER.debug("", e);
}
catch (IOException e) {
LOGGER.debug("", e);
}
}
@Override
public void setProperties(Hashtable props) { }
@Override
public void setColorModel(ColorModel model) { }
@Override
public void setHints(int hintFlags) { }
}
class TileCache {
private static final int ROW_COUNT = 128;
private Hashtable<Region, byte[]> compressedTiles =
new Hashtable<Region, byte[]>();
private JPEGCodec codec = new JPEGCodec();
private CodecOptions options = new CodecOptions();
private ByteVector toCompress = new ByteVector();
private int row = 0;
private Region lastRegion = null;
private byte[] lastTile = null;
private int yy = 0, hh = 0;
public TileCache(int yy, int hh) {
options.interleaved = true;
options.littleEndian = false;
this.yy = yy;
this.hh = hh;
}
public void add(byte[] pixels, int x, int y, int w, int h)
throws FormatException, IOException
{
toCompress.add(pixels);
row++;
if ((y % ROW_COUNT) == ROW_COUNT - 1 || y == getHeight() - 1 ||
y == yy + hh - 1)
{
Region r = new Region(x, y - row + 1, w, row);
options.width = w;
options.height = row;
options.channels = 1;
options.bitsPerSample = 8;
options.signed = false;
byte[] compressed = codec.compress(toCompress.toByteArray(), options);
compressedTiles.put(r, compressed);
toCompress.clear();
}
}
public void add(int[] pixels, int x, int y, int w, int h)
throws FormatException, IOException
{
byte[] buf = new byte[pixels.length * 3];
for (int i=0; i<pixels.length; i++) {
buf[i * 3] = (byte) ((pixels[i] & 0xff0000) >> 16);
buf[i * 3 + 1] = (byte) ((pixels[i] & 0xff00) >> 8);
buf[i * 3 + 2] = (byte) (pixels[i] & 0xff);
}
toCompress.add(buf);
row++;
if ((y % ROW_COUNT) == ROW_COUNT - 1 || y == getHeight() - 1 ||
y == yy + hh - 1)
{
Region r = new Region(x, y - row + 1, w, row);
options.width = w;
options.height = row;
options.channels = 3;
options.bitsPerSample = 8;
options.signed = false;
byte[] compressed = codec.compress(toCompress.toByteArray(), options);
compressedTiles.put(r, compressed);
toCompress.clear();
row = 0;
}
}
public byte[] get(int x, int y, int w, int h)
throws FormatException, IOException
{
Region[] keys = compressedTiles.keySet().toArray(new Region[0]);
Region r = new Region(x, y, w, h);
for (Region key : keys) {
if (key.intersects(r)) {
r = key;
}
}
if (!r.equals(lastRegion)) {
lastRegion = r;
byte[] compressed = null;
compressed = compressedTiles.get(r);
if (compressed == null) return null;
lastTile = codec.decompress(compressed, options);
}
int pixel = options.channels * (options.bitsPerSample / 8);
byte[] buf = new byte[w * h * pixel];
for (int i=0; i<h; i++) {
System.arraycopy(lastTile, r.width * pixel * (i + y - r.y) + (x - r.x),
buf, i * w * pixel, pixel * w);
}
return buf;
}
}
}
| gpl-2.0 |
THU-EarthInformationScienceLab/CAFE_NODE | datamanager-core/src/main/java/cn/edu/tsinghua/cess/task/service/impl/executor/index/IndexParser.java | 168 | package cn.edu.tsinghua.cess.task.service.impl.executor.index;
public interface IndexParser {
public Index parse(TemporalRange range, TemporalRange specified);
}
| gpl-2.0 |
as-1/STSP | libraries/OpenTS/docs/tutorial/simple/Main.java | 1529 |
import org.coinor.opents.*;
public class Main
{
public static void main (String args[])
{
// Initialize our objects
java.util.Random r = new java.util.Random( 12345 );
double[][] customers = new double[20][2];
for( int i = 0; i < 20; i++ )
for( int j = 0; j < 2; j++ )
customers[i][j] = r.nextDouble()*200;
ObjectiveFunction objFunc = new MyObjectiveFunction( customers );
Solution initialSolution = new MySolution( customers );
MoveManager moveManager = new MyMoveManager();
TabuList tabuList = new SimpleTabuList( 7 ); // In OpenTS package
// Create Tabu Search object
TabuSearch tabuSearch = new SingleThreadedTabuSearch(
initialSolution,
moveManager,
objFunc,
tabuList,
new BestEverAspirationCriteria(), // In OpenTS package
false ); // maximizing = yes/no; false means minimizing
// Start solving
tabuSearch.setIterationsToGo( 100 );
tabuSearch.startSolving();
// Show solution
MySolution best = (MySolution)tabuSearch.getBestSolution();
System.out.println( "Best Solution:\n" + best );
int[] tour = best.tour;
for( int i = 0; i < tour.length; i++ )
System.out.println(
customers[tour[i]][0] + "\t" + customers[tour[i]][1] );
} // end main
} // end class Main
| gpl-2.0 |
veer66/PaliNLP | src/de/unitrier/daalft/pali/morphology/element/ChangingOccurrence.java | 1080 | package de.unitrier.daalft.pali.morphology.element;
import de.unitrier.daalft.pali.general.Alphabet;
/**
* Changes the word to which it is attached
* @author David
*
*/
public class ChangingOccurrence extends Occurrence {
/**
* Constructor
* @param in information
*/
public ChangingOccurrence (String in) {
super(in);
}
@Override
public String apply(String word) {
// determine type of change
if (occ.matches("m(\\d+)")) {
int offset = Integer.parseInt(occ.substring(1));
return word.substring(0, word.length()-offset);
}
if (occ.matches("l(\\d+)")) {
int offset = word.length() - Integer.parseInt(occ.substring(1)) + 1;
StringBuilder sb = new StringBuilder();
for (int i = 0; i < word.length(); i++) {
if (i == offset) {
sb.append(Alphabet.getLong(word.charAt(i)+""));
} else {
sb.append(word.charAt(i));
}
}
return sb.toString();
}
return word;
}
@Override
public ConstructedWord apply(ConstructedWord cw) {
String w = cw.getStem();
String w2 = apply(w);
cw.setStem(w2);
return cw;
}
}
| gpl-2.0 |
skyHALud/codenameone | Ports/iOSPort/xmlvm/src/ios/org/xmlvm/ios/CoreMedia.java | 4656 | package org.xmlvm.ios;
import java.util.*;
import org.xmlvm.XMLVMSkeletonOnly;
@XMLVMSkeletonOnly
public class CoreMedia {
/*
* Static methods
*/
/**
* void CMRemoveAttachment(CMAttachmentBearerRef target, CFStringRef key) ;
*/
public static void CMRemoveAttachment(CMAttachmentBearer target, String key){
throw new RuntimeException("Stub");
}
/**
* OSStatus CMTextFormatDescriptionGetDefaultStyle( CMFormatDescriptionRef desc, uint16_t *outLocalFontID, Boolean *outBold, Boolean *outItalic, Boolean *outUnderline, CGFloat *outFontSize, CGFloat outColorComponents[4]) ;
*/
public static int CMTextFormatDescriptionGetDefaultStyle(CMFormatDescription desc, short[] outLocalFontID, byte[] outBold, byte[] outItalic, byte[] outUnderline, float[] outFontSize, float[] outColorComponents){
throw new RuntimeException("Stub");
}
/**
* OSStatus CMAudioSampleBufferCreateWithPacketDescriptions( CFAllocatorRef allocator, CMBlockBufferRef dataBuffer, Boolean dataReady, CMSampleBufferMakeDataReadyCallback makeDataReadyCallback, void *makeDataReadyRefcon, CMFormatDescriptionRef formatDescription, CMItemCount numSamples, CMTime sbufPTS, const AudioStreamPacketDescription *packetDescriptions, CMSampleBufferRef *sBufOut) ;
*/
public static int CMAudioSampleBufferCreateWithPacketDescriptions(CFAllocator allocator, CMBlockBuffer dataBuffer, byte dataReady, Object makeDataReadyCallback, byte[] makeDataReadyRefcon, CMFormatDescription formatDescription, long numSamples, CMTime sbufPTS, Reference<AudioStreamPacketDescription> packetDescriptions, CMSampleBuffer sBufOut){
throw new RuntimeException("Stub");
}
/**
* OSStatus CMTextFormatDescriptionGetFontName( CMFormatDescriptionRef desc, uint16_t localFontID, CFStringRef *outFontName) ;
*/
public static int CMTextFormatDescriptionGetFontName(CMFormatDescription desc, short localFontID, String outFontName){
throw new RuntimeException("Stub");
}
/**
* OSStatus CMTextFormatDescriptionGetJustification( CMFormatDescriptionRef desc, CMTextJustificationValue *outHorizontalJust, CMTextJustificationValue *outVerticalJust) ;
*/
public static int CMTextFormatDescriptionGetJustification(CMFormatDescription desc, byte[] outHorizontalJust, byte[] outVerticalJust){
throw new RuntimeException("Stub");
}
/**
* OSStatus CMTextFormatDescriptionGetDisplayFlags( CMFormatDescriptionRef desc, CMTextDisplayFlags *outDisplayFlags) ;
*/
public static int CMTextFormatDescriptionGetDisplayFlags(CMFormatDescription desc, int[] outDisplayFlags){
throw new RuntimeException("Stub");
}
/**
* void CMSetAttachment(CMAttachmentBearerRef target, CFStringRef key, CFTypeRef value, CMAttachmentMode attachmentMode) ;
*/
public static void CMSetAttachment(CMAttachmentBearer target, String key, byte[] value, int attachmentMode){
throw new RuntimeException("Stub");
}
/**
* CFDictionaryRef CMCopyDictionaryOfAttachments(CFAllocatorRef allocator, CMAttachmentBearerRef target, CMAttachmentMode attachmentMode) ;
*/
public static CFDictionary CMCopyDictionaryOfAttachments(CFAllocator allocator, CMAttachmentBearer target, int attachmentMode){
throw new RuntimeException("Stub");
}
/**
* void CMSetAttachments(CMAttachmentBearerRef target, CFDictionaryRef theAttachments, CMAttachmentMode attachmentMode) ;
*/
public static void CMSetAttachments(CMAttachmentBearer target, CFDictionary theAttachments, int attachmentMode){
throw new RuntimeException("Stub");
}
/**
* CFTypeRef CMGetAttachment(CMAttachmentBearerRef target, CFStringRef key, CMAttachmentMode *attachmentModeOut) ;
*/
public static byte[] CMGetAttachment(CMAttachmentBearer target, String key, int[] attachmentModeOut){
throw new RuntimeException("Stub");
}
/**
* void CMPropagateAttachments(CMAttachmentBearerRef source, CMAttachmentBearerRef destination) ;
*/
public static void CMPropagateAttachments(CMAttachmentBearer source, CMAttachmentBearer destination){
throw new RuntimeException("Stub");
}
/**
* OSStatus CMTextFormatDescriptionGetDefaultTextBox( CMFormatDescriptionRef desc, Boolean originIsAtTopLeft, CGFloat heightOfTextTrack, CGRect *outDefaultTextBox) ;
*/
public static int CMTextFormatDescriptionGetDefaultTextBox(CMFormatDescription desc, byte originIsAtTopLeft, float heightOfTextTrack, Reference<CGRect> outDefaultTextBox){
throw new RuntimeException("Stub");
}
/**
* void CMRemoveAllAttachments(CMAttachmentBearerRef target) ;
*/
public static void CMRemoveAllAttachments(CMAttachmentBearer target){
throw new RuntimeException("Stub");
}
/*
* Constructors
*/
/** Default constructor */
CoreMedia() {}
}
| gpl-2.0 |
mixaceh/openyu-mix.j | openyu-mix-core/src/main/java/org/openyu/mix/sasang/log/SasangPlayLog.java | 1216 | package org.openyu.mix.sasang.log;
import java.util.List;
import org.openyu.mix.app.log.AppLogEntity;
import org.openyu.mix.item.vo.Item;
import org.openyu.mix.sasang.service.SasangService.PlayType;
import org.openyu.mix.sasang.vo.Outcome;
/**
* 四象玩的log
*
* log不做bean,直接用entity處理掉
*/
public interface SasangPlayLog extends AppLogEntity
{
String KEY = SasangPlayLog.class.getName();
/**
* 玩的類別
*
* @return
*/
PlayType getPlayType();
void setPlayType(PlayType playType);
/**
* 玩的時間
*
* @return
*/
Long getPlayTime();
void setPlayTime(Long playTime);
/**
* 玩的結果
*
* @return
*/
Outcome getOutcome();
void setOutcome(Outcome outcome);
/**
* 真正成功扣道具及儲值幣的次數
*
* @return
*/
Integer getRealTimes();
void setRealTimes(Integer realTimes);
/**
* 消耗的金幣
*
* @return
*/
Long getSpendGold();
void setSpendGold(Long spendGold);
/**
* 消耗的道具
*
* @return
*/
List<Item> getSpendItems();
void setSpendItems(List<Item> spendItems);
/**
* 消耗的儲值幣
*
* @return
*/
Integer getSpendCoin();
void setSpendCoin(Integer spendCoin);
}
| gpl-2.0 |
VytautasBoznis/l2.skilas.lt | aCis_gameserver/java/net/sf/l2j/gameserver/model/L2Macro.java | 1612 | /*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later
* version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.l2j.gameserver.model;
public class L2Macro
{
public final static int CMD_TYPE_SKILL = 1;
public final static int CMD_TYPE_ACTION = 3;
public final static int CMD_TYPE_SHORTCUT = 4;
public int id;
public final int icon;
public final String name;
public final String descr;
public final String acronym;
public final L2MacroCmd[] commands;
public static class L2MacroCmd
{
public final int entry;
public final int type;
public final int d1; // skill_id or page for shortcuts
public final int d2; // shortcut
public final String cmd;
public L2MacroCmd(int pEntry, int pType, int pD1, int pD2, String pCmd)
{
entry = pEntry;
type = pType;
d1 = pD1;
d2 = pD2;
cmd = pCmd;
}
}
public L2Macro(int pId, int pIcon, String pName, String pDescr, String pAcronym, L2MacroCmd[] pCommands)
{
id = pId;
icon = pIcon;
name = pName;
descr = pDescr;
acronym = pAcronym;
commands = pCommands;
}
} | gpl-2.0 |
smarr/Truffle | substratevm/src/com.oracle.svm.core/src/com/oracle/svm/core/graal/nodes/ReadReturnAddressNode.java | 2335 | /*
* Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.oracle.svm.core.graal.nodes;
import org.graalvm.compiler.graph.NodeClass;
import org.graalvm.compiler.nodeinfo.NodeCycles;
import org.graalvm.compiler.nodeinfo.NodeInfo;
import org.graalvm.compiler.nodeinfo.NodeSize;
import org.graalvm.compiler.nodes.FixedWithNextNode;
import org.graalvm.compiler.nodes.spi.LIRLowerable;
import org.graalvm.compiler.nodes.spi.NodeLIRBuilderTool;
import com.oracle.svm.core.FrameAccess;
import jdk.vm.ci.meta.Value;
@NodeInfo(cycles = NodeCycles.CYCLES_1, size = NodeSize.SIZE_1)
public final class ReadReturnAddressNode extends FixedWithNextNode implements LIRLowerable {
public static final NodeClass<ReadReturnAddressNode> TYPE = NodeClass.create(ReadReturnAddressNode.class);
public ReadReturnAddressNode() {
super(TYPE, FrameAccess.getWordStamp());
}
@Override
public void generate(NodeLIRBuilderTool gen) {
assert FrameAccess.returnAddressSize() > 0;
Value result = gen.getLIRGeneratorTool().emitReadReturnAddress(FrameAccess.getWordStamp(), FrameAccess.returnAddressSize());
gen.setResult(this, result);
}
}
| gpl-2.0 |
mschoettle/ecse429-fall15-project | ca.mcgill.sel.ram.gui/src/ca/mcgill/sel/ram/ui/examples/TextTest.java | 2982 | package ca.mcgill.sel.ram.ui.examples;
import org.eclipse.emf.ecore.EObject;
import ca.mcgill.sel.ram.ui.RamApp;
import ca.mcgill.sel.ram.ui.components.RamTextComponent;
import ca.mcgill.sel.ram.ui.components.RamTextComponent.Alignment;
import ca.mcgill.sel.ram.ui.scenes.RamAbstractScene;
import ca.mcgill.sel.ram.ui.scenes.handler.impl.DefaultRamSceneHandler;
import ca.mcgill.sel.ram.ui.utils.ResourceUtils;
public final class TextTest {
public class TextScene extends RamAbstractScene<DefaultRamSceneHandler> {
/**
* @param app
*/
public TextScene(final RamApp app) {
super(app, "grid");
final RamTextComponent left = new RamTextComponent("Left\naligned");
left.setNoStroke(false);
left.setAlignment(Alignment.LEFT_ALIGN);
left.translate(100, 100);
getCanvas().addChild(left);
final RamTextComponent right = new RamTextComponent("Right\naligned");
right.setNoStroke(false);
right.setAlignment(Alignment.RIGHT_ALIGN);
right.translate(200, 100);
getCanvas().addChild(right);
final RamTextComponent center = new RamTextComponent("Centered\nText");
center.setNoStroke(false);
center.setAlignment(Alignment.CENTER_ALIGN);
center.translate(300, 100);
getCanvas().addChild(center);
final RamTextComponent maxed = new RamTextComponent("ThisOneHasA max width");
maxed.setNoStroke(false);
maxed.setAlignment(Alignment.LEFT_ALIGN);
maxed.setMaximumWidth(100);
maxed.translate(100, 200);
getCanvas().addChild(maxed);
final RamTextComponent editable = new RamTextComponent("This one is editable");
editable.setNoStroke(false);
editable.setAlignment(Alignment.LEFT_ALIGN);
editable.translate(200, 200);
editable.enableKeyboard(true);
getCanvas().addChild(editable);
}
@Override
protected void initMenu() {
// TODO Auto-generated method stub
}
@Override
protected EObject getElementToSave() {
// TODO Auto-generated method stub
return null;
}
}
private TextTest() {
ResourceUtils.loadLibraries();
RamApp.initialize(new Runnable() {
@Override
public void run() {
RamApp app = RamApp.getApplication();
app.changeScene(new TextScene(app));
}
});
}
/**
* Starts the example.
*
* @param args
* unused.
*/
public static void main(final String[] args) {
new TextTest();
}
}
| gpl-2.0 |
percy-g2/Novathor_xperia_u8500 | 6.1.1.B.1.54/external/junit/src/junit/runner/LoadingTestCollector.java | 1703 | package junit.runner;
import java.lang.reflect.Modifier;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* An implementation of a TestCollector that loads
* all classes on the class path and tests whether
* it is assignable from Test or provides a static suite method.
* @see TestCollector
*/
public class LoadingTestCollector extends ClassPathTestCollector {
TestCaseClassLoader fLoader;
public LoadingTestCollector() {
fLoader= new TestCaseClassLoader();
}
protected boolean isTestClass(String classFileName) {
try {
if (classFileName.endsWith(".class")) {
Class testClass= classFromFile(classFileName);
return (testClass != null) && isTestClass(testClass);
}
}
catch (ClassNotFoundException expected) {
}
catch (NoClassDefFoundError notFatal) {
}
return false;
}
Class classFromFile(String classFileName) throws ClassNotFoundException {
String className= classNameFromFile(classFileName);
if (!fLoader.isExcluded(className))
return fLoader.loadClass(className, false);
return null;
}
boolean isTestClass(Class testClass) {
if (hasSuiteMethod(testClass))
return true;
if (Test.class.isAssignableFrom(testClass) &&
Modifier.isPublic(testClass.getModifiers()) &&
hasPublicConstructor(testClass))
return true;
return false;
}
boolean hasSuiteMethod(Class testClass) {
try {
testClass.getMethod(BaseTestRunner.SUITE_METHODNAME, new Class[0]);
} catch(Exception e) {
return false;
}
return true;
}
boolean hasPublicConstructor(Class testClass) {
try {
TestSuite.getTestConstructor(testClass);
} catch(NoSuchMethodException e) {
return false;
}
return true;
}
}
| gpl-2.0 |
jasoet/Spring-JDBC | src/main/java/id/ac/pcr/springjdbc/model/Mahasiswa.java | 657 | package id.ac.pcr.springjdbc.model;
/**
* Created with IntelliJ IDEA.
* User: isaninside
* Date: 4/3/13
* Time: 10:10 AM
* To change this template use File | Settings | File Templates.
*/
public class Mahasiswa {
private int id;
private String nama;
private String nim;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getNama() {
return nama;
}
public void setNama(String nama) {
this.nama = nama;
}
public String getNim() {
return nim;
}
public void setNim(String nim) {
this.nim = nim;
}
}
| gpl-2.0 |
paninij/paninij | core/proc/src/test/paninij/org/paninij/proc/check/signature/HasNestedTypeCore.java | 178 | package org.paninij.proc.check.signature;
import org.paninij.lang.Signature;
@Signature
interface HasNestedTypeCore
{
enum Nested {
// Nothing needed here.
}
}
| gpl-2.0 |