repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
theArchonius/gerrit-attachments
src/main/java/com/eclipsesource/gerrit/plugins/fileattachment/api/entities/converter/BaseFileEntityConverter.java
4106
/** * */ package com.eclipsesource.gerrit.plugins.fileattachment.api.entities.converter; import com.eclipsesource.gerrit.plugins.fileattachment.api.AttachmentTarget; import com.eclipsesource.gerrit.plugins.fileattachment.api.ContentType; import com.eclipsesource.gerrit.plugins.fileattachment.api.File; import com.eclipsesource.gerrit.plugins.fileattachment.api.FileDescription; import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.EntityConverter; import com.eclipsesource.gerrit.plugins.fileattachment.api.entities.FileEntity; import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.BinaryFile; import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.GenericContentType; import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.GenericFileDescription; import com.eclipsesource.gerrit.plugins.fileattachment.api.impl.TextFile; import org.apache.commons.codec.binary.Base64; import java.nio.charset.Charset; /** * An entity writer which creates {@link FileEntity}s from {@link File}s. * * @author Florian Zoubek * */ public class BaseFileEntityConverter implements EntityConverter<File, FileEntity, AttachmentTarget, AttachmentTarget> { @Override public FileEntity toEntity(File file, AttachmentTarget context) { FileEntity fileEntity = new FileEntity(); FileDescription fileDescription = file.getFileDescription(); fileEntity.setFileName(fileDescription.getServerFileName()); fileEntity.setFilePath(fileDescription.getServerFilePath()); ContentType contentType = file.getContentType(); fileEntity.setContentType(contentType.getContentTypeIdentifier()); if (contentType.isBinary()) { // encode the content as base64 as JSON does not support binary data (Gson // supports it, but then we are bound to Gson forever - also there is // currently no easy way to modify the Gson configuration through the // Gerrit API ) String content = Base64.encodeBase64String(file.getContent()); fileEntity.setContent(content); fileEntity.setEncodingMethod("base64"); } else { // obtain the text and write it directly into the the entity - we don't // need to encode textual data /* * TODO refactor to avoid unnecessary conversions * * actually we convert strings to bytes in the TextFile.getContent() * method and back to a string here. Maybe we should think of a solution * that avoid this unnecessary conversion? */ Charset charset = Charset.defaultCharset(); // search for specific charset in the content type, if there exists none, // use the system default charset if (contentType != null) { String sCharset = contentType.getParameters().get("charset"); if (sCharset != null) { charset = Charset.forName(sCharset); } } fileEntity.setContent(new String(file.getContent(), charset)); } return fileEntity; } @Override public File toObject(FileEntity jsonEntity, AttachmentTarget context) { ContentType contentType = new GenericContentType(jsonEntity.getContentType()); File file = null; FileDescription fileDescription= new GenericFileDescription(jsonEntity.getFilePath(), jsonEntity.getFileName()); // decode, if necessary String encodingMethod = jsonEntity.getEncodingMethod(); byte[] content = null; String sContent = null; if (encodingMethod == null || encodingMethod.isEmpty() || encodingMethod.equalsIgnoreCase("none")){ sContent = jsonEntity.getContent(); }else{ if(encodingMethod.equalsIgnoreCase("base64")){ content = Base64.decodeBase64(jsonEntity.getContent()); }else{ // unsupported encoding method return null; } } // TODO replace by decision based on the type, not on the binary property if(contentType.isBinary()){ file = new BinaryFile(fileDescription, contentType, content, context); }else{ file = new TextFile(fileDescription, contentType, sContent, context); } return file; } }
epl-1.0
willrogers/dawnsci
org.eclipse.dawnsci.nexus/src/org/eclipse/dawnsci/nexus/impl/NXflipperImpl.java
3165
/*- ******************************************************************************* * Copyright (c) 2015 Diamond Light Source Ltd. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * This file was auto-generated from the NXDL XML definition. * Generated at: 2015-09-29T13:43:53.722+01:00 *******************************************************************************/ package org.eclipse.dawnsci.nexus.impl; import org.eclipse.dawnsci.analysis.api.dataset.IDataset; import org.eclipse.dawnsci.analysis.dataset.impl.Dataset; import org.eclipse.dawnsci.nexus.*; /** * Template of a beamline spin flipper. * * @version 1.0 */ public class NXflipperImpl extends NXobjectImpl implements NXflipper { private static final long serialVersionUID = 1L; // no state in this class, so always compatible public static final String NX_TYPE = "type"; public static final String NX_FLIP_TURNS = "flip_turns"; public static final String NX_COMP_TURNS = "comp_turns"; public static final String NX_GUIDE_TURNS = "guide_turns"; public static final String NX_FLIP_CURRENT = "flip_current"; public static final String NX_COMP_CURRENT = "comp_current"; public static final String NX_GUIDE_CURRENT = "guide_current"; public static final String NX_THICKNESS = "thickness"; protected NXflipperImpl(long oid) { super(oid); } @Override public Class<? extends NXobject> getNXclass() { return NXflipper.class; } @Override public NXbaseClass getNXbaseClass() { return NXbaseClass.NX_FLIPPER; } @Override public IDataset getType() { return getDataset(NX_TYPE); } public void setType(IDataset type) { setDataset(NX_TYPE, type); } @Override public IDataset getFlip_turns() { return getDataset(NX_FLIP_TURNS); } public void setFlip_turns(IDataset flip_turns) { setDataset(NX_FLIP_TURNS, flip_turns); } @Override public IDataset getComp_turns() { return getDataset(NX_COMP_TURNS); } public void setComp_turns(IDataset comp_turns) { setDataset(NX_COMP_TURNS, comp_turns); } @Override public IDataset getGuide_turns() { return getDataset(NX_GUIDE_TURNS); } public void setGuide_turns(IDataset guide_turns) { setDataset(NX_GUIDE_TURNS, guide_turns); } @Override public IDataset getFlip_current() { return getDataset(NX_FLIP_CURRENT); } public void setFlip_current(IDataset flip_current) { setDataset(NX_FLIP_CURRENT, flip_current); } @Override public IDataset getComp_current() { return getDataset(NX_COMP_CURRENT); } public void setComp_current(IDataset comp_current) { setDataset(NX_COMP_CURRENT, comp_current); } @Override public IDataset getGuide_current() { return getDataset(NX_GUIDE_CURRENT); } public void setGuide_current(IDataset guide_current) { setDataset(NX_GUIDE_CURRENT, guide_current); } @Override public IDataset getThickness() { return getDataset(NX_THICKNESS); } public void setThickness(IDataset thickness) { setDataset(NX_THICKNESS, thickness); } }
epl-1.0
sunix/che-plugins
plugin-git/che-plugin-git-ext-git/src/main/java/org/eclipse/che/ide/ext/git/server/nativegit/SshKeysManager.java
6978
/******************************************************************************* * Copyright (c) 2012-2015 Codenvy, S.A. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Codenvy, S.A. - initial API and implementation *******************************************************************************/ package org.eclipse.che.ide.ext.git.server.nativegit; import org.eclipse.che.api.core.UnauthorizedException; import org.eclipse.che.commons.env.EnvironmentContext; import org.eclipse.che.ide.ext.git.server.GitException; import org.eclipse.che.ide.ext.git.server.commons.Util; import org.eclipse.che.ide.ext.ssh.server.SshKey; import org.eclipse.che.ide.ext.ssh.server.SshKeyPair; import org.eclipse.che.ide.ext.ssh.server.SshKeyStore; import org.eclipse.che.ide.ext.ssh.server.SshKeyStoreException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import javax.inject.Singleton; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Iterator; import java.util.Set; /** * Writes SSH key into file. * * @author Eugene Voevodin */ @Singleton public class SshKeysManager { private static final Logger LOG = LoggerFactory.getLogger(SshKeysManager.class); private static final String DEFAULT_KEY_DIRECTORY_PATH = System.getProperty("java.io.tmpdir"); private static final String DEFAULT_KEY_NAME = "identity"; //used in tests static String keyDirectoryPath; // TODO(GUICE): initialize private final SshKeyStore sshKeyStore; private final Set<SshKeyUploader> sshKeyUploaders; @Inject public SshKeysManager(SshKeyStore sshKeyStore, Set<SshKeyUploader> sshKeyUploaders) { this.sshKeyStore = sshKeyStore; this.sshKeyUploaders = sshKeyUploaders; } public static String getKeyDirectoryPath() { return (keyDirectoryPath == null ? DEFAULT_KEY_DIRECTORY_PATH : keyDirectoryPath) + '/' + EnvironmentContext.getCurrent().getUser().getName(); } /** * Writes SSH key into file. * * @param url * SSH url to git repository * @return file that contains SSH key * @throws IllegalArgumentException * if specified URL is not SSH url * @throws GitException * if other error occurs */ public File writeKeyFile(String url) throws GitException { final String host = Util.getHost(url); if (host == null) { throw new IllegalArgumentException(String.format("Unable get host name from %s. Probably isn't a SSH URL", url)); } SshKey publicKey; SshKey privateKey; // check keys existence and generate if need try { if ((privateKey = sshKeyStore.getPrivateKey(host)) != null) { publicKey = sshKeyStore.getPublicKey(host); if (publicKey == null) { sshKeyStore.removeKeys(host); SshKeyPair sshKeyPair = sshKeyStore.genKeyPair(host, null, null); publicKey = sshKeyPair.getPublicKey(); privateKey = sshKeyPair.getPrivateKey(); } } else { SshKeyPair sshKeyPair = sshKeyStore.genKeyPair(host, null, null); publicKey = sshKeyPair.getPublicKey(); privateKey = sshKeyPair.getPrivateKey(); } } catch (SshKeyStoreException e) { throw new GitException(e.getMessage(), e); } // create directories if need final File keyDirectory = new File(getKeyDirectoryPath(), host); if (!keyDirectory.exists()) { keyDirectory.mkdirs(); } // save private key in local file final File keyFile = new File(getKeyDirectoryPath() + '/' + host + '/' + DEFAULT_KEY_NAME); try (FileOutputStream fos = new FileOutputStream(keyFile)) { fos.write(privateKey.getBytes()); } catch (IOException e) { LOG.error("Cant store key", e); throw new GitException("Cant store ssh key. "); } //set perm to -r--r--r-- keyFile.setReadOnly(); //set perm to ---------- keyFile.setReadable(false, false); //set perm to -r-------- keyFile.setReadable(true, true); //set perm to -rw------- keyFile.setWritable(true, true); SshKeyUploader uploader = null; for (Iterator<SshKeyUploader> itr = sshKeyUploaders.iterator(); uploader == null && itr.hasNext(); ) { SshKeyUploader next = itr.next(); if (next.match(url)) { uploader = next; } } if (uploader != null) { // upload public key try { uploader.uploadKey(publicKey); } catch (IOException e) { throw new GitException(e.getMessage(), e); } catch (UnauthorizedException e) { // Git action might fail without uploaded public SSH key. LOG.warn(String.format("Unable upload public SSH key with %s", uploader.getClass().getSimpleName()), e); } } else { // Git action might fail without SSH key. LOG.warn(String.format("Not found ssh key uploader for %s", host)); } return keyFile; } /** * * /home/jumper/code/plugin-git/codenvy-ext-git/target/ssh-keys/host.com/codenvy/identity * /home/jumper/code/plugin-git/codenvy-ext-git/target/ssh-keys/codenvy/host.com/identity * * Removes ssh key from file system. * If ssh key doesn't exist - nothing will be done. * <p/> * This method should be used with remote git commands * to clean up ssh keys from filesystem after it executions * * @param url * url which is used to fetch host from it * @throws IllegalArgumentException * when it is not possible to fetch host from {@code url} * @see Util#getHost(String) */ public void removeKey(String url) { final String host = Util.getHost(url); if (host == null) { throw new IllegalArgumentException(String.format("Unable get host name from %s. Probably isn't a SSH URL", url)); } final Path key = Paths.get(getKeyDirectoryPath()) .resolve(host) .resolve(DEFAULT_KEY_NAME); if (!Files.exists(key)) return; try { Files.delete(key); } catch (IOException e) { LOG.error("It is not possible to remove ssh key {}", key); } } }
epl-1.0
fp7-netide/Engine
core/core.logpub/src/main/java/eu/netide/core/logpub/LogPub.java
7421
package eu.netide.core.logpub; import java.util.LinkedList; import eu.netide.core.api.Constants; import eu.netide.core.api.MessageHandlingResult; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.zeromq.ZFrame; import org.zeromq.ZMQ; import org.zeromq.ZMQException; import org.zeromq.ZMsg; import eu.netide.core.api.IBackendManager; import eu.netide.core.api.IBackendMessageListener; import eu.netide.core.api.IManagementMessageListener; import eu.netide.core.api.IShimManager; import eu.netide.core.api.IShimMessageListener; import eu.netide.lib.netip.ManagementMessage; import eu.netide.lib.netip.Message; import eu.netide.lib.netip.NetIPConverter; public class LogPub implements IBackendMessageListener, IShimMessageListener, IManagementMessageListener, Runnable{ private static final String STOP_COMMAND = "Control.STOP"; private static final String CONTROL_ADDRESS = "inproc://LogPubControl"; private static final int DEFAULT_PUB_PORT = 5557; private static final int DEFAULT_SUB_PORT = 5558; private static final Logger log = LoggerFactory.getLogger(LogPub.class); private int pubPort; private int subPort; private IShimManager shimManager; private IBackendManager backendManager; private ZMQ.Context context; private Thread thread; public LogPub() { log.info("LogPub Constructor."); } public void Start() { log.info("LogPub Start()."); context = ZMQ.context(1); thread = new Thread(this); thread.setName("LogPub Receive Loop"); thread.start(); } public void Stop() { if (thread != null) { ZMQ.Socket stopSocket = context.socket(ZMQ.PUSH); stopSocket.connect(CONTROL_ADDRESS); stopSocket.send(STOP_COMMAND); stopSocket.close(); try { thread.join(); context.term(); } catch (InterruptedException e) { log.error("", e); } } log.info("LogPub stopped."); } @Override public void run() { log.info("LogPub started."); ZMQ.Socket pubSocket = context.socket(ZMQ.PUB); try{ pubSocket.bind("tcp://*:" + (pubPort==0?DEFAULT_PUB_PORT:pubPort)); }catch(ZMQException e){ log.error("PUB address already in use!"); Stop(); } log.info("Listening PUB queue on port " + (pubPort==0?DEFAULT_PUB_PORT:pubPort)); ZMQ.Socket subSocket = context.socket(ZMQ.ROUTER); subSocket.setIdentity("logpub".getBytes(ZMQ.CHARSET)); try{ subSocket.bind("tcp://*:" + (subPort==0?DEFAULT_SUB_PORT:subPort)); }catch(ZMQException e){ log.error("PUB address already in use!"); Stop(); } log.info("Listening SUB queue on port " + (subPort==0?DEFAULT_SUB_PORT:subPort)); ZMQ.Socket controlSocket = context.socket(ZMQ.PULL); controlSocket.bind(CONTROL_ADDRESS); log.info("Control queue on address: " + CONTROL_ADDRESS); // Register the queues in the poller try{ ZMQ.Poller poller = new ZMQ.Poller(2); poller.register(subSocket, ZMQ.Poller.POLLIN); poller.register(controlSocket, ZMQ.Poller.POLLIN); while (!Thread.currentThread().isInterrupted()) { poller.poll(10); if (poller.pollin(0)) { ZMsg zmqMessage = ZMsg.recvMsg(subSocket); String dst = null; byte[] data = null; try{ ZFrame header = zmqMessage.pop(); dst = zmqMessage.popString(); data = zmqMessage.getLast().getData(); Message netideMessage = NetIPConverter.parseRawMessage(data); log.debug("Data received in SUB queue: to "+dst+ ". (data:"+netideMessage.toByteRepresentation()+")"); if (dst.startsWith("1_")) // send message to shim try{ shimManager.sendMessage(netideMessage); }catch (NullPointerException e) { log.error("shim manager not set"); } else if (dst.startsWith("0_")) // send message to backend try{ backendManager.sendMessage(netideMessage); }catch (NullPointerException e) { log.error("backend manager not set"); } else log.error("Got unknown message in SUB queue:" + netideMessage.toString()); }catch(NullPointerException | IllegalArgumentException e){ log.error("Error in LogPub:");e.printStackTrace(); } } if (poller.pollin(1)) { ZMsg message = ZMsg.recvMsg(controlSocket); if (message.getFirst().toString().equals(STOP_COMMAND)) { log.info("Received STOP command.\nExiting..."); break; } else { log.debug("Sending message to PUB queue"); message.send(pubSocket); } } } } catch (Exception ex) { log.error("Error in ZeroMQBasedConnector receive loop.", ex); } finally { pubSocket.close(); subSocket.close(); controlSocket.close(); } } public void setPubPort(int pub_port) { this.pubPort = pub_port; } public int getPubPort() { return pubPort; } public void setSubPort(int sub_port) { this.subPort = sub_port; } public int getSubPort() { return subPort; } @Override public MessageHandlingResult OnBackendMessage(Message message, String originId) { log.debug("Received message from backend"); OnShimAndBackendMessage(message, "0", originId); return MessageHandlingResult.RESULT_PASS; } @Override public MessageHandlingResult OnShimMessage(Message message, String originId) { log.debug("Received message from shim"); OnShimAndBackendMessage(message, "1", originId); return MessageHandlingResult.RESULT_PASS; } @Override public void OnOutgoingBackendMessage(Message message, String backendId) { log.debug("Received message to backend"); OnShimAndBackendMessage(message, "2", backendId); } @Override public void OnUnhandledBackendMessage(Message message, String originId) { } @Override public void OnOutgoingShimMessage(Message message) { log.debug("Received message to shim"); OnShimAndBackendMessage(message, "3", Constants.SHIM); } @Override public void OnUnhandeldShimMessage(Message message, String originId) { } private void OnShimAndBackendMessage(Message message, String origin, String originId){ log.debug("Received message from "+origin+"_"+originId+":" + message.toString()); ZMQ.Socket sendSocket = context.socket(ZMQ.PUSH); sendSocket.connect(CONTROL_ADDRESS); sendSocket.sendMore("*"); // TODO : Add topic handling sendSocket.sendMore(origin+"_"+originId); sendSocket.send(message.toByteRepresentation()); sendSocket.close(); } @Override public void OnManagementMessage(ManagementMessage message) { log.debug("Received message from management:" + message.toString()); ZMQ.Socket sendSocket = context.socket(ZMQ.PUSH); sendSocket.connect(CONTROL_ADDRESS); sendSocket.send(message.getPayloadString()); sendSocket.close(); } /** * Sets the shim manager. * * @param manager the manager */ public void setShimManager(IShimManager manager) { shimManager = manager; log.debug("ShimManager set."); } /** * Gets the shim manager. * * @return the shim manager */ public IShimManager getShimManager() { return shimManager; } /** * Sets the backend manager. * * @param manager the manager */ public void setBackendManager(IBackendManager manager) { backendManager = manager; log.debug("BackendManager set."); } /** * Gets the backend manager. * * @return the backend manager */ public IBackendManager getBackendManager() { return backendManager; } @Override public void OnBackendRemoved(String backEndName, LinkedList<Integer> removedModules) { // TODO : Send message to the PUB queue? } }
epl-1.0
krasv/flowr
commons/ant/org.flowr.ant.tasks/src/main/java/org/flowr/ant/tasks/LeadStringTask.java
1532
/** * DB Systel GmbH / i.S.A. Dresden GmbH & Co. KG (c) 2010 */ package org.flowr.ant.tasks; import org.apache.tools.ant.BuildException; import org.apache.tools.ant.PropertyHelper; /** * Ant task evaluating the text part after a specified separator. *<p>usage:</p> * <pre> * &lt;leadString property="<i>result.prop.name</i>" separator="<i>anySeparatorText</i>" last="<i>true|false, default==false</i>" text="<i>any text or ${property.to.scan}</i>" /&gt; * </pre> * <p>Sample</p> *<pre> * &lt;property name="build.version.full" value="1.0.0.201101012359" /&gt;<br> * &lt;leadString property="build.version" separator="." last="true" text="${build.version.full}" /&gt;<br> * &lt;echo message="build.version = ${build.version}" /&gt;<br> * * results "build.version = 1.0.0" *</pre> * @author SvenKrause * */ public class LeadStringTask extends AbstractSeparatorbasedStringTask { private boolean last; /** * @param last * the last to set */ public void setLast(boolean last) { this.last = last; } @Override public void init() throws BuildException { super.init(); last = false; } @Override public void execute() throws BuildException { validate(); PropertyHelper ph = PropertyHelper.getPropertyHelper(this.getProject()); int indexOf = last ? text.lastIndexOf(separator) : text.indexOf(separator); if (indexOf != -1) { String lead = text.substring(0, indexOf); ph.setProperty("", propName, lead, true); } else { ph.setProperty("", propName, text, true); } } }
epl-1.0
fabiophillip/sumosensei
src/br/ufrn/dimap/pairg/sumosensei/android/ExplicacaoItensActivity.java
5043
package br.ufrn.dimap.pairg.sumosensei.android; import com.phiworks.dapartida.ArmazenaMostrarRegrasModosOnline; import doteppo.ArmazenaMostrarRegrasTreinamento; import android.content.Intent; import android.graphics.Typeface; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.TextView; public class ExplicacaoItensActivity extends ActivityDoJogoComSom { private boolean mostrarExplicacaoItensNovamente;//inicialmente isso é true private String qualDosModosOnlineMostrarEmSeguida; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); super.getGameHelper().setMaxAutoSignInAttempts(0); setContentView(R.layout.activity_explicacao_itens); Bundle containerDadosQualModoDeJogoJogar = getIntent().getExtras(); if(containerDadosQualModoDeJogoJogar != null) { qualDosModosOnlineMostrarEmSeguida = containerDadosQualModoDeJogoJogar.getString("qual_dos_modos_online_jogar"); } mostrarExplicacaoItensNovamente = true; String fontpath = "fonts/Wonton.ttf"; Typeface tf = Typeface.createFromAsset(getAssets(), fontpath); TextView textviewTituloExplicaItens = (TextView) findViewById(R.id.tituloTelaExplicacaoItens); textviewTituloExplicaItens.setTypeface(tf); TextView textviewTituloExplicaItem1 = (TextView) findViewById(R.id.texto_titulo_item1); textviewTituloExplicaItem1.setTypeface(tf); TextView textviewTituloExplicaItem2 = (TextView) findViewById(R.id.texto_titulo_item2); textviewTituloExplicaItem2.setTypeface(tf); TextView textviewTituloExplicaItem3 = (TextView) findViewById(R.id.texto_titulo_item3); textviewTituloExplicaItem3.setTypeface(tf); TextView textviewTituloExplicaItem4 = (TextView) findViewById(R.id.texto_titulo_item4); textviewTituloExplicaItem4.setTypeface(tf); String fontpath2 = "fonts/chifont.ttf"; Typeface tf2 = Typeface.createFromAsset(getAssets(), fontpath2); TextView textviewSubtituloExplicaItem1 = (TextView) findViewById(R.id.texto_subtitulo_item1); textviewSubtituloExplicaItem1.setTypeface(tf2); TextView textviewSubtituloExplicaItem2 = (TextView) findViewById(R.id.texto_subtitulo_item2); textviewSubtituloExplicaItem2.setTypeface(tf2); TextView textviewSubtituloExplicaItem3 = (TextView) findViewById(R.id.texto_subtitulo_item3); textviewSubtituloExplicaItem3.setTypeface(tf2); TextView textviewSubtituloExplicaItem4 = (TextView) findViewById(R.id.texto_subtitulo_item4); textviewSubtituloExplicaItem4.setTypeface(tf2); String fontpathBrPraTexto = "fonts/gilles_comic_br.ttf"; Typeface tfBrPraTexto = Typeface.createFromAsset(getAssets(), fontpathBrPraTexto); TextView textviewExplicacaoItens = (TextView) findViewById(R.id.explicacao_itens); TextView textviewExplicacaoItem1 = (TextView) findViewById(R.id.texto_explica_item1); TextView textviewExplicacaoItem2 = (TextView) findViewById(R.id.texto_explica_item2); TextView textviewExplicacaoItem3 = (TextView) findViewById(R.id.texto_explica_item3); TextView textviewExplicacaoItem4 = (TextView) findViewById(R.id.texto_explica_item4); TextView textviewExplicarItensNovamente = (TextView) findViewById(R.id.texto_mostrar_explicacao_itens); textviewExplicacaoItens.setTypeface(tfBrPraTexto); textviewExplicacaoItem1.setTypeface(tfBrPraTexto); textviewExplicacaoItem2.setTypeface(tfBrPraTexto); textviewExplicacaoItem3.setTypeface(tfBrPraTexto); textviewExplicacaoItem4.setTypeface(tfBrPraTexto); textviewExplicarItensNovamente.setTypeface(tfBrPraTexto); } @Override public void onSignInFailed() { // TODO Auto-generated method stub } @Override public void onSignInSucceeded() { // TODO Auto-generated method stub } public void mudarValorMostrarAvisoItens(View v) { Button checkboxMostrarExplicacaoItensNovamente = (Button)findViewById(R.id.checkbox_mostrar_aviso_itens); if(this.mostrarExplicacaoItensNovamente == false) { this.mostrarExplicacaoItensNovamente = true; checkboxMostrarExplicacaoItensNovamente.setBackground(getResources().getDrawable(R.drawable.checkbox_marcada_regras_treinamento)); } else { this.mostrarExplicacaoItensNovamente = false; checkboxMostrarExplicacaoItensNovamente.setBackground(getResources().getDrawable(R.drawable.checkbox_desmarcada_regras_treinamento)); } ArmazenaMostrarRegrasModosOnline guardaConfiguracoes = ArmazenaMostrarRegrasModosOnline.getInstance(); guardaConfiguracoes.alterarMostrarExplicacaoItens(getApplicationContext(), mostrarExplicacaoItensNovamente); } public void jogarModoOnline(View v) { if(this.qualDosModosOnlineMostrarEmSeguida.compareTo("casual") == 0) { Intent iniciaTelaCasual = new Intent(ExplicacaoItensActivity.this, TelaModoCasual.class); startActivity(iniciaTelaCasual); finish(); } else { Intent iniciaTelaCompeticao = new Intent(ExplicacaoItensActivity.this, TelaModoCompeticao.class); startActivity(iniciaTelaCompeticao); finish(); } } }
epl-1.0
bfg-repo-cleaner-demos/eclipselink.runtime-bfg-strip-big-blobs
moxy/eclipselink.moxy.test/src/org/eclipse/persistence/testing/jaxb/xmlschema/attributeformdefault/unqualified/AttributeFormDefaultUnqualifiedTestCases.java
2794
/******************************************************************************* * Copyright (c) 1998, 2012 Oracle and/or its affiliates. All rights reserved. * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 * which accompanies this distribution. * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: * Denise Smith - 2.3 ******************************************************************************/ package org.eclipse.persistence.testing.jaxb.xmlschema.attributeformdefault.unqualified; import java.io.InputStream; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.eclipse.persistence.jaxb.MarshallerProperties; import org.eclipse.persistence.jaxb.UnmarshallerProperties; import org.eclipse.persistence.testing.jaxb.JAXBWithJSONTestCases; public class AttributeFormDefaultUnqualifiedTestCases extends JAXBWithJSONTestCases{ protected final static String XML_RESOURCE = "org/eclipse/persistence/testing/jaxb/xmlschema/attributeformdefault/unqualifiedaddress.xml"; protected final static String JSON_RESOURCE = "org/eclipse/persistence/testing/jaxb/xmlschema/attributeformdefault/unqualifiedaddress.json"; public AttributeFormDefaultUnqualifiedTestCases(String name) throws Exception { super(name); } public void setUp() throws Exception { setControlDocument(XML_RESOURCE); setControlJSON(JSON_RESOURCE); super.setUp(); Type[] types = new Type[1]; types[0] = Address.class; setTypes(types); Map namespaces = new HashMap<String, String>(); namespaces.put("myns","ns0"); jaxbMarshaller.setProperty(MarshallerProperties.NAMESPACE_PREFIX_MAPPER, namespaces); jaxbUnmarshaller.setProperty(UnmarshallerProperties.JSON_NAMESPACE_PREFIX_MAPPER, namespaces); } protected Object getControlObject() { Address addr = new Address(); addr.city = "Ottawa"; addr.street ="Main Street"; addr.street2 ="Street2"; addr.street3 ="Street3"; addr.street4 ="Street4"; return addr; } public void testSchemaGen() throws Exception{ InputStream controlInputStream = ClassLoader.getSystemResourceAsStream("org/eclipse/persistence/testing/jaxb/xmlschema/attributeformdefault/unqualified.xsd"); List<InputStream> controlSchemas = new ArrayList<InputStream>(); controlSchemas.add(controlInputStream); this.testSchemaGen(controlSchemas); } }
epl-1.0
sazgin/elexis-3-core
ch.elexis.core/src-gen/ch/elexis/core/model/util/ModelSwitch.java
17995
/** * Copyright (c) 2013 MEDEVIT <office@medevit.at>. * 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: * MEDEVIT <office@medevit.at> - initial API and implementation */ package ch.elexis.core.model.util; import ch.elexis.core.model.*; import org.eclipse.emf.ecore.EObject; import org.eclipse.emf.ecore.EPackage; import org.eclipse.emf.ecore.util.Switch; /** * <!-- begin-user-doc --> * The <b>Switch</b> for the model's inheritance hierarchy. * It supports the call {@link #doSwitch(EObject) doSwitch(object)} * to invoke the <code>caseXXX</code> method for each class of the model, * starting with the actual class of the object * and proceeding up the inheritance hierarchy * until a non-null result is returned, * which is the result of the switch. * <!-- end-user-doc --> * @see ch.elexis.core.model.ModelPackage * @generated */ public class ModelSwitch<T1> extends Switch<T1> { /** * The cached model package * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected static ModelPackage modelPackage; /** * Creates an instance of the switch. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public ModelSwitch() { if (modelPackage == null) { modelPackage = ModelPackage.eINSTANCE; } } /** * Checks whether this is a switch for the given package. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param ePackage the package in question. * @return whether this is a switch for the given package. * @generated */ @Override protected boolean isSwitchFor(EPackage ePackage) { return ePackage == modelPackage; } /** * Calls <code>caseXXX</code> for each class of the model until one returns a non null result; it yields that result. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return the first non-null result returned by a <code>caseXXX</code> call. * @generated */ @Override protected T1 doSwitch(int classifierID, EObject theEObject) { switch (classifierID) { case ModelPackage.ICONTACT: { IContact iContact = (IContact)theEObject; T1 result = caseIContact(iContact); if (result == null) result = caseIdentifiable(iContact); if (result == null) result = caseDeleteable(iContact); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.IPERSISTENT_OBJECT: { IPersistentObject iPersistentObject = (IPersistentObject)theEObject; T1 result = caseIPersistentObject(iPersistentObject); if (result == null) result = caseIdentifiable(iPersistentObject); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.IXID: { IXid iXid = (IXid)theEObject; T1 result = caseIXid(iXid); if (result == null) result = caseIPersistentObject(iXid); if (result == null) result = caseIdentifiable(iXid); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.ICODE_ELEMENT: { ICodeElement iCodeElement = (ICodeElement)theEObject; T1 result = caseICodeElement(iCodeElement); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.ICHANGE_LISTENER: { IChangeListener iChangeListener = (IChangeListener)theEObject; T1 result = caseIChangeListener(iChangeListener); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.ISTICKER: { ISticker iSticker = (ISticker)theEObject; T1 result = caseISticker(iSticker); if (result == null) result = caseComparable(iSticker); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.IPERSON: { IPerson iPerson = (IPerson)theEObject; T1 result = caseIPerson(iPerson); if (result == null) result = caseIContact(iPerson); if (result == null) result = caseIdentifiable(iPerson); if (result == null) result = caseDeleteable(iPerson); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.IPATIENT: { IPatient iPatient = (IPatient)theEObject; T1 result = caseIPatient(iPatient); if (result == null) result = caseIPerson(iPatient); if (result == null) result = caseIContact(iPatient); if (result == null) result = caseIdentifiable(iPatient); if (result == null) result = caseDeleteable(iPatient); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.IUSER: { IUser iUser = (IUser)theEObject; T1 result = caseIUser(iUser); if (result == null) result = caseIContact(iUser); if (result == null) result = caseIdentifiable(iUser); if (result == null) result = caseDeleteable(iUser); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.IDENTIFIABLE: { Identifiable identifiable = (Identifiable)theEObject; T1 result = caseIdentifiable(identifiable); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.DELETEABLE: { Deleteable deleteable = (Deleteable)theEObject; T1 result = caseDeleteable(deleteable); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.ILAB_ITEM: { ILabItem iLabItem = (ILabItem)theEObject; T1 result = caseILabItem(iLabItem); if (result == null) result = caseIdentifiable(iLabItem); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.ILAB_RESULT: { ILabResult iLabResult = (ILabResult)theEObject; T1 result = caseILabResult(iLabResult); if (result == null) result = caseIdentifiable(iLabResult); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.ILAB_ORDER: { ILabOrder iLabOrder = (ILabOrder)theEObject; T1 result = caseILabOrder(iLabOrder); if (result == null) result = caseIdentifiable(iLabOrder); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.IPERIOD: { IPeriod iPeriod = (IPeriod)theEObject; T1 result = caseIPeriod(iPeriod); if (result == null) result = caseIdentifiable(iPeriod); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.IDOCUMENT: { IDocument iDocument = (IDocument)theEObject; T1 result = caseIDocument(iDocument); if (result == null) result = caseIdentifiable(iDocument); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.ICATEGORY: { ICategory iCategory = (ICategory)theEObject; T1 result = caseICategory(iCategory); if (result == null) result = defaultCase(theEObject); return result; } case ModelPackage.IHISTORY: { IHistory iHistory = (IHistory)theEObject; T1 result = caseIHistory(iHistory); if (result == null) result = defaultCase(theEObject); return result; } default: return defaultCase(theEObject); } } /** * Returns the result of interpreting the object as an instance of '<em>IContact</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>IContact</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseIContact(IContact object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>IPersistent Object</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>IPersistent Object</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseIPersistentObject(IPersistentObject object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>IXid</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>IXid</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseIXid(IXid object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>ICode Element</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>ICode Element</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseICodeElement(ICodeElement object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>IChange Listener</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>IChange Listener</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseIChangeListener(IChangeListener object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>ISticker</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>ISticker</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseISticker(ISticker object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>IPerson</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>IPerson</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseIPerson(IPerson object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>IPatient</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>IPatient</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseIPatient(IPatient object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>IUser</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>IUser</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseIUser(IUser object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Identifiable</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Identifiable</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseIdentifiable(Identifiable object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Deleteable</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Deleteable</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseDeleteable(Deleteable object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>ILab Item</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>ILab Item</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseILabItem(ILabItem object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>ILab Result</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>ILab Result</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseILabResult(ILabResult object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>ILab Order</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>ILab Order</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseILabOrder(ILabOrder object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>IPeriod</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>IPeriod</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseIPeriod(IPeriod object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>IDocument</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>IDocument</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseIDocument(IDocument object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>ICategory</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>ICategory</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseICategory(ICategory object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>IHistory</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>IHistory</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public T1 caseIHistory(IHistory object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>Comparable</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>Comparable</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) doSwitch(EObject) * @generated */ public <T> T1 caseComparable(Comparable<T> object) { return null; } /** * Returns the result of interpreting the object as an instance of '<em>EObject</em>'. * <!-- begin-user-doc --> * This implementation returns null; * returning a non-null result will terminate the switch, but this is the last case anyway. * <!-- end-user-doc --> * @param object the target of the switch. * @return the result of interpreting the object as an instance of '<em>EObject</em>'. * @see #doSwitch(org.eclipse.emf.ecore.EObject) * @generated */ @Override public T1 defaultCase(EObject object) { return null; } } //ModelSwitch
epl-1.0
ELTE-Soft/txtUML
dev/plugins/hu.elte.txtuml.api.model.execution/src/hu/elte/txtuml/api/model/execution/diagnostics/protocol/ModelEvent.java
774
package hu.elte.txtuml.api.model.execution.diagnostics.protocol; /** * Model related event on an instance */ public class ModelEvent extends InstanceEvent { private static final long serialVersionUID = 8194665363543638635L; public final String eventTargetClassName; public ModelEvent(MessageType type, int serviceInstanceID, String modelClassName, String modelClassInstanceID, String modelClassInstanceName, String eventTargetClassName) { super(type, serviceInstanceID, modelClassName, modelClassInstanceID, modelClassInstanceName); assert type == MessageType.PROCESSING_SIGNAL || type == MessageType.USING_TRANSITION || type == MessageType.ENTERING_VERTEX || type == MessageType.LEAVING_VERTEX; this.eventTargetClassName = eventTargetClassName; } }
epl-1.0
rickard-von-essen/egit
org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/history/GenerateHistoryJob.java
4164
/******************************************************************************* * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> * * 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.egit.ui.internal.history; import java.io.IOException; import org.eclipse.core.runtime.IProgressMonitor; import org.eclipse.core.runtime.IStatus; import org.eclipse.core.runtime.Status; import org.eclipse.core.runtime.jobs.Job; import org.eclipse.egit.ui.Activator; import org.eclipse.egit.ui.JobFamilies; import org.eclipse.egit.ui.UIPreferences; import org.eclipse.egit.ui.UIText; import org.eclipse.egit.ui.internal.trace.GitTraceLocation; import org.eclipse.osgi.util.NLS; class GenerateHistoryJob extends Job { private static final int BATCH_SIZE = 256; private final int maxCommits = Activator.getDefault().getPreferenceStore() .getInt(UIPreferences.HISTORY_MAX_NUM_COMMITS); private final GitHistoryPage page; private final SWTCommitList allCommits; private int lastUpdateCnt; private long lastUpdateAt; private boolean trace; GenerateHistoryJob(final GitHistoryPage ghp, final SWTCommitList list) { super(NLS.bind(UIText.HistoryPage_refreshJob, Activator.getDefault() .getRepositoryUtil().getRepositoryName( ghp.getInputInternal().getRepository()))); page = ghp; allCommits = list; trace = GitTraceLocation.HISTORYVIEW.isActive(); } @Override protected IStatus run(final IProgressMonitor monitor) { IStatus status = Status.OK_STATUS; boolean incomplete = false; try { if (trace) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.HISTORYVIEW.getLocation()); page.setErrorMessage(NLS.bind( UIText.GenerateHistoryJob_BuildingListMessage, page .getName())); try { for (;;) { final int oldsz = allCommits.size(); if (trace) GitTraceLocation.getTrace().trace( GitTraceLocation.HISTORYVIEW.getLocation(), "Filling commit list"); //$NON-NLS-1$ allCommits.fillTo(oldsz + BATCH_SIZE - 1); if (monitor.isCanceled()) { page.setErrorMessage(NLS.bind( UIText.GenerateHistoryJob_CancelMessage, page .getName())); return Status.CANCEL_STATUS; } if (allCommits.size() == 0) { page.setErrorMessage(NLS.bind( UIText.GenerateHistoryJob_NoCommits, page.getName())); break; } if (maxCommits > 0 && allCommits.size() > maxCommits) incomplete = true; if (incomplete || oldsz == allCommits.size()) break; monitor.setTaskName(NLS .bind("Found {0} commits", Integer.valueOf(allCommits.size()))); //$NON-NLS-1$ final long now = System.currentTimeMillis(); if (now - lastUpdateAt < 2000 && lastUpdateCnt > 0) continue; updateUI(incomplete); lastUpdateAt = now; } } catch (IOException e) { status = new Status(IStatus.ERROR, Activator.getPluginId(), UIText.GenerateHistoryJob_errorComputingHistory, e); } updateUI(incomplete); } finally { monitor.done(); if (trace) GitTraceLocation.getTrace().traceExit( GitTraceLocation.HISTORYVIEW.getLocation()); } return status; } void updateUI(boolean incomplete) { if (trace) GitTraceLocation.getTrace().traceEntry( GitTraceLocation.HISTORYVIEW.getLocation()); try { if (!incomplete && allCommits.size() == lastUpdateCnt) return; final SWTCommit[] asArray = new SWTCommit[allCommits.size()]; allCommits.toArray(asArray); page.showCommitList(this, allCommits, asArray, incomplete); lastUpdateCnt = allCommits.size(); } finally { if (trace) GitTraceLocation.getTrace().traceExit( GitTraceLocation.HISTORYVIEW.getLocation()); } } @Override public boolean belongsTo(Object family) { if (family.equals(JobFamilies.GENERATE_HISTORY)) return true; return super.belongsTo(family); } }
epl-1.0
gemoc/activitydiagram
dev/gemoc_sequential/language_workbench/org.gemoc.activitydiagram.sequential.xactivitydiagram/src-gen/org/gemoc/activitydiagram/sequential/xactivitydiagram/aspects/ForkNodeAspectForkNodeAspectProperties.java
153
package org.gemoc.activitydiagram.sequential.xactivitydiagram.aspects; @SuppressWarnings("all") public class ForkNodeAspectForkNodeAspectProperties { }
epl-1.0
NABUCCO/org.nabucco.testautomation.script
org.nabucco.testautomation.script.ui.rcp/src/main/man/org/nabucco/testautomation/script/ui/rcp/multipage/metadata/masterdetail/MetadataMaintenanceMasterDetailBlock.java
8978
/* * Copyright 2012 PRODYNA AG * * Licensed under the Eclipse Public License (EPL), Version 1.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.opensource.org/licenses/eclipse-1.0.php or * http://www.nabucco.org/License.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.nabucco.testautomation.script.ui.rcp.multipage.metadata.masterdetail; import java.util.HashSet; import java.util.Map; import java.util.Set; import org.eclipse.ui.forms.DetailsPart; import org.nabucco.framework.base.facade.datatype.Datatype; import org.nabucco.framework.plugin.base.component.multipage.masterdetail.MasterDetailBlock; import org.nabucco.framework.plugin.base.component.multipage.masterdetail.MasterDetailBlockLayouter; import org.nabucco.framework.plugin.base.layout.Layoutable; import org.nabucco.framework.plugin.base.view.NabuccoMessageManager; import org.nabucco.testautomation.property.facade.datatype.BooleanProperty; import org.nabucco.testautomation.property.facade.datatype.DateProperty; import org.nabucco.testautomation.property.facade.datatype.FileProperty; import org.nabucco.testautomation.property.facade.datatype.NumericProperty; import org.nabucco.testautomation.property.facade.datatype.PropertyList; import org.nabucco.testautomation.property.facade.datatype.SqlProperty; import org.nabucco.testautomation.property.facade.datatype.TextProperty; import org.nabucco.testautomation.property.facade.datatype.XPathProperty; import org.nabucco.testautomation.property.facade.datatype.XmlProperty; import org.nabucco.testautomation.property.ui.rcp.multipage.detail.PropertyDetailPageView; import org.nabucco.testautomation.script.facade.datatype.metadata.Metadata; import org.nabucco.testautomation.script.facade.datatype.metadata.MetadataLabel; import org.nabucco.testautomation.script.ui.rcp.multipage.metadata.MetadataMaintenanceMultiPageEditView; import org.nabucco.testautomation.script.ui.rcp.multipage.metadata.masterdetail.detail.fileproperty.FilePropertyDetailPageView; import org.nabucco.testautomation.script.ui.rcp.multipage.metadata.masterdetail.detail.metadata.MetadataDetailPageView; import org.nabucco.testautomation.script.ui.rcp.multipage.metadata.model.MetadataMaintenanceMultiPageEditViewModel; /** * MetadataMaintenanceMasterDetailBlock * * @author Markus Jorroch, PRODYNA AG */ public class MetadataMaintenanceMasterDetailBlock extends MasterDetailBlock<MetadataMaintenanceMultiPageEditViewModel> implements Layoutable<MetadataMaintenanceMultiPageEditViewModel> { public static String ID = "org.nabucco.testautomation.script.ui.rcp.multipage.metadata.masterdetail.MetadataMaintenanceMasterDetailBlock"; public MetadataMaintenanceMasterDetailBlock(MetadataMaintenanceMultiPageEditViewModel model, NabuccoMessageManager messageManager, MetadataMaintenanceMultiPageEditView view) { super(messageManager, view, model); } @Override protected void registerPages(DetailsPart arg0) { Map<Class<? extends Datatype>, Set<String>> typeToInvisiblePropertiesMap = this.getTypeToInvisiblePropertiesMap(); Set<String> readOnlyProperties = new HashSet<String>(); Set<String> invisibleProperties = new HashSet<String>(); /* * Metadata */ readOnlyProperties.add("identificationKey"); readOnlyProperties.add("owner"); invisibleProperties.add("id"); invisibleProperties.add("version"); detailsPart.registerPage(Metadata.class, new MetadataDetailPageView(this, getManagedForm(), getManagedFormViewPart(), nabuccoMessageManager, ID, ID + "Metadata", invisibleProperties, readOnlyProperties)); detailsPart.registerPage(MetadataLabel.class, new PropertyDetailPageView<MetadataMaintenanceMultiPageEditViewModel>( this, getManagedForm(), getManagedFormViewPart(), nabuccoMessageManager, ID, ID + "MetadataLabel", invisibleProperties, new HashSet<String>())); /* * Property */ invisibleProperties = new HashSet<String>(); readOnlyProperties = new HashSet<String>(); invisibleProperties.add("owner"); invisibleProperties.add("identificationKey"); invisibleProperties.add("id"); invisibleProperties.add("version"); invisibleProperties.add("filename"); invisibleProperties.add("reference"); readOnlyProperties.add("type"); detailsPart.registerPage(TextProperty.class, new PropertyDetailPageView<MetadataMaintenanceMultiPageEditViewModel>(this, getManagedForm(), getManagedFormViewPart(), nabuccoMessageManager, ID, ID + "TextProperty", invisibleProperties, readOnlyProperties)); typeToInvisiblePropertiesMap.put(TextProperty.class, invisibleProperties); detailsPart.registerPage(BooleanProperty.class, new PropertyDetailPageView<MetadataMaintenanceMultiPageEditViewModel>(this, getManagedForm(), getManagedFormViewPart(), nabuccoMessageManager, ID, ID + "BooleanProperty", invisibleProperties, readOnlyProperties)); typeToInvisiblePropertiesMap.put(BooleanProperty.class, invisibleProperties); detailsPart.registerPage(DateProperty.class, new PropertyDetailPageView<MetadataMaintenanceMultiPageEditViewModel>(this, getManagedForm(), getManagedFormViewPart(), nabuccoMessageManager, ID, ID + "DateProperty", invisibleProperties, readOnlyProperties)); typeToInvisiblePropertiesMap.put(DateProperty.class, invisibleProperties); detailsPart.registerPage(NumericProperty.class, new PropertyDetailPageView<MetadataMaintenanceMultiPageEditViewModel>(this, getManagedForm(), getManagedFormViewPart(), nabuccoMessageManager, ID, ID + "NumericProperty", invisibleProperties, readOnlyProperties)); typeToInvisiblePropertiesMap.put(NumericProperty.class, invisibleProperties); detailsPart.registerPage(XPathProperty.class, new PropertyDetailPageView<MetadataMaintenanceMultiPageEditViewModel>(this, getManagedForm(), getManagedFormViewPart(), nabuccoMessageManager, ID, ID + "XPathProperty", invisibleProperties, readOnlyProperties)); typeToInvisiblePropertiesMap.put(XPathProperty.class, invisibleProperties); detailsPart.registerPage(XmlProperty.class, new PropertyDetailPageView<MetadataMaintenanceMultiPageEditViewModel>(this, getManagedForm(), getManagedFormViewPart(), nabuccoMessageManager, ID, ID + "XmlProperty", invisibleProperties, readOnlyProperties)); typeToInvisiblePropertiesMap.put(XmlProperty.class, invisibleProperties); detailsPart.registerPage(FileProperty.class, new FilePropertyDetailPageView(this, getManagedForm(), getManagedFormViewPart(), nabuccoMessageManager, ID, ID + "FileProperty", invisibleProperties, readOnlyProperties)); detailsPart.registerPage(SqlProperty.class, new PropertyDetailPageView<MetadataMaintenanceMultiPageEditViewModel>(this, getManagedForm(), getManagedFormViewPart(), nabuccoMessageManager, ID, ID + "SqlProperty", invisibleProperties, readOnlyProperties)); /* * PropertyList */ invisibleProperties = new HashSet<String>(); readOnlyProperties = new HashSet<String>(); readOnlyProperties.add("owner"); readOnlyProperties.add("type"); readOnlyProperties.add("identificationKey"); invisibleProperties.add("id"); invisibleProperties.add("version"); invisibleProperties.add("reused"); invisibleProperties.add("usageType"); invisibleProperties.add("reference"); detailsPart.registerPage(PropertyList.class, new PropertyDetailPageView<MetadataMaintenanceMultiPageEditViewModel>(this, getManagedForm(), getManagedFormViewPart(), nabuccoMessageManager, ID + ".PropertyList", ID + "PropertyList", invisibleProperties, readOnlyProperties)); typeToInvisiblePropertiesMap.put(PropertyList.class, invisibleProperties); } /** * {@inheritDoc} * * @return */ protected MasterDetailBlockLayouter<MetadataMaintenanceMultiPageEditViewModel> getLayouter() { return new MetadataMaintenanceMasterDetailBlockLayouter(); } }
epl-1.0
puckpuck/idapi-wrapper
idapi-wrapper/src/com/actuate/aces/idapi/InformationObjectExecuter.java
5575
/* * Copyright (c) 2014 Actuate Corporation */ package com.actuate.aces.idapi; import com.actuate.aces.idapi.control.ActuateException; import com.actuate.schemas.*; import org.apache.axis.attachments.AttachmentPart; import org.w3c.dom.Document; import org.xml.sax.SAXException; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.ParserConfigurationException; import javax.xml.rpc.ServiceException; import javax.xml.soap.SOAPException; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.rmi.RemoteException; import java.util.Iterator; public class InformationObjectExecuter extends BaseController { public InformationObjectExecuter(BaseController controller) { super(controller); } public InformationObjectExecuter(String host, String authenticationId) throws MalformedURLException, ServiceException { super(host, authenticationId); } public InformationObjectExecuter(String host, String username, String password, String volume) throws ServiceException, ActuateException, MalformedURLException { super(host, username, password, volume); } public InformationObjectExecuter(String host, String username, String password, String volume, byte[] extendedCredentials) throws ServiceException, ActuateException, MalformedURLException { super(host, username, password, volume, extendedCredentials); } public InputStream getXmlStream(String infoObjectName) { ExecuteQueryResponse executeQueryResponse = getExecuteQueryId(infoObjectName); if (executeQueryResponse == null) return null; setConnectionHandle(executeQueryResponse.getConnectionHandle()); ObjectIdentifier objectIdentifier = new ObjectIdentifier(); objectIdentifier.setId(executeQueryResponse.getObjectId()); ViewParameter viewParameter = new ViewParameter(); viewParameter.setFormat("XMLData"); ComponentType componentType = new ComponentType(); componentType.setId("0"); GetContent getContent = new GetContent(); getContent.setObject(objectIdentifier); getContent.setViewParameter(viewParameter); getContent.setComponent(componentType); getContent.setDownloadEmbedded(false); GetContentResponse getContentResponse; try { getContentResponse = acxControl.proxy.getContent(getContent); } catch (RemoteException e) { e.printStackTrace(); return null; } try { Iterator iter = acxControl.actuateAPI.getCall().getMessageContext().getResponseMessage().getAttachments(); while (iter.hasNext()) { AttachmentPart attachmentPart = (AttachmentPart) iter.next(); return attachmentPart.getDataHandler().getInputStream(); } } catch (IOException e) { e.printStackTrace(); } catch (SOAPException e) { e.printStackTrace(); } return null; } public Document getDocument(String infoObjectName) throws ParserConfigurationException, IOException, SAXException { InputStream inputStream = getXmlStream(infoObjectName); if (inputStream == null) return null; Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(inputStream); inputStream.close(); return document; } public String getXml(String infoObjectName) throws IOException { InputStream inputStream = getXmlStream(infoObjectName); if (inputStream == null) return null; StringBuffer stringBuffer = new StringBuffer(); byte[] buf = new byte[1024]; int len = 0; while ((len = inputStream.read(buf)) > 0) { stringBuffer.append(new String(buf, 0, len)); } inputStream.close(); return stringBuffer.toString(); } private ExecuteQueryResponse getExecuteQueryId(String infoObjectName) { ArrayOfColumnDefinition arrayOfColumnDefinition = getAvailableColumns(infoObjectName); if (arrayOfColumnDefinition == null) return null; Query query = new Query(); query.setAvailableColumnList(arrayOfColumnDefinition); query.setSelectColumnList(getSelectColumnList(arrayOfColumnDefinition)); query.setSuppressDetailRows(false); query.setOutputDistinctRowsOnly(false); query.setSupportedQueryFeatures(SupportedQueryFeatures.UI_Version_2); ExecuteQuery executeQuery = new ExecuteQuery(); executeQuery.setInputFileName(infoObjectName); executeQuery.setJobName("$$$TRANSIENT_JOB$$$"); executeQuery.setSaveOutputFile(false); executeQuery.setProgressiveViewing(false); executeQuery.setRunLatestVersion(true); executeQuery.setWaitTime(300); executeQuery.setQuery(query); ExecuteQueryResponse executeQueryResponse; try { executeQueryResponse = acxControl.proxy.executeQuery(executeQuery); } catch (RemoteException e) { e.printStackTrace(); return null; } return executeQueryResponse; } private ArrayOfColumnDefinition getAvailableColumns(String infoObjectName) { GetQuery getQuery = new GetQuery(); getQuery.setQueryFileName(infoObjectName); GetQueryResponse getQueryResponse; try { getQueryResponse = acxControl.proxy.getQuery(getQuery); } catch (RemoteException e) { e.printStackTrace(); return null; } if (getQueryResponse == null || getQueryResponse.getQuery() == null) return null; return getQueryResponse.getQuery().getAvailableColumnList(); } private ArrayOfString getSelectColumnList(ArrayOfColumnDefinition arrayOfColumnDefinition) { ColumnDefinition[] columnDefinitions = arrayOfColumnDefinition.getColumnDefinition(); String[] columnList = new String[columnDefinitions.length]; for (int i = 0; i < columnDefinitions.length; i++) { columnList[i] = columnDefinitions[i].getName(); } return new ArrayOfString(columnList); } }
epl-1.0
oscerd/core
parser-java/api/src/main/java/org/jboss/forge/addon/parser/java/ui/JavaPackageCommand.java
416
/** * Copyright 2015 Red Hat, Inc. and/or its affiliates. * * Licensed under the Eclipse Public License version 1.0, available at * http://www.eclipse.org/legal/epl-v10.html */ package org.jboss.forge.addon.parser.java.ui; import org.jboss.forge.addon.ui.command.UICommand; /** * @author <a href="mailto:ggastald@redhat.com">George Gastaldi</a> */ public interface JavaPackageCommand extends UICommand { }
epl-1.0
muros-ct/kapua
locator/service/src/main/java/org/eclipse/kapua/model/config/metatype/KapuaToption.java
3975
/******************************************************************************* * 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.model.config.metatype; import java.util.List; import java.util.Map; import javax.xml.bind.annotation.*; import javax.xml.namespace.QName; import org.w3c.dom.Element; /** * <p> * Java class for Toption complex type. * * <p> * The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Toption"&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;any processContents='lax' maxOccurs="unbounded" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;attribute name="label" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="value" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;anyAttribute/&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * @since 1.0 * */ @XmlRootElement(name = "Option", namespace = "http://www.osgi.org/xmlns/metatype/v1.2.0") @XmlAccessorType(XmlAccessType.PROPERTY) @XmlType(name = "Toption", propOrder = { "any" }, factoryClass = MetatypeXmlRegistry.class, factoryMethod = "newKapuaToption") public interface KapuaToption { /** * Gets the value of the any property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the any property. * * <p> * For example, to add a new item, do as follows: * * <pre> * getAny().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Object } * * */ @XmlAnyElement(lax = true) public List<Object> getAny(); /** * Gets the value of the label property. * * @return * possible object is * {@link String } * */ @XmlAttribute(name = "label", required = true) public String getLabel(); /** * Sets the value of the label property. * * @param value * allowed object is * {@link String } * */ public void setLabel(String value); /** * Gets the value of the value property. * * @return * possible object is * {@link String } * */ @XmlAttribute(name = "value", required = true) public String getValue(); /** * Sets the value of the value property. * * @param value * allowed object is * {@link String } * */ public void setValue(String value); /** * Gets a map that contains attributes that aren't bound to any typed property on this class. * * <p> * the map is keyed by the name of the attribute and * the value is the string value of the attribute. * * the map returned by this method is live, and you can add new attribute * by updating the map directly. Because of this design, there's no setter. * * * @return * always non-null */ @XmlAnyAttribute public Map<QName, String> getOtherAttributes(); }
epl-1.0
occiware/Multi-Cloud-Studio
plugins/org.eclipse.cmf.occi.multicloud.aws.ec2/src-gen/org/eclipse/cmf/occi/multicloud/aws/ec2/impl/X1_32xlargeImpl.java
10365
/** * Copyright (c) 2015-2017 Obeo, Inria * 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: * - William Piers <william.piers@obeo.fr> * - Philippe Merle <philippe.merle@inria.fr> * - Faiez Zalila <faiez.zalila@inria.fr> */ package org.eclipse.cmf.occi.multicloud.aws.ec2.impl; import org.eclipse.cmf.occi.multicloud.aws.ec2.Ec2Package; import org.eclipse.cmf.occi.multicloud.aws.ec2.X1_32xlarge; import org.eclipse.emf.common.notify.Notification; import org.eclipse.emf.ecore.EClass; import org.eclipse.emf.ecore.impl.ENotificationImpl; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>X1 32xlarge</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.eclipse.cmf.occi.multicloud.aws.ec2.impl.X1_32xlargeImpl#getOcciComputeMemory <em>Occi Compute Memory</em>}</li> * <li>{@link org.eclipse.cmf.occi.multicloud.aws.ec2.impl.X1_32xlargeImpl#getInstanceType <em>Instance Type</em>}</li> * <li>{@link org.eclipse.cmf.occi.multicloud.aws.ec2.impl.X1_32xlargeImpl#getOcciComputeCores <em>Occi Compute Cores</em>}</li> * <li>{@link org.eclipse.cmf.occi.multicloud.aws.ec2.impl.X1_32xlargeImpl#getOcciComputeEphemeralStorageSize <em>Occi Compute Ephemeral Storage Size</em>}</li> * </ul> * * @generated */ public class X1_32xlargeImpl extends MemoryoptimizedImpl implements X1_32xlarge { /** * The default value of the '{@link #getOcciComputeMemory() <em>Occi Compute Memory</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOcciComputeMemory() * @generated * @ordered */ protected static final Float OCCI_COMPUTE_MEMORY_EDEFAULT = new Float(1952.0F); /** * The cached value of the '{@link #getOcciComputeMemory() <em>Occi Compute Memory</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOcciComputeMemory() * @generated * @ordered */ protected Float occiComputeMemory = OCCI_COMPUTE_MEMORY_EDEFAULT; /** * The default value of the '{@link #getInstanceType() <em>Instance Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getInstanceType() * @generated * @ordered */ protected static final String INSTANCE_TYPE_EDEFAULT = "x1.32xlarge"; /** * The cached value of the '{@link #getInstanceType() <em>Instance Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getInstanceType() * @generated * @ordered */ protected String instanceType = INSTANCE_TYPE_EDEFAULT; /** * The default value of the '{@link #getOcciComputeCores() <em>Occi Compute Cores</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOcciComputeCores() * @generated * @ordered */ protected static final Integer OCCI_COMPUTE_CORES_EDEFAULT = new Integer(128); /** * The cached value of the '{@link #getOcciComputeCores() <em>Occi Compute Cores</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOcciComputeCores() * @generated * @ordered */ protected Integer occiComputeCores = OCCI_COMPUTE_CORES_EDEFAULT; /** * The default value of the '{@link #getOcciComputeEphemeralStorageSize() <em>Occi Compute Ephemeral Storage Size</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOcciComputeEphemeralStorageSize() * @generated * @ordered */ protected static final Float OCCI_COMPUTE_EPHEMERAL_STORAGE_SIZE_EDEFAULT = new Float(3840.0F); /** * The cached value of the '{@link #getOcciComputeEphemeralStorageSize() <em>Occi Compute Ephemeral Storage Size</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #getOcciComputeEphemeralStorageSize() * @generated * @ordered */ protected Float occiComputeEphemeralStorageSize = OCCI_COMPUTE_EPHEMERAL_STORAGE_SIZE_EDEFAULT; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected X1_32xlargeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Ec2Package.eINSTANCE.getX1_32xlarge(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Float getOcciComputeMemory() { return occiComputeMemory; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setOcciComputeMemory(Float newOcciComputeMemory) { Float oldOcciComputeMemory = occiComputeMemory; occiComputeMemory = newOcciComputeMemory; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Ec2Package.X1_32XLARGE__OCCI_COMPUTE_MEMORY, oldOcciComputeMemory, occiComputeMemory)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public String getInstanceType() { return instanceType; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setInstanceType(String newInstanceType) { String oldInstanceType = instanceType; instanceType = newInstanceType; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Ec2Package.X1_32XLARGE__INSTANCE_TYPE, oldInstanceType, instanceType)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Integer getOcciComputeCores() { return occiComputeCores; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setOcciComputeCores(Integer newOcciComputeCores) { Integer oldOcciComputeCores = occiComputeCores; occiComputeCores = newOcciComputeCores; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Ec2Package.X1_32XLARGE__OCCI_COMPUTE_CORES, oldOcciComputeCores, occiComputeCores)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public Float getOcciComputeEphemeralStorageSize() { return occiComputeEphemeralStorageSize; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setOcciComputeEphemeralStorageSize(Float newOcciComputeEphemeralStorageSize) { Float oldOcciComputeEphemeralStorageSize = occiComputeEphemeralStorageSize; occiComputeEphemeralStorageSize = newOcciComputeEphemeralStorageSize; if (eNotificationRequired()) eNotify(new ENotificationImpl(this, Notification.SET, Ec2Package.X1_32XLARGE__OCCI_COMPUTE_EPHEMERAL_STORAGE_SIZE, oldOcciComputeEphemeralStorageSize, occiComputeEphemeralStorageSize)); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Object eGet(int featureID, boolean resolve, boolean coreType) { switch (featureID) { case Ec2Package.X1_32XLARGE__OCCI_COMPUTE_MEMORY: return getOcciComputeMemory(); case Ec2Package.X1_32XLARGE__INSTANCE_TYPE: return getInstanceType(); case Ec2Package.X1_32XLARGE__OCCI_COMPUTE_CORES: return getOcciComputeCores(); case Ec2Package.X1_32XLARGE__OCCI_COMPUTE_EPHEMERAL_STORAGE_SIZE: return getOcciComputeEphemeralStorageSize(); } return super.eGet(featureID, resolve, coreType); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eSet(int featureID, Object newValue) { switch (featureID) { case Ec2Package.X1_32XLARGE__OCCI_COMPUTE_MEMORY: setOcciComputeMemory((Float)newValue); return; case Ec2Package.X1_32XLARGE__INSTANCE_TYPE: setInstanceType((String)newValue); return; case Ec2Package.X1_32XLARGE__OCCI_COMPUTE_CORES: setOcciComputeCores((Integer)newValue); return; case Ec2Package.X1_32XLARGE__OCCI_COMPUTE_EPHEMERAL_STORAGE_SIZE: setOcciComputeEphemeralStorageSize((Float)newValue); return; } super.eSet(featureID, newValue); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void eUnset(int featureID) { switch (featureID) { case Ec2Package.X1_32XLARGE__OCCI_COMPUTE_MEMORY: setOcciComputeMemory(OCCI_COMPUTE_MEMORY_EDEFAULT); return; case Ec2Package.X1_32XLARGE__INSTANCE_TYPE: setInstanceType(INSTANCE_TYPE_EDEFAULT); return; case Ec2Package.X1_32XLARGE__OCCI_COMPUTE_CORES: setOcciComputeCores(OCCI_COMPUTE_CORES_EDEFAULT); return; case Ec2Package.X1_32XLARGE__OCCI_COMPUTE_EPHEMERAL_STORAGE_SIZE: setOcciComputeEphemeralStorageSize(OCCI_COMPUTE_EPHEMERAL_STORAGE_SIZE_EDEFAULT); return; } super.eUnset(featureID); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean eIsSet(int featureID) { switch (featureID) { case Ec2Package.X1_32XLARGE__OCCI_COMPUTE_MEMORY: return OCCI_COMPUTE_MEMORY_EDEFAULT == null ? occiComputeMemory != null : !OCCI_COMPUTE_MEMORY_EDEFAULT.equals(occiComputeMemory); case Ec2Package.X1_32XLARGE__INSTANCE_TYPE: return INSTANCE_TYPE_EDEFAULT == null ? instanceType != null : !INSTANCE_TYPE_EDEFAULT.equals(instanceType); case Ec2Package.X1_32XLARGE__OCCI_COMPUTE_CORES: return OCCI_COMPUTE_CORES_EDEFAULT == null ? occiComputeCores != null : !OCCI_COMPUTE_CORES_EDEFAULT.equals(occiComputeCores); case Ec2Package.X1_32XLARGE__OCCI_COMPUTE_EPHEMERAL_STORAGE_SIZE: return OCCI_COMPUTE_EPHEMERAL_STORAGE_SIZE_EDEFAULT == null ? occiComputeEphemeralStorageSize != null : !OCCI_COMPUTE_EPHEMERAL_STORAGE_SIZE_EDEFAULT.equals(occiComputeEphemeralStorageSize); } 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(" (occiComputeMemory: "); result.append(occiComputeMemory); result.append(", instanceType: "); result.append(instanceType); result.append(", occiComputeCores: "); result.append(occiComputeCores); result.append(", occiComputeEphemeralStorageSize: "); result.append(occiComputeEphemeralStorageSize); result.append(')'); return result.toString(); } } //X1_32xlargeImpl
epl-1.0
hudson3-plugins/coverity-plugin
src/main/java/com/coverity/ws/v5/GetCIDsForStreamsResponse.java
1883
package com.coverity.ws.v5; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for getCIDsForStreamsResponse complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="getCIDsForStreamsResponse"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="return" type="{http://www.w3.org/2001/XMLSchema}long" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "getCIDsForStreamsResponse", propOrder = { "_return" }) public class GetCIDsForStreamsResponse { @XmlElement(name = "return", type = Long.class) protected List<Long> _return; /** * Gets the value of the return property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the return property. * * <p> * For example, to add a new item, do as follows: * <pre> * getReturn().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link Long } * * */ public List<Long> getReturn() { if (_return == null) { _return = new ArrayList<Long>(); } return this._return; } }
epl-1.0
elucash/eclipse-oxygen
org.eclipse.jdt.ui/src/org/eclipse/jdt/internal/ui/filters/FilterDescriptor.java
9298
/******************************************************************************* * Copyright (c) 2000, 2011 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jdt.internal.ui.filters; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import com.ibm.icu.text.Collator; import org.eclipse.core.runtime.Assert; import org.eclipse.core.runtime.IConfigurationElement; import org.eclipse.core.runtime.IExtensionRegistry; import org.eclipse.core.runtime.ISafeRunnable; import org.eclipse.core.runtime.Platform; import org.eclipse.core.runtime.SafeRunner; import org.eclipse.jface.util.SafeRunnable; import org.eclipse.jface.viewers.ViewerFilter; import org.eclipse.ui.IPluginContribution; import org.eclipse.ui.activities.WorkbenchActivityHelper; import org.eclipse.jdt.internal.corext.util.Messages; import org.eclipse.jdt.ui.JavaUI; /** * Represents a custom filter which is provided by the * "org.eclipse.jdt.ui.javaElementFilters" extension point. * * since 2.0 */ public class FilterDescriptor implements Comparable<FilterDescriptor>, IPluginContribution { private static String PATTERN_FILTER_ID_PREFIX= "_patternFilterId_"; //$NON-NLS-1$ private static final String EXTENSION_POINT_NAME= "javaElementFilters"; //$NON-NLS-1$ private static final String FILTER_TAG= "filter"; //$NON-NLS-1$ private static final String PATTERN_ATTRIBUTE= "pattern"; //$NON-NLS-1$ private static final String ID_ATTRIBUTE= "id"; //$NON-NLS-1$ /** * @deprecated as of 3.0 use {@link FilterDescriptor#TARGET_ID_ATTRIBUTE} */ @Deprecated private static final String VIEW_ID_ATTRIBUTE= "viewId"; //$NON-NLS-1$ private static final String TARGET_ID_ATTRIBUTE= "targetId"; //$NON-NLS-1$ private static final String CLASS_ATTRIBUTE= "class"; //$NON-NLS-1$ private static final String NAME_ATTRIBUTE= "name"; //$NON-NLS-1$ private static final String ENABLED_ATTRIBUTE= "enabled"; //$NON-NLS-1$ private static final String DESCRIPTION_ATTRIBUTE= "description"; //$NON-NLS-1$ /** * @deprecated use "enabled" instead */ @Deprecated private static final String SELECTED_ATTRIBUTE= "selected"; //$NON-NLS-1$ private static FilterDescriptor[] fgFilterDescriptors; private IConfigurationElement fElement; /** * Returns all contributed Java element filters. * @return all contributed Java element filters */ public static FilterDescriptor[] getFilterDescriptors() { if (fgFilterDescriptors == null) { IExtensionRegistry registry= Platform.getExtensionRegistry(); IConfigurationElement[] elements= registry.getConfigurationElementsFor(JavaUI.ID_PLUGIN, EXTENSION_POINT_NAME); fgFilterDescriptors= createFilterDescriptors(elements); } return fgFilterDescriptors; } /** * Returns all Java element filters which * are contributed to the given view. * @param targetId the target id * @return all contributed Java element filters for the given view */ public static FilterDescriptor[] getFilterDescriptors(String targetId) { FilterDescriptor[] filterDescs= FilterDescriptor.getFilterDescriptors(); List<FilterDescriptor> result= new ArrayList<>(filterDescs.length); for (int i= 0; i < filterDescs.length; i++) { String tid= filterDescs[i].getTargetId(); if (WorkbenchActivityHelper.filterItem(filterDescs[i])) continue; if (tid == null || tid.equals(targetId)) result.add(filterDescs[i]); } return result.toArray(new FilterDescriptor[result.size()]); } /** * Creates a new filter descriptor for the given configuration element. * @param element configuration element */ private FilterDescriptor(IConfigurationElement element) { fElement= element; // it is either a pattern filter or a custom filter Assert.isTrue(isPatternFilter() ^ isCustomFilter(), "An extension for extension-point org.eclipse.jdt.ui.javaElementFilters does not specify a correct filter"); //$NON-NLS-1$ Assert.isNotNull(getId(), "An extension for extension-point org.eclipse.jdt.ui.javaElementFilters does not provide a valid ID"); //$NON-NLS-1$ Assert.isNotNull(getName(), "An extension for extension-point org.eclipse.jdt.ui.javaElementFilters does not provide a valid name"); //$NON-NLS-1$ } /** * Creates a new <code>ViewerFilter</code>. * This method is only valid for viewer filters. * @return a new <code>ViewerFilter</code> */ public ViewerFilter createViewerFilter() { if (!isCustomFilter()) return null; final ViewerFilter[] result= new ViewerFilter[1]; String message= Messages.format(FilterMessages.FilterDescriptor_filterCreationError_message, getId()); ISafeRunnable code= new SafeRunnable(message) { /* * @see org.eclipse.core.runtime.ISafeRunnable#run() */ @Override public void run() throws Exception { result[0]= (ViewerFilter)fElement.createExecutableExtension(CLASS_ATTRIBUTE); } }; SafeRunner.run(code); return result[0]; } //---- XML Attribute accessors --------------------------------------------- /** * Returns the filter's id. * <p> * This attribute is mandatory for custom filters. * The ID for pattern filters is * PATTERN_FILTER_ID_PREFIX plus the pattern itself. * </p> * @return the filter id */ public String getId() { if (isPatternFilter()) { String targetId= getTargetId(); if (targetId == null) return PATTERN_FILTER_ID_PREFIX + getPattern(); else return targetId + PATTERN_FILTER_ID_PREFIX + getPattern(); } else return fElement.getAttribute(ID_ATTRIBUTE); } /** * Returns the filter's name. * <p> * If the name of a pattern filter is missing * then the pattern is used as its name. * </p> * @return the filter's name */ public String getName() { String name= fElement.getAttribute(NAME_ATTRIBUTE); if (name == null && isPatternFilter()) name= getPattern(); return name; } /** * Returns the filter's pattern. * * @return the pattern string or <code>null</code> if it's not a pattern filter */ public String getPattern() { return fElement.getAttribute(PATTERN_ATTRIBUTE); } /** * Returns the filter's viewId. * * @return the view ID or <code>null</code> if the filter is for all views * @since 3.0 */ public String getTargetId() { String tid= fElement.getAttribute(TARGET_ID_ATTRIBUTE); if (tid != null) return tid; // Backwards compatibility code return fElement.getAttribute(VIEW_ID_ATTRIBUTE); } /** * Returns the filter's description. * * @return the description or <code>null</code> if no description is provided */ public String getDescription() { String description= fElement.getAttribute(DESCRIPTION_ATTRIBUTE); if (description == null) description= ""; //$NON-NLS-1$ return description; } /** * @return <code>true</code> if this filter is a custom filter. */ public boolean isPatternFilter() { return getPattern() != null; } /** * @return <code>true</code> if this filter is a pattern filter. */ public boolean isCustomFilter() { return fElement.getAttribute(CLASS_ATTRIBUTE) != null; } /** * Returns <code>true</code> if the filter * is initially enabled. * * This attribute is optional and defaults to <code>true</code>. * @return returns <code>true</code> if the filter is initially enabled */ public boolean isEnabled() { String strVal= fElement.getAttribute(ENABLED_ATTRIBUTE); if (strVal == null) // backward compatibility strVal= fElement.getAttribute(SELECTED_ATTRIBUTE); return strVal == null || Boolean.valueOf(strVal).booleanValue(); } @Override public int compareTo(FilterDescriptor o) { return Collator.getInstance().compare(getName(), o.getName()); } //---- initialization --------------------------------------------------- /** * Creates the filter descriptors. * @param elements the configuration elements * @return new filter descriptors */ private static FilterDescriptor[] createFilterDescriptors(IConfigurationElement[] elements) { List<FilterDescriptor> result= new ArrayList<>(5); Set<String> descIds= new HashSet<>(5); for (int i= 0; i < elements.length; i++) { final IConfigurationElement element= elements[i]; if (FILTER_TAG.equals(element.getName())) { final FilterDescriptor[] desc= new FilterDescriptor[1]; SafeRunner.run(new SafeRunnable(FilterMessages.FilterDescriptor_filterDescriptionCreationError_message) { @Override public void run() throws Exception { desc[0]= new FilterDescriptor(element); } }); if (desc[0] != null && !descIds.contains(desc[0].getId())) { result.add(desc[0]); descIds.add(desc[0].getId()); } } } return result.toArray(new FilterDescriptor[result.size()]); } @Override public String getLocalId() { return fElement.getAttribute(ID_ATTRIBUTE); } @Override public String getPluginId() { return fElement.getContributor().getName(); } }
epl-1.0
jesusc/bento
plugins/genericity.language.gbind.resource.ui/src-gen/gbind/resource/gbind/ui/GbindColorManager.java
1081
/** * <copyright> * </copyright> * * */ package gbind.resource.gbind.ui; /** * A class for RGB-based color objects. */ public class GbindColorManager { protected java.util.Map<org.eclipse.swt.graphics.RGB, org.eclipse.swt.graphics.Color> fColorTable = new java.util.LinkedHashMap<org.eclipse.swt.graphics.RGB, org.eclipse.swt.graphics.Color>(10); /** * Disposes all colors in the cache. */ public void dispose() { java.util.Iterator<org.eclipse.swt.graphics.Color> e = fColorTable.values().iterator(); while (e.hasNext()) { e.next().dispose(); } } /** * Constructs and caches the given color. * * @param rgb The color as org.eclipse.swt.graphics.RGB * * @return The color (from cache or newly constructed) */ public org.eclipse.swt.graphics.Color getColor(org.eclipse.swt.graphics.RGB rgb) { org.eclipse.swt.graphics.Color color = fColorTable.get(rgb); if (color == null) { color = new org.eclipse.swt.graphics.Color(org.eclipse.swt.widgets.Display.getCurrent(), rgb); fColorTable.put(rgb, color); } return color; } }
epl-1.0
debabratahazra/DS
designstudio/components/t24server/core/com.odcgroup.t24.server.external/src/main/java/com/odcgroup/t24/server/external/model/internal/LocalRefApplicationLoader.java
3065
package com.odcgroup.t24.server.external.model.internal; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.StringTokenizer; import com.odcgroup.t24.server.external.model.IExternalObject; import com.odcgroup.t24.server.external.model.LocalRefApplicationDetail; import com.odcgroup.t24.server.external.util.T24AgentConnection; import com.odcgroup.t24.server.external.util.T24AgentConnection.T24Response; import com.odcgroup.t24.server.external.util.T24AgentConnectionHelper; /** * * TODO: Document me! * @author hdebabrata * */ public class LocalRefApplicationLoader extends ExternalLoader { private static final String GET_LOCALREF_APPLICATION_TABLE_AS_XML = "T24CatalogServiceImpl.getLocalRefTableAsXml"; private static final String GET_LOCALREF_APPLICATION_TABLE_LIST = "T24CatalogServiceImpl.getLocalRefTableObjects"; protected LocalRefApplicationLoader(Properties properties) { super(properties); } @SuppressWarnings("unchecked") @Override public <T extends IExternalObject> List<T> getObjectDetails() throws T24ServerException { T24AgentConnection connection = getConnection(); if (connection == null) { throw new T24ServerException( "There is no connection with the T24 server."); } List<LocalRefApplicationDetail> localRefApps = new ArrayList<LocalRefApplicationDetail>(); T24Response responseTableList = connection.call(GET_LOCALREF_APPLICATION_TABLE_LIST, null, null); String tableLists = responseTableList.getValue(0); T24AgentConnectionHelper.checkForValidLicense(responseTableList.getParameters()); StringTokenizer strTokenTableList = new StringTokenizer(tableLists, "#"); List<String> tableList = new ArrayList<String>(strTokenTableList.countTokens()); while (strTokenTableList.hasMoreElements()) { tableList.add((String)strTokenTableList.nextElement()); } for (Iterator<String> iterator = tableList.iterator(); iterator.hasNext();) { String table = (String) iterator.next(); T24Response response = connection.call(GET_LOCALREF_APPLICATION_TABLE_AS_XML, table, null,null); String tableName = response.getValue(0); StringTokenizer localRefNameST = new StringTokenizer(tableName, RESPONSE_SEPARATOR); while (localRefNameST.hasMoreElements()) { String elementName = localRefNameST.nextElement().toString(); LocalRefApplicationDetail localRefDetail = new LocalRefApplicationDetail(elementName); localRefApps.add(localRefDetail); } } return (List<T>) localRefApps; } @Override public <T extends IExternalObject> String getObjectAsXML(T detail) throws T24ServerException { T24AgentConnection connection = getConnection(); if (connection == null) {throw new T24ServerException( "There is no connection with the T24 server."); //$NON-NLS-1$ } String LocalRefApplicationName = detail.getName(); T24Response response = connection.call(GET_LOCALREF_APPLICATION_TABLE_AS_XML, LocalRefApplicationName, null, null); return response.getValue(1); } }
epl-1.0
opendaylight/ovsdb
hwvtepsouthbound/hwvtepsouthbound-impl/src/main/java/org/opendaylight/ovsdb/hwvtepsouthbound/HwvtepDisconnectCliCmd.java
3257
/* * Copyright (c) 2020 Ericsson India Global Services Pvt Ltd. and others. All rights reserved. * * This program and the accompanying materials are made available under the * terms of the Eclipse Public License v1.0 which accompanies this distribution, * and is available at http://www.eclipse.org/legal/epl-v10.html */ package org.opendaylight.ovsdb.hwvtepsouthbound; import edu.umd.cs.findbugs.annotations.SuppressFBWarnings; import org.apache.karaf.shell.commands.Command; import org.apache.karaf.shell.commands.Option; import org.apache.karaf.shell.console.OsgiCommandSupport; import org.opendaylight.mdsal.binding.api.DataBroker; import org.opendaylight.mdsal.binding.api.ReadWriteTransaction; import org.opendaylight.mdsal.common.api.LogicalDatastoreType; import org.opendaylight.yang.gen.v1.urn.ietf.params.xml.ns.yang.ietf.inet.types.rev130715.Uri; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NetworkTopology; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.NodeId; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.TopologyId; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.Topology; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.TopologyKey; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.Node; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeBuilder; import org.opendaylight.yang.gen.v1.urn.tbd.params.xml.ns.yang.network.topology.rev131021.network.topology.topology.NodeKey; import org.opendaylight.yangtools.yang.binding.InstanceIdentifier; @Command(scope = "hwvtep", name = "disconnect", description = "Disconnect a node") public class HwvtepDisconnectCliCmd extends OsgiCommandSupport { private DataBroker dataBroker; @Option(name = "-nodeid", description = "Node Id", required = false, multiValued = false) String nodeid; public static final TopologyId HWVTEP_TOPOLOGY_ID = new TopologyId(new Uri("hwvtep:1")); public void setDataBroker(DataBroker dataBroker) { this.dataBroker = dataBroker; } @Override @SuppressFBWarnings("UWF_FIELD_NOT_INITIALIZED_IN_CONSTRUCTOR") protected Object doExecute() throws Exception { ReadWriteTransaction tx = dataBroker.newReadWriteTransaction(); tx.put(LogicalDatastoreType.CONFIGURATION, getIid(), new NodeBuilder().setNodeId(new NodeId(new Uri(nodeid + "/disconnect"))).build()); tx.commit().get(); session.getConsole().println("Successfully disconnected " + nodeid); return ""; } private InstanceIdentifier<Node> getIid() { NodeId nodeId = new NodeId(new Uri(nodeid + "/disconnect")); NodeKey nodeKey = new NodeKey(nodeId); TopologyKey topoKey = new TopologyKey(HWVTEP_TOPOLOGY_ID); return InstanceIdentifier.builder(NetworkTopology.class) .child(Topology.class, topoKey) .child(Node.class, nodeKey) .build(); } }
epl-1.0
junit-team/junit4
src/main/java/org/junit/runner/JUnitCore.java
5862
package org.junit.runner; import junit.runner.Version; import org.junit.internal.JUnitSystem; import org.junit.internal.RealSystem; import org.junit.internal.TextListener; import org.junit.internal.runners.JUnit38ClassRunner; import org.junit.runner.notification.RunListener; import org.junit.runner.notification.RunNotifier; /** * <code>JUnitCore</code> is a facade for running tests. It supports running JUnit 4 tests, * JUnit 3.8.x tests, and mixtures. To run tests from the command line, run * <code>java org.junit.runner.JUnitCore TestClass1 TestClass2 ...</code>. * For one-shot test runs, use the static method {@link #runClasses(Class[])}. * If you want to add special listeners, * create an instance of {@link org.junit.runner.JUnitCore} first and use it to run the tests. * * @see org.junit.runner.Result * @see org.junit.runner.notification.RunListener * @see org.junit.runner.Request * @since 4.0 */ public class JUnitCore { private final RunNotifier notifier = new RunNotifier(); /** * Run the tests contained in the classes named in the <code>args</code>. * If all tests run successfully, exit with a status of 0. Otherwise exit with a status of 1. * Write feedback while tests are running and write * stack traces for all failed tests after the tests all complete. * * @param args names of classes in which to find tests to run */ public static void main(String... args) { Result result = new JUnitCore().runMain(new RealSystem(), args); System.exit(result.wasSuccessful() ? 0 : 1); } /** * Run the tests contained in <code>classes</code>. Write feedback while the tests * are running and write stack traces for all failed tests after all tests complete. This is * similar to {@link #main(String[])}, but intended to be used programmatically. * * @param classes Classes in which to find tests * @return a {@link Result} describing the details of the test run and the failed tests. */ public static Result runClasses(Class<?>... classes) { return runClasses(defaultComputer(), classes); } /** * Run the tests contained in <code>classes</code>. Write feedback while the tests * are running and write stack traces for all failed tests after all tests complete. This is * similar to {@link #main(String[])}, but intended to be used programmatically. * * @param computer Helps construct Runners from classes * @param classes Classes in which to find tests * @return a {@link Result} describing the details of the test run and the failed tests. */ public static Result runClasses(Computer computer, Class<?>... classes) { return new JUnitCore().run(computer, classes); } /** * @param system system to run with * @param args from main() */ Result runMain(JUnitSystem system, String... args) { system.out().println("JUnit version " + Version.id()); JUnitCommandLineParseResult jUnitCommandLineParseResult = JUnitCommandLineParseResult.parse(args); RunListener listener = new TextListener(system); addListener(listener); return run(jUnitCommandLineParseResult.createRequest(defaultComputer())); } /** * @return the version number of this release */ public String getVersion() { return Version.id(); } /** * Run all the tests in <code>classes</code>. * * @param classes the classes containing tests * @return a {@link Result} describing the details of the test run and the failed tests. */ public Result run(Class<?>... classes) { return run(defaultComputer(), classes); } /** * Run all the tests in <code>classes</code>. * * @param computer Helps construct Runners from classes * @param classes the classes containing tests * @return a {@link Result} describing the details of the test run and the failed tests. */ public Result run(Computer computer, Class<?>... classes) { return run(Request.classes(computer, classes)); } /** * Run all the tests contained in <code>request</code>. * * @param request the request describing tests * @return a {@link Result} describing the details of the test run and the failed tests. */ public Result run(Request request) { return run(request.getRunner()); } /** * Run all the tests contained in JUnit 3.8.x <code>test</code>. Here for backward compatibility. * * @param test the old-style test * @return a {@link Result} describing the details of the test run and the failed tests. */ public Result run(junit.framework.Test test) { return run(new JUnit38ClassRunner(test)); } /** * Do not use. Testing purposes only. */ public Result run(Runner runner) { Result result = new Result(); RunListener listener = result.createListener(); notifier.addFirstListener(listener); try { notifier.fireTestRunStarted(runner.getDescription()); runner.run(notifier); notifier.fireTestRunFinished(result); } finally { removeListener(listener); } return result; } /** * Add a listener to be notified as the tests run. * * @param listener the listener to add * @see org.junit.runner.notification.RunListener */ public void addListener(RunListener listener) { notifier.addListener(listener); } /** * Remove a listener. * * @param listener the listener to remove */ public void removeListener(RunListener listener) { notifier.removeListener(listener); } static Computer defaultComputer() { return new Computer(); } }
epl-1.0
dkincaid/clumcl
src/generated/java/gov/nih/nlm/uts/webservice/metadata/GetAllSourceTermTypesResponse.java
1969
package gov.nih.nlm.uts.webservice.metadata; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for getAllSourceTermTypesResponse complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="getAllSourceTermTypesResponse"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="return" type="{http://webservice.uts.umls.nlm.nih.gov/}sourceTermTypeDTO" maxOccurs="unbounded" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "getAllSourceTermTypesResponse", propOrder = { "_return" }) public class GetAllSourceTermTypesResponse { @XmlElement(name = "return") protected List<SourceTermTypeDTO> _return; /** * Gets the value of the return property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the return property. * * <p> * For example, to add a new item, do as follows: * <pre> * getReturn().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link SourceTermTypeDTO } * * */ public List<SourceTermTypeDTO> getReturn() { if (_return == null) { _return = new ArrayList<SourceTermTypeDTO>(); } return this._return; } }
epl-1.0
szarnekow/xsemantics
plugins/it.xsemantics.runtime/src/it/xsemantics/runtime/ResultWithFailure.java
534
/** * */ package it.xsemantics.runtime; /** * The result of a rule invocation * * @author Lorenzo Bettini * */ public class ResultWithFailure { private RuleFailedException ruleFailedException; public ResultWithFailure() { } public ResultWithFailure(RuleFailedException ruleFailedException) { super(); this.ruleFailedException = ruleFailedException; } public RuleFailedException getRuleFailedException() { return ruleFailedException; } public boolean failed() { return ruleFailedException != null; } }
epl-1.0
michele-loreti/jResp
examples/org.cmg.examples.pingpong/src/org/cmg/jresp/examples/pingpong/VirtualPingPong.java
2416
/** * Copyright (c) 2012 Concurrency and Mobility Group. * Universita' di Firenze * * 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: * Michele Loreti */ package org.cmg.jresp.examples.pingpong; import java.io.IOException; import org.cmg.jresp.behaviour.Agent; import org.cmg.jresp.comp.Node; import org.cmg.jresp.knowledge.ActualTemplateField; import org.cmg.jresp.knowledge.Template; import org.cmg.jresp.knowledge.Tuple; import org.cmg.jresp.knowledge.ts.TupleSpace; import org.cmg.jresp.topology.PointToPoint; import org.cmg.jresp.topology.Self; import org.cmg.jresp.topology.VirtualPort; import org.cmg.jresp.topology.VirtualPortAddress; /** * @author Michele Loreti * */ public class VirtualPingPong { public static void main(String[] argv) throws IOException { VirtualPort vp = new VirtualPort(10); Node pingNode = new Node("ping", new TupleSpace()); pingNode.addPort(vp); Agent ping = new PingAgent(); Agent pong = new PongAgent(); pingNode.addAgent(ping); Node pongNode = new Node("pong", new TupleSpace()); pongNode.addPort(vp); pongNode.addAgent(pong); pongNode.start(); pingNode.start(); } public static class PingAgent extends Agent { PointToPoint other = new PointToPoint("pong", new VirtualPortAddress(10)); public PingAgent() { super("PING"); } @Override protected void doRun() { try { while (true) { System.out.println("PING!"); put(new Tuple("PING"), other); System.out.println("PING DONE!"); get(new Template(new ActualTemplateField("PONG")), Self.SELF); System.out.println("GET PONG!"); } } catch (Exception e) { e.printStackTrace(); } } } public static class PongAgent extends Agent { PointToPoint other = new PointToPoint("ping", new VirtualPortAddress(10)); public PongAgent() { super("PONG"); } @Override protected void doRun() { try { while (true) { get(new Template(new ActualTemplateField("PING")), Self.SELF); System.out.println("GET PING!"); System.out.println("PONG!"); put(new Tuple("PONG"), other); System.out.println("PONG DONE!"); } } catch (Exception e) { e.printStackTrace(); } } } }
epl-1.0
nickmain/xmind
bundles/org.xmind.ui.mindmap/src/org/xmind/ui/commands/CreateTopicCommand.java
1356
/* ****************************************************************************** * Copyright (c) 2006-2012 XMind Ltd. and others. * * This file is a part of XMind 3. XMind releases 3 and * above are dual-licensed under the Eclipse Public License (EPL), * which is available at http://www.eclipse.org/legal/epl-v10.html * and the GNU Lesser General Public License (LGPL), * which is available at http://www.gnu.org/licenses/lgpl.html * See http://www.xmind.net/license.html for details. * * Contributors: * XMind Ltd. - initial API and implementation *******************************************************************************/ package org.xmind.ui.commands; import org.eclipse.core.runtime.Assert; import org.xmind.core.ITopic; import org.xmind.core.IWorkbook; import org.xmind.gef.command.CreateCommand; public class CreateTopicCommand extends CreateCommand { private IWorkbook workbook; private ITopic topic; public CreateTopicCommand(IWorkbook workbook) { Assert.isNotNull(workbook); this.workbook = workbook; } public boolean canCreate() { if (topic == null) { topic = workbook.createTopic(); } return topic != null; } protected Object create() { canCreate(); return topic; } }
epl-1.0
whizzosoftware/hobson-hub-scheduler
src/main/java/com/whizzosoftware/hobson/scheduler/condition/TriggerConditionListener.java
777
/******************************************************************************* * Copyright (c) 2014 Whizzo Software, LLC. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package com.whizzosoftware.hobson.scheduler.condition; import com.whizzosoftware.hobson.scheduler.ical.ICalTask; /** * Interface for listeners to be alerted when a trigger condition occurs. * * @author Dan Noguerol */ public interface TriggerConditionListener { void onTriggerCondition(ICalTask task, long now); }
epl-1.0
debabratahazra/DS
designstudio/components/workbench/ui/com.odcgroup.workbench.el.ui/src-gen/com/odcgroup/workbench/el/ui/contentassist/AbstractDSELProposalProvider.java
3430
/* * generated by Xtext */ package com.odcgroup.workbench.el.ui.contentassist; import org.eclipse.emf.ecore.EObject; import org.eclipse.xtext.*; import org.eclipse.xtext.ui.editor.contentassist.ICompletionProposalAcceptor; import org.eclipse.xtext.ui.editor.contentassist.ContentAssistContext; /** * Represents a generated, default implementation of superclass {@link ch.vorburger.el.ui.contentassist.ELProposalProvider}. * Methods are dynamically dispatched on the first parameter, i.e., you can override them * with a more concrete subtype. */ @SuppressWarnings("all") public class AbstractDSELProposalProvider extends ch.vorburger.el.ui.contentassist.ELProposalProvider { public void completeXUnaryOperation_Feature(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { lookupCrossReference(((CrossReference)assignment.getTerminal()), context, acceptor); } public void completeXUnaryOperation_Operand(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void completeXBlockExpression_Expressions(EObject model, Assignment assignment, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { completeRuleCall(((RuleCall)assignment.getTerminal()), context, acceptor); } public void complete_XExpression(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_XLiteral(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_XUnaryOperation(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_XBlockExpression(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_XSwitchExpression(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_OpSingleAssign(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_OpEquality(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_OpCompare(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_OpUnary(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_OpOr(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_OpAnd(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } public void complete_COMMENT(EObject model, RuleCall ruleCall, ContentAssistContext context, ICompletionProposalAcceptor acceptor) { // subclasses may override } }
epl-1.0
bradsdavis/cxml-api
src/main/java/org/cxml/fulfill/SharedSecret.java
1780
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.5-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2015.09.23 at 11:18:10 AM CEST // package org.cxml.fulfill; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAnyElement; import javax.xml.bind.annotation.XmlMixed; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import org.w3c.dom.Element; /** * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "content" }) @XmlRootElement(name = "SharedSecret") public class SharedSecret { @XmlMixed @XmlAnyElement protected List<Object> content; /** * Gets the value of the content property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the content property. * * <p> * For example, to add a new item, do as follows: * <pre> * getContent().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * {@link Element } * * */ public List<Object> getContent() { if (content == null) { content = new ArrayList<Object>(); } return this.content; } }
epl-1.0
k3b/pixymeta-android
pixymeta-lib/src/main/java/pixy/io/ReadStrategyMM.java
4621
/** * Copyright (c) 2014-2016 by Wen Yu. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Any modifications to this file must keep this entire header intact. */ package pixy.io; import java.io.InputStream; import java.io.IOException; /** * Read strategy for Motorola byte order BIG-ENDIAN stream. * * @author Wen Yu, yuwen_66@yahoo.com * @version 1.0 12/27/2012 */ public class ReadStrategyMM implements ReadStrategy { private static final ReadStrategyMM instance = new ReadStrategyMM(); public static ReadStrategyMM getInstance() { return instance; } private ReadStrategyMM(){} public int readInt(byte[] buf, int start_idx) { return (((buf[start_idx++]&0xff)<<24)|((buf[start_idx++]&0xff)<<16)| ((buf[start_idx++]&0xff)<<8)|(buf[start_idx++]&0xff)); } public int readInt(InputStream is) throws IOException { byte[] buf = new byte[4]; IOUtils.readFully(is, buf); return (((buf[0]&0xff)<<24)|((buf[1]&0xff)<<16)|((buf[2]&0xff)<<8)|(buf[3]&0xff)); } public long readLong(byte[] buf, int start_idx) { return (((buf[start_idx++]&0xffL)<<56)|((buf[start_idx++]&0xffL)<<48)| ((buf[start_idx++]&0xffL)<<40)|((buf[start_idx++]&0xffL)<<32)|((buf[start_idx++]&0xffL)<<24)| ((buf[start_idx++]&0xffL)<<16)|((buf[start_idx++]&0xffL)<<8)|(buf[start_idx]&0xffL)); } public long readLong(InputStream is) throws IOException { byte[] buf = new byte[8]; IOUtils.readFully(is, buf); return (((buf[0]&0xffL)<<56)|((buf[1]&0xffL)<<48)| ((buf[2]&0xffL)<<40)|((buf[3]&0xffL)<<32)|((buf[4]&0xffL)<<24)| ((buf[5]&0xffL)<<16)|((buf[6]&0xffL)<<8)|(buf[7]&0xffL)); } public float readS15Fixed16Number(byte[] buf, int start_idx) { short s15 = (short)(((buf[start_idx++]&0xff)<<8)|(buf[start_idx++]&0xff)); int fixed16 = (((buf[start_idx++]&0xff)<<8)|(buf[start_idx]&0xff)); return s15 + fixed16/65536.0f; } public float readS15Fixed16Number(InputStream is) throws IOException { byte[] buf = new byte[4]; IOUtils.readFully(is, buf); short s15 = (short)((buf[1]&0xff)|((buf[0]&0xff)<<8)); int fixed16 = ((buf[3]&0xff)|((buf[2]&0xff)<<8)); return s15 + fixed16/65536.0f; } public short readShort(byte[] buf, int start_idx) { return (short)(((buf[start_idx++]&0xff)<<8)|(buf[start_idx]&0xff)); } public short readShort(InputStream is) throws IOException { byte[] buf = new byte[2]; IOUtils.readFully(is, buf); return (short)(((buf[0]&0xff)<<8)|(buf[1]&0xff)); } public float readU16Fixed16Number(byte[] buf, int start_idx) { int u16 = (((buf[start_idx++]&0xff)<<8)|(buf[start_idx++]&0xff)); int fixed16 = (((buf[start_idx++]&0xff)<<8)|(buf[start_idx]&0xff)); return u16 + fixed16/65536.0f; } public float readU16Fixed16Number(InputStream is) throws IOException { byte[] buf = new byte[4]; IOUtils.readFully(is, buf); int u16 = ((buf[1]&0xff)|((buf[0]&0xff)<<8)); int fixed16 = ((buf[3]&0xff)|((buf[2]&0xff)<<8)); return u16 + fixed16/65536.0f; } public float readU8Fixed8Number(byte[] buf, int start_idx) { int u8 = (buf[start_idx++]&0xff); int fixed8 = (buf[start_idx]&0xff); return u8 + fixed8/256.0f; } public float readU8Fixed8Number(InputStream is) throws IOException { byte[] buf = new byte[2]; IOUtils.readFully(is, buf); int u8 = (buf[0]&0xff); int fixed8 = (buf[1]&0xff); return u8 + fixed8/256.0f; } public long readUnsignedInt(byte[] buf, int start_idx) { return (((buf[start_idx++]&0xff)<<24)|((buf[start_idx++]&0xff)<<16)| ((buf[start_idx++]&0xff)<<8)|(buf[start_idx++]&0xff))& 0xffffffffL; } public long readUnsignedInt(InputStream is) throws IOException { byte[] buf = new byte[4]; IOUtils.readFully(is, buf); return (((buf[0]&0xff)<<24)|((buf[1]&0xff)<<16)| ((buf[2]&0xff)<<8)|(buf[3]&0xff))& 0xffffffffL; } public int readUnsignedShort(byte[] buf, int start_idx) { return (((buf[start_idx++]&0xff)<<8)|(buf[start_idx]&0xff)); } public int readUnsignedShort(InputStream is) throws IOException { byte[] buf = new byte[2]; IOUtils.readFully(is, buf); return (((buf[0]&0xff)<<8)|(buf[1]&0xff)); } }
epl-1.0
miklossy/xtext-core
org.eclipse.xtext.tests/src-gen/org/eclipse/xtext/serializer/contextFinderTest/AttributeExclusionTest.java
2551
/** * generated by Xtext */ package org.eclipse.xtext.serializer.contextFinderTest; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Attribute Exclusion Test</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link org.eclipse.xtext.serializer.contextFinderTest.AttributeExclusionTest#getAttr1 <em>Attr1</em>}</li> * <li>{@link org.eclipse.xtext.serializer.contextFinderTest.AttributeExclusionTest#getAttr2 <em>Attr2</em>}</li> * </ul> * * @see org.eclipse.xtext.serializer.contextFinderTest.ContextFinderTestPackage#getAttributeExclusionTest() * @model * @generated */ public interface AttributeExclusionTest extends EObject { /** * Returns the value of the '<em><b>Attr1</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Attr1</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Attr1</em>' attribute. * @see #setAttr1(String) * @see org.eclipse.xtext.serializer.contextFinderTest.ContextFinderTestPackage#getAttributeExclusionTest_Attr1() * @model * @generated */ String getAttr1(); /** * Sets the value of the '{@link org.eclipse.xtext.serializer.contextFinderTest.AttributeExclusionTest#getAttr1 <em>Attr1</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Attr1</em>' attribute. * @see #getAttr1() * @generated */ void setAttr1(String value); /** * Returns the value of the '<em><b>Attr2</b></em>' attribute. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Attr2</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Attr2</em>' attribute. * @see #setAttr2(String) * @see org.eclipse.xtext.serializer.contextFinderTest.ContextFinderTestPackage#getAttributeExclusionTest_Attr2() * @model * @generated */ String getAttr2(); /** * Sets the value of the '{@link org.eclipse.xtext.serializer.contextFinderTest.AttributeExclusionTest#getAttr2 <em>Attr2</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Attr2</em>' attribute. * @see #getAttr2() * @generated */ void setAttr2(String value); } // AttributeExclusionTest
epl-1.0
TatyPerson/Xtext2Sonar
evaluation-scenarios/sonar-PogoDsl/PogoDsl-squid/src/main/java/org/sonar/PogoDsl/lexer/PogoDslLexer.java
3633
package org.sonar.PogoDsl.lexer; import static com.sonar.sslr.impl.channel.RegexpChannelBuilder.ANY_CHAR; import static com.sonar.sslr.impl.channel.RegexpChannelBuilder.and; import static com.sonar.sslr.impl.channel.RegexpChannelBuilder.commentRegexp; import static com.sonar.sslr.impl.channel.RegexpChannelBuilder.o2n; import static com.sonar.sslr.impl.channel.RegexpChannelBuilder.opt; import static com.sonar.sslr.impl.channel.RegexpChannelBuilder.regexp; import org.sonar.PogoDsl.PogoDslConfiguration; import org.sonar.PogoDsl.api.PogoDslTokenType; import org.sonar.PogoDsl.channels.CharacterLiteralsChannel; import org.sonar.PogoDsl.channels.StringLiteralsChannel; import org.sonar.PogoDsl.api.PogoDslKeyword; import org.sonar.PogoDsl.api.PogoDslPunctuator; import com.sonar.sslr.impl.Lexer; import com.sonar.sslr.impl.channel.BlackHoleChannel; import com.sonar.sslr.impl.channel.IdentifierAndKeywordChannel; import com.sonar.sslr.impl.channel.PunctuatorChannel; import com.sonar.sslr.impl.channel.UnknownCharacterChannel; public final class PogoDslLexer { private PogoDslLexer() { } public static Lexer create() { return create(new PogoDslConfiguration()); } private static final String INTEGER_SUFFIX = "(((U|u)(LL|ll|L|l)?)|((LL|ll|L|l)(u|U)?))"; private static final String EXP = "([Ee][+-]?+[0-9_]++)"; private static final String FLOAT_SUFFIX = "(f|l|F|L)"; public static Lexer create(PogoDslConfiguration conf) { Lexer.Builder builder = Lexer.builder() .withCharset(conf.getCharset()) .withFailIfNoChannelToConsumeOneCharacter(true) .withChannel(new BlackHoleChannel("\\s")) // Comments // C++ Standard, Section 2.8 "Comments" .withChannel(commentRegexp("//[^\\n\\r]*+")) .withChannel(commentRegexp("/\\*", ANY_CHAR + "*?", "\\*/")) // backslash at the end of the line: just throw away .withChannel(new BackslashChannel()) // Preprocessor directives //.withChannel(new PreprocessorChannel()) // C++ Standard, Section 2.14.3 "Character literals" .withChannel(new CharacterLiteralsChannel()) // C++ Standard, Section 2.14.5 "String literals" .withChannel(new StringLiteralsChannel()) // C++ Standard, Section 2.14.4 "Floating literals" .withChannel(regexp(PogoDslTokenType.NUMBER, "[0-9]++\\.[0-9]*+" + opt(EXP) + opt(FLOAT_SUFFIX))) .withChannel(regexp(PogoDslTokenType.NUMBER, "\\.[0-9]++" + opt(EXP) + opt(FLOAT_SUFFIX))) .withChannel(regexp(PogoDslTokenType.NUMBER, "[0-9]++" + EXP + opt(FLOAT_SUFFIX))) // C++ Standard, Section 2.14.2 "Integer literals" .withChannel(regexp(PogoDslTokenType.NUMBER, "[1-9][0-9]*+" + opt(INTEGER_SUFFIX))) // Decimal literals .withChannel(regexp(PogoDslTokenType.NUMBER, "0[0-7]++" + opt(INTEGER_SUFFIX))) // Octal Literals .withChannel(regexp(PogoDslTokenType.NUMBER, "0[xX][0-9a-fA-F]++" + opt(INTEGER_SUFFIX))) // Hex Literals .withChannel(regexp(PogoDslTokenType.NUMBER, "0" + opt(INTEGER_SUFFIX))) // Decimal zero // TODO: // C++ Standard, Section 2.14.8 "User-defined literals" // C++ Standard, Section 2.12 "Keywords" // C++ Standard, Section 2.11 "Identifiers" .withChannel(new IdentifierAndKeywordChannel(and("[a-zA-Z_]", o2n("\\w")), true, PogoDslKeyword.values())) // C++ Standard, Section 2.13 "Operators and punctuators" .withChannel(new PunctuatorChannel(PogoDslPunctuator.values())) .withChannel(new UnknownCharacterChannel()); return builder.build(); } }
epl-1.0
angelozerr/angular2-eclipse
ts.eclipse.ide.angular.core/src/ts/eclipse/ide/angular/core/html/INgBindingCollector.java
190
package ts.eclipse.ide.angular.core.html; public interface INgBindingCollector { void collect(String matchingString, String name, String description, INgBindingType bindingType); }
epl-1.0
smadelenat/CapellaModeAutomata
Semantic/Scenario/org.gemoc.scenario.xdsml/src-gen/org/gemoc/scenario/xdsml/functionscenario/adapters/functionscenariomt/capellacommon/GenericTraceAdapter.java
25983
package org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.capellacommon; import fr.inria.diverse.melange.adapters.EObjectAdapter; import java.util.Collection; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; import org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.FunctionScenarioMTAdaptersFactory; import org.polarsys.capella.core.data.capellacommon.GenericTrace; @SuppressWarnings("all") public class GenericTraceAdapter extends EObjectAdapter<GenericTrace> implements org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.GenericTrace { private FunctionScenarioMTAdaptersFactory adaptersFactory; public GenericTraceAdapter() { super(org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.FunctionScenarioMTAdaptersFactory.getInstance()); adaptersFactory = org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.FunctionScenarioMTAdaptersFactory.getInstance(); } @Override public String getId() { return adaptee.getId(); } @Override public void setId(final String o) { adaptee.setId(o); } @Override public String getSid() { return adaptee.getSid(); } @Override public void setSid(final String o) { adaptee.setSid(o); } @Override public boolean isVisibleInDoc() { return adaptee.isVisibleInDoc(); } @Override public void setVisibleInDoc(final boolean o) { adaptee.setVisibleInDoc(o); } @Override public boolean isVisibleInLM() { return adaptee.isVisibleInLM(); } @Override public void setVisibleInLM(final boolean o) { adaptee.setVisibleInLM(o); } @Override public String getSummary() { return adaptee.getSummary(); } @Override public void setSummary(final String o) { adaptee.setSummary(o); } @Override public String getDescription() { return adaptee.getDescription(); } @Override public void setDescription(final String o) { adaptee.setDescription(o); } @Override public String getReview() { return adaptee.getReview(); } @Override public void setReview(final String o) { adaptee.setReview(o); } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.emde.ElementExtension> */Object ownedExtensions_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.emde.ElementExtension> */Object getOwnedExtensions() { if (ownedExtensions_ == null) ownedExtensions_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedExtensions(), adaptersFactory, eResource); return ownedExtensions_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractConstraint> */Object constraints_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractConstraint> */Object getConstraints() { if (constraints_ == null) constraints_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getConstraints(), adaptersFactory, eResource); return constraints_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractConstraint> */Object ownedConstraints_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractConstraint> */Object getOwnedConstraints() { if (ownedConstraints_ == null) ownedConstraints_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedConstraints(), adaptersFactory, eResource); return ownedConstraints_; } @Override public org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractInformationFlow getRealizedFlow() { return () adaptersFactory.createAdapter(adaptee.getRealizedFlow(), eResource); } @Override public void setRealizedFlow(final org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractInformationFlow o) { if (o != null) adaptee.setRealizedFlow(((org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.modellingcore.AbstractInformationFlowAdapter) o).getAdaptee()); else adaptee.setRealizedFlow(null); } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractTrace> */Object incomingTraces_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractTrace> */Object getIncomingTraces() { if (incomingTraces_ == null) incomingTraces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getIncomingTraces(), adaptersFactory, eResource); return incomingTraces_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractTrace> */Object outgoingTraces_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractTrace> */Object getOutgoingTraces() { if (outgoingTraces_ == null) outgoingTraces_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOutgoingTraces(), adaptersFactory, eResource); return outgoingTraces_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.AbstractPropertyValue> */Object ownedPropertyValues_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.AbstractPropertyValue> */Object getOwnedPropertyValues() { if (ownedPropertyValues_ == null) ownedPropertyValues_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedPropertyValues(), adaptersFactory, eResource); return ownedPropertyValues_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyType> */Object ownedEnumerationPropertyTypes_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyType> */Object getOwnedEnumerationPropertyTypes() { if (ownedEnumerationPropertyTypes_ == null) ownedEnumerationPropertyTypes_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedEnumerationPropertyTypes(), adaptersFactory, eResource); return ownedEnumerationPropertyTypes_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.AbstractPropertyValue> */Object appliedPropertyValues_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.AbstractPropertyValue> */Object getAppliedPropertyValues() { if (appliedPropertyValues_ == null) appliedPropertyValues_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAppliedPropertyValues(), adaptersFactory, eResource); return appliedPropertyValues_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.PropertyValueGroup> */Object ownedPropertyValueGroups_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.PropertyValueGroup> */Object getOwnedPropertyValueGroups() { if (ownedPropertyValueGroups_ == null) ownedPropertyValueGroups_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getOwnedPropertyValueGroups(), adaptersFactory, eResource); return ownedPropertyValueGroups_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.PropertyValueGroup> */Object appliedPropertyValueGroups_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.PropertyValueGroup> */Object getAppliedPropertyValueGroups() { if (appliedPropertyValueGroups_ == null) appliedPropertyValueGroups_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAppliedPropertyValueGroups(), adaptersFactory, eResource); return appliedPropertyValueGroups_; } @Override public org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyLiteral getStatus() { return () adaptersFactory.createAdapter(adaptee.getStatus(), eResource); } @Override public void setStatus(final org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyLiteral o) { if (o != null) adaptee.setStatus(((org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.capellacore.EnumerationPropertyLiteralAdapter) o).getAdaptee()); else adaptee.setStatus(null); } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyLiteral> */Object features_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyLiteral> */Object getFeatures() { if (features_ == null) features_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getFeatures(), adaptersFactory, eResource); return features_; } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.requirement.Requirement> */Object appliedRequirements_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.requirement.Requirement> */Object getAppliedRequirements() { if (appliedRequirements_ == null) appliedRequirements_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getAppliedRequirements(), adaptersFactory, eResource); return appliedRequirements_; } @Override public org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.TraceableElement getTargetElement() { return () adaptersFactory.createAdapter(adaptee.getTargetElement(), eResource); } @Override public void setTargetElement(final org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.TraceableElement o) { if (o != null) adaptee.setTargetElement(((org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.modellingcore.TraceableElementAdapter) o).getAdaptee()); else adaptee.setTargetElement(null); } @Override public org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.TraceableElement getSourceElement() { return () adaptersFactory.createAdapter(adaptee.getSourceElement(), eResource); } @Override public void setSourceElement(final org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.TraceableElement o) { if (o != null) adaptee.setSourceElement(((org.gemoc.scenario.xdsml.functionscenario.adapters.functionscenariomt.modellingcore.TraceableElementAdapter) o).getAdaptee()); else adaptee.setSourceElement(null); } private /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.KeyValue> */Object keyValuePairs_; @Override public /* EList<org.gemoc.scenario.xdsml.functionscenariomt.capellacore.KeyValue> */Object getKeyValuePairs() { if (keyValuePairs_ == null) keyValuePairs_ = fr.inria.diverse.melange.adapters.EListAdapter.newInstance(adaptee.getKeyValuePairs(), adaptersFactory, eResource); return keyValuePairs_; } @Override public org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.TraceableElement getSource() { return () adaptersFactory.createAdapter(adaptee.getSource(), eResource); } @Override public org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.TraceableElement getTarget() { return () adaptersFactory.createAdapter(adaptee.getTarget(), eResource); } @Override public void destroy() { adaptee.destroy(); } @Override public String getFullLabel() { return adaptee.getFullLabel(); } @Override public String getLabel() { return adaptee.getLabel(); } @Override public boolean hasUnnamedLabel() { return adaptee.hasUnnamedLabel(); } protected final static String ID_EDEFAULT = null; protected final static String SID_EDEFAULT = null; protected final static boolean VISIBLE_IN_DOC_EDEFAULT = true; protected final static boolean VISIBLE_IN_LM_EDEFAULT = true; protected final static String SUMMARY_EDEFAULT = null; protected final static String DESCRIPTION_EDEFAULT = null; protected final static String REVIEW_EDEFAULT = null; @Override public EClass eClass() { return org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.eINSTANCE.getGenericTrace(); } @Override public Object eGet(final int featureID, final boolean resolve, final boolean coreType) { switch (featureID) { case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OWNED_EXTENSIONS: return getOwnedExtensions(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__ID: return getId(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__SID: return getSid(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__CONSTRAINTS: return getConstraints(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OWNED_CONSTRAINTS: return getOwnedConstraints(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__REALIZED_FLOW: return getRealizedFlow(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__INCOMING_TRACES: return getIncomingTraces(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OUTGOING_TRACES: return getOutgoingTraces(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__VISIBLE_IN_DOC: return isVisibleInDoc() ? Boolean.TRUE : Boolean.FALSE; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__VISIBLE_IN_LM: return isVisibleInLM() ? Boolean.TRUE : Boolean.FALSE; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__SUMMARY: return getSummary(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__DESCRIPTION: return getDescription(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__REVIEW: return getReview(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OWNED_PROPERTY_VALUES: return getOwnedPropertyValues(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OWNED_ENUMERATION_PROPERTY_TYPES: return getOwnedEnumerationPropertyTypes(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__APPLIED_PROPERTY_VALUES: return getAppliedPropertyValues(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OWNED_PROPERTY_VALUE_GROUPS: return getOwnedPropertyValueGroups(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__APPLIED_PROPERTY_VALUE_GROUPS: return getAppliedPropertyValueGroups(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__STATUS: return getStatus(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__FEATURES: return getFeatures(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__APPLIED_REQUIREMENTS: return getAppliedRequirements(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__TARGET_ELEMENT: return getTargetElement(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__SOURCE_ELEMENT: return getSourceElement(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__KEY_VALUE_PAIRS: return getKeyValuePairs(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__SOURCE: return getSource(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__TARGET: return getTarget(); } return super.eGet(featureID, resolve, coreType); } @Override public boolean eIsSet(final int featureID) { switch (featureID) { case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OWNED_EXTENSIONS: return getOwnedExtensions() != null && !getOwnedExtensions().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__ID: return getId() != ID_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__SID: return getSid() != SID_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__CONSTRAINTS: return getConstraints() != null && !getConstraints().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OWNED_CONSTRAINTS: return getOwnedConstraints() != null && !getOwnedConstraints().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__REALIZED_FLOW: return getRealizedFlow() != null; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__INCOMING_TRACES: return getIncomingTraces() != null && !getIncomingTraces().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OUTGOING_TRACES: return getOutgoingTraces() != null && !getOutgoingTraces().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__VISIBLE_IN_DOC: return isVisibleInDoc() != VISIBLE_IN_DOC_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__VISIBLE_IN_LM: return isVisibleInLM() != VISIBLE_IN_LM_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__SUMMARY: return getSummary() != SUMMARY_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__DESCRIPTION: return getDescription() != DESCRIPTION_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__REVIEW: return getReview() != REVIEW_EDEFAULT; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OWNED_PROPERTY_VALUES: return getOwnedPropertyValues() != null && !getOwnedPropertyValues().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OWNED_ENUMERATION_PROPERTY_TYPES: return getOwnedEnumerationPropertyTypes() != null && !getOwnedEnumerationPropertyTypes().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__APPLIED_PROPERTY_VALUES: return getAppliedPropertyValues() != null && !getAppliedPropertyValues().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OWNED_PROPERTY_VALUE_GROUPS: return getOwnedPropertyValueGroups() != null && !getOwnedPropertyValueGroups().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__APPLIED_PROPERTY_VALUE_GROUPS: return getAppliedPropertyValueGroups() != null && !getAppliedPropertyValueGroups().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__STATUS: return getStatus() != null; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__FEATURES: return getFeatures() != null && !getFeatures().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__APPLIED_REQUIREMENTS: return getAppliedRequirements() != null && !getAppliedRequirements().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__TARGET_ELEMENT: return getTargetElement() != null; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__SOURCE_ELEMENT: return getSourceElement() != null; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__KEY_VALUE_PAIRS: return getKeyValuePairs() != null && !getKeyValuePairs().isEmpty(); case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__SOURCE: return getSource() != null; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__TARGET: return getTarget() != null; } return super.eIsSet(featureID); } @Override public void eSet(final int featureID, final Object newValue) { switch (featureID) { case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OWNED_EXTENSIONS: getOwnedExtensions().clear(); getOwnedExtensions().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__ID: setId( (java.lang.String) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__SID: setSid( (java.lang.String) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OWNED_CONSTRAINTS: getOwnedConstraints().clear(); getOwnedConstraints().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__REALIZED_FLOW: setRealizedFlow( (org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.AbstractInformationFlow) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__VISIBLE_IN_DOC: setVisibleInDoc(((java.lang.Boolean) newValue).booleanValue()); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__VISIBLE_IN_LM: setVisibleInLM(((java.lang.Boolean) newValue).booleanValue()); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__SUMMARY: setSummary( (java.lang.String) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__DESCRIPTION: setDescription( (java.lang.String) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__REVIEW: setReview( (java.lang.String) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OWNED_PROPERTY_VALUES: getOwnedPropertyValues().clear(); getOwnedPropertyValues().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OWNED_ENUMERATION_PROPERTY_TYPES: getOwnedEnumerationPropertyTypes().clear(); getOwnedEnumerationPropertyTypes().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__APPLIED_PROPERTY_VALUES: getAppliedPropertyValues().clear(); getAppliedPropertyValues().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__OWNED_PROPERTY_VALUE_GROUPS: getOwnedPropertyValueGroups().clear(); getOwnedPropertyValueGroups().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__APPLIED_PROPERTY_VALUE_GROUPS: getAppliedPropertyValueGroups().clear(); getAppliedPropertyValueGroups().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__STATUS: setStatus( (org.gemoc.scenario.xdsml.functionscenariomt.capellacore.EnumerationPropertyLiteral) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__FEATURES: getFeatures().clear(); getFeatures().addAll((Collection) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__TARGET_ELEMENT: setTargetElement( (org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.TraceableElement) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__SOURCE_ELEMENT: setSourceElement( (org.gemoc.scenario.xdsml.functionscenariomt.modellingcore.TraceableElement) newValue); return; case org.gemoc.scenario.xdsml.functionscenariomt.capellacommon.CapellacommonPackage.GENERIC_TRACE__KEY_VALUE_PAIRS: getKeyValuePairs().clear(); getKeyValuePairs().addAll((Collection) newValue); return; } super.eSet(featureID, newValue); } }
epl-1.0
sonatype/nexus-public
components/nexus-blobstore-file/src/main/java/org/sonatype/nexus/blobstore/file/package-info.java
885
/* * Sonatype Nexus (TM) Open Source Version * Copyright (c) 2008-present Sonatype, Inc. * All rights reserved. Includes the third-party code listed at http://links.sonatype.com/products/nexus/oss/attributions. * * This program and the accompanying materials are made available under the terms of the Eclipse Public License Version 1.0, * which accompanies this distribution and is available at http://www.eclipse.org/legal/epl-v10.html. * * Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc. "Sonatype" and "Sonatype Nexus" are trademarks * of Sonatype, Inc. Apache Maven is a trademark of the Apache Software Foundation. M2eclipse is a trademark of the * Eclipse Foundation. All other trademarks are the property of their respective owners. */ /** * Local-file blob store components. * * @since 3.0 */ package org.sonatype.nexus.blobstore.file;
epl-1.0
codenvy/codenvy
wsagent/wsagent-codenvy/src/main/java/com/codenvy/api/agent/CodenvyProjectServiceLinksInjector.java
1156
/* * 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 com.codenvy.api.agent; import com.google.inject.Inject; import com.google.inject.name.Named; import java.net.URI; import javax.ws.rs.core.UriBuilder; import org.eclipse.che.api.project.server.ProjectService; import org.eclipse.che.api.project.server.ProjectServiceLinksInjector; /** * Helps to inject {@link ProjectService} related links. * * @author Valeriy Svydenko */ public class CodenvyProjectServiceLinksInjector extends ProjectServiceLinksInjector { private final String host; @Inject public CodenvyProjectServiceLinksInjector(@Named("che.api") String apiEndpoint) { host = UriBuilder.fromUri(apiEndpoint).build().getHost(); } @Override protected String tuneUrl(URI url) { return UriBuilder.fromUri(url).host(host).build().toString(); } }
epl-1.0
andieguo/ORMLiteDemo
src/com/andieguo/ormlitedemo/test/DempartmentDaoTest.java
492
package com.andieguo.ormlitedemo.test; import android.test.AndroidTestCase; public class DempartmentDaoTest extends AndroidTestCase implements InterfaceTester { @Override public void testSave() { // TODO Auto-generated method stub } @Override public void testFindById() { // TODO Auto-generated method stub } @Override public void testUpdate() { // TODO Auto-generated method stub } @Override public void testDelete() { // TODO Auto-generated method stub } }
epl-1.0
rkadle/Tank
api/src/main/java/com/intuit/tank/vm/vmManager/JobUtil.java
1554
/** * Copyright 2011 Intuit Inc. All Rights Reserved */ package com.intuit.tank.vm.vmManager; /* * #%L * Intuit Tank Api * %% * Copyright (C) 2011 - 2015 Intuit 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 * #L% */ import java.util.Collection; import org.apache.log4j.Logger; /** * JobUtil * * @author dangleton * */ public final class JobUtil { private static final Logger LOG = Logger.getLogger(JobUtil.class); /** * private constructor to implement util */ private JobUtil() { } /** * @param users * @param total * @return users */ public static final int parseUserString(String users) { int result = 0; String u = users.trim(); try { result = Integer.valueOf(u); } catch (NumberFormatException e) { LOG.error("Error parsing number of users value of " + users); } return result; } /** * calculates total number of virtual users by summing the regions. * * @return users */ public static final int calculateTotalVirtualUsers(Collection<? extends RegionRequest> jobRegions) { int result = 0; for (RegionRequest region : jobRegions) { result += JobUtil.parseUserString(region.getUsers()); } return result; } }
epl-1.0
shamsmahmood/priorityworkstealing
src/main/java/edu/rice/habanero/benchmarks/trapezoid/PriorityBlockingQueueBenchmark.java
1019
package edu.rice.habanero.benchmarks.trapezoid; import edu.rice.habanero.benchmarks.BenchmarkRunner; import edu.rice.habanero.concurrent.executors.PriorityBlockingQueueTaskExecutor; import edu.rice.habanero.concurrent.executors.TaskExecutor; import java.util.concurrent.TimeUnit; /** * @author <a href="http://shams.web.rice.edu/">Shams Imam</a> (shams@rice.edu) */ public class PriorityBlockingQueueBenchmark extends AbstractBenchmark { public static void main(final String[] args) { BenchmarkRunner.runBenchmark(args, new PriorityBlockingQueueBenchmark()); } @Override protected TaskExecutor createTaskExecutor() { final int numThreads = BenchmarkRunner.numThreads(); final int minPriorityInc = BenchmarkRunner.minPriority(); final int maxPriorityInc = BenchmarkRunner.maxPriority(); return new PriorityBlockingQueueTaskExecutor( numThreads, numThreads, 0L, TimeUnit.MILLISECONDS, minPriorityInc, maxPriorityInc); } }
epl-1.0
klst-com/metasfresh
de.metas.adempiere.adempiere/base/src/main/java-legacy/org/compiere/print/layout/ImageElement.java
11006
/****************************************************************************** * Product: Adempiere ERP & CRM Smart Business Solution * * Copyright (C) 1999-2006 ComPiere, Inc. All Rights Reserved. * * This program is free software; you can redistribute it and/or modify it * * under the terms version 2 of the GNU General Public License as published * * by the Free Software Foundation. This program is distributed in the hope * * that it will be useful, but WITHOUT ANY WARRANTY; without even the implied * * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * See the GNU 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. * * For the text or an alternative of this public license, you may reach us * * ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA * * or via info@compiere.org or http://www.compiere.org/license.html * *****************************************************************************/ package org.compiere.print.layout; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Toolkit; import java.awt.geom.AffineTransform; import java.awt.geom.Point2D; import java.math.BigDecimal; import java.net.MalformedURLException; import java.net.URL; import java.util.Properties; import org.compiere.model.MAttachment; import org.compiere.model.MImage; import org.compiere.print.MPrintFormatItem; import org.compiere.print.PrintDataElement; import org.compiere.util.CCache; import org.compiere.util.Env; /** * Image Element * * @author Jorg Janke * @version $Id: ImageElement.java,v 1.3 2006/07/30 00:53:02 jjanke Exp $ */ public class ImageElement extends PrintElement { /** * Create Image from URL * @param imageURLString image url * @return image element */ public static ImageElement get (String imageURLString) { Object key = imageURLString; ImageElement image = (ImageElement)s_cache.get(key); if (image == null) { image = new ImageElement(imageURLString); s_cache.put(key, image); } return new ImageElement(image.getImage()); } // get /** * Create Image from URL * @param imageURL image url * @return image element */ public static ImageElement get (URL imageURL) { Object key = imageURL; ImageElement image = (ImageElement)s_cache.get(key); if (image == null) { image = new ImageElement(imageURL); s_cache.put(key, image); } return new ImageElement(image.getImage()); } // get /** * Create Image from Attachment * @param AD_PrintFormatItem_ID record id * @return image element */ public static ImageElement get (int AD_PrintFormatItem_ID) { Object key = new Integer(AD_PrintFormatItem_ID); ImageElement image = (ImageElement)s_cache.get(key); if (image == null) { image = new ImageElement(AD_PrintFormatItem_ID); s_cache.put(key, image); } return new ImageElement(image.getImage()); } // get /** * Create Image from database column * @param data the printdataelement, containing the reference * @param imageURLString image url - containing just the AD_Image_ID reference * @return image element */ public static ImageElement get(PrintDataElement data, String imageURLString) { Object key = (BigDecimal) data.getValue(); ImageElement image = (ImageElement)s_cache.get(key); if (image == null) { BigDecimal imkeybd = (BigDecimal) data.getValue(); int imkeyint = 0; if (imkeybd != null) imkeyint = imkeybd.intValue(); image = new ImageElement(imkeyint, false); s_cache.put(key, image); } return new ImageElement(image.getImage()); } // get /** 60 minute Cache */ private static CCache<Object,ImageElement> s_cache = new CCache<Object,ImageElement>("ImageElement", 10, 60); /************************************************************************** * Create from existing Image * @param image image */ public ImageElement(Image image) { m_image = image; if (m_image != null) log.debug("Image=" + image); else log.warn("Image is NULL"); } // ImageElement /** * Create Image from URL * @param imageURLstring image url */ private ImageElement(String imageURLstring) { URL imageURL = getURL(imageURLstring); if (imageURL != null) { m_image = Toolkit.getDefaultToolkit().createImage(imageURL); if (m_image != null) log.debug("URL=" + imageURL); else log.warn("Not loaded - URL=" + imageURL); } else log.warn("Invalid URL=" + imageURLstring); } // ImageElement /** * Create Image from URL * @param imageURL image url */ private ImageElement(URL imageURL) { if (imageURL != null) { m_image = Toolkit.getDefaultToolkit().createImage(imageURL); if (m_image != null) log.debug("URL=" + imageURL); else log.warn("Not loaded - URL=" + imageURL); } else log.error("ImageURL is NULL"); } // ImageElement /** * Create Image from Attachment * @param AD_PrintFormatItem_ID record id */ private ImageElement(int AD_PrintFormatItem_ID) { loadAttachment(AD_PrintFormatItem_ID); } // ImageElement /** * Create Image from Attachment or Column * @param record_ID_ID record id from printformat or column * @param isAttachment flag to indicate if is attachment or is a column from DB */ public ImageElement(int record_ID, boolean isAttachment) { if (isAttachment) loadAttachment(record_ID); else loadFromDB(record_ID); } // ImageElement /** The Image */ private Image m_image = null; /** Scale */ private double m_scaleFactor = 1; /************************************************************************** * Get URL from String * @param urlString url or resource * @return URL or null */ private URL getURL (String urlString) { URL url = null; // not a URL - may be a resource if (urlString.indexOf("://") == -1) { ClassLoader cl = getClass().getClassLoader(); url = cl.getResource(urlString); if (url != null) return url; log.warn("Not found - " + urlString); return null; } // load URL try { url = new URL (urlString); } catch (MalformedURLException ex) { log.warn(urlString, ex); } return url; } // getURL; /** * Load from DB * @param record_ID record id */ private void loadFromDB(int record_ID) { MImage mimage = MImage.get(Env.getCtx(), record_ID); if (mimage == null) { log.warn("No Image - record_ID=" + record_ID); return; } byte[] imageData = mimage.getData(); if (imageData != null) m_image = Toolkit.getDefaultToolkit().createImage(imageData); if (m_image != null) log.debug(mimage.toString() + " - Size=" + imageData.length); else log.warn(mimage.toString() + " - not loaded (must be gif or jpg) - record_ID=" + record_ID); } // loadFromDB /** * Load Attachment * @param AD_PrintFormatItem_ID record id */ private void loadAttachment(int AD_PrintFormatItem_ID) { MAttachment attachment = MAttachment.get(Env.getCtx(), MPrintFormatItem.Table_ID, AD_PrintFormatItem_ID); if (attachment == null) { log.warn("No Attachment - AD_PrintFormatItem_ID=" + AD_PrintFormatItem_ID); return; } if (attachment.getEntryCount() != 1) { log.warn("Need just 1 Attachment Entry = " + attachment.getEntryCount()); return; } byte[] imageData = attachment.getEntryData(0); if (imageData != null) m_image = Toolkit.getDefaultToolkit().createImage(imageData); if (m_image != null) log.debug(attachment.getEntryName(0) + " - Size=" + imageData.length); else log.warn(attachment.getEntryName(0) + " - not loaded (must be gif or jpg) - AD_PrintFormatItem_ID=" + AD_PrintFormatItem_ID); } // loadAttachment /************************************************************************** * Calculate Image Size. * Set p_width & p_height * @return true if calculated */ protected boolean calculateSize() { p_width = 0; p_height = 0; if (m_image == null) return true; // we have an image // if the image was not loaded, consider that there is no image - teo_sarca [ 1674706 ] if (waitForLoad(m_image) && m_image != null) { p_width = m_image.getWidth(this); p_height = m_image.getHeight(this); if (p_width * p_height == 0) return true; // don't bother scaling and prevent div by 0 // 0 = unlimited so scale to fit restricted dimension /* teo_sarca, [ 1673548 ] Image is not scaled in a report table cell if (p_maxWidth * p_maxHeight != 0) // scale to maintain aspect ratio { if (p_width/p_height > p_maxWidth/p_maxHeight) // image "fatter" than available area m_scaleFactor = p_maxWidth/p_width; else m_scaleFactor = p_maxHeight/p_height; } */ m_scaleFactor = 1; if (p_maxWidth != 0 && p_width > p_maxWidth) m_scaleFactor = p_maxWidth / p_width; if (p_maxHeight != 0 && p_height > p_maxHeight && p_maxHeight/p_height < m_scaleFactor) m_scaleFactor = p_maxHeight / p_height; p_width = (float) m_scaleFactor * p_width; p_height = (float) m_scaleFactor * p_height; } // If the image is not loaded set it to null. // This prevents SecurityException when invoking getWidth() or getHeight(). - teo_sarca [ 1674706 ] else { m_image = null; } return true; } // calculateSize /** * Get the Image * @return image */ public Image getImage() { return m_image; } // getImage /** * Get image scale factor. * * @author teo_sarca - [ 1673548 ] Image is not scaled in a report table cell * @return scale factor */ public double getScaleFactor() { if (!p_sizeCalculated) p_sizeCalculated = calculateSize(); return m_scaleFactor; } /** * Paint Image * @param g2D Graphics * @param pageStart top left Location of page * @param pageNo page number for multi page support (0 = header/footer) - ignored * @param ctx print context * @param isView true if online view (IDs are links) */ public void paint(Graphics2D g2D, int pageNo, Point2D pageStart, Properties ctx, boolean isView) { if (m_image == null) return; // Position Point2D.Double location = getAbsoluteLocation(pageStart); int x = (int)location.x; if (MPrintFormatItem.FIELDALIGNMENTTYPE_TrailingRight.equals(p_FieldAlignmentType)) x += p_maxWidth - p_width; else if (MPrintFormatItem.FIELDALIGNMENTTYPE_Center.equals(p_FieldAlignmentType)) x += (p_maxWidth - p_width) / 2; int y = (int)location.y; // map a scaled and shifted version of the image to device space AffineTransform transform = new AffineTransform(); transform.translate(x,y); transform.scale(m_scaleFactor, m_scaleFactor); g2D.drawImage(m_image, transform, this); } // paint } // ImageElement
gpl-2.0
sebastianoe/s4j
test/tools/javac/sql/SELECT/RuntimeExpectIntegerList.java
1048
/* * @test /nodynamiccopyright/ * @summary Lists of simple types (here: Integer) * @compile RuntimeExpectIntegerList.java -sqlrepo /Users/sebastian/ma/jdk7u-langtools/test/tools/javac/sql/repo.json * @run main RuntimeExpectIntegerList */ import java.util.ArrayList; import java.util.List; import com.google.common.collect.Lists; import com.google.common.collect.Iterables; public class RuntimeExpectIntegerList { public static void main(String[] args) { ArrayList<Integer> expectedList = Lists.newArrayList(12, 5, 17); // Concrete list expected ArrayList<Integer> qties1 = SQL[SELECT quantity FROM line_item ORDER BY id LIMIT 3]; assert(qties1.size() == 3); assert(Iterables.elementsEqual(qties1, expectedList)); // Abstract list expected List<Integer> qties2 = SQL[SELECT quantity FROM line_item ORDER BY id LIMIT 3]; assert(qties2.size() == 3); assert(Iterables.elementsEqual(qties2, expectedList)); assert(qties2 instanceof ArrayList); } }
gpl-2.0
damirkusar/jvoicebridge
voicelib/src/com/sun/mpk20/voicelib/impl/service/voice/BridgeConnection.java
36037
/* * Copyright 2007 Sun Microsystems, Inc. * * This file is part of jVoiceBridge. * * jVoiceBridge is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation and distributed hereunder * to you. * * jVoiceBridge 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/>. * * Sun designates this particular file as subject to the "Classpath" * exception as provided by Sun in the License file that accompanied this * code. */ package com.sun.mpk20.voicelib.impl.service.voice; import com.sun.mpk20.voicelib.app.BridgeInfo; import com.sun.voip.CallParticipant; import com.sun.voip.client.connector.CallStatus; import com.sun.voip.client.connector.impl.VoiceBridgeConnection; import java.io.BufferedReader; import java.io.EOFException; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Reader; import java.io.Serializable; import java.io.Writer; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.UnknownHostException; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.ArrayList; import java.util.Collection; import java.util.Hashtable; import java.util.Iterator; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.ConcurrentHashMap; /** * * @author jkaplan */ public class BridgeConnection extends VoiceBridgeConnection { /** a logger */ private static final Logger logger = Logger.getLogger(BridgeConnection.class.getName()); /** the end-of-message pattern */ private static final Pattern END_OF_MESSAGE = Pattern.compile("^END -- (.*)"); /** the underlying connection to the bridge */ private Socket socket; /** the reader */ private BufferedReader reader; /** the writer */ private PrintWriter writer; private String privateHost; private int privateControlPort; private int privateSipPort; private String publicHost; private int publicControlPort; private int publicSipPort; private boolean synchronous; private Hashtable<String, String> conferences = new Hashtable<String, String>(); /* * This map contains the CallParticipant for each call on this bridge * connection. */ private ConcurrentHashMap<String, CallParticipant> callParticipantMap = new ConcurrentHashMap<String, CallParticipant>(); private static int watchdogTimeout; private static int bridgePingTimeout; private long bridgePingTime; private boolean pingTimeout = false; private BridgeOfflineListener offlineListener; private SocketChannel socketChannel; static { String s = System.getProperty( "com.sun.sgs.impl.service.voice.watchdog.timeout"); if (s != null) { try { watchdogTimeout = Integer.parseInt(s); } catch (NumberFormatException e) { logger.info("Invalid watchdog timeout: " + s + ". Defaulting to " + watchdogTimeout + " sec."); } } logger.info("Watchdog timeout is " + watchdogTimeout + " seconds"); s = System.getProperty( "com.sun.sgs.impl.service.voice.bridge.ping.timeout"); if (s != null) { try { bridgePingTimeout = Integer.parseInt(s); } catch (NumberFormatException e) { logger.info("Invalid bridgePingTimeout timeout: " + s + ". Defaulting to " + bridgePingTimeout + " sec."); } } logger.info("Bridge ping timeout is " + bridgePingTimeout + " seconds"); } /** * Creates a new instance of BridgeConnection */ public BridgeConnection( String privateHost, int privateControlPort, int privateSipPort, boolean synchronous) throws IOException { this(privateHost, privateControlPort, privateSipPort, privateHost, privateControlPort, privateSipPort, synchronous); } public BridgeConnection( String privateHost, int privateControlPort, int privateSipPort, String publicHost, int publicControlPort, int publicSipPort, boolean synchronous) throws IOException { super(privateHost, privateControlPort); this.privateHost = privateHost; this.privateControlPort = privateControlPort; this.privateSipPort = privateSipPort; this.publicHost = publicHost; this.publicControlPort = publicControlPort; this.publicSipPort = publicSipPort; this.synchronous = synchronous; /* * Connect to get bridge status */ super.connect(); /* * Connect in synchronous mode to get command status. */ connect(true); /* * SocketChannels seem to perform much better than Sockets. */ InetAddress ia = InetAddress.getByName(privateHost); InetSocketAddress bridgeSocketAddress = new InetSocketAddress(ia, privateControlPort); socketChannel = SocketChannel.open(bridgeSocketAddress); //socketChannel.configureBlocking(false); Socket socket = socketChannel.socket(); socket.setSendBufferSize(2 * 1024 * 1024); logger.info("Created a socket channel to " + bridgeSocketAddress + " sendBufferSize " + socket.getSendBufferSize()); } public void addBridgeOfflineListener( BridgeOfflineListener offlineListener) { this.offlineListener = offlineListener; } public static CallStatus parseCallStatus(String s) throws IOException { return VoiceBridgeConnection.parseCallStatus(s); } public String getPrivateHost() { return privateHost; } public int getPrivateControlPort() { return privateControlPort; } public int getPrivateSipPort() { return privateSipPort; } public String getPublicHost() { return publicHost; } public int getPublicControlPort() { return publicControlPort; } public int getPublicSipPort() { return publicSipPort; } public String getPublicAddress() { return publicHost + ":" + publicSipPort; } public void monitorConference(String conferenceId) throws IOException { int ix; String s = ""; String c = conferenceId; if ((ix = conferenceId.indexOf(":")) > 0) { s += "cc=" + conferenceId + "\n"; c = conferenceId.substring(0, ix); s += "wgo=" + c + ":" + c + ":noCommonMix=true" + "\n"; } synchronized (conferences) { /* * Remember conferences we're monitoring * so we don't monitor more than once. */ if (conferences.get(conferenceId) == null) { s += "mcc=" + true + ":" + c + "\n"; sendMessage(s); conferences.put(conferenceId, conferenceId); logger.finest("Monitoring conference " + s + " " + this); } else { logger.finest("Already monitoring " + s + " " + this); } } } public Hashtable<String, String> getConferences() { return conferences; } public void monitorConferences(Hashtable<String, String> conferences) { Collection<String> c = conferences.values(); Iterator<String> it = c.iterator(); while (it.hasNext()) { try { monitorConference(it.next()); } catch (IOException e) { logger.info("Unable to monitor conference " + e.getMessage()); } } } public void addCall(CallParticipant cp) { callParticipantMap.put(cp.getCallId(), cp); logger.finer("added call " + cp.getCallId() + " " + callParticipantMap.size()); } /* * Called by endCall when call ends. */ private int removeCall(CallParticipant cp) { callParticipantMap.remove(cp.getCallId()); logger.finer("removed call " + cp.getCallId() + " " + callParticipantMap.size()); return callParticipantMap.size(); } private int removeCall(String callId) { callParticipantMap.remove(callId); logger.finer("removed call " + callId + " " + callParticipantMap.size()); return callParticipantMap.size(); } public int getNumberOfCalls() { return callParticipantMap.size(); } public CallParticipant getCallParticipant(String callId) { return callParticipantMap.get(callId); } public String setupCall(CallParticipant cp) throws IOException { monitorConference(cp.getConferenceId()); addCall(cp); BridgeResponse br = sendWithResponse(cp.getCallSetupRequest()); logger.fine("setupCall status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("setupCall contents " + br.getContents()); return br.getContents(); default: removeCall(cp); throw new IOException("setupCall failed: " + br.getMessage()); } } public void migrateCall(CallParticipant cp, boolean cancel) throws IOException { if (isConnected() == false) { return; } BridgeResponse br; if (cancel == true) { br = sendWithResponse("cancelMigration=" + cp.getCallId() + "\n"); } else { cp.setMigrateCall(true); br = sendWithResponse(cp.getCallSetupRequest()); } logger.fine("migrate status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.fine("migrate contents " + br.getContents()); return; default: logger.fine("migrate failed: " + br.getMessage()); throw new IOException("migrate failed: " + br.getMessage()); } } public void endCall(String callId) throws IOException { if (callId.equals("0") == false && callParticipantMap.get(callId) == null) { logger.fine("Call not found " + callId); return; } if (isConnected() == false) { return; } BridgeResponse br; br = sendWithResponse("cancel=" + callId + "\n"); logger.fine("endCall status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("endCall contents " + br.getContents()); return; default: throw new IOException("endCall failed: " + br.getMessage()); } } public void muteCall(String callId, boolean isMuted) throws IOException { BridgeResponse br; br = sendWithResponse("mute=" + isMuted + ":" + callId + "\n"); logger.fine("muteCall status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("muteCall contents " + br.getContents()); return; default: throw new IOException("muteCall failed: " + br.getMessage()); } } public void transferCall(String callId, String conferenceId) throws IOException { BridgeResponse br; br = sendWithResponse("transferCall=" + callId + ":" + conferenceId + "\n"); logger.fine("transferCall status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("transferCall contents " + br.getContents()); return; default: throw new IOException("transferCall failed: " + br.getMessage()); } } /** * Set the stereo volumes for a call.All values are from 0.0 (mute) to * 1.0 (normal) and higher to increase volume. Normally volumes are * [1.0, 0.0, 0.0, 1.0]. These volumes are private to the source * call. * * @param sourceCallId the call id that hears the volume changes * @param targetCallId the call id that has its volumes changed * @param privateMixParameters and array of 4 doubles. * front/back, left/right, up/down, volume */ public void setPrivateMix(String sourceCallId, String targetCallId, double[] privateMixParameters) throws IOException { String s = "pmx=" + privateMixParameters[0] + ":" + privateMixParameters[1] + ":" + privateMixParameters[2] + ":" + privateMixParameters[3] + ":" + targetCallId + ":" + sourceCallId + "\n"; int n = socketChannel.write( ByteBuffer.wrap(s.getBytes(), 0, s.length())); if (n < s.length()) { logger.info("Tried to write " + s.length() + ", actually wrote " + n); } if (false) { BridgeResponse br = sendWithResponse(s + "\n"); logger.finest("setPrivateMix status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finer("setPrivateMix success"); return; default: throw new IOException("setPrivateMix failed: " + br.getMessage()); } } } public void setPrivateMix(String commands) throws IOException { int n = socketChannel.write(ByteBuffer.wrap(commands.getBytes(), 0, commands.length())); if (n < commands.length()) { logger.info("Tried to write " + commands.length() + ", actually wrote " + n); } } /** * Start a new input treatment */ public void newInputTreatment(String callId, String treatment) throws IOException { BridgeResponse br = sendWithResponse("startInputTreatment=" + treatment + ":" + callId + "\n"); logger.finest("newInputTreatment status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("newInputTreatment success"); return; default: throw new IOException("newInputTreatment failed: " + br.getMessage()); } } public void pauseInputTreatment(String callId, boolean isPaused) throws IOException { BridgeResponse br = sendWithResponse("pauseInputTreatment=" + isPaused + ":" + callId + "\n"); logger.finest("pauseInputTreatment status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("pauseInputTreatment success"); return; default: throw new IOException("pauseInputTreatment failed: " + br.getMessage()); } } public void resumeInputTreatment(String callId) throws IOException { BridgeResponse br = sendWithResponse("resumeTreatmentToCall=" + callId + "\n"); logger.finest("resumeTreatment status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("resumeTreatment success"); return; default: throw new IOException("resumeTreatment failed: " + br.getMessage()); } } public void stopInputTreatment(String callId) throws IOException { BridgeResponse br = sendWithResponse("stopInputTreatment=" + callId + "\n"); logger.finest("stopInputTreatment status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("stopInputTreatment success"); return; default: throw new IOException("stopInputTreatment failed: " + br.getMessage()); } } /** * Restart input treatment for a call */ public void restartInputTreatment(String callId) throws IOException { BridgeResponse br = sendWithResponse("restartInputTreatment=" + callId + "\n"); logger.finest("restartInputTreatment status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("restartInputTreatment success"); return; default: throw new IOException("restartInputTreatment failed: " + br.getMessage()); } } public void playTreatmentToCall(String callId, String treatment) throws IOException { BridgeResponse br = sendWithResponse("playTreatmentToCall=" + treatment + ":" + callId + "\n"); logger.finest("playTreatmentToCall status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("playTreatmentToCall success"); return; default: throw new IOException("playTreatmentToCall failed: " + br.getMessage()); } } public void pauseTreatmentToCall(String callId, String treatment) throws IOException { BridgeResponse br = sendWithResponse("pauseTreatmentToCall=" + callId + ":" + treatment + "\n"); logger.finest("pauseTreatmentToCall status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("pauseTreatmentToCall success"); return; default: throw new IOException("pauseTreatmentToCall failed: " + br.getMessage()); } } public void stopTreatmentToCall(String callId, String treatment) throws IOException { BridgeResponse br = sendWithResponse("stopTreatmentToCall=" + callId + ":" + treatment + "\n"); logger.finest("stopTreatmentToCall status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("stopTreatmentToCall success"); return; default: throw new IOException("stopTreatmentToCall failed: " + br.getMessage()); } } public void setSpatialAudio(boolean enabled) throws IOException { BridgeResponse br = sendWithResponse("spatialAudio=" + enabled + "\n"); logger.finest("setSpatialAudio status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("setSpatialAudio success"); return; default: throw new IOException("setSpatialAudio failed: " + br.getMessage()); } } public void setSpatialMinVolume(double spatialMinVolume) throws IOException { BridgeResponse br = sendWithResponse("smv=" + spatialMinVolume + "\n"); logger.finest("setSpatialMinVolume status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("setSpatialMinVolume success"); return; default: throw new IOException("setSpatialMinVolume failed: " + br.getMessage()); } } public void setSpatialFalloff(double spatialFalloff) throws IOException { BridgeResponse br = sendWithResponse("spatialFalloff=" + spatialFalloff + "\n"); logger.finest("setSpatialAudio status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("setSpatialFalloff success"); return; default: throw new IOException("setSpatialFalloff failed: " + br.getMessage()); } } public void setSpatialEchoDelay(double spatialEchoDelay) throws IOException { BridgeResponse br = sendWithResponse("spatialEchoDelay=" + (Math.round(spatialEchoDelay * 100000) / 100000.) + "\n"); logger.finest("setSpatialAudio status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("setSpatialEchoDelay success"); return; default: throw new IOException("setSpatialEchoDelay failed: " + br.getMessage()); } } public void setSpatialEchoVolume(double spatialEchoVolume) throws IOException { BridgeResponse br = sendWithResponse("spatialEchoVolume=" + (Math.round(spatialEchoVolume * 100000) / 100000.) + "\n"); logger.finest("setSpatialAudio status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("setSpatialEchoVolume success"); return; default: throw new IOException("setSpatialEchoVolume failed: " + br.getMessage()); } } public void setSpatialBehindVolume(double spatialBehindVolume) throws IOException { BridgeResponse br = sendWithResponse("spatialBehindVolume=" + (Math.round(spatialBehindVolume * 100000) / 100000.) + "\n"); logger.finest("setSpatialAudio status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("setSpatialBehindVolume success"); return; default: throw new IOException("setSpatialBehindVolume failed: " + br.getMessage()); } } public void forwardData(String sourceCallId, String targetCallId) throws IOException { String cmd = "forwardData=" + targetCallId + ":" + sourceCallId + "\n"; BridgeResponse br = sendWithResponse(cmd); logger.finest("forwardData status " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("forwardData success: " + cmd); return; default: throw new IOException("forwardData failed: " + cmd + " " + br.getMessage()); } } public String getBridgeStatus() throws IOException { String cmd = "gs\n"; BridgeResponse br = sendWithResponse(cmd); logger.finest("getStatus " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("getStatus success: " + cmd); return br.getContents().toString(); default: throw new IOException("getStatus failed: " + cmd + " " + br.getMessage()); } } public String getCallInfo() throws IOException { String cmd = "ci\n"; BridgeResponse br = sendWithResponse(cmd); logger.finest("getCallInfo " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("getCallInfo success: " + cmd); return br.getContents().toString(); default: throw new IOException("getCallInfo failed: " + cmd + " " + br.getMessage()); } } public String getCallStatus(String callId) throws IOException { String cmd = "gcs=" + callId + "\n"; BridgeResponse br = sendWithResponse(cmd); logger.finest("getCallStatus " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("getCallStatus success: " + cmd); return br.getContents().toString(); default: throw new IOException("getCallStatus failed: " + cmd + " " + br.getMessage()); } } public String getBridgeInfo() throws IOException { String cmd = "tp\n"; BridgeResponse br = sendWithResponse(cmd); logger.finest("getBridgeInfo " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("getBridgeInfo success: " + cmd); return br.getContents().toString(); default: throw new IOException("getBridgeInfo failed: " + cmd + " " + br.getMessage()); } } public String suspend(boolean suspend) throws IOException { String cmd; if (suspend) { cmd = "suspend\n"; } else { cmd = "resume\n"; } BridgeResponse br = sendWithResponse(cmd); logger.finest("getStatus " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("suspend success: " + cmd); return br.getMessage(); default: throw new IOException("suspend failed: " + cmd + " " + br.getMessage()); } } public String startRecordingToCall(String callId, String recordingFile) throws IOException { String cmd = "recordToMember=t:" + callId + ":" + recordingFile + ":" + "au" + "\n"; BridgeResponse br = sendWithResponse(cmd); logger.finest("getStatus " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("recordToMember success: " + cmd); return br.getMessage(); default: throw new IOException("recordToMember failed: " + cmd + " " + br.getMessage()); } } public void stopRecordingToCall(String callId) throws IOException { String cmd = "recordToMember=f:" + callId + "\n"; BridgeResponse br = sendWithResponse(cmd); logger.finest("getStatus " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("stop recording success: " + cmd); //return br.getMessage(); return; default: throw new IOException("stop recording failed: " + cmd + " " + br.getMessage()); } } public String recordCall(String callId, String recordingFile, boolean isRecording) throws IOException { String cmd = "recordFromMember=" + isRecording + ":" + callId + ":" + recordingFile + ":" + "au" + "\n"; BridgeResponse br = sendWithResponse(cmd); logger.finest("getStatus " + br.getStatus()); switch (br.getStatus()) { case SUCCESS: logger.finest("recordFromMember success: " + cmd); return br.getMessage(); default: throw new IOException("recordFromMember failed: " + cmd + " " + br.getMessage()); } } /** * Send a message to the bridge and wait for response. This method waits * for a status confirmation from the bridge, and returns whatever that * status is once it is complete. * @param message the message to send * @return the status and message received from the bridge * @throws IOException if there is an error sending the message */ private BridgeConnection getBridgeConnection() { return this; } private synchronized BridgeResponse sendWithResponse(String message) throws IOException { logger.finest("sendWithResponse() - send: '" + message + "'"); checkConnection(); // send the message sendImpl(message); Timer timer = new Timer(); if (watchdogTimeout > 0) { timer.schedule(new TimerTask() { public void run() { logger.info("No response from bridge! " + getBridgeConnection()); disconnect(); sendBridgeOfflineNotification(); }}, watchdogTimeout * 1000); } // read the response StringBuffer contents = new StringBuffer(); String line; while ((line = reader.readLine()) != null) { timer.cancel(); // see if this was an end-of-message line Matcher m = END_OF_MESSAGE.matcher(line); if (m.matches()) { String status = m.group(1).trim(); return new BridgeResponse(status, contents.toString()); } // it's not -- add it to the contents contents.append(line + "\n"); } timer.cancel(); // if we got here, the stream closed before we received the // end-of-message line. This means an abnormal termination. throw new IOException("Unexpected end of stream. Message so far: " + contents.toString()); } /** * Implementation of send * @param message the message to send * @throws IOException if there is an error sending */ private synchronized void sendImpl(String message) throws IOException { // send the message if (writer == null) { throw new IOException("Not connected"); } checkConnection(); writer.print(message); writer.flush(); } public boolean isConnected() { if (socket == null) { logger.finest("socket is null"); return false; } if (socket.isClosed()) { logger.finest("socket is closed"); return false; } if (socket.isConnected() == false) { logger.finest("socket is not connected"); return false; } if (super.isConnected() == false) { logger.finest("super is not connected"); return false; } if (socket.isOutputShutdown() || socket.isInputShutdown()) { return false; } return true; } private void checkConnection() throws IOException { if (isConnected() == false) { throw new IOException("Not connected!"); } } /** * Get the connection to the bridge, opening the socket if necessary. This * method also creates the socket, reader and writer class variables. * @param force if true, force a new connection * @throws IOException if there an error connecting to the * bridge */ private synchronized void connect(boolean force) throws IOException { if (socket == null || socket.isClosed() || force) { logger.fine("Connecting to " + privateHost + " " + privateControlPort); socket = new Socket(privateHost, privateControlPort); socket.setSendBufferSize(256*1024); if (watchdogTimeout != 0) { new ConnectionWatchdog(this); gotBridgePing(); } Reader isr = new InputStreamReader(socket.getInputStream()); Writer osw = new OutputStreamWriter(socket.getOutputStream()); reader = new BufferedReader(isr); writer = new PrintWriter(osw); writer.println("sm=true"); // do some initial setup on the connection writer.flush(); String s = reader.readLine(); // read first line String publicAddress = publicHost + ":" + publicSipPort; String pattern = "BridgePublicAddress='"; int ix = s.indexOf(pattern); int end = -1;; if (ix >= 0) { s = s.substring(ix + pattern.length()); end = s.indexOf("'"); } if (end >= 0) { s = s.substring(0, end); String[] tokens = s.split(":"); try { publicAddress = InetAddress.getByName(tokens[0]).getHostAddress(); } catch (UnknownHostException e) { logger.info("Unknown host: " + tokens[0]); } try { publicAddress += ":" + Integer.parseInt(tokens[1]); } catch (NumberFormatException e) { logger.info("Invalid bridge public address: " + tokens[1]); } catch (ArrayIndexOutOfBoundsException e) { logger.info("Missing port number"); } } logger.info("Bridge public address is " + publicAddress); } else { logger.info("Already connected to " + socket); } } public void disconnect() { if (socket == null) { return; } logger.info("disconnect"); super.disconnect(); try { socket.close(); } catch (IOException e) { } socket = null; } /** * A response from the bridge */ static class BridgeResponse { private enum Status { SUCCESS, FAILURE, UNKNOWN; } private Status status; private String message; private String contents; public BridgeResponse(String status, String contents) { parseStatus(status); this.contents = contents; } public Status getStatus() { return status; } public String getMessage() { return message; } public String getContents() { return contents; } private void parseStatus(String statusStr) { if (statusStr == null) { status = Status.UNKNOWN; } else if (statusStr.startsWith("SUCCESS")) { status = Status.SUCCESS; } else if (statusStr.startsWith("FAILURE:")) { status = Status.FAILURE; message = statusStr.substring("FAILURE:".length()).trim(); } else { status = Status.UNKNOWN; message = "Unrecognized status: " + statusStr; } } } public void bridgeOffline(BridgeConnection bc) { String s = bc.getPrivateHost() + "_" + bc.getPrivateControlPort(); ArrayList<CallParticipant> cpArray = getCallParticipantArray(); while (cpArray.size() > 0) { CallParticipant cp = cpArray.remove(0); String callId = cp.getCallId(); if (callId.indexOf(s) >= 0) { logger.fine("Ending call to disconnected bridge " + callId); try { endCall(callId); } catch (IOException e) { logger.info("Unable to end call to " + callId); } } } } public ArrayList<CallParticipant> getCallParticipantArray() { ArrayList<CallParticipant> cpArray = new ArrayList<CallParticipant>(); Collection<CallParticipant> c = callParticipantMap.values(); Iterator<CallParticipant> it = c.iterator(); while (it.hasNext()) { cpArray.add(it.next()); } return cpArray; } public void gotBridgePing() { bridgePingTime = System.currentTimeMillis(); pingTimeout = false; } public boolean pingTimeout() { return pingTimeout; } public boolean equals(BridgeConnection bc) { return bc.privateHost.equals(privateHost) && bc.privateControlPort == privateControlPort && bc.privateSipPort == privateSipPort && bc.publicHost.equals(publicHost) && bc.publicControlPort == publicControlPort && bc.publicSipPort == publicSipPort; } public boolean equals(String publicHost, String publicSipPort) { return this.publicHost.equals(publicHost) && String.valueOf(this.publicSipPort).equals(publicSipPort); } public String toString() { return privateHost + ":" + privateControlPort + ":" + privateSipPort + ":" + publicHost + ":" + publicControlPort + ":" + publicSipPort; } private boolean offlineNotificationSent; private void sendBridgeOfflineNotification() { synchronized (this) { if (offlineNotificationSent == false && offlineListener != null) { logger.info("Sending bridge down notification: " + toString()); offlineListener.bridgeOffline(this, getCallParticipantArray()); offlineNotificationSent = true; } } } class ConnectionWatchdog extends Thread { private BridgeConnection bridgeConnection; public ConnectionWatchdog(BridgeConnection bridgeConnection) { this.bridgeConnection = bridgeConnection; start(); } public void run() { bridgePingTime = System.currentTimeMillis(); while (bridgeConnection.isConnected()) { long elapsed = 0; while (bridgeConnection.isConnected()) { long now = System.currentTimeMillis(); if (bridgePingTimeout != 0) { elapsed = now - bridgePingTime; if (elapsed > bridgePingTimeout * 1000) { if (pingTimeout == false) { pingTimeout = true; break; // we haven't heard from the bridge } } else { logger.finest("elapsed " + elapsed); pingTimeout = false; } } try { Thread.sleep(watchdogTimeout * 1000); } catch (InterruptedException e) { logger.info("sleep interrupted!"); } continue; } if (bridgeConnection.isConnected() == false) { logger.info("Bridge " + bridgeConnection.toString() + " disconnected " + callParticipantMap.size() + " calls"); } else { logger.info("Bridge " + bridgeConnection.toString() + " went offline, elapsed " + (elapsed / 1000.) + " seconds, " + callParticipantMap.size() + " calls"); } disconnect(); sendBridgeOfflineNotification(); break; } logger.info("ConnectionWatchdog done watching " + bridgeConnection); } } }
gpl-2.0
stereokrauts/stereoscope
stereoscope.mixer.yamaha.y01v96i/src/main/java/com/stereokrauts/stereoscope/mixer/yamaha/y01v96i/Y01v96iMidiReceiver.java
470
package com.stereokrauts.stereoscope.mixer.yamaha.y01v96i; import com.stereokrauts.stereoscope.mixer.yamaha.genericmidsize.midi.GenericMidsizeMidiReceiver; import model.mixer.interfaces.IAmMixer; /** * This class receives MIDI data from the Yamaha 01v96. * @author th * */ public class Y01v96iMidiReceiver extends GenericMidsizeMidiReceiver { public Y01v96iMidiReceiver(final IAmMixer partner) { super(partner); //this.yammi = (Y01v96iMixer) partner; } }
gpl-2.0
Vaculik/creatures-hunting
ApiLayer/src/main/java/cz/muni/fi/pa165/dto/UserSystemLoginDTO.java
1559
package cz.muni.fi.pa165.dto; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; /** * @author Karel Vaculik */ public class UserSystemLoginDTO { @NotNull @Size(min=3, max=64) private String loginName; @NotNull @Size(min=3, max=64) private String password; public String getLoginName() { return loginName; } public void setLoginName(String loginName) { this.loginName = loginName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof UserSystemLoginDTO)) return false; UserSystemLoginDTO that = (UserSystemLoginDTO) o; if (getLoginName() != null ? !getLoginName().equals(that.getLoginName()) : that.getLoginName() != null) return false; return !(getPassword() != null ? !getPassword().equals(that.getPassword()) : that.getPassword() != null); } @Override public int hashCode() { int result = getLoginName() != null ? getLoginName().hashCode() : 0; result = 31 * result + (getPassword() != null ? getPassword().hashCode() : 0); return result; } @Override public String toString() { return "UserSystemLoginDTO{" + "loginName='" + loginName + '\'' + ", password='" + password + '\'' + '}'; } }
gpl-2.0
Tongbupan/Jarsync
source/org/metastatic/rsync/v2/ChecksumEncoder.java
1818
/* ChecksumEncoder -- rsync protocol checksum encoder. $Id: ChecksumEncoder.java,v 1.1 2003/07/18 23:22:13 rsdio Exp $ Copyright (C) 2003 Casey Marshall <rsdio@metastatic.org> This file is a part of Jarsync. Jarsync 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. Jarsync 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 Jarsync; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.metastatic.rsync.v2; import java.io.IOException; import java.io.OutputStream; import org.metastatic.rsync.ChecksumPair; import org.metastatic.rsync.Configuration; public class ChecksumEncoder extends org.metastatic.rsync.ChecksumEncoder { // Constructor. // ------------------------------------------------------------------------- public ChecksumEncoder(Configuration config, OutputStream out) { super(config, out); } // Instance methods. // ------------------------------------------------------------------------- public void write(ChecksumPair pair) throws IOException { int weak = pair.getWeak(); out.write(weak & 0xFF); out.write((weak >>> 8) & 0xFF); out.write((weak >>> 16) & 0xFF); out.write((weak >>> 24)); out.write(pair.getStrong()); } public void doFinal() { // Empty. } public boolean requiresOrder() { return true; } }
gpl-2.0
niloc132/mauve-gwt
src/main/java/gnu/testlet/java/lang/InterruptedException/classInfo/getName.java
1628
// Test for method java.lang.InterruptedException.getClass().getName() // Copyright (C) 2012 Pavel Tisnovsky <ptisnovs@redhat.com> // This file is part of Mauve. // Mauve 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, or (at your option) // any later version. // Mauve 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 Mauve; see the file COPYING. If not, write to // the Free Software Foundation, Inc., 51 Franklin Street, // Fifth Floor, Boston, MA 02110-1301 USA. package gnu.testlet.java.lang.InterruptedException.classInfo; import gnu.testlet.TestHarness; import gnu.testlet.Testlet; import java.lang.InterruptedException; /** * Test for method java.lang.InterruptedException.getClass().getName() */ public class getName implements Testlet { /** * Runs the test using the specified harness. * * @param harness the test harness (<code>null</code> not permitted). */ public void test(TestHarness harness) { // create instance of a class Double Object o = new InterruptedException("InterruptedException"); // get a runtime class of an object "o" Class c = o.getClass(); harness.check(c.getName(), "java.lang.InterruptedException"); } }
gpl-2.0
delafer/j7project
commontools/commons-j7/src/main/java/net/j7/commons/streams/Streams.java
3188
package net.j7.commons.streams; import java.io.*; import java.nio.charset.Charset; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import net.j7.commons.base.CommonUtils; import net.j7.commons.base.NotNull; public class Streams { /** The technical logger to use. */ private static final Logger logger = LoggerFactory.getLogger(Streams.class); private static final String DEFAULT_CHARSET = "UTF-8"; /** * The default size of the buffer. */ public static final int DEFAULT_BUFFER_SIZE = 256; /** * @param os * @param inquiry * @throws IOException */ public static void stringToStream(OutputStream os, String text, String encoding) throws IOException { os.write(text.getBytes(Charset.forName(CommonUtils.nvl(encoding, DEFAULT_CHARSET)))); os.flush(); } /** * Convert stream to string. * * @param is the is * @param encoding the encoding * @return the string * @throws IOException Signals that an I/O exception has occurred. */ public static String convertStreamToString(InputStream is, String encoding) throws IOException { /* * To convert the InputStream to String we use the * Reader.read(char[] buffer) method. We iterate until the * Reader return -1 which means there's no more data to * read. We use the StringWriter class to produce the string. */ if (is != null) { Writer writer = new StringWriter(); char[] buffer = new char[512]; Reader reader = null; try { InputStreamReader isReader = encoding != null ? new InputStreamReader(is, encoding) : new InputStreamReader(is); reader = new BufferedReader(isReader); int n; while ((n = reader.read(buffer)) > 0) { writer.write(buffer, 0, n); } } finally { reader.close(); } return writer.toString(); } else { return ""; } } /** * Copy bytes from an <code>InputStream</code> to an * <code>OutputStream</code>. * @param input the <code>InputStream</code> to read from * @param output the <code>OutputStream</code> to write to * @return the number of bytes copied * @throws IOException In case of an I/O problem */ public static final int copy(InputStream input, OutputStream output) throws IOException { byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; int count = 0; int n; while (-1 != (n = input.read(buffer))) { output.write(buffer, 0, n); count += n; } return count; } public static void close(Closeable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (IOException e) { logger.error("Error closing closeable", e); } } public static void closeSilently(Closeable closeable) { if (closeable == null) { return; } try { closeable.close(); } catch (IOException e) { // silently } } }
gpl-2.0
z0isch/garble
Garble.Android/Garble.Android/obj/Debug/android/src/garble/android/Record.java
1107
package garble.android; public class Record extends android.app.Activity implements mono.android.IGCUserPeer { static final String __md_methods; static { __md_methods = "n_onCreate:(Landroid/os/Bundle;)V:GetOnCreate_Landroid_os_Bundle_Handler\n" + ""; mono.android.Runtime.register ("Garble.Android.Record, Garble.Android, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", Record.class, __md_methods); } public Record () throws java.lang.Throwable { super (); if (getClass () == Record.class) mono.android.TypeManager.Activate ("Garble.Android.Record, Garble.Android, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "", this, new java.lang.Object[] { }); } public void onCreate (android.os.Bundle p0) { n_onCreate (p0); } private native void n_onCreate (android.os.Bundle p0); java.util.ArrayList refList; public void monodroidAddReference (java.lang.Object obj) { if (refList == null) refList = new java.util.ArrayList (); refList.add (obj); } public void monodroidClearReferences () { if (refList != null) refList.clear (); } }
gpl-2.0
klst-com/metasfresh
de.metas.adempiere.adempiere/base/src/main/java/org/eevolution/api/impl/ProductBOMBL.java
3184
package org.eevolution.api.impl; /* * #%L * de.metas.adempiere.adempiere.base * %% * Copyright (C) 2015 metas GmbH * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * <http://www.gnu.org/licenses/gpl-2.0.html>. * #L% */ import java.math.BigDecimal; import java.util.Date; import java.util.Properties; import org.adempiere.model.InterfaceWrapperHelper; import org.adempiere.util.Services; import org.compiere.model.I_M_Product; import org.compiere.util.Env; import org.eevolution.api.IProductBOMBL; import org.eevolution.api.IProductBOMDAO; import org.eevolution.api.IProductLowLevelUpdater; import org.eevolution.model.I_PP_Product_BOM; import org.eevolution.model.I_PP_Product_BOMLine; public class ProductBOMBL implements IProductBOMBL { @Override public boolean isValidFromTo(final I_PP_Product_BOM productBOM, final Date date) { final Date validFrom = productBOM.getValidFrom(); if (validFrom != null && date.before(validFrom)) { return false; } final Date validTo = productBOM.getValidTo(); if (validTo != null && date.after(validTo)) { return false; } return true; } @Override public boolean isValidFromTo(final I_PP_Product_BOMLine bomLine, final Date date) { final Date validFrom = bomLine.getValidFrom(); if (validFrom != null && date.before(validFrom)) { return false; } final Date validTo = bomLine.getValidTo(); if (validTo != null && date.after(validTo)) { return false; } return true; } @Override public void setIsBOM(final I_M_Product product) { final boolean hasBOMs = Services.get(IProductBOMDAO.class).hasBOMs(product); product.setIsBOM(hasBOMs); } @Override public int calculateProductLowestLevel(final I_M_Product product) { final Properties ctx = InterfaceWrapperHelper.getCtx(product); final String trxName = InterfaceWrapperHelper.getTrxName(product); final int productId = product.getM_Product_ID(); return new ProductLowLevelCalculator(ctx, trxName).getLowLevel(productId); } @Override public IProductLowLevelUpdater updateProductLowLevels() { return new ProductLowLevelUpdater(); } @Override public BigDecimal calculateQtyWithScrap(final BigDecimal qty, final BigDecimal qtyScrap) { if (qty == null || qty.signum() == 0) { return BigDecimal.ZERO; } if (qtyScrap == null || qtyScrap.signum() == 0) { return qty; } final BigDecimal scrapPerc = qtyScrap.divide(Env.ONEHUNDRED, 8, BigDecimal.ROUND_UP); final BigDecimal qtyPlusScrapPerc = BigDecimal.ONE.add(scrapPerc); final BigDecimal qtyPlusScap = qty.multiply(qtyPlusScrapPerc); return qtyPlusScap; } }
gpl-2.0
Jianchu/checker-framework
checker/jdk/lock/src/java/lang/Object.java
1357
package java.lang; import org.checkerframework.dataflow.qual.Pure; import org.checkerframework.dataflow.qual.SideEffectFree; import org.checkerframework.checker.lock.qual.*; import org.checkerframework.checker.initialization.qual.*; public class Object { public Object() { throw new RuntimeException("skeleton method"); } public boolean equals(@GuardSatisfied Object this,@GuardSatisfied Object a1) { throw new RuntimeException("skeleton method"); } public String toString(@GuardSatisfied Object this) { throw new RuntimeException("skeleton method"); } public final void wait(Object this, long a1, int a2) throws InterruptedException { throw new RuntimeException("skeleton method"); } public final void wait(Object this) throws InterruptedException { throw new RuntimeException("skeleton method"); } private static native void registerNatives(); public final native Class<? extends Object> getClass(@GuardSatisfied Object this); public native int hashCode(@GuardSatisfied Object this); protected native Object clone(@GuardSatisfied Object this) throws CloneNotSupportedException; public final native void notify(); public final native void notifyAll(); public final native void wait(long timeout) throws InterruptedException; protected void finalize() throws Throwable { throw new RuntimeException("skeleton method"); } }
gpl-2.0
bwagner/utf-x-framework-svn-trunk
src/java/utfx/framework/XSLTTransformTestCase.java
22260
package utfx.framework; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.StringReader; import java.lang.reflect.InvocationTargetException; import java.net.URISyntaxException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.stream.StreamResult; import javax.xml.xpath.XPath; import javax.xml.xpath.XPathConstants; import javax.xml.xpath.XPathExpressionException; import javax.xml.xpath.XPathFactory; import org.apache.log4j.Logger; import org.w3c.dom.DOMConfiguration; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.w3c.dom.bootstrap.DOMImplementationRegistry; import org.w3c.dom.ls.DOMImplementationLS; import org.w3c.dom.ls.LSOutput; import org.w3c.dom.ls.LSSerializer; import org.xml.sax.SAXException; import utfx.util.DOMWriter; /** * JUnit extension for testing XSLT stylesheets. * <p> * Copyright &copy; 2004 - <a href="http://www.usq.edu.au"> University of * Southern Queensland. </a> * </p> * <p> * This program is free software; you can redistribute it and/or modify it under * the terms of the <a href="http://www.gnu.org/licenses/gpl.txt">GNU General * Public License v2 </a> as published by the Free Software Foundation. * </p> * <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> * <code> * $Source: /cvs/utf-x/framework/src/java/utfx/framework/XSLTTransformTestCase.java,v $ * </code> * * @author Jacek Radajewski * @author Oliver Lucido * @author Sally MacFarlane * @author Alex Daniel * @version $Revision$ $Date$ $Name: $ */ public class XSLTTransformTestCase extends UTFXTestCase { /** XPath factory */ private XPathFactory xpf; /** XPath */ private XPath xpath; /** The name of this test case */ private String testName; /** XSLT transformer used to transform the source */ private Transformer transformer; /** transformer.Source */ private Source transformSource; /** The source input */ private String sourceString; /** The expected output */ private String expectedString; /** The message to output when the assertion fails */ private String failureMessage; private String templateName; /** LOG4J logging facility */ private Logger log; /** source builder used to parse utfx:source fragments */ private SourceParser sourceBuilder; /** DOM3 implementation registry */ private DOMImplementationRegistry domRegistry; /** DOM Load/Save implementation */ private DOMImplementationLS domImplLS; /** DOM Load/Save serializer */ private LSSerializer domSerializer; /** DOM Configuration object */ private DOMConfiguration domConfig; private boolean validateSource = false; private boolean validateExpected = false; private boolean useSourceParser = false; /** value of href attribute in &lt;utfx:source&gt; */ private ExternalResource externalSourceFile; /** value of href attribute in &lt;utfx:expected&gt; */ private ExternalResource externalExpectedFile; private String expectedDocType; /** * We need to flag badly formed tests at assambly time and throw an * exception at test run time; this is due to JUnit limitation; */ private MalformedTestException mte = null; /** XSLTTestFileSuite that is the parent of this XSLTTransformTestCase */ private XSLTTestFileSuite parentSuite; /** * Get the failureMessage. Method used for testing. * * @return failureMessage */ public String getFailureMessage() { return failureMessage; } /** * Get the <code>useSourceParser</code> value. Method used for testing. * * @return true if use-source-parser="yes" is set on &lt;utfx:source&gt; */ public boolean useSourceParser() { return useSourceParser; } /** * Get the <code>validateExpected</code> value. Method used for testing. * * @return false if validate="no" has been set on &lt;utfx:expected&lt; and * true otherwise. NOTE: validate="yes" is the default. */ public boolean validateExpected() { return validateExpected; } /** * Get the <code>validateExpected</code> value. Method used for testing. * * @return false if validate="no" has been set on &lt;utfx:source&lt; and * true otherwise. NOTE: validate="yes" is the default. */ public boolean validateSource() { return validateSource; } /** * Constructs an XsltTestCase. * * @param testName * the name of this test * @param source * the source input * @param expected * the expected output * @throws InstantiationException * @throws InvocationTargetException * @throws IllegalAccessException * @throws NoSuchMethodException * @throws ClassNotFoundException * @throws XPathExpressionException * @throws MalformedTestException */ public XSLTTransformTestCase(Element elem, XSLTTestFileSuite parentSuite) throws Exception { super("testTransform"); log = Logger.getLogger("utfx.framework"); this.templateName = null; this.sourceBuilder = parentSuite.getDefaultSourceBuilder(); this.parentSuite = parentSuite; xpf = XPathFactory.newInstance(); xpath = xpf.newXPath(); xpath.setNamespaceContext(new UTFXNamespaceContext()); domRegistry = DOMImplementationRegistry.newInstance(); domImplLS = (DOMImplementationLS) domRegistry .getDOMImplementation("LS"); domSerializer = domImplLS.createLSSerializer(); domConfig = domSerializer.getDomConfig(); domConfig.setParameter("xml-declaration", false); processNode(elem); } /** * Process utfx:test element and create appropriate test components. * * @param testElement * dom.Element representing utfx:test * * @throws Exception * upon error. */ private void processNode(Element testElement) throws Exception { testName = xpath.evaluate("utfx:name", testElement); if (testName == null || "".equals(testName)) { testName = "name not set"; } templateName = xpath.evaluate("utfx:call-template/@name", testElement); if ("yes".equals(xpath.evaluate( "utfx:assert-equal/@normalise-internal-whitespace", testElement))) { normaliseInternalWhitespace = true; } if ("no".equals(xpath.evaluate( "utfx:assert-equal/utfx:source/@validate", testElement)) || !parentSuite.doSourceValidation()) { validateSource = false; } else { validateSource = true; } if ("no".equals(xpath.evaluate( "utfx:assert-equal/utfx:expected/@validate", testElement)) || !parentSuite.doExpectedValidation()) { validateExpected = false; } else { validateExpected = true; } if ("yes".equals(xpath .evaluate("utfx:assert-equal/utfx:source/@use-source-parser", testElement))) { useSourceParser = true; } externalSourceFile = new ExternalResource(getStringFromXpath(testElement, "utfx:assert-equal/utfx:source/@href"), parentSuite.getFile()); externalExpectedFile = new ExternalResource(getStringFromXpath(testElement, "utfx:assert-equal/utfx:expected/@href"), parentSuite.getFile()); if (!isValid(testElement)) { return; } try { setTestSourceBuilder(testElement); setTransformSource(testElement); setExpectedString(testElement); } catch (Exception e) { log.error("failed processing test element(s): ", e); } failureMessage = xpath.evaluate(".//utfx:message", testElement); if (failureMessage == null || "".equals(failureMessage)) { failureMessage = "UTF-X test failed"; } } /** * Set String to null or to value depending on result of XPath * * @param testElement * @param xpathExpr * @return String * @throws XPathExpressionException */ protected String getStringFromXpath(Element testElement, String xpathExpr) throws XPathExpressionException { String result; Object node = xpath.evaluate(xpathExpr, testElement, XPathConstants.NODE); if (node == null) { result = null; } else { result = xpath.evaluate(xpathExpr, testElement); } return result; } /** * Set source builder for this test. If this test does not specify its own * source builder then the source builder set by the file test suite will be * used. * * @param testElement * this UTF-X test as DOM Element. * @throws XPathExpressionException * @throws ClassNotFoundException * @throws NoSuchMethodException * @throws IllegalAccessException * @throws InvocationTargetException * @throws InstantiationException */ private void setTestSourceBuilder(Element testElement) throws Exception { SourceParserFactory sbLoader = new SourceParserFactory(); Element sbElem = (Element) xpath.evaluate("utfx:source-builder", testElement, XPathConstants.NODE); if (sbElem != null) { sourceBuilder = sbLoader.getSourceParser(sbElem); } } /** * Serialize the given node to a String. * * @param node * @return * @throws Exception */ public String serializeNode(Node node) throws Exception { ByteArrayOutputStream baos; DOMWriter domWriter; String result; LSOutput lsOutput; short nodeType = node.getNodeType(); // there seems to be a bug with the DOM3 serializer which causes // an NPE when serializing empty elements or any non-element node - // current workaround is to use the utfx.util.DOMWriter in such cases baos = new ByteArrayOutputStream(0x200); if ((nodeType == Node.ELEMENT_NODE) && node.hasChildNodes()) { lsOutput = domImplLS.createLSOutput(); lsOutput.setByteStream(baos); lsOutput.setEncoding("UTF-8"); domSerializer.write(node, lsOutput); } else { log.info("using DOMWriter"); baos = new ByteArrayOutputStream(); domWriter = new DOMWriter(baos); domWriter.print(node); } result = baos.toString("UTF8"); return result; } /** * Set transform.Source object. * * @param testElement * dom.Element representing the UTF-X test. * @throws Exception */ private void setTransformSource(Element testElement) throws Exception { sourceString = generateSourceString(testElement); // create a validation test case if required if (validateSource) { parentSuite.addTest(new XMLValidationTestCase(testName + " [source fragment validation]", sourceString)); } // set transformSource if (useSourceParser) { ByteArrayInputStream sourceStream = new ByteArrayInputStream(sourceString.getBytes()); transformSource = sourceBuilder.getSource(sourceStream); } else { DefaultSourceParser defaultSourceParser = new DefaultSourceParser(); // fixing https://utf-x.dev.java.net/issues/show_bug.cgi?id=74 - Two-byte UTF-8 characters in TDFs transformSource = defaultSourceParser.getSource(new StringReader(sourceString)); } } /** * Generate the source string out of testElement * * @param testElement * @return sourceString * @throws XPathExpressionException * @throws Exception */ protected String generateSourceString(Element testElement) throws XPathExpressionException, Exception { Document doc = testElement.getOwnerDocument(); Element sourceWrapper = doc.createElement("utfx-wrapper"); NodeList sourceNodes = generateSourceNodes(testElement); // append sourceNodes to utfx-wrapper element appendNodes(sourceWrapper, sourceNodes); // if utfx:source is empty and call-template is used we have to add a // second utfx-wrapper element if (isUsingCallTemplate() && (sourceNodes.getLength() == 0)) { sourceWrapper.appendChild(doc.createElement("utfx-wrapper")); } return getSourceDocType("utfx-wrapper") + serializeNode(sourceWrapper); } /** * Appends a list of nodes to an element * * @param sourceWrapper * @param sourceNodes */ private void appendNodes(Element sourceWrapper, NodeList sourceNodes) { for (int i = 0; i < sourceNodes.getLength(); i++) { Node node = sourceNodes.item(i); sourceWrapper.appendChild(node); } } /** * Generates a node list from the utfx:source element * * Normally the node list is read from the TDF. * When using a href it is read from an external file. * * @param testElement * @return node list * @throws XPathExpressionException * @throws FileNotFoundException * @throws ParserConfigurationException * @throws SAXException * @throws IOException * @throws URISyntaxException */ protected NodeList generateSourceNodes(Element testElement) throws XPathExpressionException, FileNotFoundException, ParserConfigurationException, SAXException, IOException, URISyntaxException { if (externalSourceFile.isAvailable()) { return externalSourceFile.getNodes(testElement.getOwnerDocument()); } else { return generateSourceNodesFromTDF(testElement); } } /** * Generates the node list from the TDF * * @param testElement * @return node list * @throws XPathExpressionException */ protected NodeList generateSourceNodesFromTDF(Element testElement) throws XPathExpressionException { NodeList sourceNodes = (NodeList) xpath.evaluate( "utfx:assert-equal/utfx:source/node()", testElement, XPathConstants.NODESET); return sourceNodes; } public Source getTransformSource() { return transformSource; } /** * @param testElement * @throws Exception */ private void setExpectedString(Element testElement) throws Exception { expectedDocType = getExpectedDocType("utfx-wrapper"); expectedString = expectedDocType + generateExpectedString(testElement); // create a validation test case if required if (validateExpected) { parentSuite.addTest(new XMLValidationTestCase(testName + " [expected fragment validation]", expectedString)); } } /** * Generates the expected string for the test * * @param testElement * @return expected string * @throws Exception */ private String generateExpectedString(Element testElement) throws Exception { Document doc = testElement.getOwnerDocument(); Element expectedWrapper = doc.createElement("utfx-wrapper"); NodeList expectedNodes = generateExpectedNodes(testElement); appendNodes(expectedWrapper, expectedNodes); return serializeNode(expectedWrapper); } /** * Generates a node list from utfx:expected depending on whether an external file is in use * * @param testElement * @return node list * @throws XPathExpressionException * @throws FileNotFoundException * @throws ParserConfigurationException * @throws SAXException * @throws IOException * @throws URISyntaxException */ private NodeList generateExpectedNodes(Element testElement) throws XPathExpressionException, FileNotFoundException, ParserConfigurationException, SAXException, IOException, URISyntaxException { if (externalExpectedFile.isAvailable()) { return externalExpectedFile.getNodes(testElement.getOwnerDocument()); } else { return generateExpectedNodesFromTDF(testElement); } } /** * Generates a node list from utfx:expected from the TDF * * @param testElement * @return node list * @throws XPathExpressionException */ private NodeList generateExpectedNodesFromTDF(Element testElement) throws XPathExpressionException { return (NodeList) xpath.evaluate( "utfx:assert-equal/utfx:expected/node()", testElement, XPathConstants.NODESET); } /** * Returns the expectedString of the test (currently only used by JUnit tests) * * @return expectedString of test */ public String getExpectedString() { return expectedString; } /** * Sanity Checks on utfx:test * * @param testElement * @throws XPathExpressionException */ private boolean isValid(Element testElement) throws XPathExpressionException { if (xpath.evaluate(".//utfx:assert-equal", testElement, XPathConstants.NODE) == null) { mte = new MalformedTestException("each test must contain at least " + "one <utfx:assert-equal> element"); return false; } if (xpath.evaluate(".//utfx:source", testElement, XPathConstants.NODE) == null) { mte = new MalformedTestException("required element <utfx:source>" + " is missing"); return false; } if (xpath.evaluate(".//utfx:expected", testElement, XPathConstants.NODE) == null) { mte = new MalformedTestException("required element <utf:expected>" + " is missing"); return false; } return true; } /** * Tests if this is using a named-template transformer. */ public boolean isUsingCallTemplate() { return (templateName != null) && (!templateName.equals("")); } /** * Sets the transformer to be used. */ public void setTransformer(Transformer transformer) { this.transformer = transformer; } /** * Transforms the source using the transformer and asserts their * equivalence. This is the method that is called by the JUnit framework to * run the UTF-X test. */ public void testTransform() throws Exception { // check if we have a MalformedTestException to throw if (mte != null) { throw mte; } log.debug(testName + " :: testTransform()"); if (transformer == null) { fail("No transformer defined for " + testName); } ByteArrayOutputStream actualOutputStream = new ByteArrayOutputStream(); transformer.clearParameters(); transformer.transform(transformSource, new StreamResult( actualOutputStream)); String actualString = ""; if (expectedDocType != null) { actualString = expectedDocType; } actualString += actualOutputStream.toString("UTF8"); log.debug("source=[" + sourceString + "]"); log.debug("actual=[" + actualString + "]"); log.debug("expected=[" + expectedString + "]"); assertEquivXML(failureMessage, new ByteArrayInputStream(expectedString .getBytes("UTF8")), new ByteArrayInputStream(actualString .getBytes("UTF8"))); } /** * Generate doctype declaration from root element name, public identifier * and system identifier. * * @param rootTagName * @param publicID * @param systemID * @return */ private String getDocType(String rootTagName, String publicID, String systemID) { String doctype = ""; if (rootTagName == null || publicID == null || systemID == null || "".equals(rootTagName) || "".equals(publicID) || "".equals(systemID)) { return ""; } doctype += "<!DOCTYPE "; doctype += rootTagName + " PUBLIC "; doctype += "\"" + publicID + "\" "; doctype += "\"" + systemID + "\" [ <!ELEMENT utfx-wrapper ANY> ]>\n"; return doctype; } private String getSourceDocType(String rootTagName) { return getDocType(rootTagName, parentSuite.getSourcePublicId(), parentSuite.getSourceSystemId()); } private String getExpectedDocType(String rootTagName) { return getDocType(rootTagName, parentSuite.getExpectedPublicId(), parentSuite.getExpectedSystemId()); } public String toString() { return testName; } }
gpl-2.0
34benma/openjdk
jdk/src/java.base/share/classes/java/util/stream/Streams.java
29202
/* * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package java.util.stream; import java.util.Comparator; import java.util.Objects; import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.DoubleConsumer; import java.util.function.IntConsumer; import java.util.function.LongConsumer; import jdk.internal.HotSpotIntrinsicCandidate; /** * Utility methods for operating on and creating streams. * * <p>Unless otherwise stated, streams are created as sequential streams. A * sequential stream can be transformed into a parallel stream by calling the * {@code parallel()} method on the created stream. * * @since 1.8 */ final class Streams { private Streams() { throw new Error("no instances"); } /** * An object instance representing no value, that cannot be an actual * data element of a stream. Used when processing streams that can contain * {@code null} elements to distinguish between a {@code null} value and no * value. */ static final Object NONE = new Object(); /** * An {@code int} range spliterator. */ static final class RangeIntSpliterator implements Spliterator.OfInt { // Can never be greater that upTo, this avoids overflow if upper bound // is Integer.MAX_VALUE // All elements are traversed if from == upTo & last == 0 private int from; private final int upTo; // 1 if the range is closed and the last element has not been traversed // Otherwise, 0 if the range is open, or is a closed range and all // elements have been traversed private int last; RangeIntSpliterator(int from, int upTo, boolean closed) { this(from, upTo, closed ? 1 : 0); } private RangeIntSpliterator(int from, int upTo, int last) { this.from = from; this.upTo = upTo; this.last = last; } @Override public boolean tryAdvance(IntConsumer consumer) { Objects.requireNonNull(consumer); final int i = from; if (i < upTo) { from++; consumer.accept(i); return true; } else if (last > 0) { last = 0; consumer.accept(i); return true; } return false; } @Override @HotSpotIntrinsicCandidate public void forEachRemaining(IntConsumer consumer) { Objects.requireNonNull(consumer); int i = from; final int hUpTo = upTo; int hLast = last; from = upTo; last = 0; while (i < hUpTo) { consumer.accept(i++); } if (hLast > 0) { // Last element of closed range consumer.accept(i); } } @Override public long estimateSize() { // Ensure ranges of size > Integer.MAX_VALUE report the correct size return ((long) upTo) - from + last; } @Override public int characteristics() { return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE | Spliterator.NONNULL | Spliterator.DISTINCT | Spliterator.SORTED; } @Override public Comparator<? super Integer> getComparator() { return null; } @Override public Spliterator.OfInt trySplit() { long size = estimateSize(); return size <= 1 ? null // Left split always has a half-open range : new RangeIntSpliterator(from, from = from + splitPoint(size), 0); } /** * The spliterator size below which the spliterator will be split * at the mid-point to produce balanced splits. Above this size the * spliterator will be split at a ratio of * 1:(RIGHT_BALANCED_SPLIT_RATIO - 1) * to produce right-balanced splits. * * <p>Such splitting ensures that for very large ranges that the left * side of the range will more likely be processed at a lower-depth * than a balanced tree at the expense of a higher-depth for the right * side of the range. * * <p>This is optimized for cases such as IntStream.range(0, Integer.MAX_VALUE) * that is likely to be augmented with a limit operation that limits the * number of elements to a count lower than this threshold. */ private static final int BALANCED_SPLIT_THRESHOLD = 1 << 24; /** * The split ratio of the left and right split when the spliterator * size is above BALANCED_SPLIT_THRESHOLD. */ private static final int RIGHT_BALANCED_SPLIT_RATIO = 1 << 3; private int splitPoint(long size) { int d = (size < BALANCED_SPLIT_THRESHOLD) ? 2 : RIGHT_BALANCED_SPLIT_RATIO; // Cast to int is safe since: // 2 <= size < 2^32 // 2 <= d <= 8 return (int) (size / d); } } /** * A {@code long} range spliterator. * * This implementation cannot be used for ranges whose size is greater * than Long.MAX_VALUE */ static final class RangeLongSpliterator implements Spliterator.OfLong { // Can never be greater that upTo, this avoids overflow if upper bound // is Long.MAX_VALUE // All elements are traversed if from == upTo & last == 0 private long from; private final long upTo; // 1 if the range is closed and the last element has not been traversed // Otherwise, 0 if the range is open, or is a closed range and all // elements have been traversed private int last; RangeLongSpliterator(long from, long upTo, boolean closed) { this(from, upTo, closed ? 1 : 0); } private RangeLongSpliterator(long from, long upTo, int last) { assert upTo - from + last > 0; this.from = from; this.upTo = upTo; this.last = last; } @Override public boolean tryAdvance(LongConsumer consumer) { Objects.requireNonNull(consumer); final long i = from; if (i < upTo) { from++; consumer.accept(i); return true; } else if (last > 0) { last = 0; consumer.accept(i); return true; } return false; } @Override public void forEachRemaining(LongConsumer consumer) { Objects.requireNonNull(consumer); long i = from; final long hUpTo = upTo; int hLast = last; from = upTo; last = 0; while (i < hUpTo) { consumer.accept(i++); } if (hLast > 0) { // Last element of closed range consumer.accept(i); } } @Override public long estimateSize() { return upTo - from + last; } @Override public int characteristics() { return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.IMMUTABLE | Spliterator.NONNULL | Spliterator.DISTINCT | Spliterator.SORTED; } @Override public Comparator<? super Long> getComparator() { return null; } @Override public Spliterator.OfLong trySplit() { long size = estimateSize(); return size <= 1 ? null // Left split always has a half-open range : new RangeLongSpliterator(from, from = from + splitPoint(size), 0); } /** * The spliterator size below which the spliterator will be split * at the mid-point to produce balanced splits. Above this size the * spliterator will be split at a ratio of * 1:(RIGHT_BALANCED_SPLIT_RATIO - 1) * to produce right-balanced splits. * * <p>Such splitting ensures that for very large ranges that the left * side of the range will more likely be processed at a lower-depth * than a balanced tree at the expense of a higher-depth for the right * side of the range. * * <p>This is optimized for cases such as LongStream.range(0, Long.MAX_VALUE) * that is likely to be augmented with a limit operation that limits the * number of elements to a count lower than this threshold. */ private static final long BALANCED_SPLIT_THRESHOLD = 1 << 24; /** * The split ratio of the left and right split when the spliterator * size is above BALANCED_SPLIT_THRESHOLD. */ private static final long RIGHT_BALANCED_SPLIT_RATIO = 1 << 3; private long splitPoint(long size) { long d = (size < BALANCED_SPLIT_THRESHOLD) ? 2 : RIGHT_BALANCED_SPLIT_RATIO; // 2 <= size <= Long.MAX_VALUE return size / d; } } private static abstract class AbstractStreamBuilderImpl<T, S extends Spliterator<T>> implements Spliterator<T> { // >= 0 when building, < 0 when built // -1 == no elements // -2 == one element, held by first // -3 == two or more elements, held by buffer int count; // Spliterator implementation for 0 or 1 element // count == -1 for no elements // count == -2 for one element held by first @Override public S trySplit() { return null; } @Override public long estimateSize() { return -count - 1; } @Override public int characteristics() { return Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.ORDERED | Spliterator.IMMUTABLE; } } static final class StreamBuilderImpl<T> extends AbstractStreamBuilderImpl<T, Spliterator<T>> implements Stream.Builder<T> { // The first element in the stream // valid if count == 1 T first; // The first and subsequent elements in the stream // non-null if count == 2 SpinedBuffer<T> buffer; /** * Constructor for building a stream of 0 or more elements. */ StreamBuilderImpl() { } /** * Constructor for a singleton stream. * * @param t the single element */ StreamBuilderImpl(T t) { first = t; count = -2; } // StreamBuilder implementation @Override public void accept(T t) { if (count == 0) { first = t; count++; } else if (count > 0) { if (buffer == null) { buffer = new SpinedBuffer<>(); buffer.accept(first); count++; } buffer.accept(t); } else { throw new IllegalStateException(); } } public Stream.Builder<T> add(T t) { accept(t); return this; } @Override public Stream<T> build() { int c = count; if (c >= 0) { // Switch count to negative value signalling the builder is built count = -count - 1; // Use this spliterator if 0 or 1 elements, otherwise use // the spliterator of the spined buffer return (c < 2) ? StreamSupport.stream(this, false) : StreamSupport.stream(buffer.spliterator(), false); } throw new IllegalStateException(); } // Spliterator implementation for 0 or 1 element // count == -1 for no elements // count == -2 for one element held by first @Override public boolean tryAdvance(Consumer<? super T> action) { Objects.requireNonNull(action); if (count == -2) { action.accept(first); count = -1; return true; } else { return false; } } @Override public void forEachRemaining(Consumer<? super T> action) { Objects.requireNonNull(action); if (count == -2) { action.accept(first); count = -1; } } } static final class IntStreamBuilderImpl extends AbstractStreamBuilderImpl<Integer, Spliterator.OfInt> implements IntStream.Builder, Spliterator.OfInt { // The first element in the stream // valid if count == 1 int first; // The first and subsequent elements in the stream // non-null if count == 2 SpinedBuffer.OfInt buffer; /** * Constructor for building a stream of 0 or more elements. */ IntStreamBuilderImpl() { } /** * Constructor for a singleton stream. * * @param t the single element */ IntStreamBuilderImpl(int t) { first = t; count = -2; } // StreamBuilder implementation @Override public void accept(int t) { if (count == 0) { first = t; count++; } else if (count > 0) { if (buffer == null) { buffer = new SpinedBuffer.OfInt(); buffer.accept(first); count++; } buffer.accept(t); } else { throw new IllegalStateException(); } } @Override public IntStream build() { int c = count; if (c >= 0) { // Switch count to negative value signalling the builder is built count = -count - 1; // Use this spliterator if 0 or 1 elements, otherwise use // the spliterator of the spined buffer return (c < 2) ? StreamSupport.intStream(this, false) : StreamSupport.intStream(buffer.spliterator(), false); } throw new IllegalStateException(); } // Spliterator implementation for 0 or 1 element // count == -1 for no elements // count == -2 for one element held by first @Override public boolean tryAdvance(IntConsumer action) { Objects.requireNonNull(action); if (count == -2) { action.accept(first); count = -1; return true; } else { return false; } } @Override public void forEachRemaining(IntConsumer action) { Objects.requireNonNull(action); if (count == -2) { action.accept(first); count = -1; } } } static final class LongStreamBuilderImpl extends AbstractStreamBuilderImpl<Long, Spliterator.OfLong> implements LongStream.Builder, Spliterator.OfLong { // The first element in the stream // valid if count == 1 long first; // The first and subsequent elements in the stream // non-null if count == 2 SpinedBuffer.OfLong buffer; /** * Constructor for building a stream of 0 or more elements. */ LongStreamBuilderImpl() { } /** * Constructor for a singleton stream. * * @param t the single element */ LongStreamBuilderImpl(long t) { first = t; count = -2; } // StreamBuilder implementation @Override public void accept(long t) { if (count == 0) { first = t; count++; } else if (count > 0) { if (buffer == null) { buffer = new SpinedBuffer.OfLong(); buffer.accept(first); count++; } buffer.accept(t); } else { throw new IllegalStateException(); } } @Override public LongStream build() { int c = count; if (c >= 0) { // Switch count to negative value signalling the builder is built count = -count - 1; // Use this spliterator if 0 or 1 elements, otherwise use // the spliterator of the spined buffer return (c < 2) ? StreamSupport.longStream(this, false) : StreamSupport.longStream(buffer.spliterator(), false); } throw new IllegalStateException(); } // Spliterator implementation for 0 or 1 element // count == -1 for no elements // count == -2 for one element held by first @Override public boolean tryAdvance(LongConsumer action) { Objects.requireNonNull(action); if (count == -2) { action.accept(first); count = -1; return true; } else { return false; } } @Override public void forEachRemaining(LongConsumer action) { Objects.requireNonNull(action); if (count == -2) { action.accept(first); count = -1; } } } static final class DoubleStreamBuilderImpl extends AbstractStreamBuilderImpl<Double, Spliterator.OfDouble> implements DoubleStream.Builder, Spliterator.OfDouble { // The first element in the stream // valid if count == 1 double first; // The first and subsequent elements in the stream // non-null if count == 2 SpinedBuffer.OfDouble buffer; /** * Constructor for building a stream of 0 or more elements. */ DoubleStreamBuilderImpl() { } /** * Constructor for a singleton stream. * * @param t the single element */ DoubleStreamBuilderImpl(double t) { first = t; count = -2; } // StreamBuilder implementation @Override public void accept(double t) { if (count == 0) { first = t; count++; } else if (count > 0) { if (buffer == null) { buffer = new SpinedBuffer.OfDouble(); buffer.accept(first); count++; } buffer.accept(t); } else { throw new IllegalStateException(); } } @Override public DoubleStream build() { int c = count; if (c >= 0) { // Switch count to negative value signalling the builder is built count = -count - 1; // Use this spliterator if 0 or 1 elements, otherwise use // the spliterator of the spined buffer return (c < 2) ? StreamSupport.doubleStream(this, false) : StreamSupport.doubleStream(buffer.spliterator(), false); } throw new IllegalStateException(); } // Spliterator implementation for 0 or 1 element // count == -1 for no elements // count == -2 for one element held by first @Override public boolean tryAdvance(DoubleConsumer action) { Objects.requireNonNull(action); if (count == -2) { action.accept(first); count = -1; return true; } else { return false; } } @Override public void forEachRemaining(DoubleConsumer action) { Objects.requireNonNull(action); if (count == -2) { action.accept(first); count = -1; } } } abstract static class ConcatSpliterator<T, T_SPLITR extends Spliterator<T>> implements Spliterator<T> { protected final T_SPLITR aSpliterator; protected final T_SPLITR bSpliterator; // True when no split has occurred, otherwise false boolean beforeSplit; // Never read after splitting final boolean unsized; public ConcatSpliterator(T_SPLITR aSpliterator, T_SPLITR bSpliterator) { this.aSpliterator = aSpliterator; this.bSpliterator = bSpliterator; beforeSplit = true; // The spliterator is known to be unsized before splitting if the // sum of the estimates overflows. unsized = aSpliterator.estimateSize() + bSpliterator.estimateSize() < 0; } @Override public T_SPLITR trySplit() { @SuppressWarnings("unchecked") T_SPLITR ret = beforeSplit ? aSpliterator : (T_SPLITR) bSpliterator.trySplit(); beforeSplit = false; return ret; } @Override public boolean tryAdvance(Consumer<? super T> consumer) { boolean hasNext; if (beforeSplit) { hasNext = aSpliterator.tryAdvance(consumer); if (!hasNext) { beforeSplit = false; hasNext = bSpliterator.tryAdvance(consumer); } } else hasNext = bSpliterator.tryAdvance(consumer); return hasNext; } @Override public void forEachRemaining(Consumer<? super T> consumer) { if (beforeSplit) aSpliterator.forEachRemaining(consumer); bSpliterator.forEachRemaining(consumer); } @Override public long estimateSize() { if (beforeSplit) { // If one or both estimates are Long.MAX_VALUE then the sum // will either be Long.MAX_VALUE or overflow to a negative value long size = aSpliterator.estimateSize() + bSpliterator.estimateSize(); return (size >= 0) ? size : Long.MAX_VALUE; } else { return bSpliterator.estimateSize(); } } @Override public int characteristics() { if (beforeSplit) { // Concatenation loses DISTINCT and SORTED characteristics return aSpliterator.characteristics() & bSpliterator.characteristics() & ~(Spliterator.DISTINCT | Spliterator.SORTED | (unsized ? Spliterator.SIZED | Spliterator.SUBSIZED : 0)); } else { return bSpliterator.characteristics(); } } @Override public Comparator<? super T> getComparator() { if (beforeSplit) throw new IllegalStateException(); return bSpliterator.getComparator(); } static class OfRef<T> extends ConcatSpliterator<T, Spliterator<T>> { OfRef(Spliterator<T> aSpliterator, Spliterator<T> bSpliterator) { super(aSpliterator, bSpliterator); } } private static abstract class OfPrimitive<T, T_CONS, T_SPLITR extends Spliterator.OfPrimitive<T, T_CONS, T_SPLITR>> extends ConcatSpliterator<T, T_SPLITR> implements Spliterator.OfPrimitive<T, T_CONS, T_SPLITR> { private OfPrimitive(T_SPLITR aSpliterator, T_SPLITR bSpliterator) { super(aSpliterator, bSpliterator); } @Override public boolean tryAdvance(T_CONS action) { boolean hasNext; if (beforeSplit) { hasNext = aSpliterator.tryAdvance(action); if (!hasNext) { beforeSplit = false; hasNext = bSpliterator.tryAdvance(action); } } else hasNext = bSpliterator.tryAdvance(action); return hasNext; } @Override public void forEachRemaining(T_CONS action) { if (beforeSplit) aSpliterator.forEachRemaining(action); bSpliterator.forEachRemaining(action); } } static class OfInt extends ConcatSpliterator.OfPrimitive<Integer, IntConsumer, Spliterator.OfInt> implements Spliterator.OfInt { OfInt(Spliterator.OfInt aSpliterator, Spliterator.OfInt bSpliterator) { super(aSpliterator, bSpliterator); } } static class OfLong extends ConcatSpliterator.OfPrimitive<Long, LongConsumer, Spliterator.OfLong> implements Spliterator.OfLong { OfLong(Spliterator.OfLong aSpliterator, Spliterator.OfLong bSpliterator) { super(aSpliterator, bSpliterator); } } static class OfDouble extends ConcatSpliterator.OfPrimitive<Double, DoubleConsumer, Spliterator.OfDouble> implements Spliterator.OfDouble { OfDouble(Spliterator.OfDouble aSpliterator, Spliterator.OfDouble bSpliterator) { super(aSpliterator, bSpliterator); } } } /** * Given two Runnables, return a Runnable that executes both in sequence, * even if the first throws an exception, and if both throw exceptions, add * any exceptions thrown by the second as suppressed exceptions of the first. */ static Runnable composeWithExceptions(Runnable a, Runnable b) { return new Runnable() { @Override public void run() { try { a.run(); } catch (Throwable e1) { try { b.run(); } catch (Throwable e2) { try { e1.addSuppressed(e2); } catch (Throwable ignore) {} } throw e1; } b.run(); } }; } /** * Given two streams, return a Runnable that * executes both of their {@link BaseStream#close} methods in sequence, * even if the first throws an exception, and if both throw exceptions, add * any exceptions thrown by the second as suppressed exceptions of the first. */ static Runnable composedClose(BaseStream<?, ?> a, BaseStream<?, ?> b) { return new Runnable() { @Override public void run() { try { a.close(); } catch (Throwable e1) { try { b.close(); } catch (Throwable e2) { try { e1.addSuppressed(e2); } catch (Throwable ignore) {} } throw e1; } b.close(); } }; } }
gpl-2.0
tvidas/OpenLV
cmu/forensics/mbr/PartitionEntry.java
9594
/* PartitionEntry.java Copyright (C) 2006-2008 Carnegie Mellon University Tim Vidas <tvidas at gmail d0t com> Brian Kaplan <bfkaplan at cmu d0t edu> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package cmu.forensics.mbr; /** * ParitionEntry * Represents one of the four partition entries in an MBR * @author Tim Vidas * @author Brian Kaplan * @version 0.7, Jan 2009 */ public class PartitionEntry { private static final int PARTITION_ENTRY_SIZE = 16; private int[] entryBytes; //known type signatures to sanity check validity of the partition entry and mbr private int[] validPartitionTypes = {0x00, 0x10, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0e, 0x0f, 0x10, 0x11, 0x12, 0x14, 0x16, 0x17, 0x18, 0x1b, 0x1c, 0x1e, 0x24, 0x39, 0x3c, 0x40, 0x41, 0x42, 0x4d, 0x4e, 0x4f, 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x5c, 0x61, 0x63, 0x64, 0x65, 0x70, 0x75, 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x8e, 0x93, 0x94, 0x9f, 0xa0, 0xa5, 0xa6, 0xa7, 0xa8, 0xa9, 0xab, 0xb7, 0xb8, 0xbb, 0xbe, 0xbf, 0xc1, 0xc4, 0xc6, 0xc7, 0xda, 0xdb, 0xde, 0xdf, 0xe1, 0xe3, 0xe4, 0xeb, 0xee, 0xef, 0xf0, 0xf1, 0xf4, 0xf2, 0xfd, 0xfe, 0xff}; //structure of parititon table private int state; //byte 1 private int beginHead; //byte 2 private int beginCylinderSector; //byte 3+4 private int partitionType; //byte 5 private int endHead; //byte 6 private int endCylinderSector; //byte 7+8 private long relativeSector; //byte 9+10+11+12 (sectors between mbr and 1st sector of parition) private long numSectors; //byte 13+14+15+16 /** * constructor * @param an integer array of the partition entry */ public PartitionEntry(int[] pe) { if(pe.length == PARTITION_ENTRY_SIZE) entryBytes = pe; else entryBytes = new int[PARTITION_ENTRY_SIZE]; state = entryBytes[0]; beginHead = entryBytes[1]; beginCylinderSector = ((entryBytes[3] << 8) | entryBytes[2]); //combine bytes 3 + 2 (backwards) partitionType = entryBytes[4]; endHead = entryBytes[5]; endCylinderSector =((entryBytes[7] << 8) | entryBytes[6]); //combine bytes 7 + 6 (backwards) relativeSector = ((entryBytes[11] & 0xFF) << 24) //combine bytes 8-11 (backwards) | ((entryBytes[10] & 0xFF) << 16) | ((entryBytes[9] & 0xFF) << 8) | (entryBytes[8] & 0xFF); numSectors = ((entryBytes[15] & 0xFF) << 24) //combine bytes 12-15 (backwards) | ((entryBytes[14] & 0xFF) << 16) | ((entryBytes[13] & 0xFF) << 8) | (entryBytes[12] & 0xFF); } /** * Extract 6 bit sector from Cylinder/Sector 16bit structure * * @param cylSectStructure the cylinder Sector Structure * @return just the sector part of cylSectStructure */ private static int getSector(int cylSectStructure) { return (cylSectStructure & 63); } /** * Extract 10bit cylinder from Cylinder/Sector 16bit structure * * @param cylSectStructure the cylinder Sector Structure * @return just the cylinder part of cylSectStructure */ private static int getCylinder(int cylSectStructure) { int bits8To15 = ((cylSectStructure & 65280) >> 8); int cylinderVal = bits8To15; if((cylSectStructure & 64) != 0) //if the 6th bit of the 16 bit structure is not zero cylinderVal += 256; //set bit 8 of the 10 bit cylinder value if((cylSectStructure & 128) != 0) //if the 7th bit of the 16 bit structure is not zero cylinderVal += 512; //set bit 9 of the 10 bit cylinder value return cylinderVal; } /** * gets the beginning cylinder * @return the beginning cylinder */ public int getBeginCylinder() { return getCylinder(beginCylinderSector); } /** * gets the beginning sector * @return the beginning sector */ public int getBeginSector() { return getSector(beginCylinderSector); } /** * inspector for beginHead * @return the beginHead datamember */ public int getBeginHead() { return beginHead; } /** * gets the end cylinder * @return the end cylinder */ public long getEndCylinder() { return getCylinder(endCylinderSector); } /** * gets the end sector * @return the end sector */ public long getEndSector() { return getSector(endCylinderSector); } /** * inspector for endHead * @return the endHead datamember */ public int getEndHead() { return endHead; } /** * inspector for entryBytes * @return the entryBytes datamember */ public int[] getEntryBytes() { return entryBytes; } /** * inspector for numSectors * @return the numSectors datamember */ public long getNumSectors() { return numSectors; } /** * inspector for partitionType * @return the partitionType datamember */ public int getPartitionType() { return partitionType; } /** * inspector for relativeSector * @return the relativeSector datamember */ public long getRelativeSector() { return relativeSector; } /** * inspector for state * @return the state datamember */ public int getState() { return state; } /** * checks to see if this partition is bootable (has 0x80 state) * @return true if bootable, fales otherwise */ public boolean isBootable() { return state == 0x80; //flag 0x80 means partition is bootable } /** * checks if the partition type is a "known" value so it is really * most useful for checking if something is not valid * * @return true if partition is valid, false otherwise */ public boolean isValidPartition() { for(int i = 0; i < validPartitionTypes.length; i++) { if(validPartitionTypes[i] == partitionType) return true; } return false; } /** * Really only used to check bootable partitions, so not all obscure windows partition type flags are checked * * @return true if it is a known windows partition type, false otherwise */ public boolean isNotWindowsBased() { if( partitionType == 0x07 || //NTFS partitionType == 0x0b || //FAT32 CHS partitionType == 0x0c || //FAT32 LBA partitionType == 0x06 //FAT16 ) return false; //it may be windows based else return true; //can't be windows based } /** * checks if this partition is FAT * * @return true is it's FAT, false otherwise */ public boolean isFAT() { return (partitionType == 0x0b || partitionType == 0x0c || partitionType == 0x06); } /** * checks if this partition is NTFS * * @return true is it's NTFS, false otherwise */ public boolean isNTFS() { return (partitionType == 0x07); } /** * generic toString method that assembles datamembers * @return a formated string */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Is Bootable: " + isBootable() + System.getProperty("line.separator")); sb.append("Begin Head: " + beginHead + System.getProperty("line.separator")); sb.append("Begin Cylinder: " + getCylinder(beginCylinderSector) + System.getProperty("line.separator")); sb.append("Begin Sector: " + getSector(beginCylinderSector) + System.getProperty("line.separator")); sb.append("Partition Type: " + "0x" + Integer.toHexString(partitionType) + System.getProperty("line.separator")); sb.append("End Head: " + endHead + System.getProperty("line.separator")); sb.append("End Cylinder: " + getCylinder(endCylinderSector) + System.getProperty("line.separator")); sb.append("End Sector: " + getSector(endCylinderSector) + System.getProperty("line.separator")); sb.append("Relative Sector: " + relativeSector + System.getProperty("line.separator")); sb.append("Num Sectors: " + numSectors + System.getProperty("line.separator")); return sb.toString(); } }
gpl-2.0
proyecto-adalid/adalid
source/adalid-jee1/src/meta/entidad/comun/control/acceso/RolFuncion.java
7278
/* * Este programa es software libre; usted puede redistribuirlo y/o modificarlo bajo los terminos * de la licencia "GNU General Public License" publicada por la Fundacion "Free Software Foundation". * Este programa se distribuye con la esperanza de que pueda ser util, pero SIN NINGUNA GARANTIA; * vea la licencia "GNU General Public License" para obtener mas informacion. */ package meta.entidad.comun.control.acceso; import adalid.core.AbstractPersistentEntity; import adalid.core.Key; import adalid.core.annotations.Allocation; import adalid.core.annotations.ColumnField; import adalid.core.annotations.EntityClass; import adalid.core.annotations.EntityConsoleView; import adalid.core.annotations.EntityDeleteOperation; import adalid.core.annotations.EntityDetailView; import adalid.core.annotations.EntityInsertOperation; import adalid.core.annotations.EntitySelectOperation; import adalid.core.annotations.EntityTableView; import adalid.core.annotations.EntityTreeView; import adalid.core.annotations.EntityUpdateOperation; import adalid.core.annotations.ForeignKey; import adalid.core.annotations.ManyToOne; import adalid.core.annotations.PrimaryKey; import adalid.core.annotations.PropertyField; import adalid.core.annotations.VersionProperty; import adalid.core.enums.Kleenean; import adalid.core.enums.MasterDetailView; import adalid.core.enums.Navigability; import adalid.core.enums.OnDeleteAction; import adalid.core.enums.OnUpdateAction; import adalid.core.enums.ResourceGender; import adalid.core.enums.ResourceType; import adalid.core.interfaces.Artifact; import adalid.core.interfaces.Check; import adalid.core.interfaces.Segment; import adalid.core.properties.BooleanProperty; import adalid.core.properties.LongProperty; import java.lang.reflect.Field; import meta.entidad.comun.configuracion.basica.Funcion; import meta.proyecto.base.ProyectoBase; /** * @author Jorge Campins */ @EntityClass(independent = Kleenean.FALSE, resourceType = ResourceType.OPERATION, resourceGender = ResourceGender.FEMININE) @EntitySelectOperation(enabled = Kleenean.TRUE) @EntityInsertOperation(enabled = Kleenean.TRUE) @EntityUpdateOperation(enabled = Kleenean.TRUE) @EntityDeleteOperation(enabled = Kleenean.TRUE) @EntityTableView(enabled = Kleenean.FALSE) @EntityDetailView(enabled = Kleenean.FALSE) @EntityTreeView(enabled = Kleenean.FALSE) @EntityConsoleView(enabled = Kleenean.FALSE) public class RolFuncion extends AbstractPersistentEntity { // <editor-fold defaultstate="collapsed" desc="class constructors"> @Deprecated private RolFuncion() { this(null, null); } public RolFuncion(Artifact declaringArtifact, Field declaringField) { super(declaringArtifact, declaringField); } // </editor-fold> @PrimaryKey public LongProperty idRolFuncion; @VersionProperty public LongProperty versionRolFuncion; @ForeignKey(onDelete = OnDeleteAction.CASCADE, onUpdate = OnUpdateAction.CASCADE) @ManyToOne(navigability = Navigability.BIDIRECTIONAL, view = MasterDetailView.TABLE) @ColumnField(nullable = Kleenean.FALSE) @PropertyField(required = Kleenean.TRUE, table = Kleenean.TRUE, report = Kleenean.TRUE) @Allocation(maxDepth = 1, maxRound = 0) public Rol idRol; @ForeignKey(onDelete = OnDeleteAction.CASCADE, onUpdate = OnUpdateAction.CASCADE) @ManyToOne(navigability = Navigability.UNIDIRECTIONAL, view = MasterDetailView.NONE) @ColumnField(nullable = Kleenean.FALSE) @PropertyField(required = Kleenean.TRUE, table = Kleenean.TRUE, report = Kleenean.TRUE) @Allocation(maxDepth = 2, maxRound = 0) public Funcion idFuncion; @ForeignKey(onDelete = OnDeleteAction.CASCADE, onUpdate = OnUpdateAction.CASCADE) @ManyToOne(navigability = Navigability.UNIDIRECTIONAL, view = MasterDetailView.NONE) @PropertyField(required = Kleenean.FALSE, table = Kleenean.TRUE, report = Kleenean.TRUE, create = Kleenean.TRUE) @Allocation(maxDepth = 1, maxRound = 0) public ConjuntoSegmento idConjuntoSegmento; @ColumnField(nullable = Kleenean.FALSE) @PropertyField(required = Kleenean.FALSE, table = Kleenean.TRUE, report = Kleenean.TRUE, create = Kleenean.TRUE) public BooleanProperty esAccesoPersonalizado; @ColumnField(nullable = Kleenean.FALSE) @PropertyField(required = Kleenean.FALSE, table = Kleenean.TRUE, report = Kleenean.TRUE, create = Kleenean.TRUE) public BooleanProperty esTarea; protected Key uk_rol_funcion_0001; public Segment modificables; // protected Check checkAccesoPersonalizado; // protected Check checkFuncionPersonalizada; protected Check checkFuncionSegmentada; protected Check checkTipoFuncionTarea; @Override protected void settleAttributes() { super.settleAttributes(); setSchema(ProyectoBase.getEsquemaEntidadesComunes()); setDefaultLabel("asociación Rol/Función"); setDefaultCollectionLabel("Asociaciones Rol/Función"); // setDefaultLabel(idRol, "función por rol"); // setDefaultShortLabel(idRol, "función"); setDefaultCollectionLabel(idRol, "Funciones por Rol"); setDefaultCollectionShortLabel(idRol, "Funciones"); } @Override protected void settleProperties() { super.settleProperties(); esAccesoPersonalizado.setInitialValue(idFuncion.esPersonalizable); esAccesoPersonalizado.setDefaultValue(idFuncion.esPersonalizable); esTarea.setInitialValue(false); esTarea.setDefaultValue(idFuncion.numeroTipoFuncion.isEqualTo(idFuncion.numeroTipoFuncion.PROCESO).then(true).otherwise(false)); } @Override protected void settleKeys() { super.settleKeys(); uk_rol_funcion_0001.setUnique(true); uk_rol_funcion_0001.newKeyField(idRol, idFuncion); } @Override protected void settleExpressions() { super.settleExpressions(); modificables = idRol.idRol.isGreaterOrEqualTo(10000L); modificables.setDefaultErrorMessage("el rol es un rol de configuración básica del sistema; " + "no se permite modificar ni eliminar sus funciones"); setInsertFilter(idRol.modificables); setUpdateFilter(modificables); setDeleteFilter(modificables); // checkAccesoPersonalizado = esAccesoPersonalizado.isNotNull(); // checkAccesoPersonalizado.setDefaultErrorMessage("la opción de acceso personalizado no tiene valor"); checkFuncionPersonalizada = idFuncion.esPersonalizable.isFalse().implies(esAccesoPersonalizado.isNullOrFalse()); checkFuncionPersonalizada.setDefaultErrorMessage("la función no permite acceso personalizado"); checkFuncionSegmentada = idFuncion.esSegmentable.isFalse().implies(idConjuntoSegmento.isNull()); checkFuncionSegmentada.setDefaultErrorMessage("la función no permite acceso segmentado"); checkTipoFuncionTarea = idFuncion.numeroTipoFuncion.isNullOrNotEqualTo(idFuncion.numeroTipoFuncion.PROCESO).implies(esTarea.isFalse()); checkTipoFuncionTarea.setDefaultErrorMessage("solo los procesos de negocio pueden ser tareas"); } }
gpl-2.0
calipho-sib/nextprot-api
isoform-mapper/src/main/java/org/nextprot/api/isoform/mapper/utils/SequenceVariantUtils.java
745
package org.nextprot.api.isoform.mapper.utils; import java.util.regex.Matcher; import java.util.regex.Pattern; public class SequenceVariantUtils { // TODO: It is false as isoform name can be of "non-iso" format (ex: GTBP-N for NX_P52701) public static boolean isIsoSpecific(String featureName) { if(featureName != null){ return featureName.toLowerCase().contains("iso"); }else return false; } // TODO: Also false for the same reason as above public static String getIsoformName(String featureName) { if(isIsoSpecific(featureName)){ Pattern p = Pattern.compile("\\w+-iso(\\w+)-p.+"); Matcher m = p.matcher(featureName); if (m.find()) { return String.valueOf(m.group(1)); } } return null; } }
gpl-2.0
gburca/VirtMus
VirtMus/src/com/ebixio/virtmus/PlayListSet.java
15300
/* * Copyright (C) 2006-2014 Gabriel Burca (gburca dash virtmus at ebixio dot com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package com.ebixio.virtmus; import com.ebixio.util.Log; import com.ebixio.util.PropertyChangeSupportUnique; import com.ebixio.util.WeakPropertyChangeListener; import com.ebixio.virtmus.options.Options; import com.ebixio.virtmus.stats.StatsLogger; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.File; import java.io.FilenameFilter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.logging.Level; import java.util.logging.LogRecord; import java.util.prefs.PreferenceChangeEvent; import java.util.prefs.PreferenceChangeListener; import java.util.prefs.Preferences; import javax.swing.JOptionPane; import org.openide.util.NbPreferences; /** * The set of all the PlayLists that VirtMus knows about. * @author Gabriel Burca &lt;gburca dash virtmus at ebixio dot com&gt; */ public class PlayListSet implements PreferenceChangeListener, PropertyChangeListener { private static PlayListSet instance; public final List<PlayList> playLists = Collections.synchronizedList(new ArrayList<PlayList>()); /** If this is true, {@link #PROP_ALL_PL_LOADED} has already been fired. */ public Boolean allPlayListsLoaded = new Boolean(false); private int playListsLoading = 0; private PropertyChangeSupportUnique propertyChangeSupport; private final Object pcsMutex = new Object(); /** The property fired when all PlayLists have been loaded */ public static final String PROP_ALL_PL_LOADED = "allPlayListsLoaded"; /** The property fired when all songs have been loaded */ public static final String PROP_ALL_SONGS_LOADED= "allSongsLoaded"; /** The property fired when a new PlayList has been added */ public static final String PROP_NEW_PL_ADDED = "newPlayListAdded"; /** The property fired when a PlayList has been deleted */ public static final String PROP_PL_DELETED = "playListDeleted"; private PlayListSet() { } private void init() { Preferences pref = NbPreferences.forModule(MainApp.class); pref.addPreferenceChangeListener(this); propertyChangeSupport = new PropertyChangeSupportUnique(this); addAllPlayLists(false); } /** * @return A new PlayListSet instance. */ public static synchronized PlayListSet findInstance() { if (instance == null) { instance = new PlayListSet(); instance.init(); } return instance; } public boolean isDirty() { synchronized (playLists) { for (PlayList pl : playLists) { if (pl.isDirty()) { Log.log("Dirty PlayList: " + pl.getName()); return true; } synchronized (pl.songs) { for (Song s : pl.songs) { if (s.isDirty()) { Log.log("Dirty Song: " + s.getName()); return true; } } } } } return false; } public void saveAll() { synchronized(playLists) { for (PlayList pl: playLists) pl.saveAll(); } MainApp.setStatusText("Save All finished."); } public boolean replacePlayList(PlayList replace, PlayList with) { synchronized (playLists) { int idx = playLists.lastIndexOf(replace); if (idx < 0) { return false; } else { playLists.remove(idx); playLists.add(idx, with); this.fire(PROP_NEW_PL_ADDED, replace, with); return true; } } } /** Adds a new PlayList to the set. * @param pl The PlayList to add * @return true if it was successfully added (if not null). */ public boolean addPlayList(PlayList pl) { if (pl != null) { playLists.add(pl); this.fire(PROP_NEW_PL_ADDED, null, pl); return true; } return false; } public boolean deletePlayList(PlayList pl) { if (pl.type != PlayList.Type.Normal || pl.getSourceFile() == null) return false; playLists.remove(pl); try { if (pl.getSourceFile().delete()) { fire(PROP_PL_DELETED, pl, null); return true; } } catch (Exception e) { // Ignore exception } return false; } public PlayList getPlayList(PlayList.Type type) { if (type == PlayList.Type.Default) { return playLists.get(0); } else if (type == PlayList.Type.AllSongs) { return playLists.get(1); } else { return null; } } /** * Finds all the PlayLists on disk and loads them. * @param clearSongs If true, discards all songs so they get re-loaded when * the PlayList is re-created. This would effectively refresh everything. */ public void addAllPlayLists(final boolean clearSongs) { MainApp.setStatusText("Re-loading all PlayLists"); Thread t = new AddPlayLists(NbPreferences.forModule(MainApp.class), clearSongs); t.start(); } @Override public void preferenceChange(PreferenceChangeEvent evt) { switch (evt.getKey()) { case Options.OptSongDir: Log.log("Preference SongDir changed"); /* We need the synchronization because we could be in the middle of AddPlayLists.run() when the preferences are changed, and playLists.get(1) might not exist yet (or might be something other than AllSongs). */ synchronized(AddPlayLists.class) { if (!promptForSave("Save all changes before loading new song directory?")) return; playLists.get(1).addAllSongs(new File(evt.getNewValue()), true); } break; case Options.OptPlayListDir: addAllPlayLists(false); break; } } /** * * @param msg * @return false if user selected "Cancel" */ private boolean promptForSave(String msg) { if (isDirty()) { int returnVal = JOptionPane.showConfirmDialog(null, "You have unsaved changes. " + msg, "Changes exist in currently loaded playlists or songs.", JOptionPane.YES_NO_CANCEL_OPTION); switch (returnVal) { case JOptionPane.YES_OPTION: saveAll(); break; case JOptionPane.CANCEL_OPTION: return false; case JOptionPane.NO_OPTION: default: break; } } return true; } // <editor-fold defaultstate="collapsed" desc=" Property Change Listener "> /** Listeners will be notified of any changes to the set of PlayLists. * @param pcl A property change listener to add */ public void addPropertyChangeListener (PropertyChangeListener pcl) { synchronized(pcsMutex) { propertyChangeSupport.addPropertyChangeListener(pcl); } } /** Listeners will be notified of changes to the set of PlayLists. * @param propertyName A property such as * {@link #PROP_NEW_PL_ADDED}, {@link #PROP_PL_DELETED}, * {@link #PROP_ALL_PL_LOADED}, or {@link #PROP_ALL_SONGS_LOADED}. * @param pcl The property change listener to be notified when the given * property changes. */ public void addPropertyChangeListener(String propertyName, PropertyChangeListener pcl) { synchronized(pcsMutex) { propertyChangeSupport.addPropertyChangeListener(propertyName, pcl); } } public void removePropertyChangeListener(PropertyChangeListener pcl) { synchronized(pcsMutex) { propertyChangeSupport.removePropertyChangeListener(pcl); } } private void fire(String propertyName, Object old, Object nue) { synchronized(pcsMutex) { propertyChangeSupport.firePropertyChange(propertyName, old, nue); } } // </editor-fold> /** * Monitors PlayList loading. Only after ALL PlayLists have finished loading * their songs do we fire "all songs loaded". * @param evt A PlayList property change event */ @Override public void propertyChange(PropertyChangeEvent evt) { if (evt.getPropertyName() == null) return; switch (evt.getPropertyName()) { case PlayList.PROP_LOADED: if ((boolean)evt.getNewValue()) { decrPlayListsLoading(); if (getPlayListsLoading() == 0) { fire(PROP_ALL_SONGS_LOADED, false, true); } } break; } } // <editor-fold defaultstate="collapsed" desc=" PlayList loading count "> /** * Call this every time a PlayList starts loading. */ public synchronized void incrPlayListsLoading() { playListsLoading += 1; } /** * Call this every time a PlayList finished loading. */ public synchronized void decrPlayListsLoading() { playListsLoading -= 1; } /** * This tell us if there are any PlayLists still loading. * @return The number of PlayLists currently being loaded. */ public synchronized int getPlayListsLoading() { return playListsLoading; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc=" Filesystem moves "> /** Update PlayLists so they all point to the new song. * * A PlayList could reference the same song more than once. * @param oldS The old location of the song file * @param newS The new location of the song file * @return The number of PlayLists that were impacted by the move. */ public int movedSong(File oldS, File newS) { int updated = 0; for (PlayList pl: PlayListSet.findInstance().playLists) { for (Song s: pl.songs) { if (s.getSourceFile() != null && s.getSourceFile().equals(oldS)) { s.setSourceFile(newS); updated++; } } pl.save(); // Only saves if isDirty } return updated; } /** Update Songs so they all point to the new location of a PDF file. * * @param oldPdf The old location of the PDF file * @param newPdf The new location of the PDF file * @return The number of songs that were impacted by the move. */ public int movedPdf(File oldPdf, File newPdf) { int updated = 0; for (PlayList pl: PlayListSet.findInstance().playLists) { for (Song s: pl.songs) { boolean needsSave = false; for (MusicPage mp: s.pageOrder) { if (mp.imgSrc.getSourceFile().equals(oldPdf)) { mp.imgSrc.setSourceFile(newPdf); needsSave = true; } } if (needsSave) { s.save(); updated++; } } } return updated; } // </editor-fold> class AddPlayLists extends Thread { Preferences pref; boolean clearSongs; public AddPlayLists(Preferences pref, boolean clearSongs) { this.pref = pref; this.clearSongs = clearSongs; setName("addPlayLists"); setPriority(Thread.MIN_PRIORITY); } @Override public void run() { PlayList pl; // Syncrhonized to block re-loads if there is one in progress synchronized (AddPlayLists.class) { if (!promptForSave("Save all changes before loading new playlists?")) return; playLists.clear(); // Discard all the songs so they get re-loaded when the playlist is re-created if (clearSongs) Song.clearInstantiated(); pl = new PlayList("Default Play List"); pl.type = PlayList.Type.Default; playLists.add(pl); fire(PROP_NEW_PL_ADDED, null, pl); File dir = new File(pref.get(Options.OptPlayListDir, "")); if (dir.exists() && dir.canRead() && dir.isDirectory()) { FilenameFilter filter = new FilenameFilter() { @Override public boolean accept(File dir, String name) { return name.endsWith(".playlist.xml"); } }; for (File f : Utils.listFiles(dir, filter, true)) { incrPlayListsLoading(); pl = PlayList.deserialize(f, new WeakPropertyChangeListener(PlayListSet.this, pl)); if (pl == null) { decrPlayListsLoading(); } else { playLists.add(pl); fire(PROP_NEW_PL_ADDED, null, pl); } } } pl = new PlayList("All Songs"); pl.type = PlayList.Type.AllSongs; incrPlayListsLoading(); pl.addPropertyChangeListener(PlayList.PROP_LOADED, new WeakPropertyChangeListener(PlayListSet.this, pl)); pl.addAllSongs(new File(pref.get(Options.OptSongDir, "")), true); playLists.add(pl); fire(PROP_NEW_PL_ADDED, null, pl); LogRecord rec = new LogRecord(Level.INFO, "VirtMus PlayLists"); rec.setParameters(new Object[] {playLists.size()}); StatsLogger.getLogger().log(rec); Collections.sort(playLists); synchronized(allPlayListsLoaded) { // They're not fully loaded until their songs are also loaded. fire(PROP_ALL_PL_LOADED, null, playLists); allPlayListsLoaded = true; } MainApp.setStatusText("Finished loading all PlayLists"); } } } }
gpl-2.0
jMotif/sax-vsm_classic
src/main/java/net/seninp/jmotif/direct/TfIdfEntryComparator.java
582
package net.seninp.jmotif.direct; /** * An entry comparator. * * The direct code was taken from JCOOL (Java COntinuous Optimization Library), and altered for * SAX-VSM needs. * * @see <a href="https://github.com/dhonza/JCOOL/wiki">https://github.com/dhonza/JCOOL/wiki</a> * */ import java.util.Comparator; import java.util.Map.Entry; public class TfIdfEntryComparator implements Comparator<Entry<String, Double>> { @Override public int compare(Entry<String, Double> arg0, Entry<String, Double> arg1) { return -arg0.getValue().compareTo(arg1.getValue()); } }
gpl-2.0
hdadler/sensetrace-src
com.ipv.sensetrace.RDFDatamanager/jena-2.11.0/jena-tdb/src/main/java/com/hp/hpl/jena/tdb/index/TupleIndexRecord.java
8048
/* * 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 com.hp.hpl.jena.tdb.index; import static com.hp.hpl.jena.tdb.sys.SystemTDB.SizeOfNodeId; import static java.lang.String.format; import java.util.Iterator; import org.apache.jena.atlas.iterator.* ; import org.apache.jena.atlas.lib.Bytes ; import org.apache.jena.atlas.lib.ColumnMap ; import org.apache.jena.atlas.lib.Tuple ; import com.hp.hpl.jena.tdb.TDBException; import com.hp.hpl.jena.tdb.base.record.Record; import com.hp.hpl.jena.tdb.base.record.RecordFactory; import com.hp.hpl.jena.tdb.lib.TupleLib; import com.hp.hpl.jena.tdb.store.NodeId; public class TupleIndexRecord extends TupleIndexBase { private static final boolean Check = false ; private RangeIndex index ; private RecordFactory factory ; public TupleIndexRecord(int N, ColumnMap colMapping, String name, RecordFactory factory, RangeIndex index) { super(N, colMapping, name) ; this.factory = factory ; this.index = index ; if ( factory.keyLength() != N*SizeOfNodeId) throw new TDBException(format("Mismatch: TupleIndex of length %d is not comparative with a factory for key length %d", N, factory.keyLength())) ; } /** Insert a tuple - return true if it was really added, false if it was a duplicate */ @Override protected boolean performAdd(Tuple<NodeId> tuple) { Record r = TupleLib.record(factory, tuple, colMap) ; return index.add(r) ; } /** Delete a tuple - return true if it was deleted, false if it didn't exist */ @Override protected boolean performDelete(Tuple<NodeId> tuple) { Record r = TupleLib.record(factory, tuple, colMap) ; return index.delete(r) ; } /** Find all matching tuples - a slot of NodeId.NodeIdAny (or null) means match any. * Input pattern in natural order, not index order. */ @Override protected Iterator<Tuple<NodeId>> performFind(Tuple<NodeId> pattern) { return findOrScan(pattern) ; } // Package visibility for testing. final Iterator<Tuple<NodeId>> findOrScan(Tuple<NodeId> pattern) { return findWorker(pattern, true, true) ; } final Iterator<Tuple<NodeId>> findOrPartialScan(Tuple<NodeId> pattern) { return findWorker(pattern, true, false) ; } final Iterator<Tuple<NodeId>> findByIndex(Tuple<NodeId> pattern) { return findWorker(pattern, false, false) ; } private Iterator<Tuple<NodeId>> findWorker(Tuple<NodeId> patternNaturalOrder, boolean partialScanAllowed, boolean fullScanAllowed) { if ( Check ) { if ( tupleLength != patternNaturalOrder.size() ) throw new TDBException(String.format("Mismatch: tuple length %d / index for length %d", patternNaturalOrder.size(), tupleLength)) ; } // Convert to index order. Tuple<NodeId> pattern = colMap.map(patternNaturalOrder) ; // Canonical form. int numSlots = 0 ; int leadingIdx = -2; // Index of last leading pattern NodeId. Start less than numSlots-1 boolean leading = true ; // Records. Record minRec = factory.createKeyOnly() ; Record maxRec = factory.createKeyOnly() ; // Set the prefixes. for ( int i = 0 ; i < pattern.size() ; i++ ) { NodeId X = pattern.get(i) ; if ( NodeId.isAny(X) ) { X = null ; // No longer seting leading key slots. leading = false ; continue ; } numSlots++ ; if ( leading ) { leadingIdx = i ; Bytes.setLong(X.getId(), minRec.getKey(), i*SizeOfNodeId) ; Bytes.setLong(X.getId(), maxRec.getKey(), i*SizeOfNodeId) ; } } // Is it a simple existence test? if ( numSlots == pattern.size() ) { if ( index.contains(minRec) ) return new SingletonIterator<Tuple<NodeId>>(pattern) ; else return new NullIterator<Tuple<NodeId>>() ; } Iterator<Record> iter = null ; if ( leadingIdx < 0 ) { if ( ! fullScanAllowed ) return null ; //System.out.println("Full scan") ; // Full scan necessary iter = index.iterator() ; } else { // Adjust the maxRec. NodeId X = pattern.get(leadingIdx) ; // Set the max Record to the leading NodeIds, +1. // Example, SP? inclusive to S(P+1)? exclusive where ? is zero. Bytes.setLong(X.getId()+1, maxRec.getKey(), leadingIdx*SizeOfNodeId) ; iter = index.iterator(minRec, maxRec) ; } Iterator<Tuple<NodeId>> tuples = Iter.map(iter, transformToTuple) ; if ( leadingIdx < numSlots-1 ) { if ( ! partialScanAllowed ) return null ; // Didn't match all defined slots in request. // Partial or full scan needed. //pattern.unmap(colMap) ; tuples = scan(tuples, patternNaturalOrder) ; } return tuples ; } @Override public Iterator<Tuple<NodeId>> all() { Iterator<Record> iter = index.iterator() ; return Iter.map(iter, transformToTuple) ; } private Transform<Record, Tuple<NodeId>> transformToTuple = new Transform<Record, Tuple<NodeId>>() { @Override public Tuple<NodeId> convert(Record item) { return TupleLib.tuple(item, colMap) ; } } ; private Iterator<Tuple<NodeId>> scan(Iterator<Tuple<NodeId>> iter, final Tuple<NodeId> pattern) { Filter<Tuple<NodeId>> filter = new Filter<Tuple<NodeId>>() { @Override public boolean accept(Tuple<NodeId> item) { // Check on pattern and item (both in natural order) for ( int i = 0 ; i < tupleLength ; i++ ) { NodeId n = pattern.get(i) ; // The pattern must be null/Any or match the tuple being tested. if ( ! NodeId.isAny(n) ) if ( ! item.get(i).equals(n) ) return false ; } return true ; } } ; return Iter.filter(iter, filter) ; } @Override public void close() { index.close(); } @Override public void sync() { index.sync() ; } public final RangeIndex getRangeIndex() { return index ; } //protected final RecordFactory getRecordFactory() { return factory ; } @Override public boolean isEmpty() { return index.isEmpty() ; } @Override public void clear() { index.clear() ; } @Override public long size() { return index.size() ; } }
gpl-2.0
Megacrafter127/MSBE
src/m127/smd2e/frontend/BlockChooserMenuConstructor.java
962
package m127.smd2e.frontend; import java.awt.event.ActionListener; import javax.swing.JMenu; import javax.swing.JMenuItem; import m127.smd2e.Main; import m127.smd2e.backend.Block; import m127.smd2e.backend.util.BlockGroup; public class BlockChooserMenuConstructor { public static JMenu construct(BlockGroup g, ActionListener actionListener, boolean hasEmpty) { JMenu ret=new JMenu(g.name==null?"Blocks":g.name); if(hasEmpty) { JMenuItem j=new JMenuItem("No block"); j.addActionListener(actionListener); j.setActionCommand("0"); ret.add(j); } ret.addSeparator(); for(BlockGroup gr:g.children) { ret.add(construct(gr,actionListener,false)); } ret.addSeparator(); JMenuItem j; Main m=Main.getInstance(); for(Block b:g.blocks) { j=new JMenuItem("["+b.id+"] "+b.name,m.iregister.getImage(b.iid)); j.setActionCommand(Integer.toString(b.id)); j.addActionListener(actionListener); ret.add(j); } return ret; } }
gpl-2.0
pioalpha/Pomona
src/main/java/com/github/pomona/domain/model/AlimentoRepo.java
242
package com.github.pomona.domain.model; import com.github.common.domain.model.GenericoRepo; public interface AlimentoRepo extends GenericoRepo<AlimentoUnitario, AlimentoId> { public AlimentoUnitario alimentoPeloNome(String nome); }
gpl-2.0
andykuo1/mcplus_mods
java/net/minecraftplus/mcp_glowing_slime/_CommonProxy.java
339
package net.minecraftplus.mcp_glowing_slime; import net.minecraftplus._api.MCS; import net.minecraftplus._api.base.Proxy; public class _CommonProxy extends Proxy { @Override public void Initialize() { MCS.entity(EntityGlowingSlimeball.class, "GlowingSlimeball", 0, _Glowing_Slime.INSTANCE, 80, 10, true); super.Initialize(); } }
gpl-2.0
skyforce77/TowerMiner
src/fr/skyforce77/towerminer/api/PluginInfo.java
516
package fr.skyforce77.towerminer.api; import java.util.Map; public class PluginInfo { private Map<?,?> map; public PluginInfo(Map<?,?> map) { this.map = map; } public String getName() { return map.get("name").toString(); } public String getVersion() { return map.get("version").toString(); } public String getMain() { return map.get("main").toString(); } public String getValue(String value) { return map.get(value).toString(); } public Map<?, ?> getMap() { return map; } }
gpl-2.0
CaracalDB/CaracalDB
core/src/main/java/se/sics/caracaldb/paxos/PaxosInit.java
1489
/* * This file is part of the CaracalDB distributed storage system. * * Copyright (C) 2009 Swedish Institute of Computer Science (SICS) * Copyright (C) 2009 Royal Institute of Technology (KTH) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ package se.sics.caracaldb.paxos; import se.sics.caracaldb.Address; import se.sics.caracaldb.View; import se.sics.kompics.Init; /** * * @author Lars Kroll <lkroll@sics.se> */ public class PaxosInit extends Init<Paxos> { public final View view; public final int quorum; public final long networkBound; public final Address self; public PaxosInit(View v, int quorum, long networkBound, Address self) { this.view = v; this.quorum = quorum; this.networkBound = networkBound; this.self = self; } }
gpl-2.0
BIORIMP/biorimp
BIO-RIMP/test_data/code/jhotdraw/src/main/java/org/jhotdraw/io/Base64.java
53386
package org.jhotdraw.io; /** * Encodes and decodes to and from Base64 notation. * * <p> * Change Log: * </p> * <ul> * <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added * some convenience methods for reading and writing to and from files.</li> * <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems * with other encodings (like EBCDIC).</li> * <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the * encoded data was a single byte.</li> * <li>v2.0 - I got rid of methods that used booleans to set options. * Now everything is more consolidated and cleaner. The code now detects * when data that's being decoded is gzip-compressed and will decompress it * automatically. Generally things are cleaner. You'll probably have to * change some method calls that you were making to support the new * options format (<tt>int</tt>s that you "OR" together).</li> * <li>v1.5.1 - Fixed bug when decompressing and decoding to a * byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>. * Added the ability to "suspend" encoding in the Output Stream so * you can turn on and off the encoding if you need to embed base64 * data in an otherwise "normal" stream (like an XML file).</li> * <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself. * This helps when using GZIP streams. * Added the ability to GZip-compress objects before encoding them.</li> * <li>v1.4 - Added helper methods to read/write files.</li> * <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li> * <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream * where last buffer being read, if not completely full, was not returned.</li> * <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li> * <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li> * </ul> * * <p> * I am placing this code in the Public Domain. Do with it as you will. * This software comes with no guarantees or warranties but with * plenty of well-wishing instead! * Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a> * periodically to check for updates or to contribute improvements. * </p> * * @author Robert Harder * @author rob@iharder.net * @version 2.1 */ public class Base64 { /* ******** P U B L I C F I E L D S ******** */ /** No options specified. Value is zero. */ public final static int NO_OPTIONS = 0; /** Specify encoding. */ public final static int ENCODE = 1; /** Specify decoding. */ public final static int DECODE = 0; /** Specify that data should be gzip-compressed. */ public final static int GZIP = 2; /** Don't break lines when encoding (violates strict Base64 specification) */ public final static int DONT_BREAK_LINES = 8; /* ******** P R I V A T E F I E L D S ******** */ /** Maximum line length (76) of Base64 output. */ private final static int MAX_LINE_LENGTH = 76; /** The equals sign (=) as a byte. */ private final static byte EQUALS_SIGN = (byte)'='; /** The new line character (\n) as a byte. */ private final static byte NEW_LINE = (byte)'\n'; /** Preferred encoding. */ private final static String PREFERRED_ENCODING = "UTF-8"; /** The 64 valid Base64 values. */ private final static byte[] ALPHABET; private final static byte[] _NATIVE_ALPHABET = /* May be something funny like EBCDIC */ { (byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G', (byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N', (byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U', (byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z', (byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g', (byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n', (byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u', (byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z', (byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5', (byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/' }; /** Determine which ALPHABET to use. */ static { byte[] __bytes; try { __bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes( PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException use) { __bytes = _NATIVE_ALPHABET; // Fall back to native encoding } // end catch ALPHABET = __bytes; } // end static /** * Translates a Base64 value to either its 6-bit reconstruction value * or a negative number indicating some other meaning. **/ private final static byte[] DECODABET = { -9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8 -5,-5, // Whitespace: Tab and Linefeed -9,-9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26 -9,-9,-9,-9,-9, // Decimal 27 - 31 -5, // Whitespace: Space -9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9,-9,-9, // Decimal 44 - 46 63, // Slash at decimal 47 52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine -9,-9,-9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9,-9,-9, // Decimal 62 - 64 0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N' 14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z' -9,-9,-9,-9,-9,-9, // Decimal 91 - 96 26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm' 39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z' -9,-9,-9,-9 // Decimal 123 - 126 /*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }; // I think I end up not using the BAD_ENCODING indicator. //private final static byte BAD_ENCODING = -9; // Indicates error in encoding private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding /** Defeats instantiation. */ private Base64(){} /* ******** E N C O D I N G M E T H O D S ******** */ /** * Encodes up to the first three bytes of array <var>threeBytes</var> * and returns a four-byte array in Base64 notation. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * The array <var>threeBytes</var> needs only be as big as * <var>numSigBytes</var>. * Code can reuse a byte array by passing a four-byte array as <var>b4</var>. * * @param b4 A reusable byte array to reduce array instantiation * @param threeBytes the array to convert * @param numSigBytes the number of significant bytes in your array * @return four byte array in Base64 notation. * @since 1.5.1 */ private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes ) { encode3to4( threeBytes, 0, numSigBytes, b4, 0 ); return b4; } // end encode3to4 /** * Encodes up to three bytes of the array <var>source</var> * and writes the resulting four Base64 bytes to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 3 for * the <var>source</var> array or <var>destOffset</var> + 4 for * the <var>destination</var> array. * The actual number of significant bytes in your array is * given by <var>numSigBytes</var>. * * @param source the array to convert * @param srcOffset the index where conversion begins * @param numSigBytes the number of significant bytes in your array * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the <var>destination</var> array * @since 1.3 */ private static byte[] encode3to4( byte[] source, int srcOffset, int numSigBytes, byte[] destination, int destOffset ) { // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 ) | ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 ) | ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 ); switch( numSigBytes ) { case 3: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ]; return destination; case 2: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ]; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; case 1: destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ]; destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ]; destination[ destOffset + 2 ] = EQUALS_SIGN; destination[ destOffset + 3 ] = EQUALS_SIGN; return destination; default: return destination; } // end switch } // end encode3to4 /** * Serializes an object and returns the Base64-encoded * version of that serialized object. If the object * cannot be serialized or there is another error, * the method will return <tt>null</tt>. * The object is not GZip-compressed before being encoded. * * @param serializableObject The object to encode * @return The Base64-encoded object * @since 1.4 */ public static String encodeObject( java.io.Serializable serializableObject ) { return encodeObject( serializableObject, NO_OPTIONS ); } // end encodeObject /** * Serializes an object and returns the Base64-encoded * version of that serialized object. If the object * cannot be serialized or there is another error, * the method will return <tt>null</tt>. * <p> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeObject( myObj, Base64.GZIP )</code> or * <p> * Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * * @param serializableObject The object to encode * @param options Specified options * @return The Base64-encoded object * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeObject( java.io.Serializable serializableObject, int options ) { // Streams java.io.ByteArrayOutputStream baos = null; java.io.OutputStream b64os = null; java.io.ObjectOutputStream oos = null; java.util.zip.GZIPOutputStream gzos = null; // Isolate options int gzip = (options & GZIP); int dontBreakLines = (options & DONT_BREAK_LINES); try { // ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines ); // GZip? if( gzip == GZIP ) { gzos = new java.util.zip.GZIPOutputStream( b64os ); oos = new java.io.ObjectOutputStream( gzos ); } // end if: gzip else oos = new java.io.ObjectOutputStream( b64os ); oos.writeObject( serializableObject ); } // end try catch( java.io.IOException e ) { e.printStackTrace(); return null; } // end catch finally { try{ oos.close(); } catch( Exception e ){} try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); } // end catch } // end encode /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @since 1.4 */ public static String encodeBytes( byte[] source ) { return encodeBytes( source, 0, source.length, NO_OPTIONS ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * * * @param source The data to convert * @param options Specified options * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeBytes( byte[] source, int options ) { return encodeBytes( source, 0, source.length, options ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * Does not GZip-compress data. * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @since 1.4 */ public static String encodeBytes( byte[] source, int off, int len ) { return encodeBytes( source, off, len, NO_OPTIONS ); } // end encodeBytes /** * Encodes a byte array into Base64 notation. * <p> * Valid options:<pre> * GZIP: gzip-compresses object before encoding it. * DONT_BREAK_LINES: don't break lines at 76 characters * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>encodeBytes( myData, Base64.GZIP )</code> or * <p> * Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code> * * * @param source The data to convert * @param off Offset in array where conversion should begin * @param len Length of data to convert * @param options Specified options * @see Base64#GZIP * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public static String encodeBytes( byte[] source, int off, int len, int options ) { // Isolate options int dontBreakLines = ( options & DONT_BREAK_LINES ); int gzip = ( options & GZIP ); // Compress? if( gzip == GZIP ) { java.io.ByteArrayOutputStream baos = null; java.util.zip.GZIPOutputStream gzos = null; Base64.OutputStream b64os = null; try { // GZip -> Base64 -> ByteArray baos = new java.io.ByteArrayOutputStream(); b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines ); gzos = new java.util.zip.GZIPOutputStream( b64os ); gzos.write( source, off, len ); gzos.close(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); return null; } // end catch finally { try{ gzos.close(); } catch( Exception e ){} try{ b64os.close(); } catch( Exception e ){} try{ baos.close(); } catch( Exception e ){} } // end finally // Return value according to relevant encoding. try { return new String( baos.toByteArray(), PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( baos.toByteArray() ); } // end catch } // end if: compress // Else, don't compress. Better not to use streams at all then. else { // Convert option to boolean in way that code likes it. boolean breakLines = dontBreakLines == 0; int len43 = len * 4 / 3; byte[] outBuff = new byte[ ( len43 ) // Main 4:3 + ( (len % 3) > 0 ? 4 : 0 ) // Account for padding + (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for( ; d < len2; d+=3, e+=4 ) { encode3to4( source, d+off, 3, outBuff, e ); lineLength += 4; if( breakLines && lineLength == MAX_LINE_LENGTH ) { outBuff[e+4] = NEW_LINE; e++; lineLength = 0; } // end if: end of line } // en dfor: each piece of array if( d < len ) { encode3to4( source, d+off, len - d, outBuff, e ); e += 4; } // end if: some padding needed // Return value according to relevant encoding. try { return new String( outBuff, 0, e, PREFERRED_ENCODING ); } // end try catch (java.io.UnsupportedEncodingException uue) { return new String( outBuff, 0, e ); } // end catch } // end else: don't compress } // end encodeBytes /* ******** D E C O D I N G M E T H O D S ******** */ /** * Decodes four bytes from array <var>source</var> * and writes the resulting bytes (up to three of them) * to <var>destination</var>. * The source and destination arrays can be manipulated * anywhere along their length by specifying * <var>srcOffset</var> and <var>destOffset</var>. * This method does not check to make sure your arrays * are large enough to accomodate <var>srcOffset</var> + 4 for * the <var>source</var> array or <var>destOffset</var> + 3 for * the <var>destination</var> array. * This method returns the actual number of bytes that * were converted from the Base64 encoding. * * * @param source the array to convert * @param srcOffset the index where conversion begins * @param destination the array to hold the conversion * @param destOffset the index where output will be put * @return the number of decoded bytes converted * @since 1.3 */ private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset ) { // Example: Dk== if( source[ srcOffset + 2] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); return 1; } // Example: DkL= else if( source[ srcOffset + 3 ] == EQUALS_SIGN ) { // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 ); destination[ destOffset ] = (byte)( outBuff >>> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 ); return 2; } // Example: DkLE else { try{ // Two ways to do the same thing. Don't know which way I like best. //int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 ) // | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 ) // | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 ) // | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 ); int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 ) | ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 ) | ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6) | ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) ); destination[ destOffset ] = (byte)( outBuff >> 16 ); destination[ destOffset + 1 ] = (byte)( outBuff >> 8 ); destination[ destOffset + 2 ] = (byte)( outBuff ); return 3; }catch( Exception e){ System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) ); System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) ); System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) ); System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) ); return -1; } //e nd catch } } // end decodeToBytes /** * Very low-level access to decoding ASCII characters in * the form of a byte array. Does not support automatically * gunzipping or any other "fancy" features. * * @param source The Base64 encoded data * @param off The offset of where to begin decoding * @param len The length of characters to decode * @return decoded data * @since 1.3 */ public static byte[] decode( byte[] source, int off, int len ) { int len34 = len * 3 / 4; byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for( i = off; i < off+len; i++ ) { sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits sbiDecode = DECODABET[ sbiCrop ]; if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better { if( sbiDecode >= EQUALS_SIGN_ENC ) { b4[ b4Posn++ ] = sbiCrop; if( b4Posn > 3 ) { outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn ); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if( sbiCrop == EQUALS_SIGN ) break; } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" ); return null; } // end else: } // each input character byte[] out = new byte[ outBuffPosn ]; System.arraycopy( outBuff, 0, out, 0, outBuffPosn ); return out; } // end decode /** * Decodes data from Base64 notation, automatically * detecting gzip-compressed data and decompressing it. * * @param s the string to decode * @return the decoded data * @since 1.4 */ public static byte[] decode( String s ) { byte[] bytes; try { bytes = s.getBytes( PREFERRED_ENCODING ); } // end try catch( java.io.UnsupportedEncodingException uee ) { bytes = s.getBytes(); } // end catch //</change> // Decode bytes = decode( bytes, 0, bytes.length ); // Check to see if it's gzip-compressed // GZIP Magic Two-Byte Number: 0x8b1f (35615) if( bytes != null && bytes.length >= 4 ) { int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00); if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head ) { java.io.ByteArrayInputStream bais = null; java.util.zip.GZIPInputStream gzis = null; java.io.ByteArrayOutputStream baos = null; byte[] buffer = new byte[2048]; int length = 0; try { baos = new java.io.ByteArrayOutputStream(); bais = new java.io.ByteArrayInputStream( bytes ); gzis = new java.util.zip.GZIPInputStream( bais ); while( ( length = gzis.read( buffer ) ) >= 0 ) { baos.write(buffer,0,length); } // end while: reading input // No error? Get new bytes. bytes = baos.toByteArray(); } // end try catch( java.io.IOException e ) { // Just return originally-decoded bytes } // end catch finally { try{ baos.close(); } catch( Exception e ){} try{ gzis.close(); } catch( Exception e ){} try{ bais.close(); } catch( Exception e ){} } // end finally } // end if: gzipped } // end if: bytes.length >= 2 return bytes; } // end decode /** * Attempts to decode Base64 data and deserialize a Java * Object within. Returns <tt>null</tt> if there was an error. * * @param encodedObject The Base64 data to decode * @return The decoded and deserialized object * @since 1.5 */ public static Object decodeToObject( String encodedObject ) { // Decode and gunzip if necessary byte[] objBytes = decode( encodedObject ); java.io.ByteArrayInputStream bais = null; java.io.ObjectInputStream ois = null; Object obj = null; try { bais = new java.io.ByteArrayInputStream( objBytes ); ois = new java.io.ObjectInputStream( bais ); obj = ois.readObject(); } // end try catch( java.io.IOException e ) { e.printStackTrace(); obj = null; } // end catch catch( java.lang.ClassNotFoundException e ) { e.printStackTrace(); obj = null; } // end catch finally { try{ bais.close(); } catch( Exception e ){} try{ ois.close(); } catch( Exception e ){} } // end finally return obj; } // end decodeObject /** * Convenience method for encoding data to a file. * * @param dataToEncode byte array of data to encode in base64 form * @param filename Filename for saving encoded data * @return <tt>true</tt> if successful, <tt>false</tt> otherwise * * @since 2.1 */ public static boolean encodeToFile( byte[] dataToEncode, String filename ) { boolean success = false; Base64.OutputStream bos = null; try { bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.ENCODE ); bos.write( dataToEncode ); success = true; } // end try catch( java.io.IOException e ) { success = false; } // end catch: IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally return success; } // end encodeToFile /** * Convenience method for decoding data to a file. * * @param dataToDecode Base64-encoded data as a string * @param filename Filename for saving decoded data * @return <tt>true</tt> if successful, <tt>false</tt> otherwise * * @since 2.1 */ public static boolean decodeToFile( String dataToDecode, String filename ) { boolean success = false; Base64.OutputStream bos = null; try { bos = new Base64.OutputStream( new java.io.FileOutputStream( filename ), Base64.DECODE ); bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) ); success = true; } // end try catch( java.io.IOException e ) { success = false; } // end catch: IOException finally { try{ bos.close(); } catch( Exception e ){} } // end finally return success; } // end decodeToFile /** * Convenience method for reading a base64-encoded * file and decoding it. * * @param filename Filename for reading encoded data * @return decoded byte array or null if unsuccessful * * @since 2.1 */ public static byte[] decodeFromFile( String filename ) { byte[] decodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = null; int length = 0; int numBytes = 0; // Check for size of file if( file.length() > Integer.MAX_VALUE ) { System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." ); return null; } // end if: file too big for int index buffer = new byte[ (int)file.length() ]; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.DECODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) length += numBytes; // Save in a variable to return decodedData = new byte[ length ]; System.arraycopy( buffer, 0, decodedData, 0, length ); } // end try catch( java.io.IOException e ) { System.err.println( "Error decoding from file " + filename ); } // end catch: IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return decodedData; } // end decodeFromFile /** * Convenience method for reading a binary file * and base64-encoding it. * * @param filename Filename for reading binary data * @return base64-encoded string or null if unsuccessful * * @since 2.1 */ public static String encodeFromFile( String filename ) { String encodedData = null; Base64.InputStream bis = null; try { // Set up some useful variables java.io.File file = new java.io.File( filename ); byte[] buffer = new byte[ (int)(file.length() * 1.4) ]; int length = 0; int numBytes = 0; // Open a stream bis = new Base64.InputStream( new java.io.BufferedInputStream( new java.io.FileInputStream( file ) ), Base64.ENCODE ); // Read until done while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 ) length += numBytes; // Save in a variable to return encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING ); } // end try catch( java.io.IOException e ) { System.err.println( "Error encoding from file " + filename ); } // end catch: IOException finally { try{ bis.close(); } catch( Exception e) {} } // end finally return encodedData; } // end encodeFromFile /* ******** I N N E R C L A S S I N P U T S T R E A M ******** */ /** * A {@link Base64.InputStream} will read data from another * <tt>java.io.InputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class InputStream extends java.io.FilterInputStream { private boolean encode; // Encoding or decoding private int position; // Current position in the buffer private byte[] buffer; // Small buffer holding converted data private int bufferLength; // Length of buffer (3 or 4) private int numSigBytes; // Number of meaningful bytes in the buffer private int lineLength; private boolean breakLines; // Break lines at less than 80 characters /** * Constructs a {@link Base64.InputStream} in DECODE mode. * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @since 1.3 */ public InputStream( java.io.InputStream in ) { this( in, DECODE ); } // end constructor /** * Constructs a {@link Base64.InputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>new Base64.InputStream( in, Base64.DECODE )</code> * * * @param in the <tt>java.io.InputStream</tt> from which to read data. * @param options Specified options * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 2.0 */ public InputStream( java.io.InputStream in, int options ) { super( in ); this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; this.encode = (options & ENCODE) == ENCODE; this.bufferLength = encode ? 4 : 3; this.buffer = new byte[ bufferLength ]; this.position = -1; this.lineLength = 0; } // end constructor /** * Reads enough of the input stream to convert * to/from Base64 and returns the next byte. * * @return next byte * @since 1.3 */ public int read() throws java.io.IOException { // Do we need to get data? if( position < 0 ) { if( encode ) { byte[] b3 = new byte[3]; int numBinaryBytes = 0; for( int i = 0; i < 3; i++ ) { try { int b = in.read(); // If end of stream, b is -1. if( b >= 0 ) { b3[i] = (byte)b; numBinaryBytes++; } // end if: not end of stream } // end try: read catch( java.io.IOException e ) { // Only a problem if we got no data at all. if( i == 0 ) throw e; } // end catch } // end for: each needed input byte if( numBinaryBytes > 0 ) { encode3to4( b3, 0, numBinaryBytes, buffer, 0 ); position = 0; numSigBytes = 4; } // end if: got data else { return -1; } // end else } // end if: encoding // Else decoding else { byte[] b4 = new byte[4]; int i = 0; for( i = 0; i < 4; i++ ) { // Read four "meaningful" bytes: int b = 0; do{ b = in.read(); } while( b >= 0 && DECODABET[ b & 0x7f ] <= WHITE_SPACE_ENC ); if( b < 0 ) break; // Reads a -1 if end of stream b4[i] = (byte)b; } // end for: each needed input byte if( i == 4 ) { numSigBytes = decode4to3( b4, 0, buffer, 0 ); position = 0; } // end if: got four characters else if( i == 0 ){ return -1; } // end else if: also padded correctly else { // Must have broken out from above. throw new java.io.IOException( "Improperly padded Base64 input." ); } // end } // end else: decode } // end else: get data // Got data? if( position >= 0 ) { // End of relevant data? if( /*!encode &&*/ position >= numSigBytes ) return -1; if( encode && breakLines && lineLength >= MAX_LINE_LENGTH ) { lineLength = 0; return '\n'; } // end if else { lineLength++; // This isn't important when decoding // but throwing an extra "if" seems // just as wasteful. int b = buffer[ position++ ]; if( position >= bufferLength ) position = -1; return b & 0xFF; // This is how you "cast" a byte that's // intended to be unsigned. } // end else } // end if: position >= 0 // Else error else { // When JDK1.4 is more accepted, use an assertion here. throw new java.io.IOException( "Error in Base64 code reading stream." ); } // end else } // end read /** * Calls {@link #read()} repeatedly until the end of stream * is reached or <var>len</var> bytes are read. * Returns number of bytes read into array or -1 if * end of stream is encountered. * * @param dest array to hold values * @param off offset for array * @param len max number of bytes to read into array * @return bytes read into array or -1 if end of stream is encountered. * @since 1.3 */ public int read( byte[] dest, int off, int len ) throws java.io.IOException { int i; int b; for( i = 0; i < len; i++ ) { b = read(); //if( b < 0 && i == 0 ) // return -1; if( b >= 0 ) dest[off + i] = (byte)b; else if( i == 0 ) return -1; else break; // Out of 'for' loop } // end for: each byte read return i; } // end read } // end inner class InputStream /* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */ /** * A {@link Base64.OutputStream} will write data to another * <tt>java.io.OutputStream</tt>, given in the constructor, * and encode/decode to/from Base64 notation on the fly. * * @see Base64 * @since 1.3 */ public static class OutputStream extends java.io.FilterOutputStream { private boolean encode; private int position; private byte[] buffer; private int bufferLength; private int lineLength; private boolean breakLines; private byte[] b4; // Scratch used in a few places private boolean suspendEncoding; /** * Constructs a {@link Base64.OutputStream} in ENCODE mode. * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @since 1.3 */ public OutputStream( java.io.OutputStream out ) { this( out, ENCODE ); } // end constructor /** * Constructs a {@link Base64.OutputStream} in * either ENCODE or DECODE mode. * <p> * Valid options:<pre> * ENCODE or DECODE: Encode or Decode as data is read. * DONT_BREAK_LINES: don't break lines at 76 characters * (only meaningful when encoding) * <i>Note: Technically, this makes your encoding non-compliant.</i> * </pre> * <p> * Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code> * * @param out the <tt>java.io.OutputStream</tt> to which data will be written. * @param options Specified options. * @see Base64#ENCODE * @see Base64#DECODE * @see Base64#DONT_BREAK_LINES * @since 1.3 */ public OutputStream( java.io.OutputStream out, int options ) { super( out ); this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES; this.encode = (options & ENCODE) == ENCODE; this.bufferLength = encode ? 3 : 4; this.buffer = new byte[ bufferLength ]; this.position = 0; this.lineLength = 0; this.suspendEncoding = false; this.b4 = new byte[4]; } // end constructor /** * Writes the byte to the output stream after * converting to/from Base64 notation. * When encoding, bytes are buffered three * at a time before the output stream actually * gets a write() call. * When decoding, bytes are buffered four * at a time. * * @param theByte the byte to write * @since 1.3 */ public void write(int theByte) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { super.out.write( theByte ); return; } // end if: supsended // Encode? if( encode ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) // Enough to encode. { out.write( encode3to4( b4, buffer, bufferLength ) ); lineLength += 4; if( breakLines && lineLength >= MAX_LINE_LENGTH ) { out.write( NEW_LINE ); lineLength = 0; } // end if: end of line position = 0; } // end if: enough to output } // end if: encoding // Else, Decoding else { // Meaningful Base64 character? if( DECODABET[ theByte & 0x7f ] > WHITE_SPACE_ENC ) { buffer[ position++ ] = (byte)theByte; if( position >= bufferLength ) // Enough to output. { int len = Base64.decode4to3( buffer, 0, b4, 0 ); out.write( b4, 0, len ); //out.write( Base64.decode4to3( buffer ) ); position = 0; } // end if: enough to output } // end if: meaningful base64 character else if( DECODABET[ theByte & 0x7f ] != WHITE_SPACE_ENC ) { throw new java.io.IOException( "Invalid character in Base64 data." ); } // end else: not white space either } // end else: decoding } // end write /** * Calls {@link #write(int)} repeatedly until <var>len</var> * bytes are written. * * @param theBytes array from which to read bytes * @param off offset for array * @param len max number of bytes to read into array * @since 1.3 */ public void write( byte[] theBytes, int off, int len ) throws java.io.IOException { // Encoding suspended? if( suspendEncoding ) { super.out.write( theBytes, off, len ); return; } // end if: supsended for( int i = 0; i < len; i++ ) { write( theBytes[ off + i ] ); } // end for: each byte written } // end write /** * Method added by PHIL. [Thanks, PHIL. -Rob] * This pads the buffer without closing the stream. */ public void flushBase64() throws java.io.IOException { if( position > 0 ) { if( encode ) { out.write( encode3to4( b4, buffer, position ) ); position = 0; } // end if: encoding else { throw new java.io.IOException( "Base64 input not properly padded." ); } // end else: decoding } // end if: buffer partially full } // end flush /** * Flushes and closes (I think, in the superclass) the stream. * * @since 1.3 */ public void close() throws java.io.IOException { // 1. Ensure that pending characters are written flushBase64(); // 2. Actually close the stream // Base class both flushes and closes. super.close(); buffer = null; out = null; } // end close /** * Suspends encoding of the stream. * May be helpful if you need to embed a piece of * base640-encoded data in a stream. * * @since 1.5.1 */ public void suspendEncoding() throws java.io.IOException { flushBase64(); this.suspendEncoding = true; } // end suspendEncoding /** * Resumes encoding of the stream. * May be helpful if you need to embed a piece of * base640-encoded data in a stream. * * @since 1.5.1 */ public void resumeEncoding() { this.suspendEncoding = false; } // end resumeEncoding } // end inner class OutputStream } // end class Base64
gpl-2.0
koutheir/incinerator-hotspot
nashorn/buildtools/nasgen/src/jdk/nashorn/internal/tools/nasgen/ClassGenerator.java
15997
/* * Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package jdk.nashorn.internal.tools.nasgen; import static jdk.internal.org.objectweb.asm.Opcodes.ACC_FINAL; import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PRIVATE; import static jdk.internal.org.objectweb.asm.Opcodes.ACC_PUBLIC; import static jdk.internal.org.objectweb.asm.Opcodes.ACC_STATIC; import static jdk.internal.org.objectweb.asm.Opcodes.H_INVOKESTATIC; import static jdk.internal.org.objectweb.asm.Opcodes.H_INVOKEVIRTUAL; import static jdk.nashorn.internal.tools.nasgen.StringConstants.ACCESSORPROPERTY_CREATE; import static jdk.nashorn.internal.tools.nasgen.StringConstants.ACCESSORPROPERTY_CREATE_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.ACCESSORPROPERTY_TYPE; import static jdk.nashorn.internal.tools.nasgen.StringConstants.ARRAYLIST_INIT_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.ARRAYLIST_TYPE; import static jdk.nashorn.internal.tools.nasgen.StringConstants.CLINIT; import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTIONS_EMPTY_LIST; import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTIONS_TYPE; import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTION_ADD; import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTION_ADD_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.COLLECTION_TYPE; import static jdk.nashorn.internal.tools.nasgen.StringConstants.DEFAULT_INIT_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.GETTER_PREFIX; import static jdk.nashorn.internal.tools.nasgen.StringConstants.GET_CLASS_NAME; import static jdk.nashorn.internal.tools.nasgen.StringConstants.GET_CLASS_NAME_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.INIT; import static jdk.nashorn.internal.tools.nasgen.StringConstants.LIST_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.OBJECT_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_FIELD_NAME; import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_NEWMAP; import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_NEWMAP_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.PROPERTYMAP_TYPE; import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTIONIMPL_MAKEFUNCTION; import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTIONIMPL_MAKEFUNCTION_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTIONIMPL_MAKEFUNCTION_SPECS_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTIONIMPL_TYPE; import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_SETARITY; import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_SETARITY_DESC; import static jdk.nashorn.internal.tools.nasgen.StringConstants.SCRIPTFUNCTION_TYPE; import static jdk.nashorn.internal.tools.nasgen.StringConstants.SETTER_PREFIX; import static jdk.nashorn.internal.tools.nasgen.StringConstants.TYPE_OBJECT; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.util.List; import jdk.internal.org.objectweb.asm.ClassReader; import jdk.internal.org.objectweb.asm.ClassVisitor; import jdk.internal.org.objectweb.asm.ClassWriter; import jdk.internal.org.objectweb.asm.FieldVisitor; import jdk.internal.org.objectweb.asm.Handle; import jdk.internal.org.objectweb.asm.MethodVisitor; import jdk.internal.org.objectweb.asm.Type; import jdk.nashorn.internal.tools.nasgen.MemberInfo.Kind; /** * Base class for class generator classes. * */ public class ClassGenerator { /** ASM class writer used to output bytecode for this class */ protected final ClassWriter cw; /** * Constructor */ protected ClassGenerator() { this.cw = makeClassWriter(); } MethodGenerator makeStaticInitializer() { return makeStaticInitializer(cw); } MethodGenerator makeConstructor() { return makeConstructor(cw); } MethodGenerator makeMethod(final int access, final String name, final String desc) { return makeMethod(cw, access, name, desc); } void addMapField() { addMapField(cw); } void addField(final String name, final String desc) { addField(cw, name, desc); } void addFunctionField(final String name) { addFunctionField(cw, name); } void addGetter(final String owner, final MemberInfo memInfo) { addGetter(cw, owner, memInfo); } void addSetter(final String owner, final MemberInfo memInfo) { addSetter(cw, owner, memInfo); } void emitGetClassName(final String name) { final MethodGenerator mi = makeMethod(ACC_PUBLIC, GET_CLASS_NAME, GET_CLASS_NAME_DESC); mi.loadLiteral(name); mi.returnValue(); mi.computeMaxs(); mi.visitEnd(); } static ClassWriter makeClassWriter() { return new ClassWriter(ClassWriter.COMPUTE_FRAMES | ClassWriter.COMPUTE_MAXS) { @Override protected String getCommonSuperClass(final String type1, final String type2) { try { return super.getCommonSuperClass(type1, type2); } catch (final RuntimeException | LinkageError e) { return StringConstants.OBJECT_TYPE; } } }; } static MethodGenerator makeStaticInitializer(final ClassVisitor cv) { return makeStaticInitializer(cv, CLINIT); } static MethodGenerator makeStaticInitializer(final ClassVisitor cv, final String name) { final int access = ACC_PUBLIC | ACC_STATIC; final String desc = DEFAULT_INIT_DESC; final MethodVisitor mv = cv.visitMethod(access, name, desc, null, null); return new MethodGenerator(mv, access, name, desc); } static MethodGenerator makeConstructor(final ClassVisitor cv) { final int access = 0; final String name = INIT; final String desc = DEFAULT_INIT_DESC; final MethodVisitor mv = cv.visitMethod(access, name, desc, null, null); return new MethodGenerator(mv, access, name, desc); } static MethodGenerator makeMethod(final ClassVisitor cv, final int access, final String name, final String desc) { final MethodVisitor mv = cv.visitMethod(access, name, desc, null, null); return new MethodGenerator(mv, access, name, desc); } static void emitStaticInitPrefix(final MethodGenerator mi, final String className, final int memberCount) { mi.visitCode(); if (memberCount > 0) { // new ArrayList(int) mi.newObject(ARRAYLIST_TYPE); mi.dup(); mi.push(memberCount); mi.invokeSpecial(ARRAYLIST_TYPE, INIT, ARRAYLIST_INIT_DESC); // stack: ArrayList } else { // java.util.Collections.EMPTY_LIST mi.getStatic(COLLECTIONS_TYPE, COLLECTIONS_EMPTY_LIST, LIST_DESC); // stack List } } static void emitStaticInitSuffix(final MethodGenerator mi, final String className) { // stack: Collection // pmap = PropertyMap.newMap(Collection<Property>); mi.invokeStatic(PROPERTYMAP_TYPE, PROPERTYMAP_NEWMAP, PROPERTYMAP_NEWMAP_DESC); // $nasgenmap$ = pmap; mi.putStatic(className, PROPERTYMAP_FIELD_NAME, PROPERTYMAP_DESC); mi.returnVoid(); mi.computeMaxs(); mi.visitEnd(); } @SuppressWarnings("fallthrough") private static Type memInfoType(final MemberInfo memInfo) { switch (memInfo.getJavaDesc().charAt(0)) { case 'I': return Type.INT_TYPE; case 'J': return Type.LONG_TYPE; case 'D': return Type.DOUBLE_TYPE; default: assert false : memInfo.getJavaDesc(); case 'L': return TYPE_OBJECT; } } private static String getterDesc(final MemberInfo memInfo) { return Type.getMethodDescriptor(memInfoType(memInfo)); } private static String setterDesc(final MemberInfo memInfo) { return Type.getMethodDescriptor(Type.VOID_TYPE, memInfoType(memInfo)); } static void addGetter(final ClassVisitor cv, final String owner, final MemberInfo memInfo) { final int access = ACC_PUBLIC; final String name = GETTER_PREFIX + memInfo.getJavaName(); final String desc = getterDesc(memInfo); final MethodVisitor mv = cv.visitMethod(access, name, desc, null, null); final MethodGenerator mi = new MethodGenerator(mv, access, name, desc); mi.visitCode(); if (memInfo.isStatic() && memInfo.getKind() == Kind.PROPERTY) { mi.getStatic(owner, memInfo.getJavaName(), memInfo.getJavaDesc()); } else { mi.loadLocal(0); mi.getField(owner, memInfo.getJavaName(), memInfo.getJavaDesc()); } mi.returnValue(); mi.computeMaxs(); mi.visitEnd(); } static void addSetter(final ClassVisitor cv, final String owner, final MemberInfo memInfo) { final int access = ACC_PUBLIC; final String name = SETTER_PREFIX + memInfo.getJavaName(); final String desc = setterDesc(memInfo); final MethodVisitor mv = cv.visitMethod(access, name, desc, null, null); final MethodGenerator mi = new MethodGenerator(mv, access, name, desc); mi.visitCode(); if (memInfo.isStatic() && memInfo.getKind() == Kind.PROPERTY) { mi.loadLocal(1); mi.putStatic(owner, memInfo.getJavaName(), memInfo.getJavaDesc()); } else { mi.loadLocal(0); mi.loadLocal(1); mi.putField(owner, memInfo.getJavaName(), memInfo.getJavaDesc()); } mi.returnVoid(); mi.computeMaxs(); mi.visitEnd(); } static void addMapField(final ClassVisitor cv) { // add a PropertyMap static field final FieldVisitor fv = cv.visitField(ACC_PRIVATE | ACC_STATIC | ACC_FINAL, PROPERTYMAP_FIELD_NAME, PROPERTYMAP_DESC, null, null); if (fv != null) { fv.visitEnd(); } } static void addField(final ClassVisitor cv, final String name, final String desc) { final FieldVisitor fv = cv.visitField(ACC_PRIVATE, name, desc, null, null); if (fv != null) { fv.visitEnd(); } } static void addFunctionField(final ClassVisitor cv, final String name) { addField(cv, name, OBJECT_DESC); } static void newFunction(final MethodGenerator mi, final String className, final MemberInfo memInfo, final List<MemberInfo> specs) { final boolean arityFound = (memInfo.getArity() != MemberInfo.DEFAULT_ARITY); mi.loadLiteral(memInfo.getName()); mi.visitLdcInsn(new Handle(H_INVOKESTATIC, className, memInfo.getJavaName(), memInfo.getJavaDesc())); assert specs != null; if (!specs.isEmpty()) { mi.memberInfoArray(className, specs); mi.invokeStatic(SCRIPTFUNCTIONIMPL_TYPE, SCRIPTFUNCTIONIMPL_MAKEFUNCTION, SCRIPTFUNCTIONIMPL_MAKEFUNCTION_SPECS_DESC); } else { mi.invokeStatic(SCRIPTFUNCTIONIMPL_TYPE, SCRIPTFUNCTIONIMPL_MAKEFUNCTION, SCRIPTFUNCTIONIMPL_MAKEFUNCTION_DESC); } if (arityFound) { mi.dup(); mi.push(memInfo.getArity()); mi.invokeVirtual(SCRIPTFUNCTION_TYPE, SCRIPTFUNCTION_SETARITY, SCRIPTFUNCTION_SETARITY_DESC); } } static void linkerAddGetterSetter(final MethodGenerator mi, final String className, final MemberInfo memInfo) { final String propertyName = memInfo.getName(); // stack: Collection // dup of Collection instance mi.dup(); // property = AccessorProperty.create(key, flags, getter, setter); mi.loadLiteral(propertyName); // setup flags mi.push(memInfo.getAttributes()); // setup getter method handle String javaName = GETTER_PREFIX + memInfo.getJavaName(); mi.visitLdcInsn(new Handle(H_INVOKEVIRTUAL, className, javaName, getterDesc(memInfo))); // setup setter method handle if (memInfo.isFinal()) { mi.pushNull(); } else { javaName = SETTER_PREFIX + memInfo.getJavaName(); mi.visitLdcInsn(new Handle(H_INVOKEVIRTUAL, className, javaName, setterDesc(memInfo))); } mi.invokeStatic(ACCESSORPROPERTY_TYPE, ACCESSORPROPERTY_CREATE, ACCESSORPROPERTY_CREATE_DESC); // boolean Collection.add(property) mi.invokeInterface(COLLECTION_TYPE, COLLECTION_ADD, COLLECTION_ADD_DESC); // pop return value of Collection.add mi.pop(); // stack: Collection } static void linkerAddGetterSetter(final MethodGenerator mi, final String className, final MemberInfo getter, final MemberInfo setter) { final String propertyName = getter.getName(); // stack: Collection // dup of Collection instance mi.dup(); // property = AccessorProperty.create(key, flags, getter, setter); mi.loadLiteral(propertyName); // setup flags mi.push(getter.getAttributes()); // setup getter method handle mi.visitLdcInsn(new Handle(H_INVOKESTATIC, className, getter.getJavaName(), getter.getJavaDesc())); // setup setter method handle if (setter == null) { mi.pushNull(); } else { mi.visitLdcInsn(new Handle(H_INVOKESTATIC, className, setter.getJavaName(), setter.getJavaDesc())); } mi.invokeStatic(ACCESSORPROPERTY_TYPE, ACCESSORPROPERTY_CREATE, ACCESSORPROPERTY_CREATE_DESC); // boolean Collection.add(property) mi.invokeInterface(COLLECTION_TYPE, COLLECTION_ADD, COLLECTION_ADD_DESC); // pop return value of Collection.add mi.pop(); // stack: Collection } static ScriptClassInfo getScriptClassInfo(final String fileName) throws IOException { try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName))) { return getScriptClassInfo(new ClassReader(bis)); } } static ScriptClassInfo getScriptClassInfo(final byte[] classBuf) { return getScriptClassInfo(new ClassReader(classBuf)); } private static ScriptClassInfo getScriptClassInfo(final ClassReader reader) { final ScriptClassInfoCollector scic = new ScriptClassInfoCollector(); reader.accept(scic, 0); return scic.getScriptClassInfo(); } }
gpl-2.0
janslow/QLabMasker-Server
src/com/jayanslow/qlabMasker/models/Polygon.java
1219
package com.jayanslow.qlabMasker.models; import java.util.List; import com.google.common.collect.ImmutableList; public class Polygon { private final String _name; private final RenderMode _renderMode; private final List<Point> _points; public Polygon(final String name, final RenderMode renderMode) { this(name, renderMode, ImmutableList.of()); } public Polygon(final String name, final RenderMode renderMode, final List<Point> points) { _name = name; _renderMode = renderMode; _points = points; } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (getClass() != obj.getClass()) { return false; } final Polygon other = (Polygon) obj; return _name.equals(other._name); } public String getName() { return _name; } public List<Point> getPoints() { return _points; } public RenderMode getRenderMode() { return _renderMode; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + _name.hashCode(); return result; } @Override public String toString() { return String.format("Polygon(%s)", _name); } }
gpl-2.0
maiklos-mirrors/jfx78
modules/controls/src/main/java/javafx/scene/control/TreeTablePosition.java
5561
/* * Copyright (c) 2011, 2013, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package javafx.scene.control; import java.lang.ref.WeakReference; import javafx.beans.NamedArg; /** * This class is used to represent a single row/column/cell in a TreeTableView. * This is used throughout the TreeTableView API to represent which rows/columns/cells * are currently selected, focused, being edited, etc. Note that this class is * immutable once it is created. * * <p>Because the TreeTableView can have different * {@link SelectionMode selection modes}, the row and column properties in * TablePosition can be 'disabled' to represent an entire row or column. This is * done by setting the unrequired property to -1 or null. * * @param <S> The type of the {@link TreeItem} instances contained within the * TreeTableView. * @param <T> The type of the items contained within the TreeTableColumn. * @see TreeTableView * @see TreeTableColumn * @since JavaFX 8.0 */ public class TreeTablePosition<S,T> extends TablePositionBase<TreeTableColumn<S,T>> { /*************************************************************************** * * * Constructors * * * **************************************************************************/ /** * Constructs a TreeTablePosition instance to represent the given row/column * position in the given TreeTableView instance. Both the TreeTableView and * TreeTableColumn are referenced weakly in this class, so it is possible that * they will be null when their respective getters are called. * * @param treeTableView The TreeTableView that this position is related to. * @param row The row that this TreeTablePosition is representing. * @param tableColumn The TreeTableColumn instance that this TreeTablePosition represents. */ public TreeTablePosition(@NamedArg("treeTableView") TreeTableView<S> treeTableView, @NamedArg("row") int row, @NamedArg("tableColumn") TreeTableColumn<S,T> tableColumn) { super(row, tableColumn); this.controlRef = new WeakReference<TreeTableView<S>>(treeTableView); this.treeItemRef = new WeakReference<TreeItem<S>>(treeTableView.getTreeItem(row)); } /*************************************************************************** * * * Instance Variables * * * **************************************************************************/ private final WeakReference<TreeTableView<S>> controlRef; private final WeakReference<TreeItem<S>> treeItemRef; /*************************************************************************** * * * Public API * * * **************************************************************************/ /** * The column index that this TreeTablePosition represents in the TreeTableView. It * is -1 if the TreeTableView or TreeTableColumn instances are null. */ @Override public int getColumn() { TreeTableView<S> tableView = getTreeTableView(); TreeTableColumn<S,T> tableColumn = getTableColumn(); return tableView == null || tableColumn == null ? -1 : tableView.getVisibleLeafIndex(tableColumn); } /** * The TreeTableView that this TreeTablePosition is related to. */ public final TreeTableView<S> getTreeTableView() { return controlRef.get(); } @Override public final TreeTableColumn<S,T> getTableColumn() { // Forcing the return type to be TreeTableColumn<S,T>, not TableColumnBase<S,T> return super.getTableColumn(); } /** * Returns the {@link TreeItem} that backs the {@link #getRow()} row}. */ public final TreeItem<S> getTreeItem() { return treeItemRef.get(); } }
gpl-2.0
w7cook/batch-javac
src/share/classes/com/sun/tools/javac/code/Types.java
119351
/* * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle in the LICENSE file that accompanied this code. * * This code is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.tools.javac.code; import java.lang.ref.SoftReference; import java.util.*; import com.sun.tools.javac.util.*; import com.sun.tools.javac.util.List; import com.sun.tools.javac.jvm.ClassReader; import com.sun.tools.javac.code.Attribute.RetentionPolicy; import com.sun.tools.javac.code.Lint.LintCategory; import com.sun.tools.javac.comp.Check; import static com.sun.tools.javac.code.Scope.*; import static com.sun.tools.javac.code.Type.*; import static com.sun.tools.javac.code.TypeTags.*; import static com.sun.tools.javac.code.Symbol.*; import static com.sun.tools.javac.code.Flags.*; import static com.sun.tools.javac.code.BoundKind.*; import static com.sun.tools.javac.util.ListBuffer.lb; /** * Utility class containing various operations on types. * * <p> * Unless other names are more illustrative, the following naming conventions * should be observed in this file: * * <dl> * <dt>t</dt> * <dd>If the first argument to an operation is a type, it should be named t.</dd> * <dt>s</dt> * <dd>Similarly, if the second argument to an operation is a type, it should be * named s.</dd> * <dt>ts</dt> * <dd>If an operations takes a list of types, the first should be named ts.</dd> * <dt>ss</dt> * <dd>A second list of types should be named ss.</dd> * </dl> * * <p> * <b>This is NOT part of any supported API. If you write code that depends on * this, you do so at your own risk. This code and its internal interfaces are * subject to change or deletion without notice.</b> */ public class Types { protected static final Context.Key<Types> typesKey = new Context.Key<Types>(); final Symtab syms; final JavacMessages messages; final Names names; final boolean allowBoxing; final boolean allowCovariantReturns; final boolean allowObjectToPrimitiveCast; final ClassReader reader; final Check chk; List<Warner> warnStack = List.nil(); final Name capturedName; // <editor-fold defaultstate="collapsed" desc="Instantiating"> public static Types instance(Context context) { Types instance = context.get(typesKey); if (instance == null) instance = new Types(context); return instance; } protected Types(Context context) { context.put(typesKey, this); syms = Symtab.instance(context); names = Names.instance(context); Source source = Source.instance(context); allowBoxing = source.allowBoxing(); allowCovariantReturns = source.allowCovariantReturns(); allowObjectToPrimitiveCast = source.allowObjectToPrimitiveCast(); reader = ClassReader.instance(context); chk = Check.instance(context); capturedName = names.fromString("<captured wildcard>"); messages = JavacMessages.instance(context); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="upperBound"> /** * The "rvalue conversion".<br> * The upper bound of most types is the type itself. Wildcards, on the other * hand have upper and lower bounds. * * @param t * a type * @return the upper bound of the given type */ public Type upperBound(Type t) { return upperBound.visit(t); } // where private final MapVisitor<Void> upperBound = new MapVisitor<Void>() { @Override public Type visitWildcardType(WildcardType t, Void ignored) { if (t.isSuperBound()) return t.bound == null ? syms.objectType : t.bound.bound; else return visit(t.type); } @Override public Type visitCapturedType(CapturedType t, Void ignored) { return visit(t.bound); } }; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="lowerBound"> /** * The "lvalue conversion".<br> * The lower bound of most types is the type itself. Wildcards, on the other * hand have upper and lower bounds. * * @param t * a type * @return the lower bound of the given type */ public Type lowerBound(Type t) { return lowerBound.visit(t); } // where private final MapVisitor<Void> lowerBound = new MapVisitor<Void>() { @Override public Type visitWildcardType(WildcardType t, Void ignored) { return t.isExtendsBound() ? syms.botType : visit(t.type); } @Override public Type visitCapturedType(CapturedType t, Void ignored) { return visit(t.getLowerBound()); } }; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="isUnbounded"> /** * Checks that all the arguments to a class are unbounded wildcards or * something else that doesn't make any restrictions on the arguments. If a * class isUnbounded, a raw super- or subclass can be cast to it without a * warning. * * @param t * a type * @return true iff the given type is unbounded or raw */ public boolean isUnbounded(Type t) { return isUnbounded.visit(t); } // where private final UnaryVisitor<Boolean> isUnbounded = new UnaryVisitor<Boolean>() { public Boolean visitType(Type t, Void ignored) { return true; } @Override public Boolean visitClassType(ClassType t, Void ignored) { List<Type> parms = t.tsym.type.allparams(); List<Type> args = t.allparams(); while (parms.nonEmpty()) { WildcardType unb = new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) parms.head); if (!containsType(args.head, unb)) return false; parms = parms.tail; args = args.tail; } return true; } }; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="asSub"> /** * Return the least specific subtype of t that starts with symbol sym. If none * exists, return null. The least specific subtype is determined as follows: * * <p> * If there is exactly one parameterized instance of sym that is a subtype of * t, that parameterized instance is returned.<br> * Otherwise, if the plain type or raw type `sym' is a subtype of type t, the * type `sym' itself is returned. Otherwise, null is returned. */ public Type asSub(Type t, Symbol sym) { return asSub.visit(t, sym); } // where private final SimpleVisitor<Type, Symbol> asSub = new SimpleVisitor<Type, Symbol>() { public Type visitType(Type t, Symbol sym) { return null; } @Override public Type visitClassType(ClassType t, Symbol sym) { if (t.tsym == sym) return t; Type base = asSuper(sym.type, t.tsym); if (base == null) return null; ListBuffer<Type> from = new ListBuffer<Type>(); ListBuffer<Type> to = new ListBuffer<Type>(); try { adapt(base, t, from, to); } catch (AdaptFailure ex) { return null; } Type res = subst(sym.type, from.toList(), to.toList()); if (!isSubtype(res, t)) return null; ListBuffer<Type> openVars = new ListBuffer<Type>(); for (List<Type> l = sym.type.allparams(); l.nonEmpty(); l = l.tail) if (res.contains(l.head) && !t.contains(l.head)) openVars.append(l.head); if (openVars.nonEmpty()) { if (t.isRaw()) { // The subtype of a // raw type is raw res = erasure(res); } else { // Unbound type // arguments default // to ? List<Type> opens = openVars.toList(); ListBuffer<Type> qs = new ListBuffer<Type>(); for (List<Type> iter = opens; iter.nonEmpty(); iter = iter.tail) { qs.append(new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, (TypeVar) iter.head)); } res = subst(res, opens, qs.toList()); } } return res; } @Override public Type visitErrorType(ErrorType t, Symbol sym) { return t; } }; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="isConvertible"> /** * Is t a subtype of or convertiable via boxing/unboxing convertions to s? */ public boolean isConvertible(Type t, Type s, Warner warn) { boolean tPrimitive = t.isPrimitive(); boolean sPrimitive = s.isPrimitive(); if (tPrimitive == sPrimitive) { checkUnsafeVarargsConversion(t, s, warn); return isSubtypeUnchecked(t, s, warn); } if (!allowBoxing) return false; return tPrimitive ? isSubtype(boxedClass(t).type, s) : isSubtype( unboxedType(t), s); } // where private void checkUnsafeVarargsConversion(Type t, Type s, Warner warn) { if (t.tag != ARRAY || isReifiable(t)) return; ArrayType from = (ArrayType) t; boolean shouldWarn = false; switch (s.tag) { case ARRAY: ArrayType to = (ArrayType) s; shouldWarn = from.isVarargs() && !to.isVarargs() && !isReifiable(from); break; case CLASS: shouldWarn = from.isVarargs() && isSubtype(from, s); break; } if (shouldWarn) { warn.warn(LintCategory.VARARGS); } } /** * Is t a subtype of or convertiable via boxing/unboxing convertions to s? */ public boolean isConvertible(Type t, Type s) { return isConvertible(t, s, Warner.noWarnings); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="isSubtype"> /** * Is t an unchecked subtype of s? */ public boolean isSubtypeUnchecked(Type t, Type s) { return isSubtypeUnchecked(t, s, Warner.noWarnings); } /** * Is t an unchecked subtype of s? */ public boolean isSubtypeUnchecked(Type t, Type s, Warner warn) { if (t.tag == ARRAY && s.tag == ARRAY) { if (((ArrayType) t).elemtype.tag <= lastBaseTag) { return isSameType(elemtype(t), elemtype(s)); } else { ArrayType from = (ArrayType) t; ArrayType to = (ArrayType) s; if (from.isVarargs() && !to.isVarargs() && !isReifiable(from)) { warn.warn(LintCategory.VARARGS); } return isSubtypeUnchecked(elemtype(t), elemtype(s), warn); } } else if (isSubtype(t, s)) { return true; } else if (t.tag == TYPEVAR) { return isSubtypeUnchecked(t.getUpperBound(), s, warn); } else if (s.tag == UNDETVAR) { UndetVar uv = (UndetVar) s; if (uv.inst != null) return isSubtypeUnchecked(t, uv.inst, warn); } else if (!s.isRaw()) { Type t2 = asSuper(t, s.tsym); if (t2 != null && t2.isRaw()) { if (isReifiable(s)) warn.silentWarn(LintCategory.UNCHECKED); else warn.warn(LintCategory.UNCHECKED); return true; } } return false; } /** * Is t a subtype of s?<br> * (not defined for Method and ForAll types) */ final public boolean isSubtype(Type t, Type s) { return isSubtype(t, s, true); } final public boolean isSubtypeNoCapture(Type t, Type s) { return isSubtype(t, s, false); } public boolean isSubtype(Type t, Type s, boolean capture) { if (t == s) return true; if (s.tag >= firstPartialTag) return isSuperType(s, t); if (s.isCompound()) { for (Type s2 : interfaces(s).prepend(supertype(s))) { if (!isSubtype(t, s2, capture)) return false; } return true; } Type lower = lowerBound(s); if (s != lower) return isSubtype(capture ? capture(t) : t, lower, false); return isSubtype.visit(capture ? capture(t) : t, s); } // where private TypeRelation isSubtype = new TypeRelation() { public Boolean visitType(Type t, Type s) { switch (t.tag) { case BYTE: case CHAR: return (t.tag == s.tag || t.tag + 2 <= s.tag && s.tag <= DOUBLE); case SHORT: case INT: case LONG: case FLOAT: case DOUBLE: return t.tag <= s.tag && s.tag <= DOUBLE; case BOOLEAN: case VOID: return t.tag == s.tag; case TYPEVAR: return isSubtypeNoCapture(t.getUpperBound(), s); case BOT: return s.tag == BOT || s.tag == CLASS || s.tag == ARRAY || s.tag == TYPEVAR; case WILDCARD: // we shouldn't be here - // avoids crash (see // 7034495) case NONE: return false; default: throw new AssertionError("isSubtype " + t.tag); } } private Set<TypePair> cache = new HashSet<TypePair>(); private boolean containsTypeRecursive(Type t, Type s) { TypePair pair = new TypePair(t, s); if (cache.add(pair)) { try { return containsType(t.getTypeArguments(), s.getTypeArguments()); } finally { cache.remove(pair); } } else { return containsType(t.getTypeArguments(), rewriteSupers(s) .getTypeArguments()); } } private Type rewriteSupers(Type t) { if (!t.isParameterized()) return t; ListBuffer<Type> from = lb(); ListBuffer<Type> to = lb(); adaptSelf(t, from, to); if (from.isEmpty()) return t; ListBuffer<Type> rewrite = lb(); boolean changed = false; for (Type orig : to.toList()) { Type s = rewriteSupers(orig); if (s.isSuperBound() && !s.isExtendsBound()) { s = new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass); changed = true; } else if (s != orig) { s = new WildcardType(upperBound(s), BoundKind.EXTENDS, syms.boundClass); changed = true; } rewrite.append(s); } if (changed) return subst(t.tsym.type, from.toList(), rewrite.toList()); else return t; } @Override public Boolean visitClassType(ClassType t, Type s) { Type sup = asSuper(t, s.tsym); return sup != null && sup.tsym == s.tsym // You're not allowed to write // Vector<Object> vec = new // Vector<String>(); // But with wildcards you can write // Vector<? extends Object> vec = new // Vector<String>(); // which means that subtype checking must // be done // here instead of same-type checking (via // containsType). && (!s.isParameterized() || containsTypeRecursive(s, sup)) && isSubtypeNoCapture(sup.getEnclosingType(), s.getEnclosingType()); } @Override public Boolean visitArrayType(ArrayType t, Type s) { if (s.tag == ARRAY) { if (t.elemtype.tag <= lastBaseTag) return isSameType(t.elemtype, elemtype(s)); else return isSubtypeNoCapture(t.elemtype, elemtype(s)); } if (s.tag == CLASS) { Name sname = s.tsym.getQualifiedName(); return sname == names.java_lang_Object || sname == names.java_lang_Cloneable || sname == names.java_io_Serializable; } return false; } @Override public Boolean visitUndetVar(UndetVar t, Type s) { // todo: test against origin needed? or // replace with substitution? if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN) return true; if (t.inst != null) return isSubtypeNoCapture(t.inst, s); // TODO: // ", warn"? t.hibounds = t.hibounds.prepend(s); return true; } @Override public Boolean visitErrorType(ErrorType t, Type s) { return true; } }; /** * Is t a subtype of every type in given list `ts'?<br> * (not defined for Method and ForAll types)<br> * Allows unchecked conversions. */ public boolean isSubtypeUnchecked(Type t, List<Type> ts, Warner warn) { for (List<Type> l = ts; l.nonEmpty(); l = l.tail) if (!isSubtypeUnchecked(t, l.head, warn)) return false; return true; } /** * Are corresponding elements of ts subtypes of ss? If lists are of different * length, return false. */ public boolean isSubtypes(List<Type> ts, List<Type> ss) { while (ts.tail != null && ss.tail != null /* inlined: ts.nonEmpty() && ss.nonEmpty() */&& isSubtype(ts.head, ss.head)) { ts = ts.tail; ss = ss.tail; } return ts.tail == null && ss.tail == null; /* inlined: ts.isEmpty() && ss.isEmpty(); */ } /** * Are corresponding elements of ts subtypes of ss, allowing unchecked * conversions? If lists are of different length, return false. **/ public boolean isSubtypesUnchecked(List<Type> ts, List<Type> ss, Warner warn) { while (ts.tail != null && ss.tail != null /* inlined: ts.nonEmpty() && ss.nonEmpty() */&& isSubtypeUnchecked( ts.head, ss.head, warn)) { ts = ts.tail; ss = ss.tail; } return ts.tail == null && ss.tail == null; /* inlined: ts.isEmpty() && ss.isEmpty(); */ } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="isSuperType"> /** * Is t a supertype of s? */ public boolean isSuperType(Type t, Type s) { switch (t.tag) { case ERROR: return true; case UNDETVAR: { UndetVar undet = (UndetVar) t; if (t == s || undet.qtype == s || s.tag == ERROR || s.tag == BOT) return true; if (undet.inst != null) return isSubtype(s, undet.inst); undet.lobounds = undet.lobounds.prepend(s); return true; } default: return isSubtype(s, t); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="isSameType"> /** * Are corresponding elements of the lists the same type? If lists are of * different length, return false. */ public boolean isSameTypes(List<Type> ts, List<Type> ss) { while (ts.tail != null && ss.tail != null /* inlined: ts.nonEmpty() && ss.nonEmpty() */&& isSameType(ts.head, ss.head)) { ts = ts.tail; ss = ss.tail; } return ts.tail == null && ss.tail == null; /* inlined: ts.isEmpty() && ss.isEmpty(); */ } /** * Is t the same type as s? */ public boolean isSameType(Type t, Type s) { return isSameType.visit(t, s); } // where private TypeRelation isSameType = new TypeRelation() { public Boolean visitType(Type t, Type s) { if (t == s) return true; if (s.tag >= firstPartialTag) return visit(s, t); switch (t.tag) { case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT: case DOUBLE: case BOOLEAN: case VOID: case BOT: case NONE: return t.tag == s.tag; case TYPEVAR: { if (s.tag == TYPEVAR) { // type-substitution does not // preserve type-var types // check that type var symbols and // bounds are indeed the same return t.tsym == s.tsym && visit(t.getUpperBound(), s.getUpperBound()); } else { // special case for s == ? super // X, where upper(s) = u // check that u == t, where u has // been set by Type.withTypeVar return s.isSuperBound() && !s.isExtendsBound() && visit(t, upperBound(s)); } } default: throw new AssertionError("isSameType " + t.tag); } } @Override public Boolean visitWildcardType(WildcardType t, Type s) { if (s.tag >= firstPartialTag) return visit(s, t); else return false; } @Override public Boolean visitClassType(ClassType t, Type s) { if (t == s) return true; if (s.tag >= firstPartialTag) return visit(s, t); if (s.isSuperBound() && !s.isExtendsBound()) return visit(t, upperBound(s)) && visit(t, lowerBound(s)); if (t.isCompound() && s.isCompound()) { if (!visit(supertype(t), supertype(s))) return false; HashSet<SingletonType> set = new HashSet<SingletonType>(); for (Type x : interfaces(t)) set.add(new SingletonType(x)); for (Type x : interfaces(s)) { if (!set.remove(new SingletonType(x))) return false; } return (set.isEmpty()); } return t.tsym == s.tsym && visit(t.getEnclosingType(), s.getEnclosingType()) && containsTypeEquivalent(t.getTypeArguments(), s.getTypeArguments()); } @Override public Boolean visitArrayType(ArrayType t, Type s) { if (t == s) return true; if (s.tag >= firstPartialTag) return visit(s, t); return s.tag == ARRAY && containsTypeEquivalent(t.elemtype, elemtype(s)); } @Override public Boolean visitMethodType(MethodType t, Type s) { // isSameType for methods does not // take thrown // exceptions into account! return hasSameArgs(t, s) && visit(t.getReturnType(), s.getReturnType()); } @Override public Boolean visitPackageType(PackageType t, Type s) { return t == s; } @Override public Boolean visitForAll(ForAll t, Type s) { if (s.tag != FORALL) return false; ForAll forAll = (ForAll) s; return hasSameBounds(t, forAll) && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars)); } @Override public Boolean visitUndetVar(UndetVar t, Type s) { if (s.tag == WILDCARD) // FIXME, this might be leftovers // from before capture conversion return false; if (t == s || t.qtype == s || s.tag == ERROR || s.tag == UNKNOWN) return true; if (t.inst != null) return visit(t.inst, s); t.inst = fromUnknownFun.apply(s); for (List<Type> l = t.lobounds; l.nonEmpty(); l = l.tail) { if (!isSubtype(l.head, t.inst)) return false; } for (List<Type> l = t.hibounds; l.nonEmpty(); l = l.tail) { if (!isSubtype(t.inst, l.head)) return false; } return true; } @Override public Boolean visitErrorType(ErrorType t, Type s) { return true; } }; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="fromUnknownFun"> /** * A mapping that turns all unknown types in this type to fresh unknown * variables. */ public Mapping fromUnknownFun = new Mapping("fromUnknownFun") { public Type apply(Type t) { if (t.tag == UNKNOWN) return new UndetVar(t); else return t.map(this); } }; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Contains Type"> public boolean containedBy(Type t, Type s) { switch (t.tag) { case UNDETVAR: if (s.tag == WILDCARD) { UndetVar undetvar = (UndetVar) t; WildcardType wt = (WildcardType) s; switch (wt.kind) { case UNBOUND: // similar to ? extends Object case EXTENDS: { Type bound = upperBound(s); // We should check the new upper bound against any of the // undetvar's lower bounds. for (Type t2 : undetvar.lobounds) { if (!isSubtype(t2, bound)) return false; } undetvar.hibounds = undetvar.hibounds.prepend(bound); break; } case SUPER: { Type bound = lowerBound(s); // We should check the new lower bound against any of the // undetvar's lower bounds. for (Type t2 : undetvar.hibounds) { if (!isSubtype(bound, t2)) return false; } undetvar.lobounds = undetvar.lobounds.prepend(bound); break; } } return true; } else { return isSameType(t, s); } case ERROR: return true; default: return containsType(s, t); } } boolean containsType(List<Type> ts, List<Type> ss) { while (ts.nonEmpty() && ss.nonEmpty() && containsType(ts.head, ss.head)) { ts = ts.tail; ss = ss.tail; } return ts.isEmpty() && ss.isEmpty(); } /** * Check if t contains s. * * <p> * T contains S if: * * <p> * {@code L(T) <: L(S) && U(S) <: U(T)} * * <p> * This relation is only used by ClassType.isSubtype(), that is, * * <p> * {@code C<S> <: C<T> if T contains S.} * * <p> * Because of F-bounds, this relation can lead to infinite recursion. Thus we * must somehow break that recursion. Notice that containsType() is only * called from ClassType.isSubtype(). Since the arguments have already been * checked against their bounds, we know: * * <p> * {@code U(S) <: U(T) if T is "super" bound (U(T) *is* the bound)} * * <p> * {@code L(T) <: L(S) if T is "extends" bound (L(T) is bottom)} * * @param t * a type * @param s * a type */ public boolean containsType(Type t, Type s) { return containsType.visit(t, s); } // where private TypeRelation containsType = new TypeRelation() { private Type U(Type t) { while (t.tag == WILDCARD) { WildcardType w = (WildcardType) t; if (w.isSuperBound()) return w.bound == null ? syms.objectType : w.bound.bound; else t = w.type; } return t; } private Type L(Type t) { while (t.tag == WILDCARD) { WildcardType w = (WildcardType) t; if (w.isExtendsBound()) return syms.botType; else t = w.type; } return t; } public Boolean visitType(Type t, Type s) { if (s.tag >= firstPartialTag) return containedBy(s, t); else return isSameType(t, s); } // void debugContainsType(WildcardType t, // Type s) { // System.err.println(); // System.err.format(" does %s contain %s?%n", // t, s); // System.err.format(" %s U(%s) <: U(%s) %s = %s%n", // upperBound(s), s, t, U(t), // t.isSuperBound() // || isSubtypeNoCapture(upperBound(s), // U(t))); // System.err.format(" %s L(%s) <: L(%s) %s = %s%n", // L(t), t, s, lowerBound(s), // t.isExtendsBound() // || isSubtypeNoCapture(L(t), // lowerBound(s))); // System.err.println(); // } @Override public Boolean visitWildcardType(WildcardType t, Type s) { if (s.tag >= firstPartialTag) return containedBy(s, t); else { // debugContainsType(t, s); return isSameWildcard(t, s) || isCaptureOf(s, t) || ((t.isExtendsBound() || isSubtypeNoCapture(L(t), lowerBound(s))) && (t .isSuperBound() || isSubtypeNoCapture(upperBound(s), U(t)))); } } @Override public Boolean visitUndetVar(UndetVar t, Type s) { if (s.tag != WILDCARD) return isSameType(t, s); else return false; } @Override public Boolean visitErrorType(ErrorType t, Type s) { return true; } }; public boolean isCaptureOf(Type s, WildcardType t) { if (s.tag != TYPEVAR || !((TypeVar) s).isCaptured()) return false; return isSameWildcard(t, ((CapturedType) s).wildcard); } public boolean isSameWildcard(WildcardType t, Type s) { if (s.tag != WILDCARD) return false; WildcardType w = (WildcardType) s; return w.kind == t.kind && w.type == t.type; } public boolean containsTypeEquivalent(List<Type> ts, List<Type> ss) { while (ts.nonEmpty() && ss.nonEmpty() && containsTypeEquivalent(ts.head, ss.head)) { ts = ts.tail; ss = ss.tail; } return ts.isEmpty() && ss.isEmpty(); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="isCastable"> public boolean isCastable(Type t, Type s) { return isCastable(t, s, Warner.noWarnings); } /** * Is t is castable to s?<br> * s is assumed to be an erased type.<br> * (not defined for Method and ForAll types). */ public boolean isCastable(Type t, Type s, Warner warn) { if (t == s) return true; if (t.isPrimitive() != s.isPrimitive()) return allowBoxing && (isConvertible(t, s, warn) || (allowObjectToPrimitiveCast && s.isPrimitive() && isSubtype(boxedClass(s).type, t))); if (warn != warnStack.head) { try { warnStack = warnStack.prepend(warn); checkUnsafeVarargsConversion(t, s, warn); return isCastable.visit(t, s); } finally { warnStack = warnStack.tail; } } else { return isCastable.visit(t, s); } } // where private TypeRelation isCastable = new TypeRelation() { public Boolean visitType(Type t, Type s) { if (s.tag == ERROR) return true; switch (t.tag) { case BYTE: case CHAR: case SHORT: case INT: case LONG: case FLOAT: case DOUBLE: return s.tag <= DOUBLE; case BOOLEAN: return s.tag == BOOLEAN; case VOID: return false; case BOT: return isSubtype(t, s); default: throw new AssertionError(); } } @Override public Boolean visitWildcardType(WildcardType t, Type s) { return isCastable(upperBound(t), s, warnStack.head); } @Override public Boolean visitClassType(ClassType t, Type s) { if (s.tag == ERROR || s.tag == BOT) return true; if (s.tag == TYPEVAR) { if (isCastable(t, s.getUpperBound(), Warner.noWarnings)) { warnStack.head.warn(LintCategory.UNCHECKED); return true; } else { return false; } } if (t.isCompound()) { Warner oldWarner = warnStack.head; warnStack.head = Warner.noWarnings; if (!visit(supertype(t), s)) return false; for (Type intf : interfaces(t)) { if (!visit(intf, s)) return false; } if (warnStack.head.hasLint(LintCategory.UNCHECKED)) oldWarner.warn(LintCategory.UNCHECKED); return true; } if (s.isCompound()) { // call recursively to reuse the above // code return visitClassType((ClassType) s, t); } if (s.tag == CLASS || s.tag == ARRAY) { boolean upcast; if ((upcast = isSubtype(erasure(t), erasure(s))) || isSubtype(erasure(s), erasure(t))) { if (!upcast && s.tag == ARRAY) { if (!isReifiable(s)) warnStack.head.warn(LintCategory.UNCHECKED); return true; } else if (s.isRaw()) { return true; } else if (t.isRaw()) { if (!isUnbounded(s)) warnStack.head.warn(LintCategory.UNCHECKED); return true; } // Assume |a| <: |b| final Type a = upcast ? t : s; final Type b = upcast ? s : t; final boolean HIGH = true; final boolean LOW = false; final boolean DONT_REWRITE_TYPEVARS = false; Type aHigh = rewriteQuantifiers(a, HIGH, DONT_REWRITE_TYPEVARS); Type aLow = rewriteQuantifiers(a, LOW, DONT_REWRITE_TYPEVARS); Type bHigh = rewriteQuantifiers(b, HIGH, DONT_REWRITE_TYPEVARS); Type bLow = rewriteQuantifiers(b, LOW, DONT_REWRITE_TYPEVARS); Type lowSub = asSub(bLow, aLow.tsym); Type highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym); if (highSub == null) { final boolean REWRITE_TYPEVARS = true; aHigh = rewriteQuantifiers(a, HIGH, REWRITE_TYPEVARS); aLow = rewriteQuantifiers(a, LOW, REWRITE_TYPEVARS); bHigh = rewriteQuantifiers(b, HIGH, REWRITE_TYPEVARS); bLow = rewriteQuantifiers(b, LOW, REWRITE_TYPEVARS); lowSub = asSub(bLow, aLow.tsym); highSub = (lowSub == null) ? null : asSub(bHigh, aHigh.tsym); } if (highSub != null) { if (!(a.tsym == highSub.tsym && a.tsym == lowSub.tsym)) { Assert.error(a.tsym + " != " + highSub.tsym + " != " + lowSub.tsym); } if (!disjointTypes(aHigh.allparams(), highSub.allparams()) && !disjointTypes(aHigh.allparams(), lowSub.allparams()) && !disjointTypes(aLow.allparams(), highSub.allparams()) && !disjointTypes(aLow.allparams(), lowSub.allparams())) { if (upcast ? giveWarning(a, b) : giveWarning(b, a)) warnStack.head.warn(LintCategory.UNCHECKED); return true; } } if (isReifiable(s)) return isSubtypeUnchecked(a, b); else return isSubtypeUnchecked(a, b, warnStack.head); } // Sidecast if (s.tag == CLASS) { if ((s.tsym.flags() & INTERFACE) != 0) { return ((t.tsym.flags() & FINAL) == 0) ? sideCast(t, s, warnStack.head) : sideCastFinal(t, s, warnStack.head); } else if ((t.tsym.flags() & INTERFACE) != 0) { return ((s.tsym.flags() & FINAL) == 0) ? sideCast(t, s, warnStack.head) : sideCastFinal(t, s, warnStack.head); } else { // unrelated class types return false; } } } return false; } @Override public Boolean visitArrayType(ArrayType t, Type s) { switch (s.tag) { case ERROR: case BOT: return true; case TYPEVAR: if (isCastable(s, t, Warner.noWarnings)) { warnStack.head.warn(LintCategory.UNCHECKED); return true; } else { return false; } case CLASS: return isSubtype(t, s); case ARRAY: if (elemtype(t).tag <= lastBaseTag || elemtype(s).tag <= lastBaseTag) { return elemtype(t).tag == elemtype(s).tag; } else { return visit(elemtype(t), elemtype(s)); } default: return false; } } @Override public Boolean visitTypeVar(TypeVar t, Type s) { switch (s.tag) { case ERROR: case BOT: return true; case TYPEVAR: if (isSubtype(t, s)) { return true; } else if (isCastable(t.bound, s, Warner.noWarnings)) { warnStack.head.warn(LintCategory.UNCHECKED); return true; } else { return false; } default: return isCastable(t.bound, s, warnStack.head); } } @Override public Boolean visitErrorType(ErrorType t, Type s) { return true; } }; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="disjointTypes"> public boolean disjointTypes(List<Type> ts, List<Type> ss) { while (ts.tail != null && ss.tail != null) { if (disjointType(ts.head, ss.head)) return true; ts = ts.tail; ss = ss.tail; } return false; } /** * Two types or wildcards are considered disjoint if it can be proven that no * type can be contained in both. It is conservative in that it is allowed to * say that two types are not disjoint, even though they actually are. * * The type C<X> is castable to C<Y> exactly if X and Y are not disjoint. */ public boolean disjointType(Type t, Type s) { return disjointType.visit(t, s); } // where private TypeRelation disjointType = new TypeRelation() { private Set<TypePair> cache = new HashSet<TypePair>(); public Boolean visitType(Type t, Type s) { if (s.tag == WILDCARD) return visit(s, t); else return notSoftSubtypeRecursive(t, s) || notSoftSubtypeRecursive(s, t); } private boolean isCastableRecursive(Type t, Type s) { TypePair pair = new TypePair(t, s); if (cache.add(pair)) { try { return Types.this.isCastable(t, s); } finally { cache.remove(pair); } } else { return true; } } private boolean notSoftSubtypeRecursive(Type t, Type s) { TypePair pair = new TypePair(t, s); if (cache.add(pair)) { try { return Types.this.notSoftSubtype(t, s); } finally { cache.remove(pair); } } else { return false; } } @Override public Boolean visitWildcardType(WildcardType t, Type s) { if (t.isUnbound()) return false; if (s.tag != WILDCARD) { if (t.isExtendsBound()) return notSoftSubtypeRecursive(s, t.type); else // isSuperBound() return notSoftSubtypeRecursive(t.type, s); } if (s.isUnbound()) return false; if (t.isExtendsBound()) { if (s.isExtendsBound()) return !isCastableRecursive(t.type, upperBound(s)); else if (s.isSuperBound()) return notSoftSubtypeRecursive(lowerBound(s), t.type); } else if (t.isSuperBound()) { if (s.isExtendsBound()) return notSoftSubtypeRecursive(t.type, upperBound(s)); } return false; } }; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="lowerBoundArgtypes"> /** * Returns the lower bounds of the formals of a method. */ public List<Type> lowerBoundArgtypes(Type t) { return map(t.getParameterTypes(), lowerBoundMapping); } private final Mapping lowerBoundMapping = new Mapping("lowerBound") { public Type apply(Type t) { return lowerBound(t); } }; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="notSoftSubtype"> /** * This relation answers the question: is impossible that something of type * `t' can be a subtype of `s'? This is different from the question * "is `t' not a subtype of `s'?" when type variables are involved: Integer is * not a subtype of T where <T extends Number> but it is not true that Integer * cannot possibly be a subtype of T. */ public boolean notSoftSubtype(Type t, Type s) { if (t == s) return false; if (t.tag == TYPEVAR) { TypeVar tv = (TypeVar) t; return !isCastable(tv.bound, relaxBound(s), Warner.noWarnings); } if (s.tag != WILDCARD) s = upperBound(s); return !isSubtype(t, relaxBound(s)); } private Type relaxBound(Type t) { if (t.tag == TYPEVAR) { while (t.tag == TYPEVAR) t = t.getUpperBound(); t = rewriteQuantifiers(t, true, true); } return t; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="isReifiable"> public boolean isReifiable(Type t) { return isReifiable.visit(t); } // where private UnaryVisitor<Boolean> isReifiable = new UnaryVisitor<Boolean>() { public Boolean visitType(Type t, Void ignored) { return true; } @Override public Boolean visitClassType(ClassType t, Void ignored) { if (t.isCompound()) return false; else { if (!t.isParameterized()) return true; for (Type param : t.allparams()) { if (!param.isUnbound()) return false; } return true; } } @Override public Boolean visitArrayType(ArrayType t, Void ignored) { return visit(t.elemtype); } @Override public Boolean visitTypeVar(TypeVar t, Void ignored) { return false; } }; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Array Utils"> public boolean isArray(Type t) { while (t.tag == WILDCARD) t = upperBound(t); return t.tag == ARRAY; } /** * The element type of an array. */ public Type elemtype(Type t) { switch (t.tag) { case WILDCARD: return elemtype(upperBound(t)); case ARRAY: return ((ArrayType) t).elemtype; case FORALL: return elemtype(((ForAll) t).qtype); case ERROR: return t; default: return null; } } public Type elemtypeOrType(Type t) { Type elemtype = elemtype(t); return elemtype != null ? elemtype : t; } /** * Mapping to take element type of an arraytype */ private Mapping elemTypeFun = new Mapping("elemTypeFun") { public Type apply(Type t) { return elemtype(t); } }; /** * The number of dimensions of an array type. */ public int dimensions(Type t) { int result = 0; while (t.tag == ARRAY) { result++; t = elemtype(t); } return result; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="asSuper"> /** * Return the (most specific) base type of t that starts with the given * symbol. If none exists, return null. * * @param t * a type * @param sym * a symbol */ public Type asSuper(Type t, Symbol sym) { return asSuper.visit(t, sym); } // where private SimpleVisitor<Type, Symbol> asSuper = new SimpleVisitor<Type, Symbol>() { public Type visitType(Type t, Symbol sym) { return null; } @Override public Type visitClassType(ClassType t, Symbol sym) { if (t.tsym == sym) return t; Type st = supertype(t); if (st.tag == CLASS || st.tag == TYPEVAR || st.tag == ERROR) { Type x = asSuper(st, sym); if (x != null) return x; } if ((sym.flags() & INTERFACE) != 0) { for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) { Type x = asSuper(l.head, sym); if (x != null) return x; } } return null; } @Override public Type visitArrayType(ArrayType t, Symbol sym) { return isSubtype(t, sym.type) ? sym.type : null; } @Override public Type visitTypeVar(TypeVar t, Symbol sym) { if (t.tsym == sym) return t; else return asSuper(t.bound, sym); } @Override public Type visitErrorType(ErrorType t, Symbol sym) { return t; } }; /** * Return the base type of t or any of its outer types that starts with the * given symbol. If none exists, return null. * * @param t * a type * @param sym * a symbol */ public Type asOuterSuper(Type t, Symbol sym) { switch (t.tag) { case CLASS: do { Type s = asSuper(t, sym); if (s != null) return s; t = t.getEnclosingType(); } while (t.tag == CLASS); return null; case ARRAY: return isSubtype(t, sym.type) ? sym.type : null; case TYPEVAR: return asSuper(t, sym); case ERROR: return t; default: return null; } } /** * Return the base type of t or any of its enclosing types that starts with * the given symbol. If none exists, return null. * * @param t * a type * @param sym * a symbol */ public Type asEnclosingSuper(Type t, Symbol sym) { switch (t.tag) { case CLASS: do { Type s = asSuper(t, sym); if (s != null) return s; Type outer = t.getEnclosingType(); t = (outer.tag == CLASS) ? outer : (t.tsym.owner.enclClass() != null) ? t.tsym.owner.enclClass().type : Type.noType; } while (t.tag == CLASS); return null; case ARRAY: return isSubtype(t, sym.type) ? sym.type : null; case TYPEVAR: return asSuper(t, sym); case ERROR: return t; default: return null; } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="memberType"> /** * The type of given symbol, seen as a member of t. * * @param t * a type * @param sym * a symbol */ public Type memberType(Type t, Symbol sym) { return (sym.flags() & STATIC) != 0 ? sym.type : memberType.visit(t, sym); } // where private SimpleVisitor<Type, Symbol> memberType = new SimpleVisitor<Type, Symbol>() { public Type visitType(Type t, Symbol sym) { return sym.type; } @Override public Type visitWildcardType(WildcardType t, Symbol sym) { return memberType(upperBound(t), sym); } @Override public Type visitClassType(ClassType t, Symbol sym) { Symbol owner = sym.owner; long flags = sym.flags(); if (((flags & STATIC) == 0) && owner.type.isParameterized()) { Type base = asOuterSuper(t, owner); // if t is an // intersection type T = // CT & I1 & I2 ... & In // its supertypes CT, I1, // ... In might contain // wildcards // so we need to go // through capture // conversion base = t.isCompound() ? capture(base) : base; if (base != null) { List<Type> ownerParams = owner.type.allparams(); List<Type> baseParams = base.allparams(); if (ownerParams.nonEmpty()) { if (baseParams.isEmpty()) { // then base is a // raw type return erasure(sym.type); } else { return subst(sym.type, ownerParams, baseParams); } } } } return sym.type; } @Override public Type visitTypeVar(TypeVar t, Symbol sym) { return memberType(t.bound, sym); } @Override public Type visitErrorType(ErrorType t, Symbol sym) { return t; } }; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="isAssignable"> public boolean isAssignable(Type t, Type s) { return isAssignable(t, s, Warner.noWarnings); } /** * Is t assignable to s?<br> * Equivalent to subtype except for constant values and raw types.<br> * (not defined for Method and ForAll types) */ public boolean isAssignable(Type t, Type s, Warner warn) { if (t.tag == ERROR) return true; if (t.tag <= INT && t.constValue() != null) { int value = ((Number) t.constValue()).intValue(); switch (s.tag) { case BYTE: if (Byte.MIN_VALUE <= value && value <= Byte.MAX_VALUE) return true; break; case CHAR: if (Character.MIN_VALUE <= value && value <= Character.MAX_VALUE) return true; break; case SHORT: if (Short.MIN_VALUE <= value && value <= Short.MAX_VALUE) return true; break; case INT: return true; case CLASS: switch (unboxedType(s).tag) { case BYTE: case CHAR: case SHORT: return isAssignable(t, unboxedType(s), warn); } break; } } return isConvertible(t, s, warn); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="erasure"> /** * The erasure of t {@code |t|} -- the type that results when all type * parameters in t are deleted. */ public Type erasure(Type t) { return erasure(t, false); } // where private Type erasure(Type t, boolean recurse) { if (t.tag <= lastBaseTag) return t; /* fast special case */ else return erasure.visit(t, recurse); } // where private SimpleVisitor<Type, Boolean> erasure = new SimpleVisitor<Type, Boolean>() { public Type visitType(Type t, Boolean recurse) { if (t.tag <= lastBaseTag) return t; /* * fast special case */ else return t.map(recurse ? erasureRecFun : erasureFun); } @Override public Type visitWildcardType(WildcardType t, Boolean recurse) { return erasure(upperBound(t), recurse); } @Override public Type visitClassType(ClassType t, Boolean recurse) { Type erased = t.tsym.erasure(Types.this); if (recurse) { erased = new ErasedClassType(erased.getEnclosingType(), erased.tsym); } return erased; } @Override public Type visitTypeVar(TypeVar t, Boolean recurse) { return erasure(t.bound, recurse); } @Override public Type visitErrorType(ErrorType t, Boolean recurse) { return t; } }; private Mapping erasureFun = new Mapping("erasure") { public Type apply(Type t) { return erasure(t); } }; private Mapping erasureRecFun = new Mapping("erasureRecursive") { public Type apply(Type t) { return erasureRecursive(t); } }; public List<Type> erasure(List<Type> ts) { return Type.map(ts, erasureFun); } public Type erasureRecursive(Type t) { return erasure(t, true); } public List<Type> erasureRecursive(List<Type> ts) { return Type.map(ts, erasureRecFun); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="makeCompoundType"> /** * Make a compound type from non-empty list of types * * @param bounds * the types from which the compound type is formed * @param supertype * is objectType if all bounds are interfaces, null otherwise. */ public Type makeCompoundType(List<Type> bounds, Type supertype) { ClassSymbol bc = new ClassSymbol(ABSTRACT | PUBLIC | SYNTHETIC | COMPOUND | ACYCLIC, Type.moreInfo ? names.fromString(bounds.toString()) : names.empty, syms.noSymbol); if (bounds.head.tag == TYPEVAR) // error condition, recover bc.erasure_field = syms.objectType; else bc.erasure_field = erasure(bounds.head); bc.members_field = new Scope(bc); ClassType bt = (ClassType) bc.type; bt.allparams_field = List.nil(); if (supertype != null) { bt.supertype_field = supertype; bt.interfaces_field = bounds; } else { bt.supertype_field = bounds.head; bt.interfaces_field = bounds.tail; } Assert.check(bt.supertype_field.tsym.completer != null || !bt.supertype_field.isInterface(), bt.supertype_field); return bt; } /** * Same as {@link #makeCompoundType(List,Type)}, except that the second * parameter is computed directly. Note that this might cause a symbol * completion. Hence, this version of makeCompoundType may not be called * during a classfile read. */ public Type makeCompoundType(List<Type> bounds) { Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ? supertype(bounds.head) : null; return makeCompoundType(bounds, supertype); } /** * A convenience wrapper for {@link #makeCompoundType(List)}; the arguments * are converted to a list and passed to the other method. Note that this * might cause a symbol completion. Hence, this version of makeCompoundType * may not be called during a classfile read. */ public Type makeCompoundType(Type bound1, Type bound2) { return makeCompoundType(List.of(bound1, bound2)); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="supertype"> public Type supertype(Type t) { return supertype.visit(t); } // where private UnaryVisitor<Type> supertype = new UnaryVisitor<Type>() { public Type visitType(Type t, Void ignored) { // A note on wildcards: there is no // good way to // determine a supertype for a super // bounded wildcard. return null; } @Override public Type visitClassType(ClassType t, Void ignored) { if (t.supertype_field == null) { Type supertype = ((ClassSymbol) t.tsym).getSuperclass(); // An interface has no superclass; // its supertype is Object. if (t.isInterface()) supertype = ((ClassType) t.tsym.type).supertype_field; if (t.supertype_field == null) { List<Type> actuals = classBound(t).allparams(); List<Type> formals = t.tsym.type.allparams(); if (t.hasErasedSupertypes()) { t.supertype_field = erasureRecursive(supertype); } else if (formals.nonEmpty()) { t.supertype_field = subst(supertype, formals, actuals); } else { t.supertype_field = supertype; } } } return t.supertype_field; } /** * The supertype is always a class type. If the type variable's bounds start * with a class type, this is also the supertype. Otherwise, the supertype * is java.lang.Object. */ @Override public Type visitTypeVar(TypeVar t, Void ignored) { if (t.bound.tag == TYPEVAR || (!t.bound.isCompound() && !t.bound.isInterface())) { return t.bound; } else { return supertype(t.bound); } } @Override public Type visitArrayType(ArrayType t, Void ignored) { if (t.elemtype.isPrimitive() || isSameType(t.elemtype, syms.objectType)) return arraySuperType(); else return new ArrayType(supertype(t.elemtype), t.tsym); } @Override public Type visitErrorType(ErrorType t, Void ignored) { return t; } }; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="interfaces"> /** * Return the interfaces implemented by this class. */ public List<Type> interfaces(Type t) { return interfaces.visit(t); } // where private UnaryVisitor<List<Type>> interfaces = new UnaryVisitor<List<Type>>() { public List<Type> visitType(Type t, Void ignored) { return List.nil(); } @Override public List<Type> visitClassType(ClassType t, Void ignored) { if (t.interfaces_field == null) { List<Type> interfaces = ((ClassSymbol) t.tsym).getInterfaces(); if (t.interfaces_field == null) { // If // t.interfaces_field // is null, then t // must // be a // parameterized // type (not to be // confused // with a generic // type // declaration). // Terminology: // Parameterized // type: // List<String> // Generic type // declaration: // class List<E> { // ... } // So t corresponds // to List<String> // and // t.tsym.type // corresponds to // List<E>. // The reason t // must be // parameterized // type is // that completion // will happen as a // side // effect of // calling // ClassSymbol.getInterfaces. // Since // t.interfaces_field // is null after // completion, we // can assume that // t is not the // type of a // class/interface // declaration. Assert.check(t != t.tsym.type, t); List<Type> actuals = t.allparams(); List<Type> formals = t.tsym.type.allparams(); if (t.hasErasedSupertypes()) { t.interfaces_field = erasureRecursive(interfaces); } else if (formals.nonEmpty()) { t.interfaces_field = upperBounds(subst(interfaces, formals, actuals)); } else { t.interfaces_field = interfaces; } } } return t.interfaces_field; } @Override public List<Type> visitTypeVar(TypeVar t, Void ignored) { if (t.bound.isCompound()) return interfaces(t.bound); if (t.bound.isInterface()) return List.of(t.bound); return List.nil(); } }; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="isDerivedRaw"> Map<Type, Boolean> isDerivedRawCache = new HashMap<Type, Boolean>(); public boolean isDerivedRaw(Type t) { Boolean result = isDerivedRawCache.get(t); if (result == null) { result = isDerivedRawInternal(t); isDerivedRawCache.put(t, result); } return result; } public boolean isDerivedRawInternal(Type t) { if (t.isErroneous()) return false; return t.isRaw() || supertype(t) != null && isDerivedRaw(supertype(t)) || isDerivedRaw(interfaces(t)); } public boolean isDerivedRaw(List<Type> ts) { List<Type> l = ts; while (l.nonEmpty() && !isDerivedRaw(l.head)) l = l.tail; return l.nonEmpty(); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="setBounds"> /** * Set the bounds field of the given type variable to reflect a (possibly * multiple) list of bounds. * * @param t * a type variable * @param bounds * the bounds, must be nonempty * @param supertype * is objectType if all bounds are interfaces, null otherwise. */ public void setBounds(TypeVar t, List<Type> bounds, Type supertype) { if (bounds.tail.isEmpty()) t.bound = bounds.head; else t.bound = makeCompoundType(bounds, supertype); t.rank_field = -1; } /** * Same as {@link #setBounds(Type.TypeVar,List,Type)}, except that third * parameter is computed directly, as follows: if all all bounds are interface * types, the computed supertype is Object, otherwise the supertype is simply * left null (in this case, the supertype is assumed to be the head of the * bound list passed as second argument). Note that this check might cause a * symbol completion. Hence, this version of setBounds may not be called * during a classfile read. */ public void setBounds(TypeVar t, List<Type> bounds) { Type supertype = (bounds.head.tsym.flags() & INTERFACE) != 0 ? syms.objectType : null; setBounds(t, bounds, supertype); t.rank_field = -1; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="getBounds"> /** * Return list of bounds of the given type variable. */ public List<Type> getBounds(TypeVar t) { if (t.bound.isErroneous() || !t.bound.isCompound()) return List.of(t.bound); else if ((erasure(t).tsym.flags() & INTERFACE) == 0) return interfaces(t).prepend(supertype(t)); else // No superclass was given in bounds. // In this case, supertype is Object, erasure is first interface. return interfaces(t); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="classBound"> /** * If the given type is a (possibly selected) type variable, return the * bounding class of this type, otherwise return the type itself. */ public Type classBound(Type t) { return classBound.visit(t); } // where private UnaryVisitor<Type> classBound = new UnaryVisitor<Type>() { public Type visitType(Type t, Void ignored) { return t; } @Override public Type visitClassType(ClassType t, Void ignored) { Type outer1 = classBound(t.getEnclosingType()); if (outer1 != t.getEnclosingType()) return new ClassType(outer1, t.getTypeArguments(), t.tsym); else return t; } @Override public Type visitTypeVar(TypeVar t, Void ignored) { return classBound(supertype(t)); } @Override public Type visitErrorType(ErrorType t, Void ignored) { return t; } }; // </editor-fold> // <editor-fold defaultstate="collapsed" // desc="sub signature / override equivalence"> /** * Returns true iff the first signature is a <em>sub * signature</em> of the other. This is <b>not</b> an equivalence relation. * * @jls section 8.4.2. * @see #overrideEquivalent(Type t, Type s) * @param t * first signature (possibly raw). * @param s * second signature (could be subjected to erasure). * @return true if t is a sub signature of s. */ public boolean isSubSignature(Type t, Type s) { return isSubSignature(t, s, true); } public boolean isSubSignature(Type t, Type s, boolean strict) { return hasSameArgs(t, s, strict) || hasSameArgs(t, erasure(s), strict); } /** * Returns true iff these signatures are related by <em>override * equivalence</em>. This is the natural extension of isSubSignature to an * equivalence relation. * * @jls section 8.4.2. * @see #isSubSignature(Type t, Type s) * @param t * a signature (possible raw, could be subjected to erasure). * @param s * a signature (possible raw, could be subjected to erasure). * @return true if either argument is a sub signature of the other. */ public boolean overrideEquivalent(Type t, Type s) { return hasSameArgs(t, s) || hasSameArgs(t, erasure(s)) || hasSameArgs(erasure(t), s); } // <editor-fold defaultstate="collapsed" // desc="Determining method implementation in given site"> class ImplementationCache { private WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>> _map = new WeakHashMap<MethodSymbol, SoftReference<Map<TypeSymbol, Entry>>>(); class Entry { final MethodSymbol cachedImpl; final Filter<Symbol> implFilter; final boolean checkResult; final int prevMark; public Entry(MethodSymbol cachedImpl, Filter<Symbol> scopeFilter, boolean checkResult, int prevMark) { this.cachedImpl = cachedImpl; this.implFilter = scopeFilter; this.checkResult = checkResult; this.prevMark = prevMark; } boolean matches(Filter<Symbol> scopeFilter, boolean checkResult, int mark) { return this.implFilter == scopeFilter && this.checkResult == checkResult && this.prevMark == mark; } } MethodSymbol get(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) { SoftReference<Map<TypeSymbol, Entry>> ref_cache = _map.get(ms); Map<TypeSymbol, Entry> cache = ref_cache != null ? ref_cache.get() : null; if (cache == null) { cache = new HashMap<TypeSymbol, Entry>(); _map.put(ms, new SoftReference<Map<TypeSymbol, Entry>>(cache)); } Entry e = cache.get(origin); CompoundScope members = membersClosure(origin.type, true); if (e == null || !e.matches(implFilter, checkResult, members.getMark())) { MethodSymbol impl = implementationInternal(ms, origin, checkResult, implFilter); cache.put(origin, new Entry(impl, implFilter, checkResult, members.getMark())); return impl; } else { return e.cachedImpl; } } private MethodSymbol implementationInternal(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) { for (Type t = origin.type; t.tag == CLASS || t.tag == TYPEVAR; t = supertype(t)) { while (t.tag == TYPEVAR) t = t.getUpperBound(); TypeSymbol c = t.tsym; for (Scope.Entry e = c.members().lookup(ms.name, implFilter); e.scope != null; e = e .next(implFilter)) { if (e.sym != null && e.sym.overrides(ms, origin, Types.this, checkResult)) return (MethodSymbol) e.sym; } } return null; } } private ImplementationCache implCache = new ImplementationCache(); public MethodSymbol implementation(MethodSymbol ms, TypeSymbol origin, boolean checkResult, Filter<Symbol> implFilter) { return implCache.get(ms, origin, checkResult, implFilter); } // </editor-fold> // <editor-fold defaultstate="collapsed" // desc="compute transitive closure of all members in given site"> class MembersClosureCache extends SimpleVisitor<CompoundScope, Boolean> { private WeakHashMap<TypeSymbol, Entry> _map = new WeakHashMap<TypeSymbol, Entry>(); class Entry { final boolean skipInterfaces; final CompoundScope compoundScope; public Entry(boolean skipInterfaces, CompoundScope compoundScope) { this.skipInterfaces = skipInterfaces; this.compoundScope = compoundScope; } boolean matches(boolean skipInterfaces) { return this.skipInterfaces == skipInterfaces; } } /** members closure visitor methods **/ public CompoundScope visitType(Type t, Boolean skipInterface) { return null; } @Override public CompoundScope visitClassType(ClassType t, Boolean skipInterface) { ClassSymbol csym = (ClassSymbol) t.tsym; Entry e = _map.get(csym); if (e == null || !e.matches(skipInterface)) { CompoundScope membersClosure = new CompoundScope(csym); if (!skipInterface) { for (Type i : interfaces(t)) { membersClosure.addSubScope(visit(i, skipInterface)); } } membersClosure.addSubScope(visit(supertype(t), skipInterface)); membersClosure.addSubScope(csym.members()); e = new Entry(skipInterface, membersClosure); _map.put(csym, e); } return e.compoundScope; } @Override public CompoundScope visitTypeVar(TypeVar t, Boolean skipInterface) { return visit(t.getUpperBound(), skipInterface); } } private MembersClosureCache membersCache = new MembersClosureCache(); public CompoundScope membersClosure(Type site, boolean skipInterface) { return membersCache.visit(site, skipInterface); } // </editor-fold> /** * Does t have the same arguments as s? It is assumed that both types are * (possibly polymorphic) method types. Monomorphic method types * "have the same arguments", if their argument lists are equal. Polymorphic * method types "have the same arguments", if they have the same arguments * after renaming all type variables of one to corresponding type variables in * the other, where correspondence is by position in the type parameter list. */ public boolean hasSameArgs(Type t, Type s) { return hasSameArgs(t, s, true); } public boolean hasSameArgs(Type t, Type s, boolean strict) { return hasSameArgs(t, s, strict ? hasSameArgs_strict : hasSameArgs_nonstrict); } private boolean hasSameArgs(Type t, Type s, TypeRelation hasSameArgs) { return hasSameArgs.visit(t, s); } // where private class HasSameArgs extends TypeRelation { boolean strict; public HasSameArgs(boolean strict) { this.strict = strict; } public Boolean visitType(Type t, Type s) { throw new AssertionError(); } @Override public Boolean visitMethodType(MethodType t, Type s) { return s.tag == METHOD && containsTypeEquivalent(t.argtypes, s.getParameterTypes()); } @Override public Boolean visitForAll(ForAll t, Type s) { if (s.tag != FORALL) return strict ? false : visitMethodType(t.asMethodType(), s); ForAll forAll = (ForAll) s; return hasSameBounds(t, forAll) && visit(t.qtype, subst(forAll.qtype, forAll.tvars, t.tvars)); } @Override public Boolean visitErrorType(ErrorType t, Type s) { return false; } }; TypeRelation hasSameArgs_strict = new HasSameArgs(true); TypeRelation hasSameArgs_nonstrict = new HasSameArgs(false); // </editor-fold> // <editor-fold defaultstate="collapsed" desc="subst"> public List<Type> subst(List<Type> ts, List<Type> from, List<Type> to) { return new Subst(from, to).subst(ts); } /** * Substitute all occurrences of a type in `from' with the corresponding type * in `to' in 't'. Match lists `from' and `to' from the right: If lists have * different length, discard leading elements of the longer list. */ public Type subst(Type t, List<Type> from, List<Type> to) { return new Subst(from, to).subst(t); } private class Subst extends UnaryVisitor<Type> { List<Type> from; List<Type> to; public Subst(List<Type> from, List<Type> to) { int fromLength = from.length(); int toLength = to.length(); while (fromLength > toLength) { fromLength--; from = from.tail; } while (fromLength < toLength) { toLength--; to = to.tail; } this.from = from; this.to = to; } Type subst(Type t) { if (from.tail == null) return t; else return visit(t); } List<Type> subst(List<Type> ts) { if (from.tail == null) return ts; boolean wild = false; if (ts.nonEmpty() && from.nonEmpty()) { Type head1 = subst(ts.head); List<Type> tail1 = subst(ts.tail); if (head1 != ts.head || tail1 != ts.tail) return tail1.prepend(head1); } return ts; } public Type visitType(Type t, Void ignored) { return t; } @Override public Type visitMethodType(MethodType t, Void ignored) { List<Type> argtypes = subst(t.argtypes); Type restype = subst(t.restype); List<Type> thrown = subst(t.thrown); if (argtypes == t.argtypes && restype == t.restype && thrown == t.thrown) return t; else return new MethodType(argtypes, restype, thrown, t.tsym); } @Override public Type visitTypeVar(TypeVar t, Void ignored) { for (List<Type> from = this.from, to = this.to; from.nonEmpty(); from = from.tail, to = to.tail) { if (t == from.head) { return to.head.withTypeVar(t); } } return t; } @Override public Type visitClassType(ClassType t, Void ignored) { if (!t.isCompound()) { List<Type> typarams = t.getTypeArguments(); List<Type> typarams1 = subst(typarams); Type outer = t.getEnclosingType(); Type outer1 = subst(outer); if (typarams1 == typarams && outer1 == outer) return t; else return new ClassType(outer1, typarams1, t.tsym); } else { Type st = subst(supertype(t)); List<Type> is = upperBounds(subst(interfaces(t))); if (st == supertype(t) && is == interfaces(t)) return t; else return makeCompoundType(is.prepend(st)); } } @Override public Type visitWildcardType(WildcardType t, Void ignored) { Type bound = t.type; if (t.kind != BoundKind.UNBOUND) bound = subst(bound); if (bound == t.type) { return t; } else { if (t.isExtendsBound() && bound.isExtendsBound()) bound = upperBound(bound); return new WildcardType(bound, t.kind, syms.boundClass, t.bound); } } @Override public Type visitArrayType(ArrayType t, Void ignored) { Type elemtype = subst(t.elemtype); if (elemtype == t.elemtype) return t; else return new ArrayType(upperBound(elemtype), t.tsym); } @Override public Type visitForAll(ForAll t, Void ignored) { if (Type.containsAny(to, t.tvars)) { // perform alpha-renaming of free-variables in 't' // if 'to' types contain variables that are free in 't' List<Type> freevars = newInstances(t.tvars); t = new ForAll(freevars, Types.this.subst(t.qtype, t.tvars, freevars)); } List<Type> tvars1 = substBounds(t.tvars, from, to); Type qtype1 = subst(t.qtype); if (tvars1 == t.tvars && qtype1 == t.qtype) { return t; } else if (tvars1 == t.tvars) { return new ForAll(tvars1, qtype1); } else { return new ForAll(tvars1, Types.this.subst(qtype1, t.tvars, tvars1)); } } @Override public Type visitErrorType(ErrorType t, Void ignored) { return t; } } public List<Type> substBounds(List<Type> tvars, List<Type> from, List<Type> to) { if (tvars.isEmpty()) return tvars; ListBuffer<Type> newBoundsBuf = lb(); boolean changed = false; // calculate new bounds for (Type t : tvars) { TypeVar tv = (TypeVar) t; Type bound = subst(tv.bound, from, to); if (bound != tv.bound) changed = true; newBoundsBuf.append(bound); } if (!changed) return tvars; ListBuffer<Type> newTvars = lb(); // create new type variables without bounds for (Type t : tvars) { newTvars.append(new TypeVar(t.tsym, null, syms.botType)); } // the new bounds should use the new type variables in place // of the old List<Type> newBounds = newBoundsBuf.toList(); from = tvars; to = newTvars.toList(); for (; !newBounds.isEmpty(); newBounds = newBounds.tail) { newBounds.head = subst(newBounds.head, from, to); } newBounds = newBoundsBuf.toList(); // set the bounds of new type variables to the new bounds for (Type t : newTvars.toList()) { TypeVar tv = (TypeVar) t; tv.bound = newBounds.head; newBounds = newBounds.tail; } return newTvars.toList(); } public TypeVar substBound(TypeVar t, List<Type> from, List<Type> to) { Type bound1 = subst(t.bound, from, to); if (bound1 == t.bound) return t; else { // create new type variable without bounds TypeVar tv = new TypeVar(t.tsym, null, syms.botType); // the new bound should use the new type variable in place // of the old tv.bound = subst(bound1, List.<Type> of(t), List.<Type> of(tv)); return tv; } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="hasSameBounds"> /** * Does t have the same bounds for quantified variables as s? */ boolean hasSameBounds(ForAll t, ForAll s) { List<Type> l1 = t.tvars; List<Type> l2 = s.tvars; while (l1.nonEmpty() && l2.nonEmpty() && isSameType(l1.head.getUpperBound(), subst(l2.head.getUpperBound(), s.tvars, t.tvars))) { l1 = l1.tail; l2 = l2.tail; } return l1.isEmpty() && l2.isEmpty(); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="newInstances"> /** * Create new vector of type variables from list of variables changing all * recursive bounds from old to new list. */ public List<Type> newInstances(List<Type> tvars) { List<Type> tvars1 = Type.map(tvars, newInstanceFun); for (List<Type> l = tvars1; l.nonEmpty(); l = l.tail) { TypeVar tv = (TypeVar) l.head; tv.bound = subst(tv.bound, tvars, tvars1); } return tvars1; } static private Mapping newInstanceFun = new Mapping("newInstanceFun") { public Type apply(Type t) { return new TypeVar(t.tsym, t.getUpperBound(), t.getLowerBound()); } }; // </editor-fold> public Type createMethodTypeWithParameters(Type original, List<Type> newParams) { return original.accept(methodWithParameters, newParams); } // where private final MapVisitor<List<Type>> methodWithParameters = new MapVisitor<List<Type>>() { public Type visitType(Type t, List<Type> newParams) { throw new IllegalArgumentException("Not a method type: " + t); } public Type visitMethodType(MethodType t, List<Type> newParams) { return new MethodType(newParams, t.restype, t.thrown, t.tsym); } public Type visitForAll(ForAll t, List<Type> newParams) { return new ForAll(t.tvars, t.qtype.accept(this, newParams)); } }; public Type createMethodTypeWithThrown(Type original, List<Type> newThrown) { return original.accept(methodWithThrown, newThrown); } // where private final MapVisitor<List<Type>> methodWithThrown = new MapVisitor<List<Type>>() { public Type visitType(Type t, List<Type> newThrown) { throw new IllegalArgumentException("Not a method type: " + t); } public Type visitMethodType(MethodType t, List<Type> newThrown) { return new MethodType(t.argtypes, t.restype, newThrown, t.tsym); } public Type visitForAll(ForAll t, List<Type> newThrown) { return new ForAll(t.tvars, t.qtype.accept(this, newThrown)); } }; public Type createMethodTypeWithReturn(Type original, Type newReturn) { return original.accept(methodWithReturn, newReturn); } // where private final MapVisitor<Type> methodWithReturn = new MapVisitor<Type>() { public Type visitType(Type t, Type newReturn) { throw new IllegalArgumentException("Not a method type: " + t); } public Type visitMethodType(MethodType t, Type newReturn) { return new MethodType(t.argtypes, newReturn, t.thrown, t.tsym); } public Type visitForAll(ForAll t, Type newReturn) { return new ForAll(t.tvars, t.qtype.accept(this, newReturn)); } }; // <editor-fold defaultstate="collapsed" desc="createErrorType"> public Type createErrorType(Type originalType) { return new ErrorType(originalType, syms.errSymbol); } public Type createErrorType(ClassSymbol c, Type originalType) { return new ErrorType(c, originalType); } public Type createErrorType(Name name, TypeSymbol container, Type originalType) { return new ErrorType(name, container, originalType); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="rank"> /** * The rank of a class is the length of the longest path between the class and * java.lang.Object in the class inheritance graph. Undefined for all but * reference types. */ public int rank(Type t) { switch (t.tag) { case CLASS: { ClassType cls = (ClassType) t; if (cls.rank_field < 0) { Name fullname = cls.tsym.getQualifiedName(); if (fullname == names.java_lang_Object) cls.rank_field = 0; else { int r = rank(supertype(cls)); for (List<Type> l = interfaces(cls); l.nonEmpty(); l = l.tail) { if (rank(l.head) > r) r = rank(l.head); } cls.rank_field = r + 1; } } return cls.rank_field; } case TYPEVAR: { TypeVar tvar = (TypeVar) t; if (tvar.rank_field < 0) { int r = rank(supertype(tvar)); for (List<Type> l = interfaces(tvar); l.nonEmpty(); l = l.tail) { if (rank(l.head) > r) r = rank(l.head); } tvar.rank_field = r + 1; } return tvar.rank_field; } case ERROR: return 0; default: throw new AssertionError(); } } // </editor-fold> /** * Helper method for generating a string representation of a given type * accordingly to a given locale */ public String toString(Type t, Locale locale) { return Printer.createStandardPrinter(messages).visit(t, locale); } /** * Helper method for generating a string representation of a given type * accordingly to a given locale */ public String toString(Symbol t, Locale locale) { return Printer.createStandardPrinter(messages).visit(t, locale); } // <editor-fold defaultstate="collapsed" desc="toString"> /** * This toString is slightly more descriptive than the one on Type. * * @deprecated Types.toString(Type t, Locale l) provides better support for * localization */ @Deprecated public String toString(Type t) { if (t.tag == FORALL) { ForAll forAll = (ForAll) t; return typaramsString(forAll.tvars) + forAll.qtype; } return "" + t; } // where private String typaramsString(List<Type> tvars) { StringBuilder s = new StringBuilder(); s.append('<'); boolean first = true; for (Type t : tvars) { if (!first) s.append(", "); first = false; appendTyparamString(((TypeVar) t), s); } s.append('>'); return s.toString(); } private void appendTyparamString(TypeVar t, StringBuilder buf) { buf.append(t); if (t.bound == null || t.bound.tsym.getQualifiedName() == names.java_lang_Object) return; buf.append(" extends "); // Java syntax; no need for i18n Type bound = t.bound; if (!bound.isCompound()) { buf.append(bound); } else if ((erasure(t).tsym.flags() & INTERFACE) == 0) { buf.append(supertype(t)); for (Type intf : interfaces(t)) { buf.append('&'); buf.append(intf); } } else { // No superclass was given in bounds. // In this case, supertype is Object, erasure is first interface. boolean first = true; for (Type intf : interfaces(t)) { if (!first) buf.append('&'); first = false; buf.append(intf); } } } // </editor-fold> // <editor-fold defaultstate="collapsed" // desc="Determining least upper bounds of types"> /** * A cache for closures. * * <p> * A closure is a list of all the supertypes and interfaces of a class or * interface type, ordered by ClassSymbol.precedes (that is, subclasses come * first, arbitrary but fixed otherwise). */ private Map<Type, List<Type>> closureCache = new HashMap<Type, List<Type>>(); /** * Returns the closure of a class or interface type. */ public List<Type> closure(Type t) { List<Type> cl = closureCache.get(t); if (cl == null) { Type st = supertype(t); if (!t.isCompound()) { if (st.tag == CLASS) { cl = insert(closure(st), t); } else if (st.tag == TYPEVAR) { cl = closure(st).prepend(t); } else { cl = List.of(t); } } else { cl = closure(supertype(t)); } for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) cl = union(cl, closure(l.head)); closureCache.put(t, cl); } return cl; } /** * Insert a type in a closure */ public List<Type> insert(List<Type> cl, Type t) { if (cl.isEmpty() || t.tsym.precedes(cl.head.tsym, this)) { return cl.prepend(t); } else if (cl.head.tsym.precedes(t.tsym, this)) { return insert(cl.tail, t).prepend(cl.head); } else { return cl; } } /** * Form the union of two closures */ public List<Type> union(List<Type> cl1, List<Type> cl2) { if (cl1.isEmpty()) { return cl2; } else if (cl2.isEmpty()) { return cl1; } else if (cl1.head.tsym.precedes(cl2.head.tsym, this)) { return union(cl1.tail, cl2).prepend(cl1.head); } else if (cl2.head.tsym.precedes(cl1.head.tsym, this)) { return union(cl1, cl2.tail).prepend(cl2.head); } else { return union(cl1.tail, cl2.tail).prepend(cl1.head); } } /** * Intersect two closures */ public List<Type> intersect(List<Type> cl1, List<Type> cl2) { if (cl1 == cl2) return cl1; if (cl1.isEmpty() || cl2.isEmpty()) return List.nil(); if (cl1.head.tsym.precedes(cl2.head.tsym, this)) return intersect(cl1.tail, cl2); if (cl2.head.tsym.precedes(cl1.head.tsym, this)) return intersect(cl1, cl2.tail); if (isSameType(cl1.head, cl2.head)) return intersect(cl1.tail, cl2.tail).prepend(cl1.head); if (cl1.head.tsym == cl2.head.tsym && cl1.head.tag == CLASS && cl2.head.tag == CLASS) { if (cl1.head.isParameterized() && cl2.head.isParameterized()) { Type merge = merge(cl1.head, cl2.head); return intersect(cl1.tail, cl2.tail).prepend(merge); } if (cl1.head.isRaw() || cl2.head.isRaw()) return intersect(cl1.tail, cl2.tail).prepend(erasure(cl1.head)); } return intersect(cl1.tail, cl2.tail); } // where class TypePair { final Type t1; final Type t2; TypePair(Type t1, Type t2) { this.t1 = t1; this.t2 = t2; } @Override public int hashCode() { return 127 * Types.hashCode(t1) + Types.hashCode(t2); } @Override public boolean equals(Object obj) { if (!(obj instanceof TypePair)) return false; TypePair typePair = (TypePair) obj; return isSameType(t1, typePair.t1) && isSameType(t2, typePair.t2); } } Set<TypePair> mergeCache = new HashSet<TypePair>(); private Type merge(Type c1, Type c2) { ClassType class1 = (ClassType) c1; List<Type> act1 = class1.getTypeArguments(); ClassType class2 = (ClassType) c2; List<Type> act2 = class2.getTypeArguments(); ListBuffer<Type> merged = new ListBuffer<Type>(); List<Type> typarams = class1.tsym.type.getTypeArguments(); while (act1.nonEmpty() && act2.nonEmpty() && typarams.nonEmpty()) { if (containsType(act1.head, act2.head)) { merged.append(act1.head); } else if (containsType(act2.head, act1.head)) { merged.append(act2.head); } else { TypePair pair = new TypePair(c1, c2); Type m; if (mergeCache.add(pair)) { m = new WildcardType( lub(upperBound(act1.head), upperBound(act2.head)), BoundKind.EXTENDS, syms.boundClass); mergeCache.remove(pair); } else { m = new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass); } merged.append(m.withTypeVar(typarams.head)); } act1 = act1.tail; act2 = act2.tail; typarams = typarams.tail; } Assert.check(act1.isEmpty() && act2.isEmpty() && typarams.isEmpty()); return new ClassType(class1.getEnclosingType(), merged.toList(), class1.tsym); } /** * Return the minimum type of a closure, a compound type if no unique minimum * exists. */ private Type compoundMin(List<Type> cl) { if (cl.isEmpty()) return syms.objectType; List<Type> compound = closureMin(cl); if (compound.isEmpty()) return null; else if (compound.tail.isEmpty()) return compound.head; else return makeCompoundType(compound); } /** * Return the minimum types of a closure, suitable for computing compoundMin * or glb. */ private List<Type> closureMin(List<Type> cl) { ListBuffer<Type> classes = lb(); ListBuffer<Type> interfaces = lb(); while (!cl.isEmpty()) { Type current = cl.head; if (current.isInterface()) interfaces.append(current); else classes.append(current); ListBuffer<Type> candidates = lb(); for (Type t : cl.tail) { if (!isSubtypeNoCapture(current, t)) candidates.append(t); } cl = candidates.toList(); } return classes.appendList(interfaces).toList(); } /** * Return the least upper bound of pair of types. if the lub does not exist * return null. */ public Type lub(Type t1, Type t2) { return lub(List.of(t1, t2)); } /** * Return the least upper bound (lub) of set of types. If the lub does not * exist return the type of null (bottom). */ public Type lub(List<Type> ts) { final int ARRAY_BOUND = 1; final int CLASS_BOUND = 2; int boundkind = 0; for (Type t : ts) { switch (t.tag) { case CLASS: boundkind |= CLASS_BOUND; break; case ARRAY: boundkind |= ARRAY_BOUND; break; case TYPEVAR: do { t = t.getUpperBound(); } while (t.tag == TYPEVAR); if (t.tag == ARRAY) { boundkind |= ARRAY_BOUND; } else { boundkind |= CLASS_BOUND; } break; default: if (t.isPrimitive()) return syms.errType; } } switch (boundkind) { case 0: return syms.botType; case ARRAY_BOUND: // calculate lub(A[], B[]) List<Type> elements = Type.map(ts, elemTypeFun); for (Type t : elements) { if (t.isPrimitive()) { // if a primitive type is found, then return // arraySuperType unless all the types are the // same Type first = ts.head; for (Type s : ts.tail) { if (!isSameType(first, s)) { // lub(int[], B[]) is Cloneable & Serializable return arraySuperType(); } } // all the array types are the same, return one // lub(int[], int[]) is int[] return first; } } // lub(A[], B[]) is lub(A, B)[] return new ArrayType(lub(elements), syms.arrayClass); case CLASS_BOUND: // calculate lub(A, B) while (ts.head.tag != CLASS && ts.head.tag != TYPEVAR) ts = ts.tail; Assert.check(!ts.isEmpty()); // step 1 - compute erased candidate set (EC) List<Type> cl = erasedSupertypes(ts.head); for (Type t : ts.tail) { if (t.tag == CLASS || t.tag == TYPEVAR) cl = intersect(cl, erasedSupertypes(t)); } // step 2 - compute minimal erased candidate set (MEC) List<Type> mec = closureMin(cl); // step 3 - for each element G in MEC, compute lci(Inv(G)) List<Type> candidates = List.nil(); for (Type erasedSupertype : mec) { List<Type> lci = List.of(asSuper(ts.head, erasedSupertype.tsym)); for (Type t : ts) { lci = intersect(lci, List.of(asSuper(t, erasedSupertype.tsym))); } candidates = candidates.appendList(lci); } // step 4 - let MEC be { G1, G2 ... Gn }, then we have that // lub = lci(Inv(G1)) & lci(Inv(G2)) & ... & lci(Inv(Gn)) return compoundMin(candidates); default: // calculate lub(A, B[]) List<Type> classes = List.of(arraySuperType()); for (Type t : ts) { if (t.tag != ARRAY) // Filter out any arrays classes = classes.prepend(t); } // lub(A, B[]) is lub(A, arraySuperType) return lub(classes); } } // where List<Type> erasedSupertypes(Type t) { ListBuffer<Type> buf = lb(); for (Type sup : closure(t)) { if (sup.tag == TYPEVAR) { buf.append(sup); } else { buf.append(erasure(sup)); } } return buf.toList(); } private Type arraySuperType = null; private Type arraySuperType() { // initialized lazily to avoid problems during compiler startup if (arraySuperType == null) { synchronized (this) { if (arraySuperType == null) { // JLS 10.8: all arrays implement Cloneable and Serializable. arraySuperType = makeCompoundType( List.of(syms.serializableType, syms.cloneableType), syms.objectType); } } } return arraySuperType; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Greatest lower bound"> public Type glb(List<Type> ts) { Type t1 = ts.head; for (Type t2 : ts.tail) { if (t1.isErroneous()) return t1; t1 = glb(t1, t2); } return t1; } // where public Type glb(Type t, Type s) { if (s == null) return t; else if (t.isPrimitive() || s.isPrimitive()) return syms.errType; else if (isSubtypeNoCapture(t, s)) return t; else if (isSubtypeNoCapture(s, t)) return s; List<Type> closure = union(closure(t), closure(s)); List<Type> bounds = closureMin(closure); if (bounds.isEmpty()) { // length == 0 return syms.objectType; } else if (bounds.tail.isEmpty()) { // length == 1 return bounds.head; } else { // length > 1 int classCount = 0; for (Type bound : bounds) if (!bound.isInterface()) classCount++; if (classCount > 1) return createErrorType(t); } return makeCompoundType(bounds); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="hashCode"> /** * Compute a hash code on a type. */ public static int hashCode(Type t) { return hashCode.visit(t); } // where private static final UnaryVisitor<Integer> hashCode = new UnaryVisitor<Integer>() { public Integer visitType(Type t, Void ignored) { return t.tag; } @Override public Integer visitClassType(ClassType t, Void ignored) { int result = visit(t.getEnclosingType()); result *= 127; result += t.tsym.flatName().hashCode(); for (Type s : t.getTypeArguments()) { result *= 127; result += visit(s); } return result; } @Override public Integer visitWildcardType(WildcardType t, Void ignored) { int result = t.kind.hashCode(); if (t.type != null) { result *= 127; result += visit(t.type); } return result; } @Override public Integer visitArrayType(ArrayType t, Void ignored) { return visit(t.elemtype) + 12; } @Override public Integer visitTypeVar(TypeVar t, Void ignored) { return System.identityHashCode(t.tsym); } @Override public Integer visitUndetVar(UndetVar t, Void ignored) { return System.identityHashCode(t); } @Override public Integer visitErrorType(ErrorType t, Void ignored) { return 0; } }; // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Return-Type-Substitutable"> /** * Does t have a result that is a subtype of the result type of s, suitable * for covariant returns? It is assumed that both types are (possibly * polymorphic) method types. Monomorphic method types are handled in the * obvious way. Polymorphic method types require renaming all type variables * of one to corresponding type variables in the other, where correspondence * is by position in the type parameter list. */ public boolean resultSubtype(Type t, Type s, Warner warner) { List<Type> tvars = t.getTypeArguments(); List<Type> svars = s.getTypeArguments(); Type tres = t.getReturnType(); Type sres = subst(s.getReturnType(), svars, tvars); return covariantReturnType(tres, sres, warner); } /** * Return-Type-Substitutable. * * @jls section 8.4.5 */ public boolean returnTypeSubstitutable(Type r1, Type r2) { if (hasSameArgs(r1, r2)) return resultSubtype(r1, r2, Warner.noWarnings); else return covariantReturnType(r1.getReturnType(), erasure(r2.getReturnType()), Warner.noWarnings); } public boolean returnTypeSubstitutable(Type r1, Type r2, Type r2res, Warner warner) { if (isSameType(r1.getReturnType(), r2res)) return true; if (r1.getReturnType().isPrimitive() || r2res.isPrimitive()) return false; if (hasSameArgs(r1, r2)) return covariantReturnType(r1.getReturnType(), r2res, warner); if (!allowCovariantReturns) return false; if (isSubtypeUnchecked(r1.getReturnType(), r2res, warner)) return true; if (!isSubtype(r1.getReturnType(), erasure(r2res))) return false; warner.warn(LintCategory.UNCHECKED); return true; } /** * Is t an appropriate return type in an overrider for a method that returns * s? */ public boolean covariantReturnType(Type t, Type s, Warner warner) { return isSameType(t, s) || allowCovariantReturns && !t.isPrimitive() && !s.isPrimitive() && isAssignable(t, s, warner); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Box/unbox support"> /** * Return the class that boxes the given primitive. */ public ClassSymbol boxedClass(Type t) { return reader.enterClass(syms.boxedName[t.tag]); } /** * Return the boxed type if 't' is primitive, otherwise return 't' itself. */ public Type boxedTypeOrType(Type t) { return t.isPrimitive() ? boxedClass(t).type : t; } /** * Return the primitive type corresponding to a boxed type. */ public Type unboxedType(Type t) { if (allowBoxing) { for (int i = 0; i < syms.boxedName.length; i++) { Name box = syms.boxedName[i]; if (box != null && asSuper(t, reader.enterClass(box)) != null) return syms.typeOfTag[i]; } } return Type.noType; } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Capture conversion"> /* * JLS 5.1.10 Capture Conversion: * * Let G name a generic type declaration with n formal type parameters A1 ... * An with corresponding bounds U1 ... Un. There exists a capture conversion * from G<T1 ... Tn> to G<S1 ... Sn>, where, for 1 <= i <= n: * * + If Ti is a wildcard type argument (4.5.1) of the form ? then Si is a * fresh type variable whose upper bound is Ui[A1 := S1, ..., An := Sn] and * whose lower bound is the null type. * * + If Ti is a wildcard type argument of the form ? extends Bi, then Si is a * fresh type variable whose upper bound is glb(Bi, Ui[A1 := S1, ..., An := * Sn]) and whose lower bound is the null type, where glb(V1,... ,Vm) is V1 & * ... & Vm. It is a compile-time error if for any two classes (not * interfaces) Vi and Vj,Vi is not a subclass of Vj or vice versa. * * + If Ti is a wildcard type argument of the form ? super Bi, then Si is a * fresh type variable whose upper bound is Ui[A1 := S1, ..., An := Sn] and * whose lower bound is Bi. * * + Otherwise, Si = Ti. * * Capture conversion on any type other than a parameterized type (4.5) acts * as an identity conversion (5.1.1). Capture conversions never require a * special action at run time and therefore never throw an exception at run * time. * * Capture conversion is not applied recursively. */ /** * Capture conversion as specified by the JLS. */ public List<Type> capture(List<Type> ts) { List<Type> buf = List.nil(); for (Type t : ts) { buf = buf.prepend(capture(t)); } return buf.reverse(); } public Type capture(Type t) { if (t.tag != CLASS) return t; if (t.getEnclosingType() != Type.noType) { Type capturedEncl = capture(t.getEnclosingType()); if (capturedEncl != t.getEnclosingType()) { Type type1 = memberType(capturedEncl, t.tsym); t = subst(type1, t.tsym.type.getTypeArguments(), t.getTypeArguments()); } } ClassType cls = (ClassType) t; if (cls.isRaw() || !cls.isParameterized()) return cls; ClassType G = (ClassType) cls.asElement().asType(); List<Type> A = G.getTypeArguments(); List<Type> T = cls.getTypeArguments(); List<Type> S = freshTypeVariables(T); List<Type> currentA = A; List<Type> currentT = T; List<Type> currentS = S; boolean captured = false; while (!currentA.isEmpty() && !currentT.isEmpty() && !currentS.isEmpty()) { if (currentS.head != currentT.head) { captured = true; WildcardType Ti = (WildcardType) currentT.head; Type Ui = currentA.head.getUpperBound(); CapturedType Si = (CapturedType) currentS.head; if (Ui == null) Ui = syms.objectType; switch (Ti.kind) { case UNBOUND: Si.bound = subst(Ui, A, S); Si.lower = syms.botType; break; case EXTENDS: Si.bound = glb(Ti.getExtendsBound(), subst(Ui, A, S)); Si.lower = syms.botType; break; case SUPER: Si.bound = subst(Ui, A, S); Si.lower = Ti.getSuperBound(); break; } if (Si.bound == Si.lower) currentS.head = Si.bound; } currentA = currentA.tail; currentT = currentT.tail; currentS = currentS.tail; } if (!currentA.isEmpty() || !currentT.isEmpty() || !currentS.isEmpty()) return erasure(t); // some "rare" type involved if (captured) return new ClassType(cls.getEnclosingType(), S, cls.tsym); else return t; } // where public List<Type> freshTypeVariables(List<Type> types) { ListBuffer<Type> result = lb(); for (Type t : types) { if (t.tag == WILDCARD) { Type bound = ((WildcardType) t).getExtendsBound(); if (bound == null) bound = syms.objectType; result.append(new CapturedType(capturedName, syms.noSymbol, bound, syms.botType, (WildcardType) t)); } else { result.append(t); } } return result.toList(); } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Internal utility methods"> private List<Type> upperBounds(List<Type> ss) { if (ss.isEmpty()) return ss; Type head = upperBound(ss.head); List<Type> tail = upperBounds(ss.tail); if (head != ss.head || tail != ss.tail) return tail.prepend(head); else return ss; } private boolean sideCast(Type from, Type to, Warner warn) { // We are casting from type $from$ to type $to$, which are // non-final unrelated types. This method // tries to reject a cast by transferring type parameters // from $to$ to $from$ by common superinterfaces. boolean reverse = false; Type target = to; if ((to.tsym.flags() & INTERFACE) == 0) { Assert.check((from.tsym.flags() & INTERFACE) != 0); reverse = true; to = from; from = target; } List<Type> commonSupers = superClosure(to, erasure(from)); boolean giveWarning = commonSupers.isEmpty(); // The arguments to the supers could be unified here to // get a more accurate analysis while (commonSupers.nonEmpty()) { Type t1 = asSuper(from, commonSupers.head.tsym); Type t2 = commonSupers.head; // same as asSuper(to, // commonSupers.head.tsym); if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments())) return false; giveWarning = giveWarning || (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2)); commonSupers = commonSupers.tail; } if (giveWarning && !isReifiable(reverse ? from : to)) warn.warn(LintCategory.UNCHECKED); if (!allowCovariantReturns) // reject if there is a common method signature with // incompatible return types. chk.checkCompatibleAbstracts(warn.pos(), from, to); return true; } private boolean sideCastFinal(Type from, Type to, Warner warn) { // We are casting from type $from$ to type $to$, which are // unrelated types one of which is final and the other of // which is an interface. This method // tries to reject a cast by transferring type parameters // from the final class to the interface. boolean reverse = false; Type target = to; if ((to.tsym.flags() & INTERFACE) == 0) { Assert.check((from.tsym.flags() & INTERFACE) != 0); reverse = true; to = from; from = target; } Assert.check((from.tsym.flags() & FINAL) != 0); Type t1 = asSuper(from, to.tsym); if (t1 == null) return false; Type t2 = to; if (disjointTypes(t1.getTypeArguments(), t2.getTypeArguments())) return false; if (!allowCovariantReturns) // reject if there is a common method signature with // incompatible return types. chk.checkCompatibleAbstracts(warn.pos(), from, to); if (!isReifiable(target) && (reverse ? giveWarning(t2, t1) : giveWarning(t1, t2))) warn.warn(LintCategory.UNCHECKED); return true; } private boolean giveWarning(Type from, Type to) { Type subFrom = asSub(from, to.tsym); return to.isParameterized() && (!(isUnbounded(to) || isSubtype(from, to) || ((subFrom != null) && containsType( to.allparams(), subFrom.allparams())))); } private List<Type> superClosure(Type t, Type s) { List<Type> cl = List.nil(); for (List<Type> l = interfaces(t); l.nonEmpty(); l = l.tail) { if (isSubtype(s, erasure(l.head))) { cl = insert(cl, l.head); } else { cl = union(cl, superClosure(l.head, s)); } } return cl; } private boolean containsTypeEquivalent(Type t, Type s) { return isSameType(t, s) || // shortcut containsType(t, s) && containsType(s, t); } // <editor-fold defaultstate="collapsed" desc="adapt"> /** * Adapt a type by computing a substitution which maps a source type to a * target type. * * @param source * the source type * @param target * the target type * @param from * the type variables of the computed substitution * @param to * the types of the computed substitution. */ public void adapt(Type source, Type target, ListBuffer<Type> from, ListBuffer<Type> to) throws AdaptFailure { new Adapter(from, to).adapt(source, target); } class Adapter extends SimpleVisitor<Void, Type> { ListBuffer<Type> from; ListBuffer<Type> to; Map<Symbol, Type> mapping; Adapter(ListBuffer<Type> from, ListBuffer<Type> to) { this.from = from; this.to = to; mapping = new HashMap<Symbol, Type>(); } public void adapt(Type source, Type target) throws AdaptFailure { visit(source, target); List<Type> fromList = from.toList(); List<Type> toList = to.toList(); while (!fromList.isEmpty()) { Type val = mapping.get(fromList.head.tsym); if (toList.head != val) toList.head = val; fromList = fromList.tail; toList = toList.tail; } } @Override public Void visitClassType(ClassType source, Type target) throws AdaptFailure { if (target.tag == CLASS) adaptRecursive(source.allparams(), target.allparams()); return null; } @Override public Void visitArrayType(ArrayType source, Type target) throws AdaptFailure { if (target.tag == ARRAY) adaptRecursive(elemtype(source), elemtype(target)); return null; } @Override public Void visitWildcardType(WildcardType source, Type target) throws AdaptFailure { if (source.isExtendsBound()) adaptRecursive(upperBound(source), upperBound(target)); else if (source.isSuperBound()) adaptRecursive(lowerBound(source), lowerBound(target)); return null; } @Override public Void visitTypeVar(TypeVar source, Type target) throws AdaptFailure { // Check to see if there is // already a mapping for $source$, in which case // the old mapping will be merged with the new Type val = mapping.get(source.tsym); if (val != null) { if (val.isSuperBound() && target.isSuperBound()) { val = isSubtype(lowerBound(val), lowerBound(target)) ? target : val; } else if (val.isExtendsBound() && target.isExtendsBound()) { val = isSubtype(upperBound(val), upperBound(target)) ? val : target; } else if (!isSameType(val, target)) { throw new AdaptFailure(); } } else { val = target; from.append(source); to.append(target); } mapping.put(source.tsym, val); return null; } @Override public Void visitType(Type source, Type target) { return null; } private Set<TypePair> cache = new HashSet<TypePair>(); private void adaptRecursive(Type source, Type target) { TypePair pair = new TypePair(source, target); if (cache.add(pair)) { try { visit(source, target); } finally { cache.remove(pair); } } } private void adaptRecursive(List<Type> source, List<Type> target) { if (source.length() == target.length()) { while (source.nonEmpty()) { adaptRecursive(source.head, target.head); source = source.tail; target = target.tail; } } } } public static class AdaptFailure extends RuntimeException { static final long serialVersionUID = -7490231548272701566L; } private void adaptSelf(Type t, ListBuffer<Type> from, ListBuffer<Type> to) { try { // if (t.tsym.type != t) adapt(t.tsym.type, t, from, to); } catch (AdaptFailure ex) { // Adapt should never fail calculating a mapping from // t.tsym.type to t as there can be no merge problem. throw new AssertionError(ex); } } // </editor-fold> /** * Rewrite all type variables (universal quantifiers) in the given type to * wildcards (existential quantifiers). This is used to determine if a cast is * allowed. For example, if high is true and {@code T <: Number}, then * {@code List<T>} is rewritten to {@code List<? extends Number>}. Since * {@code List<Integer> <: * List<? extends Number>} a {@code List<T>} can be cast to * {@code List<Integer>} with a warning. * * @param t * a type * @param high * if true return an upper bound; otherwise a lower bound * @param rewriteTypeVars * only rewrite captured wildcards if false; otherwise rewrite all * type variables * @return the type rewritten with wildcards (existential quantifiers) only */ private Type rewriteQuantifiers(Type t, boolean high, boolean rewriteTypeVars) { return new Rewriter(high, rewriteTypeVars).visit(t); } class Rewriter extends UnaryVisitor<Type> { boolean high; boolean rewriteTypeVars; Rewriter(boolean high, boolean rewriteTypeVars) { this.high = high; this.rewriteTypeVars = rewriteTypeVars; } @Override public Type visitClassType(ClassType t, Void s) { ListBuffer<Type> rewritten = new ListBuffer<Type>(); boolean changed = false; for (Type arg : t.allparams()) { Type bound = visit(arg); if (arg != bound) { changed = true; } rewritten.append(bound); } if (changed) return subst(t.tsym.type, t.tsym.type.allparams(), rewritten.toList()); else return t; } public Type visitType(Type t, Void s) { return high ? upperBound(t) : lowerBound(t); } @Override public Type visitCapturedType(CapturedType t, Void s) { Type bound = visitWildcardType(t.wildcard, null); return (bound.contains(t)) ? erasure(bound) : bound; } @Override public Type visitTypeVar(TypeVar t, Void s) { if (rewriteTypeVars) { Type bound = high ? (t.bound.contains(t) ? erasure(t.bound) : visit(t.bound)) : syms.botType; return rewriteAsWildcardType(bound, t); } else return t; } @Override public Type visitWildcardType(WildcardType t, Void s) { Type bound = high ? t.getExtendsBound() : t.getSuperBound(); if (bound == null) bound = high ? syms.objectType : syms.botType; return rewriteAsWildcardType(visit(bound), t.bound); } private Type rewriteAsWildcardType(Type bound, TypeVar formal) { return high ? makeExtendsWildcard(B(bound), formal) : makeSuperWildcard( B(bound), formal); } Type B(Type t) { while (t.tag == WILDCARD) { WildcardType w = (WildcardType) t; t = high ? w.getExtendsBound() : w.getSuperBound(); if (t == null) { t = high ? syms.objectType : syms.botType; } } return t; } } /** * Create a wildcard with the given upper (extends) bound; create an unbounded * wildcard if bound is Object. * * @param bound * the upper bound * @param formal * the formal type parameter that will be substituted by the wildcard */ private WildcardType makeExtendsWildcard(Type bound, TypeVar formal) { if (bound == syms.objectType) { return new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, formal); } else { return new WildcardType(bound, BoundKind.EXTENDS, syms.boundClass, formal); } } /** * Create a wildcard with the given lower (super) bound; create an unbounded * wildcard if bound is bottom (type of {@code null}). * * @param bound * the lower bound * @param formal * the formal type parameter that will be substituted by the wildcard */ private WildcardType makeSuperWildcard(Type bound, TypeVar formal) { if (bound.tag == BOT) { return new WildcardType(syms.objectType, BoundKind.UNBOUND, syms.boundClass, formal); } else { return new WildcardType(bound, BoundKind.SUPER, syms.boundClass, formal); } } /** * A wrapper for a type that allows use in sets. */ class SingletonType { final Type t; SingletonType(Type t) { this.t = t; } public int hashCode() { return Types.hashCode(t); } public boolean equals(Object obj) { return (obj instanceof SingletonType) && isSameType(t, ((SingletonType) obj).t); } public String toString() { return t.toString(); } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Visitors"> /** * A default visitor for types. All visitor methods except visitType are * implemented by delegating to visitType. Concrete subclasses must provide an * implementation of visitType and can override other methods as needed. * * @param <R> * the return type of the operation implemented by this visitor; use * Void if no return type is needed. * @param <S> * the type of the second argument (the first being the type itself) * of the operation implemented by this visitor; use Void if a second * argument is not needed. */ public static abstract class DefaultTypeVisitor<R, S> implements Type.Visitor<R, S> { final public R visit(Type t, S s) { return t.accept(this, s); } public R visitClassType(ClassType t, S s) { return visitType(t, s); } public R visitWildcardType(WildcardType t, S s) { return visitType(t, s); } public R visitArrayType(ArrayType t, S s) { return visitType(t, s); } public R visitMethodType(MethodType t, S s) { return visitType(t, s); } public R visitPackageType(PackageType t, S s) { return visitType(t, s); } public R visitTypeVar(TypeVar t, S s) { return visitType(t, s); } public R visitCapturedType(CapturedType t, S s) { return visitType(t, s); } public R visitForAll(ForAll t, S s) { return visitType(t, s); } public R visitUndetVar(UndetVar t, S s) { return visitType(t, s); } public R visitErrorType(ErrorType t, S s) { return visitType(t, s); } } /** * A default visitor for symbols. All visitor methods except visitSymbol are * implemented by delegating to visitSymbol. Concrete subclasses must provide * an implementation of visitSymbol and can override other methods as needed. * * @param <R> * the return type of the operation implemented by this visitor; use * Void if no return type is needed. * @param <S> * the type of the second argument (the first being the symbol * itself) of the operation implemented by this visitor; use Void if * a second argument is not needed. */ public static abstract class DefaultSymbolVisitor<R, S> implements Symbol.Visitor<R, S> { final public R visit(Symbol s, S arg) { return s.accept(this, arg); } public R visitClassSymbol(ClassSymbol s, S arg) { return visitSymbol(s, arg); } public R visitMethodSymbol(MethodSymbol s, S arg) { return visitSymbol(s, arg); } public R visitOperatorSymbol(OperatorSymbol s, S arg) { return visitSymbol(s, arg); } public R visitPackageSymbol(PackageSymbol s, S arg) { return visitSymbol(s, arg); } public R visitTypeSymbol(TypeSymbol s, S arg) { return visitSymbol(s, arg); } public R visitVarSymbol(VarSymbol s, S arg) { return visitSymbol(s, arg); } } /** * A <em>simple</em> visitor for types. This visitor is simple as captured * wildcards, for-all types (generic methods), and undetermined type variables * (part of inference) are hidden. Captured wildcards are hidden by treating * them as type variables and the rest are hidden by visiting their qtypes. * * @param <R> * the return type of the operation implemented by this visitor; use * Void if no return type is needed. * @param <S> * the type of the second argument (the first being the type itself) * of the operation implemented by this visitor; use Void if a second * argument is not needed. */ public static abstract class SimpleVisitor<R, S> extends DefaultTypeVisitor<R, S> { @Override public R visitCapturedType(CapturedType t, S s) { return visitTypeVar(t, s); } @Override public R visitForAll(ForAll t, S s) { return visit(t.qtype, s); } @Override public R visitUndetVar(UndetVar t, S s) { return visit(t.qtype, s); } } /** * A plain relation on types. That is a 2-ary function on the form * Type&nbsp;&times;&nbsp;Type&nbsp;&rarr;&nbsp;Boolean. <!-- In plain text: * Type x Type -> Boolean --> */ public static abstract class TypeRelation extends SimpleVisitor<Boolean, Type> { } /** * A convenience visitor for implementing operations that only require one * argument (the type itself), that is, unary operations. * * @param <R> * the return type of the operation implemented by this visitor; use * Void if no return type is needed. */ public static abstract class UnaryVisitor<R> extends SimpleVisitor<R, Void> { final public R visit(Type t) { return t.accept(this, null); } } /** * A visitor for implementing a mapping from types to types. The default * behavior of this class is to implement the identity mapping (mapping a type * to itself). This can be overridden in subclasses. * * @param <S> * the type of the second argument (the first being the type itself) * of this mapping; use Void if a second argument is not needed. */ public static class MapVisitor<S> extends DefaultTypeVisitor<Type, S> { final public Type visit(Type t) { return t.accept(this, null); } public Type visitType(Type t, S s) { return t; } } // </editor-fold> // <editor-fold defaultstate="collapsed" desc="Annotation support"> public RetentionPolicy getRetention(Attribute.Compound a) { RetentionPolicy vis = RetentionPolicy.CLASS; // the default Attribute.Compound c = a.type.tsym.attribute(syms.retentionType.tsym); if (c != null) { Attribute value = c.member(names.value); if (value != null && value instanceof Attribute.Enum) { Name levelName = ((Attribute.Enum) value).value.name; if (levelName == names.SOURCE) vis = RetentionPolicy.SOURCE; else if (levelName == names.CLASS) vis = RetentionPolicy.CLASS; else if (levelName == names.RUNTIME) vis = RetentionPolicy.RUNTIME; else ;// /* fail soft */ throw new AssertionError(levelName); } } return vis; } // </editor-fold> }
gpl-2.0
deezzel/triary_main
Triary-ejb/test/model/ModelSuite.java
871
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package model; import org.junit.After; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.runner.RunWith; import org.junit.runners.Suite; /** * * @author kate */ @RunWith(Suite.class) @Suite.SuiteClasses({model.CommentTest.class, model.StatisticsTest.class, model.ProfileTest.class, model.PublicationTest.class, model.baseclass.BaseclassSuite.class, model.DiaryTest.class, model.UsersTest.class}) public class ModelSuite { @BeforeClass public static void setUpClass() throws Exception { } @AfterClass public static void tearDownClass() throws Exception { } @Before public void setUp() throws Exception { } @After public void tearDown() throws Exception { } }
gpl-2.0
hdadler/sensetrace-src
com.ipv.sensetrace.RDFDatamanager/jena-2.11.0/jena-arq/src/main/java/com/hp/hpl/jena/sparql/expr/E_Divide.java
1623
/* * 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 com.hp.hpl.jena.sparql.expr; import com.hp.hpl.jena.query.ARQ ; import com.hp.hpl.jena.sparql.expr.nodevalue.NodeValueOps ; import com.hp.hpl.jena.sparql.expr.nodevalue.XSDFuncOp ; import com.hp.hpl.jena.sparql.sse.Tags; public class E_Divide extends ExprFunction2 { private static final String functionName = Tags.tagDivide ; private static final String symbol = Tags.symDiv ; public E_Divide(Expr left, Expr right) { super(left, right, functionName, symbol) ; } @Override public NodeValue eval(NodeValue x, NodeValue y) { if ( ARQ.isStrictMode() ) return XSDFuncOp.numDivide(x, y) ; return NodeValueOps.divisionNV(x, y) ; } @Override public Expr copy(Expr e1, Expr e2) { return new E_Divide(e1 , e2 ) ; } }
gpl-2.0
HAW-BAI4-SE2/UniKit
project/app/assets/Global.java
4684
package assets; import net.unikit.database.common.interfaces.DatabaseConfiguration; import net.unikit.database.external.implementations.ImportDatabaseManagerFactory; import net.unikit.database.external.interfaces.*; import net.unikit.database.unikit_.implementations.UniKitDatabaseManagerFactory; import net.unikit.database.unikit_.interfaces.*; import play.Application; import play.GlobalSettings; import play.Logger; import play.Play; import java.io.IOException; import java.io.InputStream; import static net.unikit.database.common.implementations.DatabaseConfigurationUtils.createDatabaseConfigurationFromProperties; public final class Global extends GlobalSettings { private static AppointmentManager appointmentManager; private static CourseGroupManager courseGroupManager; private static CourseManager courseManager; private static FieldOfStudyManager fieldOfStudyManager; private static StudentManager studentManager; private static CourseRegistrationManager courseRegistrationManager; private static TeamApplicationManager teamApplicationManager; private static TeamInvitationManager teamInvitationManager; private static TeamManager teamManager; private static TeamRegistrationManager teamRegistrationManager; @Override public void beforeStart(Application application) { Logger.info("Initializing application..."); // Load external database Logger.info("Loading external database..."); InputStream inputStreamExternal = Play.application().resourceAsStream("database_external.properties"); DatabaseConfiguration databaseConfigurationExternal = null; try { databaseConfigurationExternal = createDatabaseConfigurationFromProperties(inputStreamExternal); } catch (IOException e) { e.printStackTrace(); } ImportDatabaseManager externalDatabaseManager = ImportDatabaseManagerFactory.createDatabaseManager(databaseConfigurationExternal); // Load internal database Logger.info("Loading internal database..."); InputStream inputStreamInternal = Play.application().resourceAsStream("database_internal.properties"); DatabaseConfiguration databaseConfigurationInternal = null; try { databaseConfigurationInternal = createDatabaseConfigurationFromProperties(inputStreamInternal); } catch (IOException e) { e.printStackTrace(); } UniKitDatabaseManager internalDatabaseManager = UniKitDatabaseManagerFactory.createDatabaseManager(databaseConfigurationInternal); // Store database managers in global values Logger.info("Initializing database managers..."); Global.appointmentManager = externalDatabaseManager.getAppointmentManager(); Global.courseGroupManager = externalDatabaseManager.getCourseGroupManager(); Global.courseManager = externalDatabaseManager.getCourseManager(); Global.fieldOfStudyManager = externalDatabaseManager.getFieldOfStudyManager(); Global.studentManager = externalDatabaseManager.getStudentManager(); Global.courseRegistrationManager = internalDatabaseManager.getCourseRegistrationManager(); Global.teamApplicationManager = internalDatabaseManager.getTeamApplicationManager(); Global.teamInvitationManager = internalDatabaseManager.getTeamInvitationManager(); Global.teamManager = internalDatabaseManager.getTeamManager(); Global.teamRegistrationManager = internalDatabaseManager.getTeamRegistrationManager(); Logger.info("Application initialized!"); } public static AppointmentManager getAppointmentManager() { return appointmentManager; } public static CourseGroupManager getCourseGroupManager() { return courseGroupManager; } public static CourseManager getCourseManager() { return courseManager; } public static FieldOfStudyManager getFieldOfStudyManager() { return fieldOfStudyManager; } public static StudentManager getStudentManager() { return studentManager; } public static CourseRegistrationManager getCourseRegistrationManager() { return courseRegistrationManager; } public static TeamApplicationManager getTeamApplicationManager() { return teamApplicationManager; } public static TeamInvitationManager getTeamInvitationManager() { return teamInvitationManager; } public static TeamManager getTeamManager() { return teamManager; } public static TeamRegistrationManager getTeamRegistrationManager() { return teamRegistrationManager; } }
gpl-2.0
lucenacaio/AtidDesktop
src/org/atid/util/GraphicsTools.java
9003
/* * Copyright (C) 2008-2010 Martin Riesz <riesz.martin at gmail.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.atid.util; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Cursor; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Image; import java.awt.Point; import java.awt.Polygon; import java.awt.Rectangle; import java.awt.Toolkit; import java.awt.image.BufferedImage; import java.awt.image.IndexColorModel; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.ImageIcon; /** * * @author Martin Riesz <riesz.martin at gmail.com> */ public class GraphicsTools { private final static String resourcesDir = "/resources/"; public static ImageIcon getIcon(String fileName) { return new ImageIcon(GraphicsTools.class.getResource(resourcesDir + fileName)); } public static Cursor getCursor(String fileName, Point center) { Toolkit tk = Toolkit.getDefaultToolkit(); Image image = tk.getImage(GraphicsTools.class.getResource(resourcesDir + fileName)); return tk.createCustomCursor(image, center, fileName); } public static BufferedImage getBufferedImage(String fileName) { try { return ImageIO.read(GraphicsTools.class.getResource(resourcesDir + fileName)); } catch (IOException ex) { Logger.getLogger(GraphicsTools.class.getName()).log(Level.SEVERE, null, ex); return new BufferedImage(1, 1, IndexColorModel.TRANSLUCENT); } } public static void setDashedStroke(Graphics g) { final float dash1[] = {4.0f}; final BasicStroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 4.0f, dash1, 0.0f); ((Graphics2D) g).setStroke(dashed); } public static void setDottedStroke(Graphics g) { final float dash1[] = {1.0f, 4.0f}; final BasicStroke dashed = new BasicStroke(1.0f, BasicStroke.CAP_BUTT, BasicStroke.JOIN_MITER, 4.0f, dash1, 0.0f); ((Graphics2D) g).setStroke(dashed); } public static void setDefaultStroke(Graphics g) { final BasicStroke defaultStroke = new BasicStroke(); ((Graphics2D) g).setStroke(defaultStroke); } public static void drawImageCentered(Graphics g, BufferedImage image, int x, int y) { while (!g.drawImage(image, x - image.getWidth() / 2, y - image.getHeight() / 2, null)) { } } public enum HorizontalAlignment { left, right, center } public enum VerticalAlignment { top, center, bottom } public static void drawString(Graphics g, String str, int x, int y, HorizontalAlignment horizontalAlignment, VerticalAlignment verticalAlignment) { int textWidth = g.getFontMetrics().stringWidth(str); final int textHeight = g.getFontMetrics().getAscent(); int resultX = x; int resultY = y; if (horizontalAlignment == HorizontalAlignment.left) { resultX = x; } else if (horizontalAlignment == HorizontalAlignment.center) { resultX = x - textWidth / 2; } else if (horizontalAlignment == HorizontalAlignment.right) { resultX = x - textWidth; } if (verticalAlignment == VerticalAlignment.top) { resultY = y + textHeight; } else if (verticalAlignment == VerticalAlignment.center) { resultY = y + textHeight / 2 - 1; } else if (verticalAlignment == VerticalAlignment.bottom) { resultY = y; } Color previousColor = g.getColor(); g.setColor(new Color(1f, 1f, 1f, 0.7f)); // g.setColor(new Color(0.7f, 0.7f, 1f, 0.7f)); //debug with this g.fillRect(resultX, resultY - textHeight + 1, textWidth, g.getFontMetrics().getHeight() - 1); g.setColor(previousColor); g.drawString(str, resultX, resultY); } //Jan Tancibok Inhibitor arc, Taken from http://stackoverflow.com/questions/21465570/two-points-and-then-finds-the-smallest-circle-and-the-smallest-rectangle-contain?rq=1 public static void drawCircle(Graphics g, int xCenter, int yCenter, int x2, int y2) { Graphics2D g2d = (Graphics2D) g; g2d.setStroke(new BasicStroke(1f)); double aDir = Math.atan2(xCenter - x2, yCenter - y2); int i2 = 9; //diameter int x1 = x2 + xCor(i2, aDir); int y1 = y2 + yCor(i2, aDir); double diameter = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)); int cx = ((x2 + x1) / 2); int cy = (y2 + y1) / 2; int tlCornerx = (int) (cx - diameter / 2); int tlCornery = (int) (cy - diameter / 2); g2d.drawOval(tlCornerx, tlCornery, (int) diameter, (int) diameter); g2d.fillOval(tlCornerx, tlCornery, (int) diameter, (int) diameter); } //Taken from http://forum.java.sun.com/thread.jspa?threadID=378460&tstart=135 public static void drawArrow(Graphics g, int xCenter, int yCenter, int x, int y) { Graphics2D g2d = (Graphics2D) g; double aDir = Math.atan2(xCenter - x, yCenter - y); //g2d.drawLine(x, y, xCenter, yCenter); g2d.setStroke(new BasicStroke(1f)); // make the arrow head solid even if dash pattern has been specified Polygon tmpPoly = new Polygon(); int i1 = 12; int i2 = 6; // make the arrow head the same size regardless of the length length tmpPoly.addPoint(x, y); // arrow tip tmpPoly.addPoint(x + xCor(i1, aDir + 0.5), y + yCor(i1, aDir + 0.5)); tmpPoly.addPoint(x + xCor(i2, aDir), y + yCor(i2, aDir)); tmpPoly.addPoint(x + xCor(i1, aDir - 0.5), y + yCor(i1, aDir - 0.5)); tmpPoly.addPoint(x, y); // arrow tip g2d.drawPolygon(tmpPoly); g2d.fillPolygon(tmpPoly); // remove this line to leave arrow head unpainted } //Jan Tancibok Reset arc public static void drawArrowDouble(Graphics g, int xCenter, int yCenter, int x, int y) { Graphics2D g2d = (Graphics2D) g; double aDir = Math.atan2(xCenter - x, yCenter - y); //g2d.drawLine(x, y, xCenter, yCenter); g2d.setStroke(new BasicStroke(1f)); // make the arrow head solid even if dash pattern has been specified Polygon tmpPoly = new Polygon(); int i1 = 12; int i2 = 6; // make the arrow head the same size regardless of the length length tmpPoly.addPoint(x, y); // arrow tip tmpPoly.addPoint(x + xCor(i1, aDir + 0.5), y + yCor(i1, aDir + 0.5)); tmpPoly.addPoint(x + xCor(i2, aDir), y + yCor(i2, aDir)); tmpPoly.addPoint(x + xCor(i1, aDir - 0.5), y + yCor(i1, aDir - 0.5)); tmpPoly.addPoint(x, y); // arrow tip g2d.drawPolygon(tmpPoly); g2d.fillPolygon(tmpPoly); i1 = 24; int move = 6; int dmove = 12; tmpPoly.addPoint(x + xCor(i2 + move, aDir), y + yCor(i2 + move, aDir)); // arrow tip tmpPoly.addPoint(x + xCor(i1, aDir - 0.25), y + yCor(i1, aDir - 0.25)); tmpPoly.addPoint(x + xCor(i2 + dmove, aDir), y + yCor(i2 + dmove, aDir)); tmpPoly.addPoint(x + xCor(i1, aDir + 0.25), y + yCor(i1, aDir + 0.25)); tmpPoly.addPoint(x + xCor(i2 + move, aDir), y + yCor(i2 + move, aDir)); // arrow tip g2d.drawPolygon(tmpPoly); g2d.fillPolygon(tmpPoly);// remove this line to leave arrow head unpainted } private static int yCor(int len, double dir) { return (int) (len * Math.cos(dir)); } private static int xCor(int len, double dir) { return (int) (len * Math.sin(dir)); } public static boolean isPointNearSegment(Point from, Point to, Point testPos, int nearTolerance) { Rectangle r = new Rectangle(testPos.x - nearTolerance / 2, testPos.y - nearTolerance / 2, nearTolerance, nearTolerance); return r.intersectsLine(from.x, from.y, to.x, to.y); } public static boolean isPointNearPoint(Point from, Point testPos, int nearTolerance) { Rectangle r1 = new Rectangle(from.x - nearTolerance / 2, from.y - nearTolerance / 2, nearTolerance, nearTolerance); Rectangle r2 = new Rectangle(testPos.x, testPos.y, 1, 1); return r2.intersects(r1); } }
gpl-2.0
icybits/ts3-sq-api
de.icybits.ts3.sq.api/src/de/icybits/ts3/sq/api/commands/SetclientchannelgroupCommand.java
396
package de.icybits.ts3.sq.api.commands; import de.icybits.ts3.sq.api.basic.Command; import de.icybits.ts3.sq.api.interfaces.ITS3CommandNames; /** * set a clients channel group * * @author Alias: Iceac Sarutobi */ public class SetclientchannelgroupCommand extends Command implements ITS3CommandNames { public SetclientchannelgroupCommand() { super(COMMAND_SETCLIENTCHANNELGROUP); } }
gpl-2.0
ydahhrk/PktGenerator
src/main/java/mx/nic/jool/pktgen/type/ByteArrayField.java
1079
package mx.nic.jool.pktgen.type; import mx.nic.jool.pktgen.BitArrayOutputStream; public class ByteArrayField implements Field { private String name; private byte[] value; public ByteArrayField(String name, byte[] defaultValue) { this.name = name; this.value = defaultValue; } @Override public String toString() { if (value == null) return null; StringBuilder sb = new StringBuilder(); for (byte bait : value) sb.append(bait).append(","); return sb.toString(); } @Override public void parse(String value) { String[] strings = value.split(","); this.value = new byte[strings.length]; for (int i = 0; i < strings.length; i++) this.value[i] = Byte.valueOf(strings[i]); } @Override public void write(BitArrayOutputStream out) { if (value != null) out.write(value); } @Override public String getName() { return name; } @Override public int getLength() { return (value != null) ? (8 * value.length) : 0; } public byte[] getValue() { return value; } public void setValue(byte[] value) { this.value = value; } }
gpl-2.0
sharpie7/circuitjs1
src/com/lushprojects/circuitjs1/client/CompositeElm.java
11923
package com.lushprojects.circuitjs1.client; import java.util.Vector; import java.util.HashMap; import java.util.Map.Entry; // Circuit element made up of a composition of other circuit elements // Using this will be (relatively) inefficient in terms of simulation performance because // all the internal workings of the element are simulated from the individual components. // However, it may allow some types of components to be more quickly programed in to the simulator // than writing each component from scratch. // // It also provides a path to allow user created circuits to be // re-imported in to the simuation as new circuit elements. // Instatiations should: // - Set the variable "diagonal" in the constructors // - Override constructors to set up the elements posts/leads etc. and configure the contents of the CompositeElm // - Override getDumpType, dump, draw, getInfo, setPoints, canViewInScope public abstract class CompositeElm extends CircuitElm { // need to use escape() instead of converting spaces to _'s so composite elements can be nested final int FLAG_ESCAPE = 1; // list of elements contained in this subcircuit Vector<CircuitElm> compElmList; // list of nodes, mapping each one to a list of elements that reference that node protected Vector<CircuitNode> compNodeList; protected int numPosts = 0; protected int numNodes = 0; protected Point posts[]; protected Vector<VoltageSourceRecord> voltageSources; CompositeElm(int xx, int yy) { super(xx, yy); } public CompositeElm(int xa, int ya, int xb, int yb, int f) { super(xa, ya, xb, yb, f); } CompositeElm(int xx, int yy, String s, int externalNodes[]) { super(xx, yy); loadComposite(null, s, externalNodes); allocNodes(); } public CompositeElm(int xa, int ya, int xb, int yb, int f, StringTokenizer st, String s, int externalNodes[]) { super(xa, ya, xb, yb, f); loadComposite(st, s, externalNodes); allocNodes(); } boolean useEscape() { return (flags & FLAG_ESCAPE) != 0; } public void loadComposite(StringTokenizer stIn, String model, int externalNodes[]) { HashMap<Integer, CircuitNode> compNodeHash = new HashMap<Integer, CircuitNode>(); StringTokenizer modelLinet = new StringTokenizer(model, "\r"); CircuitNode cn; CircuitNodeLink cnLink; VoltageSourceRecord vsRecord; compElmList = new Vector<CircuitElm>(); compNodeList = new Vector<CircuitNode>(); voltageSources = new Vector<VoltageSourceRecord>(); // Build compElmList and compNodeHash from input string while (modelLinet.hasMoreTokens()) { String line = modelLinet.nextToken(); StringTokenizer stModel = new StringTokenizer(line, " +\t\n\r\f"); String ceType = stModel.nextToken(); CircuitElm newce = CirSim.constructElement(ceType, 0, 0); if (stIn!=null) { int tint = newce.getDumpType(); String dumpedCe= stIn.nextToken(); if (useEscape()) dumpedCe = CustomLogicModel.unescape(dumpedCe); StringTokenizer stCe = new StringTokenizer(dumpedCe, useEscape() ? " " : "_"); int flags = new Integer(stCe.nextToken()).intValue(); newce = CirSim.createCe(tint, 0, 0, 0, 0, flags, stCe); } compElmList.add(newce); int thisPost = 0; while (stModel.hasMoreTokens()) { int nodeOfThisPost = new Integer(stModel.nextToken()).intValue(); // node = 0 means ground if (nodeOfThisPost == 0) { newce.setNode(thisPost, 0); newce.setNodeVoltage(thisPost, 0); thisPost++; continue; } cnLink = new CircuitNodeLink(); cnLink.num = thisPost; cnLink.elm = newce; if (!compNodeHash.containsKey(nodeOfThisPost)) { cn = new CircuitNode(); cn.links.add(cnLink); compNodeHash.put(nodeOfThisPost, cn); } else { cn = compNodeHash.get(nodeOfThisPost); cn.links.add(cnLink); } thisPost++; } } // Flatten compNodeHash in to compNodeList numPosts = externalNodes.length; for (int i = 0; i < externalNodes.length; i++) { // External Nodes First if (compNodeHash.containsKey(externalNodes[i])) { compNodeList.add(compNodeHash.get(externalNodes[i])); compNodeHash.remove(externalNodes[i]); } else throw new IllegalArgumentException(); } for (Entry<Integer, CircuitNode> entry : compNodeHash.entrySet()) { int key = entry.getKey(); compNodeList.add(compNodeHash.get(key)); } // allocate more nodes for sub-elements' internal nodes for (int i = 0; i != compElmList.size(); i++) { CircuitElm ce = compElmList.get(i); int inodes = ce.getInternalNodeCount(); for (int j = 0; j != inodes; j++) { cnLink = new CircuitNodeLink(); cnLink.num = j + ce.getPostCount(); cnLink.elm = ce; cn = new CircuitNode(); cn.links.add(cnLink); compNodeList.add(cn); } } numNodes = compNodeList.size(); // CirSim.console("Dumping compNodeList"); // for (int i = 0; i < numNodes; i++) { // CirSim.console("New node" + i + " Size of links:" + compNodeList.get(i).links.size()); // } posts = new Point[numPosts]; // Enumerate voltage sources for (int i = 0; i < compElmList.size(); i++) { int cnt = compElmList.get(i).getVoltageSourceCount(); for (int j=0;j < cnt ; j++) { vsRecord = new VoltageSourceRecord(); vsRecord.elm = compElmList.get(i); vsRecord.vsNumForElement = j; voltageSources.add(vsRecord); } } // dump new circuits with escape() flags |= FLAG_ESCAPE; } public boolean nonLinear() { return true; // Lets assume that any useful composite elements are // non-linear } public String dump() { String dumpStr=super.dump(); dumpStr += dumpElements(); return dumpStr; } public String dumpElements() { String dumpStr = ""; for (int i = 0; i < compElmList.size(); i++) { String tstring = compElmList.get(i).dump(); tstring = tstring.replaceFirst("[A-Za-z0-9]+ 0 0 0 0 ", ""); // remove unused tint x1 y1 x2 y2 coords for internal components dumpStr += " "+ CustomLogicModel.escape(tstring); } return dumpStr; } // dump subset of elements (some of them may not have any state, and/or may be very long, so we avoid dumping them for brevity) public String dumpWithMask(int mask) { String dumpStr=super.dump(); return dumpStr + dumpElements(mask); } public String dumpElements(int mask) { String dumpStr = ""; for (int i = 0; i < compElmList.size(); i++) { if ((mask & (1<<i)) == 0) continue; String tstring = compElmList.get(i).dump(); tstring = tstring.replaceFirst("[A-Za-z0-9]+ 0 0 0 0 ", ""); // remove unused tint x1 y1 x2 y2 coords for internal components dumpStr += " "+ CustomLogicModel.escape(tstring); } return dumpStr; } // are n1 and n2 connected internally somehow? public boolean getConnection(int n1, int n2) { Vector<Integer> connectedNodes = new Vector<Integer>(); // keep list of nodes connected to n1 connectedNodes.add(n1); int i; for (i = 0; i < connectedNodes.size(); i++) { // next node in list int n = connectedNodes.get(i); if (n == n2) return true; // find all elements connected to n Vector<CircuitNodeLink> cnLinks = compNodeList.get(n).links; for (int j = 0; j < cnLinks.size(); j++) { CircuitNodeLink link = cnLinks.get(j); CircuitElm lelm = link.elm; // loop through all other nodes this element has for (int k = 0; k != lelm.getConnectionNodeCount(); k++) // are they connected? if (k != link.num && lelm.getConnection(link.num, k)) { int kn = lelm.getConnectionNode(k); if (kn == 0) return true; int m; // find local node number (kn is global) and add it to list for (m = 0; m != nodes.length; m++) if (nodes[m] == kn && !connectedNodes.contains(m)) connectedNodes.add(m); } } } return false; } // is n1 connected to ground somehow? public boolean hasGroundConnection(int n1) { Vector<Integer> connectedNodes = new Vector<Integer>(); // keep list of nodes connected to n1 connectedNodes.add(n1); int i; for (i = 0; i < connectedNodes.size(); i++) { // next node in list int n = connectedNodes.get(i); // find all elements connected to n Vector<CircuitNodeLink> cnLinks = compNodeList.get(n).links; for (int j = 0; j < cnLinks.size(); j++) { CircuitNodeLink link = cnLinks.get(j); CircuitElm lelm = link.elm; if (lelm.hasGroundConnection(link.num)) return true; // loop through all other nodes this element has for (int k = 0; k != lelm.getConnectionNodeCount(); k++) // are they connected? if (k != link.num && lelm.getConnection(link.num, k)) { int kn = lelm.getConnectionNode(k); int m; // find local node number (kn is global) and add it to list for (m = 0; m != nodes.length; m++) if (nodes[m] == kn && !connectedNodes.contains(m)) connectedNodes.add(m); } } } return false; } public void reset() { for (int i = 0; i < compElmList.size(); i++) compElmList.get(i).reset(); } int getPostCount() { return numPosts; } int getInternalNodeCount() { return numNodes - numPosts; } Point getPost(int n) { return posts[n]; } void setPost(int n, Point p) { posts[n] = p; } void setPost(int n, int x, int y) { posts[n].x = x; posts[n].y = y; } public double getPower() { double power; power = 0; for (int i = 0; i < compElmList.size(); i++) power += compElmList.get(i).getPower(); return power; } public void stamp() { for (int i = 0; i < compElmList.size(); i++) { CircuitElm ce = compElmList.get(i); ce.setParentList(compElmList); ce.stamp(); } } public void startIteration() { for (int i = 0; i < compElmList.size(); i++) compElmList.get(i).startIteration(); } public void doStep() { for (int i = 0; i < compElmList.size(); i++) compElmList.get(i).doStep(); } public void stepFinished() { for (int i = 0; i < compElmList.size(); i++) compElmList.get(i).stepFinished(); } // called to set node p (local to this element) to equal n (global) public void setNode(int p, int n) { // nodes[p] = n Vector<CircuitNodeLink> cnLinks; super.setNode(p, n); cnLinks = compNodeList.get(p).links; // call setNode() for all elements that use that node for (int i = 0; i < cnLinks.size(); i++) { cnLinks.get(i).elm.setNode(cnLinks.get(i).num, n); } } public void setNodeVoltage(int n, double c) { // volts[n] = c; Vector<CircuitNodeLink> cnLinks; super.setNodeVoltage(n, c); cnLinks = compNodeList.get(n).links; for (int i = 0; i < cnLinks.size(); i++) { cnLinks.get(i).elm.setNodeVoltage(cnLinks.get(i).num, c); } volts[n]=c; } public boolean canViewInScope() { return false; } public void delete() { for (int i = 0; i < compElmList.size(); i++) compElmList.get(i).delete(); super.delete(); } public int getVoltageSourceCount() { return voltageSources.size(); } // Find the component with the nth voltage // and set the // appropriate source in that component void setVoltageSource(int n, int v) { // voltSource(n) = v; VoltageSourceRecord vsr; vsr=voltageSources.get(n); vsr.elm.setVoltageSource(vsr.vsNumForElement, v); vsr.vsNode=v; } @Override public void setCurrent(int vsn, double c) { for (int i=0;i<voltageSources.size(); i++) if (voltageSources.get(i).vsNode == vsn) { voltageSources.get(i).elm.setCurrent(vsn, c); } } double getCurrentIntoNode(int n) { double c=0; Vector<CircuitNodeLink> cnLinks; cnLinks = compNodeList.get(n).links; for (int i = 0; i < cnLinks.size(); i++) { c+=cnLinks.get(i).elm.getCurrentIntoNode(cnLinks.get(i).num); } return c; } } class VoltageSourceRecord { int vsNumForElement; int vsNode; CircuitElm elm; }
gpl-2.0
rogiermars/mt4j-core
src/org/mt4j/util/AbstractCollection.java
14930
package org.mt4j.util; import java.util.Collection; import java.util.Iterator; /** * This class provides a skeletal implementation of the <tt>Collection</tt> * interface, to minimize the effort required to implement this interface. <p> * * To implement an unmodifiable collection, the programmer needs only to * extend this class and provide implementations for the <tt>iterator</tt> and * <tt>size</tt> methods. (The iterator returned by the <tt>iterator</tt> * method must implement <tt>hasNext</tt> and <tt>next</tt>.)<p> * * To implement a modifiable collection, the programmer must additionally * override this class's <tt>add</tt> method (which otherwise throws an * <tt>UnsupportedOperationException</tt>), and the iterator returned by the * <tt>iterator</tt> method must additionally implement its <tt>remove</tt> * method.<p> * * The programmer should generally provide a void (no argument) and * <tt>Collection</tt> constructor, as per the recommendation in the * <tt>Collection</tt> interface specification.<p> * * The documentation for each non-abstract method in this class describes its * implementation in detail. Each of these methods may be overridden if * the collection being implemented admits a more efficient implementation.<p> * * This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @author Josh Bloch * @author Neal Gafter * @see Collection * @since 1.2 */ public abstract class AbstractCollection<E> implements Collection<E> { /** * Sole constructor. (For invocation by subclass constructors, typically * implicit.) */ protected AbstractCollection() { } // Query Operations /** * Returns an iterator over the elements contained in this collection. * * @return an iterator over the elements contained in this collection */ public abstract Iterator<E> iterator(); public abstract int size(); /** * {@inheritDoc} * * <p>This implementation returns <tt>size() == 0</tt>. */ public boolean isEmpty() { return size() == 0; } /** * {@inheritDoc} * * <p>This implementation iterates over the elements in the collection, * checking each element in turn for equality with the specified element. * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public boolean contains(Object o) { Iterator<E> e = iterator(); if (o==null) { while (e.hasNext()) if (e.next()==null) return true; } else { while (e.hasNext()) if (o.equals(e.next())) return true; } return false; } /** * {@inheritDoc} * * <p>This implementation returns an array containing all the elements * returned by this collection's iterator, in the same order, stored in * consecutive elements of the array, starting with index {@code 0}. * The length of the returned array is equal to the number of elements * returned by the iterator, even if the size of this collection changes * during iteration, as might happen if the collection permits * concurrent modification during iteration. The {@code size} method is * called only as an optimization hint; the correct result is returned * even if the iterator returns a different number of elements. * * <p>This method is equivalent to: * * <pre> {@code * List<E> list = new ArrayList<E>(size()); * for (E e : this) * list.add(e); * return list.toArray(); * }</pre> */ public Object[] toArray() { // Estimate size of array; be prepared to see more or fewer elements Object[] r = new Object[size()]; Iterator<E> it = iterator(); for (int i = 0; i < r.length; i++) { if (! it.hasNext()) // fewer elements than expected return Arrays.copyOf(r, i); r[i] = it.next(); } return it.hasNext() ? finishToArray(r, it) : r; } /** * {@inheritDoc} * * <p>This implementation returns an array containing all the elements * returned by this collection's iterator in the same order, stored in * consecutive elements of the array, starting with index {@code 0}. * If the number of elements returned by the iterator is too large to * fit into the specified array, then the elements are returned in a * newly allocated array with length equal to the number of elements * returned by the iterator, even if the size of this collection * changes during iteration, as might happen if the collection permits * concurrent modification during iteration. The {@code size} method is * called only as an optimization hint; the correct result is returned * even if the iterator returns a different number of elements. * * <p>This method is equivalent to: * * <pre> {@code * List<E> list = new ArrayList<E>(size()); * for (E e : this) * list.add(e); * return list.toArray(a); * }</pre> * * @throws ArrayStoreException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public <T> T[] toArray(T[] a) { // Estimate size of array; be prepared to see more or fewer elements int size = size(); T[] r = a.length >= size ? a : (T[])java.lang.reflect.Array .newInstance(a.getClass().getComponentType(), size); Iterator<E> it = iterator(); for (int i = 0; i < r.length; i++) { if (! it.hasNext()) { // fewer elements than expected if (a != r) return Arrays.copyOf(r, i); r[i] = null; // null-terminate return r; } r[i] = (T)it.next(); } return it.hasNext() ? finishToArray(r, it) : r; } /** * Reallocates the array being used within toArray when the iterator * returned more elements than expected, and finishes filling it from * the iterator. * * @param r the array, replete with previously stored elements * @param it the in-progress iterator over this collection * @return array containing the elements in the given array, plus any * further elements returned by the iterator, trimmed to size */ private static <T> T[] finishToArray(T[] r, Iterator<?> it) { int i = r.length; while (it.hasNext()) { int cap = r.length; if (i == cap) { int newCap = ((cap / 2) + 1) * 3; if (newCap <= cap) { // integer overflow if (cap == Integer.MAX_VALUE) throw new OutOfMemoryError ("Required array size too large"); newCap = Integer.MAX_VALUE; } r = Arrays.copyOf(r, newCap); } r[i++] = (T)it.next(); } // trim if overallocated return (i == r.length) ? r : Arrays.copyOf(r, i); } // Modification Operations /** * {@inheritDoc} * * <p>This implementation always throws an * <tt>UnsupportedOperationException</tt>. * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IllegalStateException {@inheritDoc} */ public boolean add(E e) { throw new UnsupportedOperationException(); } /** * {@inheritDoc} * * <p>This implementation iterates over the collection looking for the * specified element. If it finds the element, it removes the element * from the collection using the iterator's remove method. * * <p>Note that this implementation throws an * <tt>UnsupportedOperationException</tt> if the iterator returned by this * collection's iterator method does not implement the <tt>remove</tt> * method and this collection contains the specified object. * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} */ public boolean remove(Object o) { Iterator<E> e = iterator(); if (o==null) { while (e.hasNext()) { if (e.next()==null) { e.remove(); return true; } } } else { while (e.hasNext()) { if (o.equals(e.next())) { e.remove(); return true; } } } return false; } // Bulk Operations /** * {@inheritDoc} * * <p>This implementation iterates over the specified collection, * checking each element returned by the iterator in turn to see * if it's contained in this collection. If all elements are so * contained <tt>true</tt> is returned, otherwise <tt>false</tt>. * * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @see #contains(Object) */ public boolean containsAll(Collection<?> c) { Iterator<?> e = c.iterator(); while (e.hasNext()) if (!contains(e.next())) return false; return true; } /** * {@inheritDoc} * * <p>This implementation iterates over the specified collection, and adds * each object returned by the iterator to this collection, in turn. * * <p>Note that this implementation will throw an * <tt>UnsupportedOperationException</tt> unless <tt>add</tt> is * overridden (assuming the specified collection is non-empty). * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * @throws IllegalArgumentException {@inheritDoc} * @throws IllegalStateException {@inheritDoc} * * @see #add(Object) */ public boolean addAll(Collection<? extends E> c) { boolean modified = false; Iterator<? extends E> e = c.iterator(); while (e.hasNext()) { if (add(e.next())) modified = true; } return modified; } /** * {@inheritDoc} * * <p>This implementation iterates over this collection, checking each * element returned by the iterator in turn to see if it's contained * in the specified collection. If it's so contained, it's removed from * this collection with the iterator's <tt>remove</tt> method. * * <p>Note that this implementation will throw an * <tt>UnsupportedOperationException</tt> if the iterator returned by the * <tt>iterator</tt> method does not implement the <tt>remove</tt> method * and this collection contains one or more elements in common with the * specified collection. * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * * @see #remove(Object) * @see #contains(Object) */ public boolean removeAll(Collection<?> c) { boolean modified = false; Iterator<?> e = iterator(); while (e.hasNext()) { if (c.contains(e.next())) { e.remove(); modified = true; } } return modified; } /** * {@inheritDoc} * * <p>This implementation iterates over this collection, checking each * element returned by the iterator in turn to see if it's contained * in the specified collection. If it's not so contained, it's removed * from this collection with the iterator's <tt>remove</tt> method. * * <p>Note that this implementation will throw an * <tt>UnsupportedOperationException</tt> if the iterator returned by the * <tt>iterator</tt> method does not implement the <tt>remove</tt> method * and this collection contains one or more elements not present in the * specified collection. * * @throws UnsupportedOperationException {@inheritDoc} * @throws ClassCastException {@inheritDoc} * @throws NullPointerException {@inheritDoc} * * @see #remove(Object) * @see #contains(Object) */ public boolean retainAll(Collection<?> c) { boolean modified = false; Iterator<E> e = iterator(); while (e.hasNext()) { if (!c.contains(e.next())) { e.remove(); modified = true; } } return modified; } /** * {@inheritDoc} * * <p>This implementation iterates over this collection, removing each * element using the <tt>Iterator.remove</tt> operation. Most * implementations will probably choose to override this method for * efficiency. * * <p>Note that this implementation will throw an * <tt>UnsupportedOperationException</tt> if the iterator returned by this * collection's <tt>iterator</tt> method does not implement the * <tt>remove</tt> method and this collection is non-empty. * * @throws UnsupportedOperationException {@inheritDoc} */ public void clear() { Iterator<E> e = iterator(); while (e.hasNext()) { e.next(); e.remove(); } } // String conversion /** * Returns a string representation of this collection. The string * representation consists of a list of the collection's elements in the * order they are returned by its iterator, enclosed in square brackets * (<tt>"[]"</tt>). Adjacent elements are separated by the characters * <tt>", "</tt> (comma and space). Elements are converted to strings as * by {@link String#valueOf(Object)}. * * @return a string representation of this collection */ public String toString() { Iterator<E> i = iterator(); if (! i.hasNext()) return "[]"; StringBuilder sb = new StringBuilder(); sb.append('['); for (;;) { E e = i.next(); sb.append(e == this ? "(this Collection)" : e); if (! i.hasNext()) return sb.append(']').toString(); sb.append(", "); } } }
gpl-2.0
passByReference/Algorithms
java-puzzlers/8-classier-puzzlers/puzzle-74/Conundrum.java
282
public class Conundrum { public static void main(String[] args) { Enigma e = new Enigma(); System.out.println(e.equals(e)); } } final class Enigma { // Provide a class body that makes Conundrum print false. // Do *not* override equals. }
gpl-2.0
luo-isaiah/shijingshan
shijingshan-app/src/com/panguso/android/shijingshan/news/NewsPageTitleBar.java
2097
package com.panguso.android.shijingshan.news; import com.panguso.android.shijingshan.R; import android.content.Context; import android.util.AttributeSet; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageButton; import android.widget.RelativeLayout; import android.widget.TextView; /** * Specific for the blue title bar widget. * * @author Luo Yinzhuo */ public class NewsPageTitleBar extends RelativeLayout implements OnClickListener { /** * Interface definition for a callback to be invoked when a * {@link NewsPageTitleBar} 's back button is clicked. * * @author Luo Yinzhuo */ public interface OnBackListener { /** * Called when a {@link NewsPageTitleBar}'s back button has been * clicked. * * @author Luo Yinzhuo */ public void onTitleBarBack(); } /** The back button. */ private ImageButton mBack; /** The title text. */ private TextView mTitle; /** The back button listener. */ private OnBackListener mListener; /** * Construct a new instance. * * @param context The system context. * @param attrs The attributes. */ public NewsPageTitleBar(Context context, AttributeSet attrs) { super(context, attrs); LayoutInflater inflater = (LayoutInflater) context .getSystemService(Context.LAYOUT_INFLATER_SERVICE); inflater.inflate(R.layout.news_page_title_bar_widget, this); mBack = (ImageButton) findViewById(R.id.back); mTitle = (TextView) findViewById(R.id.title); mBack.setOnClickListener(this); } /** * Set the title. * * @param title The title. * @author Luo Yinzhuo */ public void setTitle(String title) { mTitle.setText(title); } /** * Set the {@link OnBackListener}. * * @param listener The {@link OnBackListener}. * @author Luo Yinzhuo */ public void setOnBackListener(OnBackListener listener) { mListener = listener; } @Override public void onClick(View v) { mListener.onTitleBarBack(); } }
gpl-2.0
FIRST-Team-2557-The-SOTABots/2014
2557_2014/src/edu/wpi/first/wpilibj/templates/commands/Latch.java
1319
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package edu.wpi.first.wpilibj.templates.commands; import edu.wpi.first.wpilibj.templates.RobotParts; /** * * @author Antonio */ public class Latch extends CommandBase { boolean latch = false; public Latch(boolean latch) { this.latch = latch; // Use requires() here to declare subsystem dependencies // eg. requires(chassis); } // Called just before this Command runs the first time protected void initialize() { RobotParts.compressor.start(); } // Called repeatedly when this Command is scheduled to run protected void execute() { RobotParts.latchCataSol.set(latch); RobotParts.fireCataSol.set(!latch); } // Make this return true when this Command no longer needs to run execute() protected boolean isFinished() { return true; } // Called once after isFinished returns true protected void end() { } // Called when another command which requires one or more of the same // subsystems is scheduled to run protected void interrupted() { } }
gpl-2.0
judgels/jerahmeel
app/org/iatoki/judgels/jerahmeel/curriculum/CurriculumJedisHibernateDao.java
496
package org.iatoki.judgels.jerahmeel.curriculum; import org.iatoki.judgels.play.model.AbstractJudgelsJedisHibernateDao; import redis.clients.jedis.JedisPool; import javax.inject.Inject; import javax.inject.Singleton; @Singleton public final class CurriculumJedisHibernateDao extends AbstractJudgelsJedisHibernateDao<CurriculumModel> implements CurriculumDao { @Inject public CurriculumJedisHibernateDao(JedisPool jedisPool) { super(jedisPool, CurriculumModel.class); } }
gpl-2.0
Skarafaz/mercury
app/src/main/java/it/skarafaz/mercury/MercuryApplication.java
4061
/* * Mercury-SSH * Copyright (C) 2017 Skarafaz * * This file is part of Mercury-SSH. * * Mercury-SSH 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. * * Mercury-SSH 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 Mercury-SSH. If not, see <http://www.gnu.org/licenses/>. */ package it.skarafaz.mercury; import android.app.Activity; import android.app.Application; import android.content.Context; import android.content.pm.PackageManager; import android.os.Environment; import android.support.v4.app.ActivityCompat; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentManager; import android.support.v4.app.FragmentTransaction; import android.support.v4.content.ContextCompat; import android.view.ViewConfiguration; import it.skarafaz.mercury.fragment.ProgressDialogFragment; import org.greenrobot.eventbus.EventBus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.lang.reflect.Field; public class MercuryApplication extends Application { private static final String S_HAS_PERMANENT_MENU_KEY = "sHasPermanentMenuKey"; private static final Logger logger = LoggerFactory.getLogger(MercuryApplication.class); private static Context context; public static Context getContext() { return context; } @Override public void onCreate() { super.onCreate(); context = this; EventBus.builder().addIndex(new EventBusIndex()).build(); // hack for devices with hw options button try { ViewConfiguration config = ViewConfiguration.get(this); Field menuKeyField = ViewConfiguration.class.getDeclaredField(S_HAS_PERMANENT_MENU_KEY); if (menuKeyField != null) { menuKeyField.setAccessible(true); menuKeyField.setBoolean(config, false); } } catch (Exception e) { logger.error(e.getMessage().replace("\n", " ")); } } public static void showProgressDialog(FragmentManager manager, String content) { FragmentTransaction transaction = manager.beginTransaction(); transaction.add(ProgressDialogFragment.newInstance(content), ProgressDialogFragment.TAG); transaction.commitAllowingStateLoss(); } public static void dismissProgressDialog(FragmentManager manager) { FragmentTransaction transaction = manager.beginTransaction(); Fragment fragment = manager.findFragmentByTag(ProgressDialogFragment.TAG); if (fragment != null) { transaction.remove(fragment); } transaction.commitAllowingStateLoss(); } public static boolean hasPermission(String permission) { return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED; } public static boolean requestPermission(Activity activity, int requestCode, String permission) { boolean requested = false; if (!ActivityCompat.shouldShowRequestPermissionRationale(activity, permission)) { ActivityCompat.requestPermissions(activity, new String[]{permission}, requestCode); requested = true; } return requested; } public static boolean isExternalStorageReadable() { String state = Environment.getExternalStorageState(); return Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state); } public static boolean isExternalStorageWritable() { String state = Environment.getExternalStorageState(); return Environment.MEDIA_MOUNTED.equals(state); } }
gpl-2.0
TDepelley/handigab
H/HandiGAB/src/handiGab/FormBean/CompteFB.java
1309
package handiGab.FormBean; import java.util.Date; import javax.faces.bean.SessionScoped; //@ManagedBean(name="CompteFB") @SessionScoped public class CompteFB { private String id; private String agence; private String devise; private String client; private Long solde; private Date dateOuverture; private Date dateFermeture; public String getId() { return id; } public void setId(String id) { this.id = id; } public Long getSolde() { return solde; } public void setSolde(Long solde) { this.solde = solde; } public Date getDateOuverture() { return dateOuverture; } public void setDateOuverture(Date dateOuverture) { this.dateOuverture = dateOuverture; } public Date getDateFermeture() { return dateFermeture; } public void setDateFermeture(Date dateFermeture) { this.dateFermeture = dateFermeture; } public String getAgence() { return agence; } public void setAgence(String agence) { this.agence = agence; } public String getDevise() { return devise; } public void setDevise(String devise) { this.devise = devise; } public String getClient() { return client; } public void setClient(String client) { this.client = client; } }
gpl-2.0
bh4017/mobac
src/main/java/mobac/gui/components/JDirectoryChooser.java
1897
/******************************************************************************* * Copyright (c) MOBAC developers * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. ******************************************************************************/ package mobac.gui.components; import java.io.File; import javax.swing.JFileChooser; import javax.swing.filechooser.FileFilter; import mobac.utilities.I18nUtils; public class JDirectoryChooser extends JFileChooser { private static final long serialVersionUID = -1954689476383812988L; public JDirectoryChooser() { super(); setDialogType(CUSTOM_DIALOG); setDialogTitle(I18nUtils.localizedStringForKey("dlg_select_dir_title")); //setApproveButtonText("Select Directory"); setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); setAcceptAllFileFilterUsed(false); addChoosableFileFilter(new FileFilter() { @Override public boolean accept(File f) { return f.isDirectory(); } @Override public String getDescription() { return I18nUtils.localizedStringForKey("dlg_select_dir_description"); } }); } @Override public void approveSelection() { if (!this.getFileFilter().accept(this.getSelectedFile())) return; super.approveSelection(); } }
gpl-2.0
delafer/j7project
commontools/thirddep-j7/src/main/java/org/eclipse/swt/internal/win32/TBBUTTONINFO.java
927
/******************************************************************************* * Copyright (c) 2000, 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 org.eclipse.swt.internal.win32; public class TBBUTTONINFO { public int cbSize; public int dwMask; public int idCommand; public int iImage; public byte fsState; public byte fsStyle; public short cx; public long /*int*/ lParam; /** @field cast=(LPTSTR) */ public long /*int*/ pszText; public int cchText; public static final int sizeof = OS.TBBUTTONINFO_sizeof (); }
gpl-2.0
demilich1/metastone
game/src/main/java/net/demilich/metastone/game/cards/MinionCard.java
3644
package net.demilich.metastone.game.cards; import java.util.Arrays; import java.util.HashSet; import java.util.Set; import net.demilich.metastone.game.Attribute; import net.demilich.metastone.game.actions.BattlecryAction; import net.demilich.metastone.game.actions.PlayCardAction; import net.demilich.metastone.game.actions.PlayMinionCardAction; import net.demilich.metastone.game.cards.desc.MinionCardDesc; import net.demilich.metastone.game.entities.minions.Minion; import net.demilich.metastone.game.entities.minions.Race; import net.demilich.metastone.game.spells.desc.BattlecryDesc; import net.demilich.metastone.game.spells.desc.trigger.TriggerDesc; public class MinionCard extends SummonCard { private static final Set<Attribute> ignoredAttributes = new HashSet<Attribute>( Arrays.asList(new Attribute[] { Attribute.PASSIVE_TRIGGER, Attribute.DECK_TRIGGER, Attribute.MANA_COST_MODIFIER, Attribute.BASE_ATTACK, Attribute.BASE_HP, Attribute.SECRET, Attribute.QUEST, Attribute.CHOOSE_ONE, Attribute.BATTLECRY, Attribute.COMBO })); private final MinionCardDesc desc; public MinionCard(MinionCardDesc desc) { super(desc); setAttribute(Attribute.BASE_ATTACK, desc.baseAttack); setAttribute(Attribute.ATTACK, desc.baseAttack); setAttribute(Attribute.BASE_HP, desc.baseHp); setAttribute(Attribute.HP, desc.baseHp); setAttribute(Attribute.MAX_HP, desc.baseHp); if (desc.race != null) { setRace(desc.race); } this.desc = desc; } protected Minion createMinion(Attribute... tags) { Minion minion = new Minion(this); for (Attribute gameTag : getAttributes().keySet()) { if (!ignoredAttributes.contains(gameTag)) { minion.setAttribute(gameTag, getAttribute(gameTag)); } } minion.setBaseAttack(getBaseAttack()); minion.setAttack(getAttack()); minion.setHp(getHp()); minion.setMaxHp(getHp()); minion.setBaseHp(getBaseHp()); BattlecryDesc battlecry = desc.battlecry; if (battlecry != null) { BattlecryAction battlecryAction = BattlecryAction.createBattlecry(battlecry.spell, battlecry.getTargetSelection()); if (battlecry.condition != null) { battlecryAction.setCondition(battlecry.condition.create()); } minion.setBattlecry(battlecryAction); } if (desc.deathrattle != null) { minion.removeAttribute(Attribute.DEATHRATTLES); minion.addDeathrattle(desc.deathrattle); } if (desc.trigger != null) { minion.addSpellTrigger(desc.trigger.create()); } if (desc.triggers != null) { for (TriggerDesc trigger : desc.triggers) { minion.addSpellTrigger(trigger.create()); } } if (desc.aura != null) { minion.addSpellTrigger(desc.aura.create()); } if (desc.cardCostModifier != null) { minion.setCardCostModifier(desc.cardCostModifier.create()); } minion.setHp(minion.getMaxHp()); return minion; } public int getAttack() { return getAttributeValue(Attribute.ATTACK); } public int getBonusAttack() { return getAttributeValue(Attribute.ATTACK_BONUS); } public int getHp() { return getAttributeValue(Attribute.HP); } public int getBonusHp() { return getAttributeValue(Attribute.HP_BONUS); } public int getBaseAttack() { return getAttributeValue(Attribute.BASE_ATTACK); } public int getBaseHp() { return getAttributeValue(Attribute.BASE_HP); } @Override public PlayCardAction play() { return new PlayMinionCardAction(getCardReference()); } public void setRace(Race race) { setAttribute(Attribute.RACE, race); } public Minion summon() { return createMinion(); } }
gpl-2.0
TheTypoMaster/Scaper
openjdk/jaxws/drop_included/jaxws_src/src/com/sun/tools/internal/ws/wsdl/document/Types.java
3415
/* * Copyright 2005-2006 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. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun 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 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 com.sun.tools.internal.ws.wsdl.document; import com.sun.tools.internal.ws.api.wsdl.TWSDLExtensible; import com.sun.tools.internal.ws.api.wsdl.TWSDLExtension; import com.sun.tools.internal.ws.wsdl.framework.Entity; import com.sun.tools.internal.ws.wsdl.framework.EntityAction; import com.sun.tools.internal.ws.wsdl.framework.ExtensibilityHelper; import com.sun.tools.internal.ws.wsdl.framework.ExtensionVisitor; import org.xml.sax.Locator; import javax.xml.namespace.QName; /** * Entity corresponding to the "types" WSDL element. * * @author WS Development Team */ public class Types extends Entity implements TWSDLExtensible { public Types(Locator locator) { super(locator); _helper = new ExtensibilityHelper(); } public QName getElementName() { return WSDLConstants.QNAME_TYPES; } public Documentation getDocumentation() { return _documentation; } public void setDocumentation(Documentation d) { _documentation = d; } public void accept(WSDLDocumentVisitor visitor) throws Exception { visitor.preVisit(this); _helper.accept(visitor); visitor.postVisit(this); } public void validateThis() { } /** * wsdl:type does not have any name attribute */ public String getNameValue() { return null; } public String getNamespaceURI() { return parent.getNamespaceURI(); } public QName getWSDLElementName() { return getElementName(); } public void addExtension(TWSDLExtension e) { _helper.addExtension(e); } public Iterable<TWSDLExtension> extensions() { return _helper.extensions(); } public TWSDLExtensible getParent() { return parent; } public void setParent(TWSDLExtensible parent) { this.parent = parent; } public void withAllSubEntitiesDo(EntityAction action) { _helper.withAllSubEntitiesDo(action); } public void accept(ExtensionVisitor visitor) throws Exception { _helper.accept(visitor); } private TWSDLExtensible parent; private ExtensibilityHelper _helper; private Documentation _documentation; }
gpl-2.0
djcoin/svn2git_gvsig_mini
src/es/prodevelop/gvsig/mini/search/suggestions/FullTextSuggestionMatrixCursor.java
2779
/* gvSIG Mini. A free mobile phone viewer of free maps. * * Copyright (C) 2011 Prodevelop. * * 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. * * For more information, contact: * * Prodevelop, S.L. * Pza. Don Juan de Villarrasa, 14 - 5 * 46001 Valencia * Spain * * +34 963 510 612 * +34 963 510 968 * prode@prodevelop.es * http://www.prodevelop.es * * gvSIG Mini has been partially funded by IMPIVA (Instituto de la Peque�a y * Mediana Empresa de la Comunidad Valenciana) & * European Union FEDER funds. * * 2011. * author Alberto Romeu aromeu@prodevelop.es */ package es.prodevelop.gvsig.mini.search.suggestions; import java.util.ArrayList; import es.prodevelop.gvsig.mini.utiles.Utilities; import android.app.SearchManager; import android.database.MatrixCursor; import android.provider.BaseColumns; public class FullTextSuggestionMatrixCursor extends MatrixCursor { public final static String[] SUGGESTION_COLUMN_NAMES = new String[] { BaseColumns._ID, SearchManager.SUGGEST_COLUMN_TEXT_1, SearchManager.SUGGEST_COLUMN_TEXT_2, /* * SearchManager.SUGGEST_COLUMN_ICON_1, * SearchManager.SUGGEST_COLUMN_ICON_2, */ /* * SearchManager.SUGGEST_COLUMN_INTENT_ACTION, */ SearchManager.SUGGEST_COLUMN_INTENT_DATA, /* * SearchManager.SUGGEST_COLUMN_INTENT_DATA_ID, * SearchManager.SUGGEST_COLUMN_INTENT_EXTRA_DATA, */ SearchManager.SUGGEST_COLUMN_QUERY, SearchManager.SUGGEST_COLUMN_SHORTCUT_ID, SearchManager.SUGGEST_COLUMN_SPINNER_WHILE_REFRESHING }; public FullTextSuggestionMatrixCursor(String[] columnNames) { super(columnNames); } public void fillMatrix(ArrayList words) { if (words == null) return; final int size = words.size(); String word; for (int i = 0; i < size; i++) { word = words.get(i).toString(); if (word != null && word.length() != 0) { word = Utilities.capitalizeFirstLetters(word); this.addRow(new Object[] { -1, word, "", /* * 0, 0, null, */word, /* * null, null, */null, null, null }); } } } }
gpl-2.0
intelie/esper
esper/src/test/java/com/espertech/esper/regression/epl/TestSelectClauseJoin.java
3301
/* * ************************************************************************************* * Copyright (C) 2008 EsperTech, Inc. All rights reserved. * * http://esper.codehaus.org * * http://www.espertech.com * * ---------------------------------------------------------------------------------- * * The software in this package is published under the terms of the GPL license * * a copy of which has been included with this distribution in the license.txt file. * * ************************************************************************************* */ package com.espertech.esper.regression.epl; import junit.framework.TestCase; import com.espertech.esper.client.*; import com.espertech.esper.client.EventType; import com.espertech.esper.support.bean.SupportBean; import com.espertech.esper.support.client.SupportConfigFactory; import com.espertech.esper.support.util.SupportUpdateListener; import java.util.Iterator; public class TestSelectClauseJoin extends TestCase { private EPServiceProvider epService; private EPStatement joinView; private SupportUpdateListener updateListener; public void setUp() { epService = EPServiceProviderManager.getDefaultProvider(SupportConfigFactory.getConfiguration()); epService.initialize(); updateListener = new SupportUpdateListener(); String eventA = SupportBean.class.getName(); String eventB = SupportBean.class.getName(); String joinStatement = "select s0.doubleBoxed, s1.intPrimitive*s1.intBoxed/2.0 as div from " + eventA + "(string='s0').win:length(3) as s0," + eventB + "(string='s1').win:length(3) as s1" + " where s0.doubleBoxed = s1.doubleBoxed"; joinView = epService.getEPAdministrator().createEPL(joinStatement); joinView.addListener(updateListener); } public void testJoinSelect() { assertNull(updateListener.getLastNewData()); sendEvent("s0", 1, 4, 5); sendEvent("s1", 1, 3, 2); EventBean[] newEvents = updateListener.getLastNewData(); assertEquals(1d, newEvents[0].get("s0.doubleBoxed")); assertEquals(3d, newEvents[0].get("div")); Iterator<EventBean> iterator = joinView.iterator(); EventBean event = iterator.next(); assertEquals(1d, event.get("s0.doubleBoxed")); assertEquals(3d, event.get("div")); } public void testEventType() { EventType result = joinView.getEventType(); assertEquals(Double.class, result.getPropertyType("s0.doubleBoxed")); assertEquals(Double.class, result.getPropertyType("div")); assertEquals(2, joinView.getEventType().getPropertyNames().length); } private void sendEvent(String s, double doubleBoxed, int intPrimitive, int intBoxed) { SupportBean bean = new SupportBean(); bean.setString(s); bean.setDoubleBoxed(doubleBoxed); bean.setIntPrimitive(intPrimitive); bean.setIntBoxed(intBoxed); epService.getEPRuntime().sendEvent(bean); } }
gpl-2.0
krishna174/Java_C
AadharValidation-PFX/src/com/pmc/acc/ekyc/exception/Auth_XSDValidationFailedException.java
237
package com.pmc.acc.ekyc.exception; public class Auth_XSDValidationFailedException extends KSASystemException { public Auth_XSDValidationFailedException() { super("E - 120: Auth XSD Validation Failed."); } }
gpl-2.0
nikolaySeveryn/abc-english-school
src/main/java/nks/abc/service/StaffService.java
465
package nks.abc.service; import java.util.List; import nks.abc.domain.dto.user.StaffDTO; import nks.abc.domain.entity.user.AccountInfo; public interface StaffService { public void add(StaffDTO employee); public List<StaffDTO> getAll(); public List<StaffDTO> getAllTeachers(); void delete(Long id, String currentUserLogin); void update(StaffDTO employeeDTO, String currentUserLogin); StaffDTO getStaffByLogin(String login); StaffDTO getById(Long id); }
gpl-2.0
Romenig/ivprog2-final
ivprog-final/src/usp/ime/line/ivprog/interpreter/execution/expressions/booleans/comparisons/LessThanOrEqualTo.java
1808
/** * Instituto de Matemática e Estatística da Universidade de São Paulo (IME-USP) * iVProg is a open source and free software of Laboratório de Informática na * Educação (LInE) licensed under GNU GPL2.0 license. * Prof. Dr. Leônidas de Oliveira Brandão - leo@ime.usp.br * Romenig da Silva Ribeiro - romenig@ime.usp.br | romenig@gmail.com * @author Romenig */ package usp.ime.line.ivprog.interpreter.execution.expressions.booleans.comparisons; import java.util.HashMap; import usp.ime.line.ivprog.interpreter.DataFactory; import usp.ime.line.ivprog.interpreter.DataObject; import usp.ime.line.ivprog.interpreter.execution.Context; import usp.ime.line.ivprog.interpreter.execution.expressions.Expression; import usp.ime.line.ivprog.interpreter.execution.expressions.value.IVPBoolean; import usp.ime.line.ivprog.interpreter.execution.expressions.value.IVPNumber; import usp.ime.line.ivprog.interpreter.execution.expressions.value.IVPValue; public class LessThanOrEqualTo extends Expression { private String expA; private String expB; /** * Set the left expression of and. EqualTo := expressionA == expressionB * * @param expressionA */ public void setExpressionA(String expressionA) { expA = expressionA; } /** * Set the right expression of and. EqualTo := expressionA == expressionB * * @param expressionB */ public void setExpressionB(String expressionB) { expB = expressionB; } public Object evaluate(Context c, HashMap map, DataFactory factory) { IVPNumber expressionA = (IVPNumber) ((DataObject)map.get(expA)).evaluate(c, map, factory); IVPNumber expressionB = (IVPNumber) ((DataObject)map.get(expB)).evaluate(c, map, factory); return expressionA.lessThanOrEqualTo(expressionB, c, map, factory); } }
gpl-2.0
thechrisjohnson/JDip
src/dip/tool/Tool.java
1935
// // @(#)Tool.java 1.00 9/2002 // // Copyright 2002 Zachary DelProposto. All rights reserved. // Use is subject to license terms. // // // 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., 675 Mass Ave, Cambridge, MA 02139, USA. // Or from http://www.gnu.org/ // package dip.tool; import java.net.URI; import javax.swing.JMenuItem; public interface Tool { // Versioning Methods /** Get the current Tool version */ public float getVersion(); /** Get the Tool Copyright Information (authors, etc.). Never should return null. */ public String getCopyrightInfo(); /** Get the Tool Web URI (web address, ftp address, etc.). Never should return null. */ public URI getWebURI(); /** Get the Email addresses. Never should return null. */ public URI[] getEmailURIs(); /** Get the Tool comment. Never should return null. */ public String getComment(); /** Get the Tool Description. Never should return null. */ public String getDescription(); /** Get the Tool name. Never should return null. */ public String getName(); // registration methods /** Creates a JMenuItem (or JMenu for sub-items) */ public JMenuItem registerJMenuItem(); /** Gets the ToolProxy object which allows a Tool access to internal data structures */ public void setToolProxy(ToolProxy toolProxy); }// interface Tool
gpl-2.0
qiuxs/ice-demos
java/Ice/session/SessionFactoryI.java
856
// ********************************************************************** // // Copyright (c) 2003-2015 ZeroC, Inc. All rights reserved. // // ********************************************************************** import Demo.*; class SessionFactoryI extends _SessionFactoryDisp { SessionFactoryI(ReapTask reaper) { _reaper = reaper; } @Override public synchronized SessionPrx create(String name, Ice.Current c) { SessionI session = new SessionI(name); SessionPrx proxy = SessionPrxHelper.uncheckedCast(c.adapter.addWithUUID(session)); _reaper.add(proxy, session); return proxy; } @Override public void shutdown(Ice.Current c) { System.out.println("Shutting down..."); c.adapter.getCommunicator().shutdown(); } private ReapTask _reaper; }
gpl-2.0
fozziethebeat/S-Space
src/test/java/edu/ucla/sspace/text/corpora/SemEvalCorpusReaderTest.java
2487
/* * Copyright (c) 2011, Lawrence Livermore National Security, LLC. Produced at * the Lawrence Livermore National Laboratory. Written by Keith Stevens, * kstevens@cs.ucla.edu OCEC-10-073 All rights reserved. * * This file is part of the S-Space package and is covered under the terms and * conditions therein. * * The S-Space package is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation and distributed hereunder to you. * * THIS SOFTWARE IS PROVIDED "AS IS" AND NO REPRESENTATIONS OR WARRANTIES, * EXPRESS OR IMPLIED ARE MADE. BY WAY OF EXAMPLE, BUT NOT LIMITATION, WE MAKE * NO REPRESENTATIONS OR WARRANTIES OF MERCHANT- ABILITY OR FITNESS FOR ANY * PARTICULAR PURPOSE OR THAT THE USE OF THE LICENSED SOFTWARE OR DOCUMENTATION * WILL NOT INFRINGE ANY THIRD PARTY PATENTS, COPYRIGHTS, TRADEMARKS OR OTHER * RIGHTS. * * 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 edu.ucla.sspace.text.corpora; import edu.ucla.sspace.text.CorpusReader; import edu.ucla.sspace.text.Document; import java.io.StringReader; import java.util.Iterator; import org.junit.Ignore; import org.junit.Test; import static org.junit.Assert.*; /** * @author Keith Stevens */ public class SemEvalCorpusReaderTest { private final String TRAIN_TEXT = "<cat.n.train><cat.n.1>chicken cat bar</cat.n.1></cat.n.train>"; private final String TEST_TEXT= "<cat.n.test><cat.n.1>chicken <TargetSentence>cat</TargetSentence> bar</cat.n.1></cat.n.test>"; @Test public void testTrainReader() throws Exception { CorpusReader<Document> reader = new SemEvalCorpusReader(); Iterator<Document> iter = reader.read(new StringReader(TRAIN_TEXT)); assertTrue(iter.hasNext()); assertEquals("cat.n.1 chicken |||| cat bar", iter.next().reader().readLine().trim()); assertFalse(iter.hasNext()); } @Test public void testTestReader() throws Exception { CorpusReader<Document> reader = new SemEvalCorpusReader(); Iterator<Document> iter = reader.read(new StringReader(TEST_TEXT)); assertTrue(iter.hasNext()); assertEquals("cat.n.1 chicken |||| cat bar", iter.next().reader().readLine().trim()); assertFalse(iter.hasNext()); } }
gpl-2.0
javajoker/infoecos
src/com/infoecos/ning/util/graph/Node.java
1518
package com.infoecos.ning.util.graph; import java.util.Stack; public class Node { protected Stack<Link> parentLinks = new Stack<Link>(); protected Stack<Link> links = new Stack<Link>(); protected NodeObject object = null; public void addParentLink(Link parentLink) { if (!parentLinks.contains(parentLink)) parentLinks.push(parentLink); } public Link[] getParentLinks() { return (Link[]) parentLinks.toArray(new Link[parentLinks.size()]); } public void removeParentLink(Link link) { parentLinks.remove(link); } public Link[] getLinks() { return (Link[]) links.toArray(new Link[links.size()]); } public void setObject(NodeObject object) { this.object = object; } public NodeObject getObject() { return object; } public void pushSubLink(Link link) throws Exception { if (!this.equals(link.getStartNode())) throw new NotLinkableException(); object.applyLink(link); Node endNode = link.getEndNode(); endNode.addParentLink(link); links.push(link); } public Link popSubLink() { Link link = links.pop(); Node endNode = link.getEndNode(); endNode.removeParentLink(link); object.removeLink(link); return link; } @Override public Object clone() throws CloneNotSupportedException { Node node = new Node(); node.object = this.object.clone(); for (Link l : parentLinks) { node.parentLinks.add(new Link(l.getStartNode(), node)); } for (Link l : links) { node.links.add(new Link(node, (Node) l.getEndNode().clone())); } return node; } }
gpl-2.0
ahuarte47/SOS
hibernate/common/src/main/java/org/n52/sos/ds/hibernate/entities/observation/series/AbstractValuedSeriesObservation.java
2117
/** * Copyright (C) 2012-2016 52°North Initiative for Geospatial Open Source * Software GmbH * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 as published * by the Free Software Foundation. * * If the program is linked with libraries which are licensed under one of * the following licenses, the combination of the program with the linked * library is not considered a "derivative work" of the program: * * - Apache License, version 2.0 * - Apache Software License, version 1.0 * - GNU Lesser General Public License, version 3 * - Mozilla Public License, versions 1.0, 1.1 and 2.0 * - Common Development and Distribution License (CDDL), version 1.0 * * Therefore the distribution of the program linked with libraries licensed * under the aforementioned licenses, is permitted by the copyright holders * if the distribution is compliant with both the GNU General Public * License version 2 and the aforementioned licenses. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General * Public License for more details. */ package org.n52.sos.ds.hibernate.entities.observation.series; import org.n52.sos.ds.hibernate.entities.observation.legacy.AbstractValuedLegacyObservation; /** * Abstract implementation of {@link ValuedSeriesObservation}. * * @author Christian Autermann * @param <T> the value type */ public abstract class AbstractValuedSeriesObservation<T> extends AbstractValuedLegacyObservation<T> implements ValuedSeriesObservation<T> { private static final long serialVersionUID = -2757686338936995366L; private Series series; @Override public Series getSeries() { return series; } @Override public void setSeries(Series series) { this.series = series; } @Override public boolean isSetSeries() { return getSeries() != null; } }
gpl-2.0
liaochente/knowledge
src/com/hh/search/action/AdvancedSearchAction.java
10328
package com.hh.search.action; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.struts2.ServletActionContext; import com.hh.base.BaseAction; import com.hh.common.CommonUtil; import com.hh.common.Constant; import com.hh.common.service.CommonService; import com.hh.search.service.AdvancedSearchService; import com.hh.search.service.QuickSearchService; import com.hh.vo.ClickStatisticVo; import com.hh.vo.DictionaryVo; import com.hh.vo.Form; import com.hh.vo.ImageVo; import com.hh.vo.StatisticVo; import com.hh.vo.UserVo; import com.hh.vo.WebsiteVo; /** * 高级检索Action * * @author user * */ public class AdvancedSearchAction extends BaseAction { /** * 运算符数据 */ private List<DictionaryVo> operators; /** * 文档类型数据 */ private List<DictionaryVo> documentTypes; /** * 高级查询SERVICE */ private AdvancedSearchService advancedSearchService; /** * 快速查询SERVICE */ private QuickSearchService quickService; /** * 公共SERVICE */ private CommonService commonService; /** * 上传文件 */ private File image; /** * 上传文件名 */ private String imageFileName; /** * 上传文件类型 */ private String imageContentType; /** * 返回的匹配网页结果 */ private List<WebsiteVo> webSiteList; /** * 返回的匹配图片结果 */ private List<ImageVo> imageList; /** * 关键字 */ private String keyWords; /** * 第一次检索出来的网页ID链 */ private String webIds; /** * 扩展查询项1 */ private List<Map<String, Object>> expansionList1; /** * 扩展查询项2 */ private List<Map<String, Object>> expansionList2; /** * 跳转高级检索页面 * * @return */ public String goAdvancedSearch() { operators = commonService.queryDictionaryByList("operator"); documentTypes = commonService.queryDictionaryByList("document_type"); return SUCCESS; } /** * 图片查询 * * @return */ public String imageQuery() { String realpath = ServletActionContext.getServletContext().getRealPath( "/upload"); UserVo user = (UserVo) session.get(Constant.USER); FileOutputStream fos = null; FileInputStream fis = null; try { fos = new FileOutputStream(realpath + "/" + imageFileName); fis = new FileInputStream(image); byte[] buffer = new byte[1024]; int len = 0; while ((len = fis.read(buffer)) > 0) { fos.write(buffer, 0, len); } fos.flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fis != null) { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } } ImageVo imageVo = advancedSearchService.queryImageInfo(imageFileName); if (imageVo != null) { imageList = advancedSearchService.queryImageByImage(imageVo); webSiteList = advancedSearchService.queryWebsitByImage(imageVo); } return SUCCESS; } /** * 文本查询 * * @return */ public String textQuery() { operators = commonService.queryDictionaryByList("operator"); documentTypes = commonService.queryDictionaryByList("document_type"); UserVo user = (UserVo) session.get(Constant.USER); this.form.setUser_id(user.getId()); webSiteList = advancedSearchService.queryWebsiteByText(this.form); imageList = advancedSearchService.queryImageByText(this.form); session.put(Constant.WEB_CLICK_STATISTIC, CommonUtil.createClickStatisticVo()); return SUCCESS; } /** * academic paper retrieval“那块在显示结果的时候只需要有webpage,不需要有image * * @return */ public String academicQuery() { operators = commonService.queryDictionaryByList("operator"); documentTypes = commonService.queryDictionaryByList("document_type"); UserVo user = (UserVo) session.get(Constant.USER); this.form.setUser_id(user.getId()); webSiteList = advancedSearchService.queryWebsiteByText(this.form); return SUCCESS; } /** * ”non- academic paper retrieval“那块在显示结果的时候webpage和image都得有 * * @return */ public String academicQuery2() { operators = commonService.queryDictionaryByList("operator"); documentTypes = commonService.queryDictionaryByList("document_type"); UserVo user = (UserVo) session.get(Constant.USER); this.form.setUser_id(user.getId()); webSiteList = advancedSearchService.queryWebsiteByText(this.form); imageList = advancedSearchService.queryImageByText(this.form); return SUCCESS; } /** * 跳转扩展查询 * * @return */ public String goExpansionQuery() { operators = commonService.queryDictionaryByList("operator"); UserVo user = (UserVo) session.get(Constant.USER); documentTypes = commonService.queryDictionaryByList("document_type"); ClickStatisticVo cvo = (ClickStatisticVo) session .get(Constant.WEB_CLICK_STATISTIC); List<StatisticVo> svoList = cvo.getList(); if (svoList != null && svoList.size() > 0) { StatisticVo vo1 = svoList.get(0); double rate1 = vo1.getRate(); StatisticVo vo2 = null; double rate2 = 0; if (svoList.size() > 1) { vo2 = svoList.get(1); rate2 = vo2.getRate(); } Map<String, Object> map = new HashMap<String, Object>(); map.put("user_id", user.getId()); if (vo2 != null) { if ((rate1 >= 0.6 && rate2 < 0.3) || (rate1 >= 0.4 && rate1 <= 0.6 && rate2 < 0.1) || rate2 == 0) {// 只扩展term1 map.put("term1", vo1.getId()); map.put("term1_rate", vo1.getRate()); } else if ((rate2 >= 0.6 && rate1 < 0.3) || (rate2 >= 0.4 && rate2 <= 0.6 && rate1 < 0.1) || rate1 == 0) {// 只扩展term2 map.put("term2", vo2.getId()); map.put("term2_rate", vo2.getRate()); } else {// term1 term2都扩展 map.put("term1", vo1.getId()); map.put("term2", vo2.getId()); map.put("term1_rate", vo1.getRate()); map.put("term2_rate", vo2.getRate()); } } else { map.put("term1", vo1.getId()); map.put("term1_rate", vo1.getRate()); } map.put("word", form.getWord()); expansionList1 = advancedSearchService.queryExpansionList(map); if (CommonUtil.isNotNull(form.getWord2_select()) && !"3".equals(form.getWord2_select()) && CommonUtil.isNotNull(form.getWord2())) { map.put("word", form.getWord2()); expansionList2 = advancedSearchService.queryExpansionList(map); } } return SUCCESS; } /** * 扩展查询 * * @return */ public String expansionQuery() { operators = commonService.queryDictionaryByList("operator"); documentTypes = commonService.queryDictionaryByList("document_type"); UserVo user = (UserVo) session.get(Constant.USER); this.form.setUser_id(user.getId()); webSiteList = advancedSearchService.queryWebsiteByText(this.form); imageList = advancedSearchService.queryImageByText(this.form); String[] words = this.form.getWord_exs(); if (words != null) { for (String word : words) { webSiteList.addAll(quickService.queryWebsitResults(word)); imageList.addAll(quickService.queryImageResults(word)); } } String[] words2 = this.form.getWord2_exs(); if (words2 != null) { for (String word : words2) { webSiteList.addAll(quickService.queryWebsitResults(word)); imageList.addAll(quickService.queryImageResults(word)); } } return SUCCESS; } public File getImage() { return image; } public void setImage(File image) { this.image = image; } public String getImageFileName() { return imageFileName; } public void setImageFileName(String imageFileName) { this.imageFileName = imageFileName; } public String getImageContentType() { return imageContentType; } public void setImageContentType(String imageContentType) { this.imageContentType = imageContentType; } public List<DictionaryVo> getOperators() { return operators; } public void setOperators(List<DictionaryVo> operators) { this.operators = operators; } public List<DictionaryVo> getDocumentTypes() { return documentTypes; } public void setDocumentTypes(List<DictionaryVo> documentTypes) { this.documentTypes = documentTypes; } public AdvancedSearchService getAdvancedSearchService() { return advancedSearchService; } public void setAdvancedSearchService( AdvancedSearchService advancedSearchService) { this.advancedSearchService = advancedSearchService; } public CommonService getCommonService() { return commonService; } public void setCommonService(CommonService commonService) { this.commonService = commonService; } public List<WebsiteVo> getWebSiteList() { return webSiteList; } public void setWebSiteList(List<WebsiteVo> webSiteList) { this.webSiteList = webSiteList; } public List<ImageVo> getImageList() { return imageList; } public void setImageList(List<ImageVo> imageList) { this.imageList = imageList; } public String getKeyWords() { return keyWords; } public void setKeyWords(String keyWords) { this.keyWords = keyWords; } public String getWebIds() { return webIds; } public void setWebIds(String webIds) { this.webIds = webIds; } public List<Map<String, Object>> getExpansionList1() { return expansionList1; } public void setExpansionList1(List<Map<String, Object>> expansionList1) { this.expansionList1 = expansionList1; } public List<Map<String, Object>> getExpansionList2() { return expansionList2; } public void setExpansionList2(List<Map<String, Object>> expansionList2) { this.expansionList2 = expansionList2; } public QuickSearchService getQuickService() { return quickService; } public void setQuickService(QuickSearchService quickService) { this.quickService = quickService; } }
gpl-2.0
AntoineDelacroix/NewSuperProject-
org.eclipse.jface/src/org/eclipse/jface/action/SubContributionItem.java
3549
/******************************************************************************* * Copyright (c) 2000, 2008 IBM Corporation and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * IBM Corporation - initial API and implementation *******************************************************************************/ package org.eclipse.jface.action; import org.eclipse.swt.widgets.Composite; import org.eclipse.swt.widgets.CoolBar; import org.eclipse.swt.widgets.Menu; import org.eclipse.swt.widgets.ToolBar; /** * A <code>SubContributionItem</code> is a wrapper for an <code>IContributionItem</code>. * It is used within a <code>SubContributionManager</code> to control the visibility * of items. * <p> * This class is not intended to be subclassed. * </p> * @noextend This class is not intended to be subclassed by clients. */ public class SubContributionItem implements IContributionItem { /** * The visibility of the item. */ private boolean visible; /** * The inner item for this contribution. */ private IContributionItem innerItem; /** * Creates a new <code>SubContributionItem</code>. * @param item the contribution item to be wrapped */ public SubContributionItem(IContributionItem item) { innerItem = item; } /** * The default implementation of this <code>IContributionItem</code> * delegates to the inner item. Subclasses may override. */ @Override public void dispose() { innerItem.dispose(); } @Override public void fill(Composite parent) { if (visible) { innerItem.fill(parent); } } @Override public void fill(Menu parent, int index) { if (visible) { innerItem.fill(parent, index); } } @Override public void fill(ToolBar parent, int index) { if (visible) { innerItem.fill(parent, index); } } @Override public String getId() { return innerItem.getId(); } /** * Returns the inner contribution item. * * @return the inner contribution item */ public IContributionItem getInnerItem() { return innerItem; } @Override public boolean isEnabled() { return innerItem.isEnabled(); } @Override public boolean isDirty() { return innerItem.isDirty(); } @Override public boolean isDynamic() { return innerItem.isDynamic(); } @Override public boolean isGroupMarker() { return innerItem.isGroupMarker(); } @Override public boolean isSeparator() { return innerItem.isSeparator(); } @Override public boolean isVisible() { return visible && innerItem.isVisible(); } @Override public void setParent(IContributionManager parent) { // do nothing, the parent of our inner item // is its SubContributionManager } @Override public void setVisible(boolean visible) { this.visible = visible; } @Override public void update() { innerItem.update(); } @Override public void update(String id) { innerItem.update(id); } @Override public void fill(CoolBar parent, int index) { if (visible) { innerItem.fill(parent, index); } } @Override public void saveWidgetState() { } }
gpl-2.0
wissame95/IF06-Projet
TaquinFinal/src/junit/TaquinSpeed.java
989
package junit; import jeu.Commande; import jeu.Taquin; import main.Main; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.TestRule; import com.carrotsearch.junitbenchmarks.BenchmarkOptions; import com.carrotsearch.junitbenchmarks.BenchmarkRule; import com.carrotsearch.junitbenchmarks.annotation.AxisRange; import com.carrotsearch.junitbenchmarks.annotation.BenchmarkMethodChart; @AxisRange(min = 0, max = 0.05) @BenchmarkMethodChart(filePrefix = "testMethodeTaquin") @BenchmarkOptions(callgc = false, benchmarkRounds = 1) public class TaquinSpeed{ Commande commande= new Commande(); Taquin taq1; @Rule public TestRule benchmarkRun = new BenchmarkRule(); @Before public void setUp(){ taq1 = (Taquin)Main.jeuFromFile("taquin/taq7.taq"); } @Test public void testSolvable(){ taq1.estSoluble(); } @Test public void testManhattan(){ taq1.nbPermutFin(); } @Test public void testResolu(){ taq1.estResolu(); } }
gpl-2.0
fowlerwill/SchoolAssignments
FowlerWill-Comp2503-Assignment05/src/exampleProgram/UserIO/ConsoleCom.java
4118
package exampleProgram.UserIO; /** * Handles basic input/output with the console * * @author JKidney * @version 2.0 * * last Modified: Sept 24, 2012 - JKidney Added new functionality into the class */ import java.util.*; public class ConsoleCom { public static final char NO_CHAR_INPUT = ' '; //default for character input private Scanner input; /** * default constructor */ public ConsoleCom() { input = new Scanner(System.in); } /** * helper method to contain printing of messages to the console * @param message the message to print */ public void print(String message) { System.out.print(message); } /** * helper method to contain printing of messages to the console with a new line * @param message the message to print */ public void println(String message) { System.out.println(message); } /** * Displays a message and waits to read a line of text from the user * @param message the message to display * @return the line inputed by the user * */ public String getInputString(String message) { print(message); return input.nextLine().trim(); } /** * Displays a message and waits to read an integer from the user * @param message the message to display * @return the integer inputed by the user */ public int getInputInt(String message) { int userInput = 0; boolean exit = true; print(message); do { try { userInput = input.nextInt(); input.nextLine(); } catch(Exception ex) { print("Not a number, please enter again: "); clearInputLine(); exit = false; } } while(!exit); return userInput; } /** * Displays a message and waits to read an integer from the user within the given range * @param message the message to display * @param low the low end of the range (inclusive) * @param high the high end of the range (inclusive) * @return the integer inputed by the user ( and verified to be within range ) */ public int getInputInRangeInt(String message, int low, int high) { int userInput = 0; boolean exit = false; do { userInput = getInputInt(message); if(userInput < low || userInput > high) print("Not within proper range ("+low+"-"+high+"), please enter again: "); else exit = true; } while(!exit); return userInput; } /** * clears one line from the input console */ public void clearInputLine() { input.nextLine(); } /** * reads one character from the input * @param message the message to display * @return the entered character or NO_CHAR_INPUT if no input */ public char getInputChar(String message) { char result = NO_CHAR_INPUT; print(message); String inputLine = input.nextLine().trim().toLowerCase(); if(inputLine.length() > 0) result = inputLine.charAt(0); return result; } /** * reads one character from the input and validates that it is a character in validChars * @param message the message to display * @param validChars a string that contains all valid chars for input by the user * @return the entered character validated */ public char getInputCharValidate(String message, String validChars) { char userInput = NO_CHAR_INPUT; boolean exit = false; String valid = validChars.toUpperCase(); do { userInput = Character.toUpperCase( getInputChar(message) ); if(valid.indexOf(userInput) == -1) println("Invalid choice ( must be one of "+validChars+"), please enter again: "); else exit = true; } while(!exit); return userInput; } /** * Asks the user a yes no answer and returns the result * @param message the message to display to the user ( y/n) will be tacked on * @return true if the user entered 'y' false otherwise */ public boolean getInputYesNo(String message) { boolean result = false; char input = Character.toUpperCase( getInputChar(message + " (y,n)") ); if(input == 'Y') result = true; return result; } /** * pauses until the user hits enter to continue */ public void pauseUntilHitEnter() { getInputString("<hit enter to continue>"); } }
gpl-2.0